blob: ddf3e58100f5de977734cf2098399517afc47ccd [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
kdanylov aka koderb0833332017-05-13 20:39:17 +030012from cephlib.common import Timeout
13
koder aka kdanilovf2865172016-12-30 03:35:11 +020014from .common_types import ConnCreds, IPAddr
koder aka kdanilov73084622016-11-16 21:51:08 +020015
16logger = logging.getLogger("wally")
17NODE_KEYS = {} # type: Dict[IPAddr, paramiko.RSAKey]
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020018SSH_KEY_PASSWD = None # type: Optional[str]
19
20
21def set_ssh_key_passwd(passwd: str) -> None:
22 global SSH_KEY_PASSWD
23 SSH_KEY_PASSWD = passwd
koder aka kdanilov73084622016-11-16 21:51:08 +020024
25
26def set_key_for_node(host_port: IPAddr, key: bytes) -> None:
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020027 with StringIO(key.decode("utf8")) as sio:
koder aka kdanilov23e6bdf2016-12-24 02:18:54 +020028 NODE_KEYS[host_port] = paramiko.RSAKey.from_private_key(sio) # type: ignore
koder aka kdanilov73084622016-11-16 21:51:08 +020029
30
31def connect(creds: ConnCreds,
32 conn_timeout: int = 60,
33 tcp_timeout: int = 15,
34 default_banner_timeout: int = 30) -> paramiko.SSHClient:
35
36 ssh = paramiko.SSHClient()
37 ssh.load_host_keys('/dev/null')
38 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
39 ssh.known_hosts = None
40
41 end_time = time.time() + conn_timeout # type: float
42
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020043 logger.debug("SSH connecting to %s", creds)
44
koder aka kdanilov73084622016-11-16 21:51:08 +020045 while True:
46 try:
47 time_left = end_time - time.time()
48 c_tcp_timeout = min(tcp_timeout, time_left)
49
50 banner_timeout_arg = {} # type: Dict[str, int]
51 if paramiko.__version_info__ >= (1, 15, 2):
52 banner_timeout_arg['banner_timeout'] = int(min(default_banner_timeout, time_left))
53
54 if creds.passwd is not None:
55 ssh.connect(creds.addr.host,
56 timeout=c_tcp_timeout,
57 username=creds.user,
58 password=cast(str, creds.passwd),
59 port=creds.addr.port,
60 allow_agent=False,
61 look_for_keys=False,
62 **banner_timeout_arg)
63 elif creds.key_file is not None:
64 ssh.connect(creds.addr.host,
65 username=creds.user,
66 timeout=c_tcp_timeout,
koder aka kdanilov23e6bdf2016-12-24 02:18:54 +020067 pkey=paramiko.RSAKey.from_private_key_file(creds.key_file, password=SSH_KEY_PASSWD),
koder aka kdanilov73084622016-11-16 21:51:08 +020068 look_for_keys=False,
69 port=creds.addr.port,
70 **banner_timeout_arg)
71 elif creds.key is not None:
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020072 with StringIO(creds.key.decode("utf8")) as sio:
koder aka kdanilov73084622016-11-16 21:51:08 +020073 ssh.connect(creds.addr.host,
74 username=creds.user,
75 timeout=c_tcp_timeout,
koder aka kdanilov23e6bdf2016-12-24 02:18:54 +020076 pkey=paramiko.RSAKey.from_private_key(sio, password=SSH_KEY_PASSWD), # type: ignore
koder aka kdanilov73084622016-11-16 21:51:08 +020077 look_for_keys=False,
78 port=creds.addr.port,
79 **banner_timeout_arg)
80 elif (creds.addr.host, creds.addr.port) in NODE_KEYS:
81 ssh.connect(creds.addr.host,
82 username=creds.user,
83 timeout=c_tcp_timeout,
84 pkey=NODE_KEYS[creds.addr],
85 look_for_keys=False,
86 port=creds.addr.port,
87 **banner_timeout_arg)
88 else:
89 key_file = os.path.expanduser('~/.ssh/id_rsa')
90 ssh.connect(creds.addr.host,
91 username=creds.user,
92 timeout=c_tcp_timeout,
93 key_filename=key_file,
94 look_for_keys=False,
95 port=creds.addr.port,
96 **banner_timeout_arg)
97 return ssh
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020098 except (socket.gaierror, paramiko.PasswordRequiredException):
koder aka kdanilov73084622016-11-16 21:51:08 +020099 raise
koder aka kdanilov962ee5f2016-12-19 02:40:08 +0200100 except socket.error:
koder aka kdanilov73084622016-11-16 21:51:08 +0200101 if time.time() > end_time:
102 raise
103 time.sleep(1)
104
105
106def wait_ssh_available(addrs: List[IPAddr],
107 timeout: int = 300,
108 tcp_timeout: float = 1.0) -> None:
109
110 addrs_set = set(addrs) # type: Set[IPAddr]
111
kdanylov aka koderb0833332017-05-13 20:39:17 +0300112 for _ in Timeout(timeout):
koder aka kdanilov73084622016-11-16 21:51:08 +0200113 selector = selectors.DefaultSelector() # type: selectors.BaseSelector
114 with selector:
115 for addr in addrs_set:
116 sock = socket.socket()
117 sock.setblocking(False)
118 try:
119 sock.connect(addr)
120 except BlockingIOError:
121 pass
122 selector.register(sock, selectors.EVENT_READ, data=addr)
123
124 etime = time.time() + tcp_timeout
125 ltime = etime - time.time()
126 while ltime > 0:
127 # convert to greater or equal integer
128 for key, _ in selector.select(timeout=int(ltime + 0.99999)):
129 selector.unregister(key.fileobj)
130 try:
131 key.fileobj.getpeername() # type: ignore
132 addrs_set.remove(key.data)
133 except OSError as exc:
134 if exc.errno == errno.ENOTCONN:
135 pass
136 ltime = etime - time.time()
137
138 if not addrs_set:
139 break
140
141