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

BaseParallelSSHRunner._get_env_vars()   A

Complexity

Conditions 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
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 oslo_config import cfg
17
import six
18
19
from st2common.runners.base import ShellRunnerMixin
20
from st2common.runners.base import ActionRunner
21
from st2common.constants.runners import REMOTE_RUNNER_PRIVATE_KEY_HEADER
22
from st2common.runners.parallel_ssh import ParallelSSHClient
23
from st2common import log as logging
24
from st2common.constants.action import LIVEACTION_STATUS_SUCCEEDED
25
from st2common.constants.action import LIVEACTION_STATUS_TIMED_OUT
26
from st2common.constants.action import LIVEACTION_STATUS_FAILED
27
from st2common.constants.runners import REMOTE_RUNNER_DEFAULT_ACTION_TIMEOUT
28
from st2common.exceptions.actionrunner import ActionRunnerPreRunError
29
30
__all__ = [
31
    'BaseParallelSSHRunner'
32
]
33
34
LOG = logging.getLogger(__name__)
35
36
# constants to lookup in runner_parameters.
37
RUNNER_HOSTS = 'hosts'
38
RUNNER_USERNAME = 'username'
39
RUNNER_PASSWORD = 'password'
40
RUNNER_PRIVATE_KEY = 'private_key'
41
RUNNER_PARALLEL = 'parallel'
42
RUNNER_SUDO = 'sudo'
43
RUNNER_ON_BEHALF_USER = 'user'
44
RUNNER_REMOTE_DIR = 'dir'
45
RUNNER_COMMAND = 'cmd'
46
RUNNER_CWD = 'cwd'
47
RUNNER_ENV = 'env'
48
RUNNER_KWARG_OP = 'kwarg_op'
49
RUNNER_TIMEOUT = 'timeout'
50
RUNNER_SSH_PORT = 'port'
51
RUNNER_BASTION_HOST = 'bastion_host'
52
RUNNER_PASSPHRASE = 'passphrase'
53
54
55
class BaseParallelSSHRunner(ActionRunner, ShellRunnerMixin):
56
57
    def __init__(self, runner_id):
58
        super(BaseParallelSSHRunner, self).__init__(runner_id=runner_id)
59
        self._hosts = None
60
        self._parallel = True
61
        self._sudo = False
62
        self._on_behalf_user = None
63
        self._username = None
64
        self._password = None
65
        self._private_key = None
66
        self._passphrase = None
67
        self._kwarg_op = '--'
68
        self._cwd = None
69
        self._env = None
70
        self._ssh_port = None
71
        self._timeout = None
72
        self._bastion_host = None
73
        self._on_behalf_user = cfg.CONF.system_user.user
74
75
        self._ssh_key_file = None
76
        self._parallel_ssh_client = None
77
        self._max_concurrency = cfg.CONF.ssh_runner.max_parallel_actions
78
79
    def pre_run(self):
80
        super(BaseParallelSSHRunner, self).pre_run()
81
82
        LOG.debug('Entering BaseParallelSSHRunner.pre_run() for liveaction_id="%s"',
83
                  self.liveaction_id)
84
        hosts = self.runner_parameters.get(RUNNER_HOSTS, '').split(',')
85
        self._hosts = [h.strip() for h in hosts if len(h) > 0]
86
        if len(self._hosts) < 1:
87
            raise ActionRunnerPreRunError('No hosts specified to run action for action %s.',
88
                                          self.liveaction_id)
89
        self._username = self.runner_parameters.get(RUNNER_USERNAME, None)
90
        self._password = self.runner_parameters.get(RUNNER_PASSWORD, None)
91
        self._private_key = self.runner_parameters.get(RUNNER_PRIVATE_KEY, None)
92
        self._passphrase = self.runner_parameters.get(RUNNER_PASSPHRASE, None)
93
94
        self._ssh_port = self.runner_parameters.get(RUNNER_SSH_PORT, None)
95
        self._ssh_key_file = self._private_key
96
        self._parallel = self.runner_parameters.get(RUNNER_PARALLEL, True)
97
        self._sudo = self.runner_parameters.get(RUNNER_SUDO, False)
98
        self._sudo = self._sudo if self._sudo else False
99
        self._on_behalf_user = self.context.get(RUNNER_ON_BEHALF_USER, self._on_behalf_user)
100
        self._cwd = self.runner_parameters.get(RUNNER_CWD, None)
101
        self._env = self.runner_parameters.get(RUNNER_ENV, {})
102
        self._kwarg_op = self.runner_parameters.get(RUNNER_KWARG_OP, '--')
103
        self._timeout = self.runner_parameters.get(RUNNER_TIMEOUT,
104
                                                   REMOTE_RUNNER_DEFAULT_ACTION_TIMEOUT)
105
        self._bastion_host = self.runner_parameters.get(RUNNER_BASTION_HOST, None)
106
107
        LOG.info('[BaseParallelSSHRunner="%s", liveaction_id="%s"] Finished pre_run.',
108
                 self.runner_id, self.liveaction_id)
109
110
        concurrency = int(len(self._hosts) / 3) + 1 if self._parallel else 1
111
        if concurrency > self._max_concurrency:
112
            LOG.debug('Limiting parallel SSH concurrency to %d.', concurrency)
113
            concurrency = self._max_concurrency
114
115
        client_kwargs = {
116
            'hosts': self._hosts,
117
            'user': self._username,
118
            'port': self._ssh_port,
119
            'concurrency': concurrency,
120
            'bastion_host': self._bastion_host,
121
            'raise_on_any_error': False,
122
            'connect': True
123
        }
124
125
        if self._password:
126
            client_kwargs['password'] = self._password
127
        elif self._private_key:
128
            # Determine if the private_key is a path to the key file or the raw key material
129
            is_key_material = self._is_private_key_material(private_key=self._private_key)
130
131
            if is_key_material:
132
                # Raw key material
133
                client_kwargs['pkey_material'] = self._private_key
134
            else:
135
                # Assume it's a path to the key file, verify the file exists
136
                client_kwargs['pkey_file'] = self._private_key
137
138
            if self._passphrase:
139
                client_kwargs['passphrase'] = self._passphrase
140
        else:
141
            # Default to stanley key file specified in the config
142
            client_kwargs['pkey_file'] = self._ssh_key_file
143
144
        self._parallel_ssh_client = ParallelSSHClient(**client_kwargs)
145
146
    def _is_private_key_material(self, private_key):
147
        return private_key and REMOTE_RUNNER_PRIVATE_KEY_HEADER in private_key.lower()
148
149
    def _get_env_vars(self):
150
        """
151
        :rtype: ``dict``
152
        """
153
        env_vars = {}
154
155
        if self._env:
156
            env_vars.update(self._env)
157
158
        # Include common st2 env vars
159
        st2_env_vars = self._get_common_action_env_variables()
160
        env_vars.update(st2_env_vars)
161
162
        return env_vars
163
164
    @staticmethod
165
    def _get_result_status(result, allow_partial_failure):
166
167
        if 'error' in result and 'traceback' in result:
168
            # Assume this is a global failure where the result dictionary doesn't contain entry
169
            # per host
170
            timeout = False
171
            success = result.get('succeeded', False)
172
            status = BaseParallelSSHRunner._get_status_for_success_and_timeout(success=success,
173
                                                                               timeout=timeout)
174
            return status
175
176
        success = not allow_partial_failure
177
        timeout = True
178
179
        for r in six.itervalues(result):
180
            r_succeess = r.get('succeeded', False) if r else False
181
            r_timeout = r.get('timeout', False) if r else False
182
183
            timeout &= r_timeout
184
185
            if allow_partial_failure:
186
                success |= r_succeess
187
                if success:
188
                    break
189
            else:
190
                success &= r_succeess
191
                if not success:
192
                    break
193
194
        status = BaseParallelSSHRunner._get_status_for_success_and_timeout(success=success,
195
                                                                           timeout=timeout)
196
197
        return status
198
199
    @staticmethod
200
    def _get_status_for_success_and_timeout(success, timeout):
201
        if success:
202
            status = LIVEACTION_STATUS_SUCCEEDED
203
        elif timeout:
204
            # Note: Right now we only set status to timeout if all the hosts have timed out
205
            status = LIVEACTION_STATUS_TIMED_OUT
206
        else:
207
            status = LIVEACTION_STATUS_FAILED
208
        return status
209