Completed
Push — develop ( 29dcc6...cfb4b4 )
by Plexxi
06:41 queued 03:14
created

BaseAction.run()   B

Complexity

Conditions 5

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 26
rs 8.0894
cc 5
1
#!/usr/bin/env python
2
3
import time
4
5
from oslo_config import cfg
6
7
from st2actions.runners.pythonrunner import Action
8
from st2actions.runners.ssh.paramiko_ssh import ParamikoSSHClient
9
10
11
class BaseAction(Action):
12
    def run(self, hostname, port, username, password=None, keyfile=None, ssh_timeout=5,
13
            sleep_delay=20, retries=10):
14
        # Note: If neither password nor key file is provided, we try to use system user
15
        # key file
16
        if not password and not keyfile:
17
            keyfile = cfg.CONF.system_user.ssh_key_file
18
            self.logger.info('Neither "password" nor "keyfile" parameter provided, '
19
                             'defaulting to using "%s" key file' % (keyfile))
20
21
        client = ParamikoSSHClient(hostname=hostname, port=port, username=username,
22
                                   password=password, key_files=keyfile,
23
                                   timeout=ssh_timeout)
24
25
        for index in range(retries):
26
            attempt = index + 1
27
28
            try:
29
                self.logger.debug('SSH connection attempt: %s' % (attempt))
30
                client.connect()
31
                return True
32
            except Exception as e:
33
                self.logger.info('Attempt %s failed (%s), sleeping for %s seconds...' %
34
                                 (attempt, str(e), sleep_delay))
35
                time.sleep(sleep_delay)
36
37
        raise Exception('Exceeded max retries (%s)' % (retries))
38