Completed
Push — master ( f3cc78...a2c705 )
by Lakshmi
14:28
created

TimersHolder.get_all()   A

Complexity

Conditions 4

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
c 2
b 0
f 0
dl 0
loc 8
rs 9.2
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
from pecan import abort
17
from six import iteritems
18
from six.moves import http_client
19
20
from st2api.controllers import resource
21
from st2common import log as logging
22
from st2common.constants.triggers import TIMER_TRIGGER_TYPES
23
from st2common.models.api.base import jsexpose
24
from st2common.models.api.trigger import TriggerAPI
25
from st2common.models.system.common import ResourceReference
26
from st2common.persistence.trigger import Trigger
27
import st2common.services.triggers as trigger_service
28
from st2common.services.triggerwatcher import TriggerWatcher
29
30
LOG = logging.getLogger(__name__)
31
32
33
class TimersHolder(object):
34
35
    def __init__(self):
36
        self._timers = {}
37
38
    def add_trigger(self, ref, trigger):
39
        self._timers[ref] = trigger
40
41
    def remove_trigger(self, ref, trigger):
42
        del self._timers[ref]
43
44
    def get_all(self, timer_type=None):
45
        timer_triggers = []
46
47
        for _, timer in iteritems(self._timers):
48
            if not timer_type or timer['type'] == timer_type:
49
                timer_triggers.append(timer)
50
51
        return timer_triggers
52
53
54
class TimersController(resource.ContentPackResourceController):
55
    model = TriggerAPI
56
    access = Trigger
57
58
    supported_filters = {
59
        'type': 'type',
60
    }
61
62
    query_options = {
63
        'sort': ['type']
64
    }
65
66
    def __init__(self, *args, **kwargs):
0 ignored issues
show
Bug introduced by
The __init__ method of the super-class ContentPackResourceController is not called.

It is generally advisable to initialize the super-class by calling its __init__ method:

class SomeParent:
    def __init__(self):
        self.x = 1

class SomeChild(SomeParent):
    def __init__(self):
        # Initialize the super class
        SomeParent.__init__(self)
Loading history...
67
        self._timers = TimersHolder()
68
        self._trigger_types = TIMER_TRIGGER_TYPES.keys()
69
        queue_suffix = self.__class__.__name__
70
        self._trigger_watcher = TriggerWatcher(create_handler=self._handle_create_trigger,
71
                                               update_handler=self._handle_update_trigger,
72
                                               delete_handler=self._handle_delete_trigger,
73
                                               trigger_types=self._trigger_types,
74
                                               queue_suffix=queue_suffix,
75
                                               exclusive=True)
76
        self._trigger_watcher.start()
77
        self._register_timer_trigger_types()
78
        self._allowed_timer_types = TIMER_TRIGGER_TYPES.keys()
79
80
    @jsexpose()
81
    def get_all(self, timer_type=None):
0 ignored issues
show
Bug introduced by
Arguments number differs from overridden 'get_all' method
Loading history...
82
        if timer_type and timer_type not in self._allowed_timer_types:
83
            msg = 'Timer type %s not in supported types - %s.' % self._allowed_timer_types
84
            abort(http_client.BAD_REQUEST, msg)
85
86
        t_all = self._timers.get_all(timer_type=timer_type)
87
        LOG.debug('Got timers: %s', t_all)
88
        return t_all
89
90
    def add_trigger(self, trigger):
91
        # Note: Permission checking for creating and deleting a timer is done during rule
92
        # creation
93
        ref = self._get_timer_ref(trigger)
94
        LOG.info('Started timer %s with parameters %s', ref, trigger['parameters'])
95
        self._timers.add_trigger(ref, trigger)
96
97
    def update_trigger(self, trigger):
98
        pass
99
100
    def remove_trigger(self, trigger):
101
        # Note: Permission checking for creating and deleting a timer is done during rule
102
        # creation
103
        ref = self._get_timer_ref(trigger)
104
105
        removed = self._timers.remove_trigger(ref, trigger)
106
        if removed:
107
            LOG.info('Stopped timer %s with parameters %s.', ref, trigger['parameters'])
108
109
    def _register_timer_trigger_types(self):
110
        for trigger_type in TIMER_TRIGGER_TYPES.values():
111
            trigger_service.create_trigger_type_db(trigger_type)
112
113
    def _get_timer_ref(self, trigger):
114
        return ResourceReference.to_string_reference(pack=trigger['pack'], name=trigger['name'])
115
116
    ##############################################
117
    # Event handler methods for the trigger events
118
    ##############################################
119
120
    def _handle_create_trigger(self, trigger):
121
        LOG.debug('Calling "add_trigger" method (trigger.type=%s)' % (trigger.type))
122
        trigger = self._sanitize_trigger(trigger=trigger)
123
        self.add_trigger(trigger=trigger)
124
125
    def _handle_update_trigger(self, trigger):
126
        LOG.debug('Calling "update_trigger" method (trigger.type=%s)' % (trigger.type))
127
        trigger = self._sanitize_trigger(trigger=trigger)
128
        self.update_trigger(trigger=trigger)
129
130
    def _handle_delete_trigger(self, trigger):
131
        LOG.debug('Calling "remove_trigger" method (trigger.type=%s)' % (trigger.type))
132
        trigger = self._sanitize_trigger(trigger=trigger)
133
        self.remove_trigger(trigger=trigger)
134
135
    def _sanitize_trigger(self, trigger):
136
        sanitized = TriggerAPI.from_model(trigger).to_dict()
137
        return sanitized
138