-
-
Notifications
You must be signed in to change notification settings - Fork 746
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #5679 from StackStorm/token_ttl
Add purging of old tokens
- Loading branch information
Showing
11 changed files
with
312 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
#!/usr/bin/env python | ||
# Licensed to the StackStorm, Inc ('StackStorm') under one or more | ||
# contributor license agreements. See the NOTICE file distributed with | ||
# this work for additional information regarding copyright ownership. | ||
# The ASF licenses this file to You under the Apache License, Version 2.0 | ||
# (the "License"); you may not use this file except in compliance with | ||
# the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import sys | ||
|
||
from st2common.cmd.purge_tokens import main | ||
|
||
if __name__ == "__main__": | ||
sys.exit(main()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
# Copyright 2022 The StackStorm Authors. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
|
||
""" | ||
A utility script that purges trigger instances older than certain | ||
timestamp. | ||
*** RISK RISK RISK. You will lose data. Run at your own risk. *** | ||
""" | ||
|
||
from __future__ import absolute_import | ||
|
||
from datetime import datetime | ||
|
||
import six | ||
import pytz | ||
from oslo_config import cfg | ||
|
||
from st2common import config | ||
from st2common import log as logging | ||
from st2common.config import do_register_cli_opts | ||
from st2common.script_setup import setup as common_setup | ||
from st2common.script_setup import teardown as common_teardown | ||
from st2common.constants.exit_codes import SUCCESS_EXIT_CODE | ||
from st2common.constants.exit_codes import FAILURE_EXIT_CODE | ||
from st2common.garbage_collection.token import purge_tokens | ||
|
||
__all__ = ["main"] | ||
|
||
LOG = logging.getLogger(__name__) | ||
|
||
|
||
def _register_cli_opts(): | ||
cli_opts = [ | ||
cfg.StrOpt( | ||
"timestamp", | ||
default=None, | ||
help="Will delete tokens whose expiry is older than " | ||
+ "this UTC timestamp. " | ||
+ "Example value: 2015-03-13T19:01:27.255542Z", | ||
) | ||
] | ||
do_register_cli_opts(cli_opts) | ||
|
||
|
||
def main(): | ||
_register_cli_opts() | ||
common_setup(config=config, setup_db=True, register_mq_exchanges=False) | ||
|
||
# Get config values | ||
timestamp = cfg.CONF.timestamp | ||
|
||
if not timestamp: | ||
LOG.error("Please supply a timestamp for purging models. Aborting.") | ||
return 1 | ||
else: | ||
timestamp = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ") | ||
timestamp = timestamp.replace(tzinfo=pytz.UTC) | ||
|
||
# Purge models. | ||
try: | ||
purge_tokens(logger=LOG, timestamp=timestamp) | ||
except Exception as e: | ||
LOG.exception(six.text_type(e)) | ||
return FAILURE_EXIT_CODE | ||
finally: | ||
common_teardown() | ||
|
||
return SUCCESS_EXIT_CODE |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
# Copyright 2022 The StackStorm Authors. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
""" | ||
Module with utility functions for purging old trigger instance objects. | ||
""" | ||
|
||
from __future__ import absolute_import | ||
|
||
import six | ||
from mongoengine.errors import InvalidQueryError | ||
|
||
from st2common.persistence.auth import Token | ||
from st2common.util import isotime | ||
|
||
__all__ = ["purge_tokens"] | ||
|
||
|
||
def purge_tokens(logger, timestamp): | ||
""" | ||
:param timestamp: Tokens which expired after this timestamp will be deleted. | ||
:type timestamp: ``datetime.datetime | ||
""" | ||
if not timestamp: | ||
raise ValueError("Specify a valid timestamp to purge.") | ||
|
||
logger.info( | ||
"Purging token instances which expired after timestamp: %s" | ||
% timestamp.strftime("%Y-%m-%dT%H:%M:%S.%fZ") | ||
) | ||
|
||
query_filters = {"expiry__lt": isotime.parse(timestamp)} | ||
|
||
try: | ||
deleted_count = Token.delete_by_query(**query_filters) | ||
except InvalidQueryError as e: | ||
msg = ( | ||
"Bad query (%s) used to delete token instances: %s" | ||
"Please contact support." | ||
% ( | ||
query_filters, | ||
six.text_type(e), | ||
) | ||
) | ||
raise InvalidQueryError(msg) | ||
except: | ||
logger.exception( | ||
"Deleting token instances using query_filters %s failed.", query_filters | ||
) | ||
else: | ||
logger.info("Deleted %s token objects" % (deleted_count)) | ||
|
||
# Print stats | ||
logger.info("All token models expired after timestamp %s were deleted.", timestamp) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
# Copyright 2022 The StackStorm Authors. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from __future__ import absolute_import | ||
from datetime import timedelta | ||
import bson | ||
|
||
from st2common import log as logging | ||
from st2common.garbage_collection.token import purge_tokens | ||
from st2common.models.db.auth import TokenDB | ||
from st2common.persistence.auth import Token | ||
from st2common.util import date as date_utils | ||
from st2tests.base import CleanDbTestCase | ||
|
||
LOG = logging.getLogger(__name__) | ||
|
||
|
||
class TestPurgeToken(CleanDbTestCase): | ||
@classmethod | ||
def setUpClass(cls): | ||
CleanDbTestCase.setUpClass() | ||
super(TestPurgeToken, cls).setUpClass() | ||
|
||
def setUp(self): | ||
super(TestPurgeToken, self).setUp() | ||
|
||
def test_no_timestamp_doesnt_delete(self): | ||
now = date_utils.get_datetime_utc_now() | ||
TestPurgeToken._create_save_token( | ||
expiry_timestamp=now - timedelta(days=20), | ||
) | ||
|
||
self.assertEqual(len(Token.get_all()), 1) | ||
expected_msg = "Specify a valid timestamp" | ||
self.assertRaisesRegexp( | ||
ValueError, | ||
expected_msg, | ||
purge_tokens, | ||
logger=LOG, | ||
timestamp=None, | ||
) | ||
self.assertEqual(len(Token.get_all()), 1) | ||
|
||
def test_purge(self): | ||
now = date_utils.get_datetime_utc_now() | ||
TestPurgeToken._create_save_token( | ||
expiry_timestamp=now - timedelta(days=20), | ||
) | ||
|
||
TestPurgeToken._create_save_token( | ||
expiry_timestamp=now - timedelta(days=5), | ||
) | ||
|
||
self.assertEqual(len(Token.get_all()), 2) | ||
purge_tokens(logger=LOG, timestamp=now - timedelta(days=10)) | ||
self.assertEqual(len(Token.get_all()), 1) | ||
|
||
@staticmethod | ||
def _create_save_token(expiry_timestamp=None): | ||
created = TokenDB( | ||
id=str(bson.ObjectId()), | ||
user="pony", | ||
token=str(bson.ObjectId()), | ||
expiry=expiry_timestamp, | ||
metadata={"service": "action-runner"}, | ||
) | ||
return Token.add_or_update(created) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters