Completed
Pull Request — master (#2296)
by Manas
06:15
created

st2common.cmd.purge_trigger_instances()   B

Complexity

Conditions 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 4
dl 0
loc 22
rs 8.9197
1
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
17
"""
18
A utility script that purges trigger instances older than certain
19
timestamp.
20
21
*** RISK RISK RISK. You will lose data. Run at your own risk. ***
22
"""
23
24
from datetime import datetime
25
import pytz
26
import sys
0 ignored issues
show
Unused Code introduced by
The import sys seems to be unused.
Loading history...
27
28
from mongoengine.errors import InvalidQueryError
29
from oslo_config import cfg
30
31
from st2common import config
32
from st2common import log as logging
33
from st2common.script_setup import setup as common_setup
34
from st2common.script_setup import teardown as common_teardown
35
from st2common.persistence.trigger import TriggerInstance
36
from st2common.util import isotime
37
38
LOG = logging.getLogger(__name__)
39
DELETED_COUNT = 0
40
41
42
def _do_register_cli_opts(opts, ignore_errors=False):
43
    for opt in opts:
44
        try:
45
            cfg.CONF.register_cli_opt(opt)
46
        except:
47
            if not ignore_errors:
48
                raise
49
50
51
def _register_cli_opts():
52
    cli_opts = [
53
        cfg.StrOpt('timestamp', default=None,
54
                   help='Will delete trigger instances older than ' +
55
                   'this UTC timestamp. ' +
56
                   'Example value: 2015-03-13T19:01:27.255542Z')
57
    ]
58
    _do_register_cli_opts(cli_opts)
59
60
61
def purge_trigger_instances(timestamp=None):
62
    if not timestamp:
63
        LOG.error('Specify a valid timestamp to purge.')
64
        return 2
65
66
    LOG.info('Purging trigger instances older than timestamp: %s' %
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
67
             timestamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
68
69
    # XXX: Think about paginating this call.
70
    query_filters = {'occurrence_time__lt': isotime.parse(timestamp)}
71
    try:
72
        TriggerInstance.delete_by_query(**query_filters)
73
    except InvalidQueryError:
74
        LOG.exception('Bad query (%s) used to delete trigger instances. ' +
75
                      'Please contact support.', query_filters)
76
        return 3
77
    except:
78
        LOG.exception('Deleting instances using query_filters %s failed.', query_filters)
79
        return 4
80
81
    # Print stats
82
    LOG.info('#### Trigger instances deleted.')
83
84
85
def main():
86
    _register_cli_opts()
87
    common_setup(config=config, setup_db=True, register_mq_exchanges=False)
88
89
    # Get config values
90
    timestamp = cfg.CONF.timestamp
91
92
    if not timestamp:
93
        LOG.error('Please supply a timestamp for purging models. Aborting.')
94
        return 1
95
    else:
96
        timestamp = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%fZ')
97
        timestamp = timestamp.replace(tzinfo=pytz.UTC)
98
99
    # Purge models.
100
    try:
101
        return purge_trigger_instances(timestamp=timestamp)
102
    finally:
103
        common_teardown()
104