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 | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 3 | import socket |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 4 | import logging |
| 5 | import os.path |
koder aka kdanilov | 3a6633e | 2015-03-26 18:20:00 +0200 | [diff] [blame] | 6 | import getpass |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 7 | import threading |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 8 | |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 9 | |
koder aka kdanilov | 3a6633e | 2015-03-26 18:20:00 +0200 | [diff] [blame] | 10 | import paramiko |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 11 | |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 12 | |
| 13 | logger = logging.getLogger("io-perf-tool") |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 14 | |
| 15 | |
koder aka kdanilov | 3a6633e | 2015-03-26 18:20:00 +0200 | [diff] [blame] | 16 | def ssh_connect(creds, retry_count=60, timeout=1): |
| 17 | ssh = paramiko.SSHClient() |
| 18 | ssh.load_host_keys('/dev/null') |
| 19 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
| 20 | ssh.known_hosts = None |
| 21 | for i in range(retry_count): |
| 22 | try: |
| 23 | if creds.user is None: |
| 24 | user = getpass.getuser() |
| 25 | else: |
| 26 | user = creds.user |
| 27 | |
| 28 | if creds.passwd is not None: |
| 29 | ssh.connect(creds.host, |
| 30 | username=user, |
| 31 | password=creds.passwd, |
| 32 | port=creds.port, |
| 33 | allow_agent=False, |
| 34 | look_for_keys=False) |
| 35 | return ssh |
| 36 | |
| 37 | if creds.key_file is not None: |
| 38 | ssh.connect(creds.host, |
| 39 | username=user, |
| 40 | key_filename=creds.key_file, |
| 41 | look_for_keys=False, |
| 42 | port=creds.port) |
| 43 | return ssh |
| 44 | |
| 45 | key_file = os.path.expanduser('~/.ssh/id_rsa') |
| 46 | ssh.connect(creds.host, |
| 47 | username=user, |
| 48 | key_filename=key_file, |
| 49 | look_for_keys=False, |
| 50 | port=creds.port) |
| 51 | return ssh |
| 52 | # raise ValueError("Wrong credentials {0}".format(creds.__dict__)) |
| 53 | except paramiko.PasswordRequiredException: |
| 54 | raise |
| 55 | except socket.error: |
| 56 | if i == retry_count - 1: |
| 57 | raise |
| 58 | time.sleep(timeout) |
| 59 | |
| 60 | |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 61 | def normalize_dirpath(dirpath): |
| 62 | while dirpath.endswith("/"): |
| 63 | dirpath = dirpath[:-1] |
| 64 | return dirpath |
| 65 | |
| 66 | |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 67 | ALL_RWX_MODE = ((1 << 9) - 1) |
| 68 | |
| 69 | |
| 70 | def ssh_mkdir(sftp, remotepath, mode=ALL_RWX_MODE, intermediate=False): |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 71 | remotepath = normalize_dirpath(remotepath) |
| 72 | if intermediate: |
| 73 | try: |
| 74 | sftp.mkdir(remotepath, mode=mode) |
| 75 | except IOError: |
| 76 | ssh_mkdir(sftp, remotepath.rsplit("/", 1)[0], mode=mode, |
| 77 | intermediate=True) |
| 78 | return sftp.mkdir(remotepath, mode=mode) |
| 79 | else: |
| 80 | sftp.mkdir(remotepath, mode=mode) |
| 81 | |
| 82 | |
| 83 | def ssh_copy_file(sftp, localfile, remfile, preserve_perm=True): |
| 84 | sftp.put(localfile, remfile) |
| 85 | if preserve_perm: |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 86 | sftp.chmod(remfile, os.stat(localfile).st_mode & ALL_RWX_MODE) |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 87 | |
| 88 | |
| 89 | def put_dir_recursively(sftp, localpath, remotepath, preserve_perm=True): |
| 90 | "upload local directory to remote recursively" |
| 91 | |
| 92 | # hack for localhost connection |
| 93 | if hasattr(sftp, "copytree"): |
| 94 | sftp.copytree(localpath, remotepath) |
| 95 | return |
| 96 | |
| 97 | assert remotepath.startswith("/"), "%s must be absolute path" % remotepath |
| 98 | |
| 99 | # normalize |
| 100 | localpath = normalize_dirpath(localpath) |
| 101 | remotepath = normalize_dirpath(remotepath) |
| 102 | |
| 103 | try: |
| 104 | sftp.chdir(remotepath) |
| 105 | localsuffix = localpath.rsplit("/", 1)[1] |
| 106 | remotesuffix = remotepath.rsplit("/", 1)[1] |
| 107 | if localsuffix != remotesuffix: |
| 108 | remotepath = os.path.join(remotepath, localsuffix) |
| 109 | except IOError: |
| 110 | pass |
| 111 | |
| 112 | for root, dirs, fls in os.walk(localpath): |
| 113 | prefix = os.path.commonprefix([localpath, root]) |
| 114 | suffix = root.split(prefix, 1)[1] |
| 115 | if suffix.startswith("/"): |
| 116 | suffix = suffix[1:] |
| 117 | |
| 118 | remroot = os.path.join(remotepath, suffix) |
| 119 | |
| 120 | try: |
| 121 | sftp.chdir(remroot) |
| 122 | except IOError: |
| 123 | if preserve_perm: |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 124 | mode = os.stat(root).st_mode & ALL_RWX_MODE |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 125 | else: |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 126 | mode = ALL_RWX_MODE |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 127 | ssh_mkdir(sftp, remroot, mode=mode, intermediate=True) |
| 128 | sftp.chdir(remroot) |
| 129 | |
| 130 | for f in fls: |
| 131 | remfile = os.path.join(remroot, f) |
| 132 | localfile = os.path.join(root, f) |
| 133 | ssh_copy_file(sftp, localfile, remfile, preserve_perm) |
| 134 | |
| 135 | |
koder aka kdanilov | 4500a5f | 2015-04-17 16:55:17 +0300 | [diff] [blame^] | 136 | def delete_file(conn, path): |
| 137 | sftp = conn.open_sftp() |
| 138 | sftp.remove(path) |
| 139 | sftp.close() |
| 140 | |
| 141 | |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 142 | def copy_paths(conn, paths): |
| 143 | sftp = conn.open_sftp() |
| 144 | try: |
| 145 | for src, dst in paths.items(): |
| 146 | try: |
| 147 | if os.path.isfile(src): |
| 148 | ssh_copy_file(sftp, src, dst) |
| 149 | elif os.path.isdir(src): |
| 150 | put_dir_recursively(sftp, src, dst) |
| 151 | else: |
| 152 | templ = "Can't copy {0!r} - " + \ |
| 153 | "it neither a file not a directory" |
| 154 | msg = templ.format(src) |
| 155 | raise OSError(msg) |
| 156 | except Exception as exc: |
| 157 | tmpl = "Scp {0!r} => {1!r} failed - {2!r}" |
| 158 | msg = tmpl.format(src, dst, exc) |
| 159 | raise OSError(msg) |
| 160 | finally: |
| 161 | sftp.close() |
| 162 | |
| 163 | |
| 164 | class ConnCreds(object): |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 165 | conn_uri_attrs = ("user", "passwd", "host", "port", "path") |
| 166 | |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 167 | def __init__(self): |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 168 | for name in self.conn_uri_attrs: |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 169 | setattr(self, name, None) |
| 170 | |
| 171 | |
| 172 | uri_reg_exprs = [] |
| 173 | |
| 174 | |
| 175 | class URIsNamespace(object): |
| 176 | class ReParts(object): |
| 177 | user_rr = "[^:]*?" |
| 178 | host_rr = "[^:]*?" |
| 179 | port_rr = "\\d+" |
| 180 | key_file_rr = "[^:@]*" |
| 181 | passwd_rr = ".*?" |
| 182 | |
| 183 | re_dct = ReParts.__dict__ |
| 184 | |
| 185 | for attr_name, val in re_dct.items(): |
| 186 | if attr_name.endswith('_rr'): |
| 187 | new_rr = "(?P<{0}>{1})".format(attr_name[:-3], val) |
| 188 | setattr(ReParts, attr_name, new_rr) |
| 189 | |
| 190 | re_dct = ReParts.__dict__ |
| 191 | |
| 192 | templs = [ |
| 193 | "^{host_rr}$", |
| 194 | "^{user_rr}@{host_rr}::{key_file_rr}$", |
| 195 | "^{user_rr}@{host_rr}:{port_rr}:{key_file_rr}$", |
| 196 | "^{user_rr}:{passwd_rr}@@{host_rr}$", |
| 197 | "^{user_rr}:{passwd_rr}@@{host_rr}:{port_rr}$", |
| 198 | ] |
| 199 | |
| 200 | for templ in templs: |
| 201 | uri_reg_exprs.append(templ.format(**re_dct)) |
| 202 | |
| 203 | |
| 204 | def parse_ssh_uri(uri): |
| 205 | # user:passwd@@ip_host:port |
| 206 | # user:passwd@@ip_host |
| 207 | # user@ip_host:port |
| 208 | # user@ip_host |
| 209 | # ip_host:port |
| 210 | # ip_host |
| 211 | # user@ip_host:port:path_to_key_file |
| 212 | # user@ip_host::path_to_key_file |
| 213 | # ip_host:port:path_to_key_file |
| 214 | # ip_host::path_to_key_file |
| 215 | |
| 216 | res = ConnCreds() |
| 217 | res.port = "22" |
| 218 | res.key_file = None |
| 219 | res.passwd = None |
| 220 | |
| 221 | for rr in uri_reg_exprs: |
| 222 | rrm = re.match(rr, uri) |
| 223 | if rrm is not None: |
| 224 | res.__dict__.update(rrm.groupdict()) |
| 225 | return res |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 226 | |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 227 | raise ValueError("Can't parse {0!r} as ssh uri value".format(uri)) |
| 228 | |
| 229 | |
| 230 | def connect(uri): |
| 231 | creds = parse_ssh_uri(uri) |
| 232 | creds.port = int(creds.port) |
| 233 | return ssh_connect(creds) |
| 234 | |
| 235 | |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 236 | all_sessions_lock = threading.Lock() |
| 237 | all_sessions = [] |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 238 | |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 239 | |
koder aka kdanilov | 4500a5f | 2015-04-17 16:55:17 +0300 | [diff] [blame^] | 240 | def run_over_ssh(conn, cmd, stdin_data=None, timeout=60, nolog=False, node=None): |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 241 | "should be replaces by normal implementation, with select" |
| 242 | transport = conn.get_transport() |
| 243 | session = transport.open_session() |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 244 | |
koder aka kdanilov | 4500a5f | 2015-04-17 16:55:17 +0300 | [diff] [blame^] | 245 | if node is None: |
| 246 | node = "" |
| 247 | |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 248 | with all_sessions_lock: |
| 249 | all_sessions.append(session) |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 250 | |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 251 | try: |
| 252 | session.set_combine_stderr(True) |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 253 | |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 254 | stime = time.time() |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 255 | |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 256 | if not nolog: |
koder aka kdanilov | 4500a5f | 2015-04-17 16:55:17 +0300 | [diff] [blame^] | 257 | logger.debug("SSH:{0} Exec {1!r}".format(node, cmd)) |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 258 | |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 259 | session.exec_command(cmd) |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 260 | |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 261 | if stdin_data is not None: |
| 262 | session.sendall(stdin_data) |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 263 | |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 264 | session.settimeout(1) |
| 265 | session.shutdown_write() |
| 266 | output = "" |
| 267 | |
| 268 | while True: |
| 269 | try: |
| 270 | ndata = session.recv(1024) |
| 271 | output += ndata |
| 272 | if "" == ndata: |
| 273 | break |
| 274 | except socket.timeout: |
| 275 | pass |
| 276 | |
| 277 | if time.time() - stime > timeout: |
| 278 | raise OSError(output + "\nExecution timeout") |
| 279 | |
| 280 | code = session.recv_exit_status() |
| 281 | finally: |
| 282 | session.close() |
| 283 | |
| 284 | if code != 0: |
koder aka kdanilov | 4500a5f | 2015-04-17 16:55:17 +0300 | [diff] [blame^] | 285 | templ = "SSH:{0} Cmd {1!r} failed with code {2}. Output: {3}" |
| 286 | raise OSError(templ.format(node, cmd, code, output)) |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 287 | |
| 288 | return output |
| 289 | |
| 290 | |
| 291 | def close_all_sessions(): |
| 292 | with all_sessions_lock: |
| 293 | for session in all_sessions: |
| 294 | try: |
| 295 | session.sendall('\x03') |
| 296 | session.close() |
| 297 | except: |
| 298 | pass |