blob: 6bba020d4613a24e71547f871306d54e6d7d4ced [file] [log] [blame]
koder aka kdanilov73084622016-11-16 21:51:08 +02001import time
2import errno
3import socket
4import logging
5import os.path
6import selectors
koder aka kdanilov962ee5f2016-12-19 02:40:08 +02007from io import StringIO
8from typing import cast, Dict, List, Set, Optional
koder aka kdanilov73084622016-11-16 21:51:08 +02009
10import paramiko
11
12from . import utils
13from .ssh_utils import ConnCreds, IPAddr
14
15logger = logging.getLogger("wally")
16NODE_KEYS = {} # type: Dict[IPAddr, paramiko.RSAKey]
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020017SSH_KEY_PASSWD = None # type: Optional[str]
18
19
20def set_ssh_key_passwd(passwd: str) -> None:
21 global SSH_KEY_PASSWD
22 SSH_KEY_PASSWD = passwd
koder aka kdanilov73084622016-11-16 21:51:08 +020023
24
25def set_key_for_node(host_port: IPAddr, key: bytes) -> None:
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020026 with StringIO(key.decode("utf8")) as sio:
koder aka kdanilov23e6bdf2016-12-24 02:18:54 +020027 NODE_KEYS[host_port] = paramiko.RSAKey.from_private_key(sio) # type: ignore
koder aka kdanilov73084622016-11-16 21:51:08 +020028
29
30def connect(creds: ConnCreds,
31 conn_timeout: int = 60,
32 tcp_timeout: int = 15,
33 default_banner_timeout: int = 30) -> paramiko.SSHClient:
34
35 ssh = paramiko.SSHClient()
36 ssh.load_host_keys('/dev/null')
37 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
38 ssh.known_hosts = None
39
40 end_time = time.time() + conn_timeout # type: float
41
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020042 logger.debug("SSH connecting to %s", creds)
43
koder aka kdanilov73084622016-11-16 21:51:08 +020044 while True:
45 try:
46 time_left = end_time - time.time()
47 c_tcp_timeout = min(tcp_timeout, time_left)
48
49 banner_timeout_arg = {} # type: Dict[str, int]
50 if paramiko.__version_info__ >= (1, 15, 2):
51 banner_timeout_arg['banner_timeout'] = int(min(default_banner_timeout, time_left))
52
53 if creds.passwd is not None:
54 ssh.connect(creds.addr.host,
55 timeout=c_tcp_timeout,
56 username=creds.user,
57 password=cast(str, creds.passwd),
58 port=creds.addr.port,
59 allow_agent=False,
60 look_for_keys=False,
61 **banner_timeout_arg)
62 elif creds.key_file is not None:
63 ssh.connect(creds.addr.host,
64 username=creds.user,
65 timeout=c_tcp_timeout,
koder aka kdanilov23e6bdf2016-12-24 02:18:54 +020066 pkey=paramiko.RSAKey.from_private_key_file(creds.key_file, password=SSH_KEY_PASSWD),
koder aka kdanilov73084622016-11-16 21:51:08 +020067 look_for_keys=False,
68 port=creds.addr.port,
69 **banner_timeout_arg)
70 elif creds.key is not None:
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020071 with StringIO(creds.key.decode("utf8")) as sio:
koder aka kdanilov73084622016-11-16 21:51:08 +020072 ssh.connect(creds.addr.host,
73 username=creds.user,
74 timeout=c_tcp_timeout,
koder aka kdanilov23e6bdf2016-12-24 02:18:54 +020075 pkey=paramiko.RSAKey.from_private_key(sio, password=SSH_KEY_PASSWD), # type: ignore
koder aka kdanilov73084622016-11-16 21:51:08 +020076 look_for_keys=False,
77 port=creds.addr.port,
78 **banner_timeout_arg)
79 elif (creds.addr.host, creds.addr.port) in NODE_KEYS:
80 ssh.connect(creds.addr.host,
81 username=creds.user,
82 timeout=c_tcp_timeout,
83 pkey=NODE_KEYS[creds.addr],
84 look_for_keys=False,
85 port=creds.addr.port,
86 **banner_timeout_arg)
87 else:
88 key_file = os.path.expanduser('~/.ssh/id_rsa')
89 ssh.connect(creds.addr.host,
90 username=creds.user,
91 timeout=c_tcp_timeout,
92 key_filename=key_file,
93 look_for_keys=False,
94 port=creds.addr.port,
95 **banner_timeout_arg)
96 return ssh
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020097 except (socket.gaierror, paramiko.PasswordRequiredException):
koder aka kdanilov73084622016-11-16 21:51:08 +020098 raise
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020099 except socket.error:
koder aka kdanilov73084622016-11-16 21:51:08 +0200100 if time.time() > end_time:
101 raise
102 time.sleep(1)
103
104
105def wait_ssh_available(addrs: List[IPAddr],
106 timeout: int = 300,
107 tcp_timeout: float = 1.0) -> None:
108
109 addrs_set = set(addrs) # type: Set[IPAddr]
110
111 for _ in utils.Timeout(timeout):
112 selector = selectors.DefaultSelector() # type: selectors.BaseSelector
113 with selector:
114 for addr in addrs_set:
115 sock = socket.socket()
116 sock.setblocking(False)
117 try:
118 sock.connect(addr)
119 except BlockingIOError:
120 pass
121 selector.register(sock, selectors.EVENT_READ, data=addr)
122
123 etime = time.time() + tcp_timeout
124 ltime = etime - time.time()
125 while ltime > 0:
126 # convert to greater or equal integer
127 for key, _ in selector.select(timeout=int(ltime + 0.99999)):
128 selector.unregister(key.fileobj)
129 try:
130 key.fileobj.getpeername() # type: ignore
131 addrs_set.remove(key.data)
132 except OSError as exc:
133 if exc.errno == errno.ENOTCONN:
134 pass
135 ltime = etime - time.time()
136
137 if not addrs_set:
138 break
139
140