Passed
Pull Request — master (#3425)
by Anthony
05:11
created

ExecuteActionAliasAction   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 2
Metric Value
dl 0
loc 40
rs 10
c 3
b 0
f 2
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A _wait_execution_to_finish() 0 12 2
A run() 0 20 1
A __init__() 0 5 1
1
import os
2
import time
3
4
from st2common.runners.base_action import Action
5
from st2client.models.action_alias import ActionAliasMatch
6
from st2client.models.aliasexecution import ActionAliasExecution
7
from st2client.commands.action import (LIVEACTION_STATUS_REQUESTED,
8
                                       LIVEACTION_STATUS_SCHEDULED,
9
                                       LIVEACTION_STATUS_RUNNING,
10
                                       LIVEACTION_STATUS_CANCELING)
11
from st2client.client import Client
12
13
14
class ExecuteActionAliasAction(Action):
15
    def __init__(self, config=None):
16
        super(ExecuteActionAliasAction, self).__init__(config=config)
17
        api_url = os.environ.get('ST2_ACTION_API_URL', None)
18
        token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None)
19
        self.client = Client(api_url=api_url, token=token)
20
21
    def run(self, text, source_channel=None, user=None):
22
        alias_match = ActionAliasMatch()
23
        alias_match.command = text
24
        alias, representation = self.client.managers['ActionAlias'].match(
25
            alias_match)
26
27
        execution = ActionAliasExecution()
28
        execution.name = alias.name
29
        execution.format = representation
30
        execution.command = text
31
        execution.source_channel = source_channel  # ?
32
        execution.notification_channel = None
33
        execution.notification_route = None
34
        execution.user = user
35
36
        action_exec_mgr = self.client.managers['ActionAliasExecution']
37
38
        execution = action_exec_mgr.create(execution)
39
        self._wait_execution_to_finish(execution.execution['id'])
40
        return execution.execution['id']
41
42
    def _wait_execution_to_finish(self, execution_id):
43
        pending_statuses = [
44
            LIVEACTION_STATUS_REQUESTED,
45
            LIVEACTION_STATUS_SCHEDULED,
46
            LIVEACTION_STATUS_RUNNING,
47
            LIVEACTION_STATUS_CANCELING
48
        ]
49
        action_exec_mgr = self.client.managers['LiveAction']
50
        execution = action_exec_mgr.get_by_id(execution_id)
51
        while execution.status in pending_statuses:
52
            time.sleep(1)
53
            execution = action_exec_mgr.get_by_id(execution_id)
54