Test Failed
Push — master ( e380d0...f5671d )
by W
02:58
created

tools/migrate_rules_to_include_pack.py (1 issue)

1
#!/usr/bin/env python
2
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
3
# contributor license agreements.  See the NOTICE file distributed with
4
# this work for additional information regarding copyright ownership.
5
# The ASF licenses this file to You under the Apache License, Version 2.0
6
# (the "License"); you may not use this file except in compliance with
7
# the License.  You may obtain a copy of the License at
8
#
9
#     http://www.apache.org/licenses/LICENSE-2.0
10
#
11
# Unless required by applicable law or agreed to in writing, software
12
# distributed under the License is distributed on an "AS IS" BASIS,
13
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
# See the License for the specific language governing permissions and
15
# limitations under the License.
16
17
from __future__ import absolute_import
18
import mongoengine as me
19
20
from st2common import config
21
from st2common.constants.pack import DEFAULT_PACK_NAME
22
from st2common.service_setup import db_setup
23
from st2common.service_setup import db_teardown
24
from st2common.models.db import MongoDBAccess
25
from st2common.models.db import stormbase
26
from st2common.models.db.rule import ActionExecutionSpecDB
27
from st2common.models.system.common import ResourceReference
28
from st2common.persistence.base import Access, ContentPackResource
29
30
31
class Migration(object):
32
    class RuleDB(stormbase.StormFoundationDB, stormbase.TagsMixin,
33
                 stormbase.ContentPackResourceMixin):
34
        """Specifies the action to invoke on the occurrence of a Trigger. It
35
        also includes the transformation to perform to match the impedance
36
        between the payload of a TriggerInstance and input of a action.
37
        Attribute:
38
            trigger: Trigger that trips this rule.
39
            criteria:
40
            action: Action to execute when the rule is tripped.
41
            status: enabled or disabled. If disabled occurrence of the trigger
42
            does not lead to execution of a action and vice-versa.
43
        """
44
        name = me.StringField(required=True)
45
        ref = me.StringField(required=True)
46
        description = me.StringField()
47
        pack = me.StringField(
48
            required=False,
49
            help_text='Name of the content pack.',
50
            unique_with='name')
51
        trigger = me.StringField()
52
        criteria = stormbase.EscapedDictField()
53
        action = me.EmbeddedDocumentField(ActionExecutionSpecDB)
54
        enabled = me.BooleanField(required=True, default=True,
55
                                  help_text=u'Flag indicating whether the rule is enabled.')
56
57
        meta = {
58
            'indexes': stormbase.TagsMixin.get_indices()
59
        }
60
61
62
# specialized access objects
63
rule_access_with_pack = MongoDBAccess(Migration.RuleDB)
64
65
66
class RuleDB(stormbase.StormBaseDB, stormbase.TagsMixin):
67
    """Specifies the action to invoke on the occurrence of a Trigger. It
68
    also includes the transformation to perform to match the impedance
69
    between the payload of a TriggerInstance and input of a action.
70
    Attribute:
71
        trigger: Trigger that trips this rule.
72
        criteria:
73
        action: Action to execute when the rule is tripped.
74
        status: enabled or disabled. If disabled occurrence of the trigger
75
        does not lead to execution of a action and vice-versa.
76
    """
77
    trigger = me.StringField()
78
    criteria = stormbase.EscapedDictField()
79
    action = me.EmbeddedDocumentField(ActionExecutionSpecDB)
80
    enabled = me.BooleanField(required=True, default=True,
81
                              help_text=u'Flag indicating whether the rule is enabled.')
82
83
    meta = {
84
        'indexes': stormbase.TagsMixin.get_indices()
85
    }
86
87
88
rule_access_without_pack = MongoDBAccess(RuleDB)
89
90
91
class RuleWithoutPack(Access):
92
    impl = rule_access_without_pack
93
94
    @classmethod
95
    def _get_impl(cls):
96
        return cls.impl
97
98
    @classmethod
99
    def _get_by_object(cls, object):
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in object.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
100
        # For Rule name is unique.
101
        name = getattr(object, 'name', '')
102
        return cls.get_by_name(name)
103
104
105
class RuleWithPack(ContentPackResource):
106
    impl = rule_access_with_pack
107
108
    @classmethod
109
    def _get_impl(cls):
110
        return cls.impl
111
112
113
def migrate_rules():
114
    try:
115
        existing_rules = RuleWithoutPack.get_all()
116
117
        for rule in existing_rules:
118
            rule_with_pack = Migration.RuleDB(
119
                id=rule.id,
120
                name=rule.name,
121
                description=rule.description,
122
                trigger=rule.trigger,
123
                criteria=rule.criteria,
124
                action=rule.action,
125
                enabled=rule.enabled,
126
                pack=DEFAULT_PACK_NAME,
127
                ref=ResourceReference.to_string_reference(pack=DEFAULT_PACK_NAME,
128
                                                          name=rule.name)
129
            )
130
            print('Migrating rule: %s to rule: %s' % (rule.name, rule_with_pack.ref))
131
            RuleWithPack.add_or_update(rule_with_pack)
132
    except Exception as e:
133
        print('Migration failed. %s' % str(e))
134
135
136
def main():
137
    config.parse_args()
138
139
    # Connect to db.
140
    db_setup()
141
142
    # Migrate rules.
143
    migrate_rules()
144
145
    # Disconnect from db.
146
    db_teardown()
147
148
149
if __name__ == '__main__':
150
    main()
151