Completed
Pull Request — master (#2965)
by Lakshmi
04:30
created

TimersController   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 79
rs 10
wmc 13

11 Methods

Rating   Name   Duplication   Size   Complexity  
A _get_timer_ref() 0 2 1
A _handle_update_trigger() 0 4 1
A _handle_create_trigger() 0 4 1
A remove_trigger() 0 8 2
A get_all() 0 5 1
A _handle_delete_trigger() 0 4 1
A update_trigger() 0 2 1
A __init__() 0 12 1
A add_trigger() 0 6 1
A _sanitize_trigger() 0 3 1
A _register_timer_trigger_types() 0 3 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
import six
17
18
from st2api.controllers import resource
19
from st2common import log as logging
20
from st2common.constants.triggers import TIMER_TRIGGER_TYPES
21
from st2common.models.api.base import jsexpose
22
from st2common.models.api.trigger import TriggerAPI
23
from st2common.models.system.common import ResourceReference
24
from st2common.persistence.trigger import Trigger
25
import st2common.services.triggers as trigger_service
26
from st2common.services.triggerwatcher import TriggerWatcher
27
28
LOG = logging.getLogger(__name__)
29
30
31
class TimersHolder(object):
32
33
    def __init__(self):
34
        self._timers = {}
35
36
    def add_trigger(self, ref, trigger):
37
        self._timers[ref] = trigger
38
39
    def remove_trigger(self, ref, trigger):
40
        del self._timers[ref]
41
42
    def get_all(self):
43
        timer_triggers = []
44
45
        LOG.info('Timers: %s', self._timers)
46
47
        for _, timer in six.iteritems(self._timers):
48
            LOG.info('Appending timer: %s', timer)
49
            timer_triggers.append(timer)
50
51
        LOG.info('Returning timers: %s', timer_triggers)
52
        return timer_triggers
53
54
55
56
class TimersController(resource.ContentPackResourceController):
57
    model = TriggerAPI
58
    access = Trigger
59
60
    supported_filters = {
61
        'type': 'type',
62
    }
63
64
    query_options = {
65
        'sort': ['type']
66
    }
67
68
    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...
69
        self._timers = TimersHolder()
70
        self._trigger_types = TIMER_TRIGGER_TYPES.keys()
71
        queue_suffix = self.__class__.__name__
72
        self._trigger_watcher = TriggerWatcher(create_handler=self._handle_create_trigger,
73
                                               update_handler=self._handle_update_trigger,
74
                                               delete_handler=self._handle_delete_trigger,
75
                                               trigger_types=self._trigger_types,
76
                                               queue_suffix=queue_suffix,
77
                                               exclusive=True)
78
        self._trigger_watcher.start()
79
        self._register_timer_trigger_types()
80
81
    @jsexpose()
82
    def get_all(self):
83
        t_all = self._timers.get_all()
84
        LOG.info('Got timers: %s', t_all)
85
        return t_all
86
87
    def add_trigger(self, trigger):
88
        # Note: Permission checking for creating and deleting a timer is done during rule
89
        # creation
90
        ref = self._get_timer_ref(trigger)
91
        LOG.info('Started timer %s with parameters %s', ref, trigger['parameters'])
92
        self._timers.add_trigger(ref, trigger)
93
94
    def update_trigger(self, trigger):
95
        pass
96
97
    def remove_trigger(self, trigger):
98
        # Note: Permission checking for creating and deleting a timer is done during rule
99
        # creation
100
        ref = self._get_timer_ref(trigger)
101
102
        removed = self._timers.remove_trigger(ref, trigger)
103
        if removed:
104
            LOG.info('Stopped timer %s with parameters', ref, trigger['parameters'])
105
106
    def _register_timer_trigger_types(self):
107
        for trigger_type in TIMER_TRIGGER_TYPES.values():
108
            trigger_service.create_trigger_type_db(trigger_type)
109
110
    def _get_timer_ref(self, trigger):
111
        return ResourceReference.to_string_reference(pack=trigger['pack'], name=trigger['name'])
112
113
    ##############################################
114
    # Event handler methods for the trigger events
115
    ##############################################
116
117
    def _handle_create_trigger(self, trigger):
118
        LOG.debug('Calling "add_trigger" method (trigger.type=%s)' % (trigger.type))
119
        trigger = self._sanitize_trigger(trigger=trigger)
120
        self.add_trigger(trigger=trigger)
121
122
    def _handle_update_trigger(self, trigger):
123
        LOG.debug('Calling "update_trigger" method (trigger.type=%s)' % (trigger.type))
124
        trigger = self._sanitize_trigger(trigger=trigger)
125
        self.update_trigger(trigger=trigger)
126
127
    def _handle_delete_trigger(self, trigger):
128
        LOG.debug('Calling "remove_trigger" method (trigger.type=%s)' % (trigger.type))
129
        trigger = self._sanitize_trigger(trigger=trigger)
130
        self.remove_trigger(trigger=trigger)
131
132
    def _sanitize_trigger(self, trigger):
133
        sanitized = TriggerAPI.from_model(trigger).to_dict()
134
        return sanitized
135