Completed
Push — master ( 8be562...193373 )
by Manas
05:42
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
27
from mongoengine.errors import InvalidQueryError
28
from oslo_config import cfg
29
30
from st2common import config
31
from st2common import log as logging
32
from st2common.script_setup import setup as common_setup
33
from st2common.script_setup import teardown as common_teardown
34
from st2common.persistence.trigger import TriggerInstance
35
from st2common.util import isotime
36
37
LOG = logging.getLogger(__name__)
38
DELETED_COUNT = 0
39
40
41
def _do_register_cli_opts(opts, ignore_errors=False):
42
    for opt in opts:
43
        try:
44
            cfg.CONF.register_cli_opt(opt)
45
        except:
46
            if not ignore_errors:
47
                raise
48
49
50
def _register_cli_opts():
51
    cli_opts = [
52
        cfg.StrOpt('timestamp', default=None,
53
                   help='Will delete trigger instances older than ' +
54
                   'this UTC timestamp. ' +
55
                   'Example value: 2015-03-13T19:01:27.255542Z')
56
    ]
57
    _do_register_cli_opts(cli_opts)
58
59
60
def purge_trigger_instances(timestamp=None):
61
    if not timestamp:
62
        LOG.error('Specify a valid timestamp to purge.')
63
        return 2
64
65
    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...
66
             timestamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
67
68
    # XXX: Think about paginating this call.
69
    query_filters = {'occurrence_time__lt': isotime.parse(timestamp)}
70
    try:
71
        TriggerInstance.delete_by_query(**query_filters)
72
    except InvalidQueryError:
73
        LOG.exception('Bad query (%s) used to delete trigger instances. ' +
74
                      'Please contact support.', query_filters)
75
        return 3
76
    except:
77
        LOG.exception('Deleting instances using query_filters %s failed.', query_filters)
78
        return 4
79
80
    # Print stats
81
    LOG.info('#### Trigger instances deleted.')
82
83
84
def main():
85
    _register_cli_opts()
86
    common_setup(config=config, setup_db=True, register_mq_exchanges=False)
87
88
    # Get config values
89
    timestamp = cfg.CONF.timestamp
90
91
    if not timestamp:
92
        LOG.error('Please supply a timestamp for purging models. Aborting.')
93
        return 1
94
    else:
95
        timestamp = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%fZ')
96
        timestamp = timestamp.replace(tzinfo=pytz.UTC)
97
98
    # Purge models.
99
    try:
100
        return purge_trigger_instances(timestamp=timestamp)
101
    finally:
102
        common_teardown()
103