koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 1 | import re |
koder aka kdanilov | 3a6633e | 2015-03-26 18:20:00 +0200 | [diff] [blame] | 2 | import time |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 3 | import errno |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 4 | import socket |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 5 | import logging |
| 6 | import os.path |
koder aka kdanilov | 3a6633e | 2015-03-26 18:20:00 +0200 | [diff] [blame] | 7 | import getpass |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 8 | import selectors |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 9 | from io import BytesIO |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 10 | from typing import Union, Optional, cast, Dict, List, Tuple |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 11 | |
koder aka kdanilov | 3a6633e | 2015-03-26 18:20:00 +0200 | [diff] [blame] | 12 | import paramiko |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 13 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 14 | from . import utils |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 15 | |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 16 | |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 17 | logger = logging.getLogger("wally") |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 18 | IPAddr = Tuple[str, int] |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 19 | |
| 20 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 21 | class URIsNamespace: |
| 22 | class ReParts: |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 23 | user_rr = "[^:]*?" |
koder aka kdanilov | 7e0f7cf | 2015-05-01 17:24:35 +0300 | [diff] [blame] | 24 | host_rr = "[^:@]*?" |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 25 | port_rr = "\\d+" |
| 26 | key_file_rr = "[^:@]*" |
| 27 | passwd_rr = ".*?" |
| 28 | |
| 29 | re_dct = ReParts.__dict__ |
| 30 | |
| 31 | for attr_name, val in re_dct.items(): |
| 32 | if attr_name.endswith('_rr'): |
| 33 | new_rr = "(?P<{0}>{1})".format(attr_name[:-3], val) |
| 34 | setattr(ReParts, attr_name, new_rr) |
| 35 | |
| 36 | re_dct = ReParts.__dict__ |
| 37 | |
| 38 | templs = [ |
| 39 | "^{host_rr}$", |
koder aka kdanilov | 7e0f7cf | 2015-05-01 17:24:35 +0300 | [diff] [blame] | 40 | "^{host_rr}:{port_rr}$", |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 41 | "^{host_rr}::{key_file_rr}$", |
| 42 | "^{host_rr}:{port_rr}:{key_file_rr}$", |
koder aka kdanilov | 7e0f7cf | 2015-05-01 17:24:35 +0300 | [diff] [blame] | 43 | "^{user_rr}@{host_rr}$", |
| 44 | "^{user_rr}@{host_rr}:{port_rr}$", |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 45 | "^{user_rr}@{host_rr}::{key_file_rr}$", |
| 46 | "^{user_rr}@{host_rr}:{port_rr}:{key_file_rr}$", |
koder aka kdanilov | 7e0f7cf | 2015-05-01 17:24:35 +0300 | [diff] [blame] | 47 | "^{user_rr}:{passwd_rr}@{host_rr}$", |
| 48 | "^{user_rr}:{passwd_rr}@{host_rr}:{port_rr}$", |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 49 | ] |
| 50 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 51 | uri_reg_exprs = [] # type: List[str] |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 52 | for templ in templs: |
| 53 | uri_reg_exprs.append(templ.format(**re_dct)) |
| 54 | |
| 55 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 56 | class ConnCreds: |
| 57 | conn_uri_attrs = ("user", "passwd", "host", "port", "key_file") |
| 58 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 59 | def __init__(self, host: str, user: str, passwd: str = None, port: int = 22, key_file: str = None) -> None: |
| 60 | self.user = user |
| 61 | self.passwd = passwd |
| 62 | self.host = host |
| 63 | self.port = port |
| 64 | self.key_file = key_file |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 65 | |
| 66 | def __str__(self) -> str: |
| 67 | return str(self.__dict__) |
| 68 | |
| 69 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 70 | def parse_ssh_uri(uri: str) -> ConnCreds: |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 71 | """Parse ssh connection URL from one of following form |
| 72 | [ssh://]user:passwd@host[:port] |
| 73 | [ssh://][user@]host[:port][:key_file] |
| 74 | """ |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 75 | |
koder aka kdanilov | 4d4771c | 2015-04-23 01:32:02 +0300 | [diff] [blame] | 76 | if uri.startswith("ssh://"): |
| 77 | uri = uri[len("ssh://"):] |
| 78 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 79 | res = ConnCreds("", getpass.getuser()) |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 80 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 81 | for rr in URIsNamespace.uri_reg_exprs: |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 82 | rrm = re.match(rr, uri) |
| 83 | if rrm is not None: |
| 84 | res.__dict__.update(rrm.groupdict()) |
| 85 | return res |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 86 | |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 87 | raise ValueError("Can't parse {0!r} as ssh uri value".format(uri)) |
| 88 | |
| 89 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 90 | NODE_KEYS = {} # type: Dict[IPAddr, paramiko.RSAKey] |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 91 | |
| 92 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 93 | def set_key_for_node(host_port: IPAddr, key: bytes) -> None: |
| 94 | with BytesIO(key) as sio: |
| 95 | NODE_KEYS[host_port] = paramiko.RSAKey.from_private_key(sio) |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 96 | |
| 97 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 98 | def ssh_connect(creds: ConnCreds, |
| 99 | conn_timeout: int = 60, |
| 100 | tcp_timeout: int = 15, |
| 101 | default_banner_timeout: int = 30) -> Tuple[paramiko.SSHClient, str, str]: |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 102 | |
| 103 | ssh = paramiko.SSHClient() |
| 104 | ssh.load_host_keys('/dev/null') |
| 105 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
| 106 | ssh.known_hosts = None |
| 107 | |
| 108 | end_time = time.time() + conn_timeout # type: float |
| 109 | |
| 110 | while True: |
| 111 | try: |
| 112 | time_left = end_time - time.time() |
| 113 | c_tcp_timeout = min(tcp_timeout, time_left) |
| 114 | |
| 115 | banner_timeout_arg = {} # type: Dict[str, int] |
| 116 | if paramiko.__version_info__ >= (1, 15, 2): |
| 117 | banner_timeout_arg['banner_timeout'] = int(min(default_banner_timeout, time_left)) |
| 118 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 119 | if creds.passwd is not None: |
| 120 | ssh.connect(creds.host, |
| 121 | timeout=c_tcp_timeout, |
| 122 | username=creds.user, |
| 123 | password=cast(str, creds.passwd), |
| 124 | port=creds.port, |
| 125 | allow_agent=False, |
| 126 | look_for_keys=False, |
| 127 | **banner_timeout_arg) |
| 128 | elif creds.key_file is not None: |
| 129 | ssh.connect(creds.host, |
| 130 | username=creds.user, |
| 131 | timeout=c_tcp_timeout, |
| 132 | key_filename=cast(str, creds.key_file), |
| 133 | look_for_keys=False, |
| 134 | port=creds.port, |
| 135 | **banner_timeout_arg) |
| 136 | elif (creds.host, creds.port) in NODE_KEYS: |
| 137 | ssh.connect(creds.host, |
| 138 | username=creds.user, |
| 139 | timeout=c_tcp_timeout, |
| 140 | pkey=NODE_KEYS[(creds.host, creds.port)], |
| 141 | look_for_keys=False, |
| 142 | port=creds.port, |
| 143 | **banner_timeout_arg) |
| 144 | else: |
| 145 | key_file = os.path.expanduser('~/.ssh/id_rsa') |
| 146 | ssh.connect(creds.host, |
| 147 | username=creds.user, |
| 148 | timeout=c_tcp_timeout, |
| 149 | key_filename=key_file, |
| 150 | look_for_keys=False, |
| 151 | port=creds.port, |
| 152 | **banner_timeout_arg) |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 153 | return ssh, "{0.host}:{0.port}".format(creds), creds.host |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 154 | except paramiko.PasswordRequiredException: |
| 155 | raise |
| 156 | except (socket.error, paramiko.SSHException): |
| 157 | if time.time() > end_time: |
| 158 | raise |
| 159 | time.sleep(1) |
| 160 | |
| 161 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 162 | def wait_ssh_available(addrs: List[IPAddr], |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 163 | timeout: int = 300, |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 164 | tcp_timeout: float = 1.0) -> None: |
| 165 | addrs = set(addrs) |
| 166 | for _ in utils.Timeout(timeout): |
| 167 | with selectors.DefaultSelector() as selector: # type: selectors.BaseSelector |
| 168 | for addr in addrs: |
| 169 | sock = socket.socket() |
| 170 | sock.setblocking(False) |
| 171 | try: |
| 172 | sock.connect(addr) |
| 173 | except BlockingIOError: |
| 174 | pass |
| 175 | selector.register(sock, selectors.EVENT_READ, data=addr) |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 176 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 177 | etime = time.time() + tcp_timeout |
| 178 | ltime = etime - time.time() |
| 179 | while ltime > 0: |
| 180 | for key, _ in selector.select(timeout=ltime): |
| 181 | selector.unregister(key.fileobj) |
| 182 | try: |
| 183 | key.fileobj.getpeername() |
| 184 | addrs.remove(key.data) |
| 185 | except OSError as exc: |
| 186 | if exc.errno == errno.ENOTCONN: |
| 187 | pass |
| 188 | ltime = etime - time.time() |
koder aka kdanilov | 4af1c1d | 2015-05-18 15:48:58 +0300 | [diff] [blame] | 189 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame^] | 190 | if not addrs: |
| 191 | break |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 192 | |
koder aka kdanilov | 0c598a1 | 2015-04-21 03:01:40 +0300 | [diff] [blame] | 193 | |