Test Failed
Pull Request — master (#3398)
by Lakshmi
07:34
created

create_trigger_instance()   C

Complexity

Conditions 8

Size

Total Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
dl 0
loc 64
rs 5.545
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 st2common import log as logging
19
from st2common.constants.triggers import TRIGGER_INSTANCE_PENDING
20
from st2common.exceptions.db import StackStormDBObjectNotFoundError
21
from st2common.models.db.trigger import TriggerInstanceDB
22
from st2common.persistence.trigger import TriggerInstance
23
from st2common.services import triggers as TriggerService
24
25
LOG = logging.getLogger('st2reactor.sensor.container_utils')
26
27
28
def create_trigger_instance(trigger, payload, occurrence_time, raise_on_no_trigger=False):
29
    """
30
    This creates a trigger instance object given trigger and payload.
31
    Trigger can be just a string reference (pack.name) or a ``dict`` containing 'id' or
32
    'uid' or type' and 'parameters' keys.
33
34
    :param trigger: Trigger reference or dictionary with trigger query filters.
35
    :type trigger: ``str`` or ``dict``
36
37
    :param payload: Trigger payload.
38
    :type payload: ``dict``
39
    """
40
    # TODO: This is nasty, this should take a unique reference and not a dict
41
    if isinstance(trigger, six.string_types):
42
        trigger_db = TriggerService.get_trigger_db_by_ref(trigger)
43
        if not trigger_db:
44
            LOG.debug('No trigger in db for %s', trigger)
45
            if raise_on_no_trigger:
46
                raise StackStormDBObjectNotFoundError('Trigger not found for %s', trigger)
47
            return None
48
        else:
49
            trigger_ptr = {'ref': trigger_db.get_reference().ref}
50
    else:
51
        # If id / uid is available we try to look up Trigger by id. This way we can avoid bug in
52
        # pymongo / mongoengine related to "parameters" dictionary lookups
53
        trigger_id = trigger.get('id', None)
54
        trigger_uid = trigger.get('uid', None)
55
56
        # TODO: Remove parameters dictionary look up when we can confirm each trigger dictionary
57
        # passed to this method always contains id or uid
58
        if trigger_id:
59
            LOG.info('Looking up TriggerDB by id: %s', trigger_id)
60
            trigger_db = TriggerService.get_trigger_db_by_id(id=trigger_id)
61
        elif trigger_uid:
62
            LOG.info('Looking up TriggerDB by uid: %s', trigger_uid)
63
            trigger_db = TriggerService.get_trigger_db_by_uid(uid=trigger_uid)
64
        else:
65
            # Last resort - look it up by parameters
66
            trigger_type = trigger.get('type', None)
67
            parameters = trigger.get('parameters', {})
68
69
            LOG.debug('Looking up TriggerDB by type and parameters: type=%s, parameters=%s',
70
                      trigger_type, parameters)
71
            trigger_db = TriggerService.get_trigger_db_given_type_and_params(type=trigger_type,
72
                                                                             parameters=parameters)
73
74
        if not trigger_db:
75
            LOG.debug('No trigger in db for %s', trigger)
76
            if raise_on_no_trigger:
77
                raise StackStormDBObjectNotFoundError('Trigger not found for %s', trigger)
78
            return None
79
        else:
80
            trigger_ptr = {
81
                'ref': trigger_db.get_reference().ref,
82
                'type': trigger_db.type,
83
                'parameters': trigger_db.parameters
84
            }
85
86
    trigger_instance = TriggerInstanceDB()
87
    trigger_instance.trigger = trigger_ptr
88
    trigger_instance.payload = payload
89
    trigger_instance.occurrence_time = occurrence_time
90
    trigger_instance.status = TRIGGER_INSTANCE_PENDING
91
    return TriggerInstance.add_or_update(trigger_instance)
92
93
94
def update_trigger_instance_status(trigger_instance, status):
95
    trigger_instance.status = status
96
    return TriggerInstance.add_or_update(trigger_instance)
97