koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 1 | import re |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 2 | import os |
koder aka kdanilov | 4af1c1d | 2015-05-18 15:48:58 +0300 | [diff] [blame] | 3 | import sys |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 4 | import time |
| 5 | import uuid |
koder aka kdanilov | afd9874 | 2015-04-24 01:27:22 +0300 | [diff] [blame] | 6 | import socket |
koder aka kdanilov | e21d747 | 2015-02-14 19:02:04 -0800 | [diff] [blame] | 7 | import logging |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 8 | import ipaddress |
koder aka kdanilov | 7acd6bd | 2015-02-12 14:28:30 -0800 | [diff] [blame] | 9 | import threading |
| 10 | import contextlib |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 11 | import subprocess |
koder aka kdanilov | 6ab4d43 | 2015-06-22 00:26:28 +0300 | [diff] [blame] | 12 | import collections |
koder aka kdanilov | 4643fd6 | 2015-02-10 16:20:13 -0800 | [diff] [blame] | 13 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame] | 14 | from .node_interfaces import IRPCNode |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 15 | from typing import (Any, Tuple, Union, List, Iterator, Dict, Callable, Iterable, Optional, |
| 16 | IO, Sequence, NamedTuple, cast) |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 17 | |
koder aka kdanilov | bb5fe07 | 2015-05-21 02:50:23 +0300 | [diff] [blame] | 18 | try: |
| 19 | import psutil |
| 20 | except ImportError: |
| 21 | psutil = None |
| 22 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 23 | try: |
| 24 | from petname import Generate as pet_generate |
| 25 | except ImportError: |
| 26 | def pet_generate(x: str, y: str) -> str: |
| 27 | return str(uuid.uuid4()) |
| 28 | |
koder aka kdanilov | e21d747 | 2015-02-14 19:02:04 -0800 | [diff] [blame] | 29 | |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 30 | logger = logging.getLogger("wally") |
koder aka kdanilov | 7acd6bd | 2015-02-12 14:28:30 -0800 | [diff] [blame] | 31 | |
| 32 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 33 | def is_ip(data: str) -> bool: |
koder aka kdanilov | 209e85d | 2015-04-27 23:11:05 +0300 | [diff] [blame] | 34 | try: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 35 | ipaddress.ip_address(data) |
| 36 | return True |
koder aka kdanilov | 209e85d | 2015-04-27 23:11:05 +0300 | [diff] [blame] | 37 | except ValueError: |
| 38 | return False |
koder aka kdanilov | 209e85d | 2015-04-27 23:11:05 +0300 | [diff] [blame] | 39 | |
| 40 | |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 41 | class StopTestError(RuntimeError): |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 42 | pass |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 43 | |
| 44 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 45 | class LogError: |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 46 | def __init__(self, message: str, exc_logger: logging.Logger = None) -> None: |
koder aka kdanilov | 4af1c1d | 2015-05-18 15:48:58 +0300 | [diff] [blame] | 47 | self.message = message |
| 48 | self.exc_logger = exc_logger |
| 49 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 50 | def __enter__(self) -> 'LogError': |
koder aka kdanilov | 4af1c1d | 2015-05-18 15:48:58 +0300 | [diff] [blame] | 51 | return self |
| 52 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 53 | def __exit__(self, tp: type, value: Exception, traceback: Any) -> bool: |
koder aka kdanilov | 4af1c1d | 2015-05-18 15:48:58 +0300 | [diff] [blame] | 54 | if value is None or isinstance(value, StopTestError): |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 55 | return False |
koder aka kdanilov | 4af1c1d | 2015-05-18 15:48:58 +0300 | [diff] [blame] | 56 | |
| 57 | if self.exc_logger is None: |
| 58 | exc_logger = sys._getframe(1).f_globals.get('logger', logger) |
| 59 | else: |
| 60 | exc_logger = self.exc_logger |
| 61 | |
| 62 | exc_logger.exception(self.message, exc_info=(tp, value, traceback)) |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 63 | raise StopTestError(self.message) from value |
koder aka kdanilov | 4af1c1d | 2015-05-18 15:48:58 +0300 | [diff] [blame] | 64 | |
| 65 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 66 | def log_block(message: str, exc_logger:logging.Logger = None) -> LogError: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 67 | logger.debug("Starts : " + message) |
| 68 | return LogError(message, exc_logger) |
| 69 | |
| 70 | |
| 71 | def check_input_param(is_ok: bool, message: str) -> None: |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 72 | if not is_ok: |
| 73 | logger.error(message) |
| 74 | raise StopTestError(message) |
| 75 | |
| 76 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 77 | def parse_creds(creds: str) -> Tuple[str, str, str]: |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 78 | """Parse simple credentials format user[:passwd]@host""" |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 79 | user, passwd_host = creds.split(":", 1) |
| 80 | |
| 81 | if '@' not in passwd_host: |
| 82 | passwd, host = passwd_host, None |
| 83 | else: |
| 84 | passwd, host = passwd_host.rsplit('@', 1) |
| 85 | |
| 86 | return user, passwd, host |
| 87 | |
| 88 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 89 | class TaskFinished(Exception): |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 90 | pass |
koder aka kdanilov | 4643fd6 | 2015-02-10 16:20:13 -0800 | [diff] [blame] | 91 | |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 92 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 93 | class Barrier: |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 94 | def __init__(self, count: int) -> None: |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 95 | self.count = count |
| 96 | self.curr_count = 0 |
| 97 | self.cond = threading.Condition() |
| 98 | self.exited = False |
| 99 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 100 | def wait(self, timeout: int=None) -> bool: |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 101 | with self.cond: |
| 102 | if self.exited: |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 103 | raise TaskFinished() |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 104 | |
| 105 | self.curr_count += 1 |
| 106 | if self.curr_count == self.count: |
| 107 | self.curr_count = 0 |
| 108 | self.cond.notify_all() |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 109 | return True |
koder aka kdanilov | 4643fd6 | 2015-02-10 16:20:13 -0800 | [diff] [blame] | 110 | else: |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 111 | self.cond.wait(timeout=timeout) |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 112 | return False |
koder aka kdanilov | 4643fd6 | 2015-02-10 16:20:13 -0800 | [diff] [blame] | 113 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 114 | def exit(self) -> None: |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 115 | with self.cond: |
| 116 | self.exited = True |
koder aka kdanilov | 7acd6bd | 2015-02-12 14:28:30 -0800 | [diff] [blame] | 117 | |
| 118 | |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 119 | SMAP = dict(k=1024, m=1024 ** 2, g=1024 ** 3, t=1024 ** 4) |
koder aka kdanilov | 8ad6e81 | 2015-03-22 14:42:18 +0200 | [diff] [blame] | 120 | |
| 121 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 122 | def ssize2b(ssize: Union[str, int]) -> int: |
koder aka kdanilov | 8ad6e81 | 2015-03-22 14:42:18 +0200 | [diff] [blame] | 123 | try: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 124 | if isinstance(ssize, int): |
koder aka kdanilov | 63e9c5a | 2015-04-28 23:06:07 +0300 | [diff] [blame] | 125 | return ssize |
koder aka kdanilov | 8ad6e81 | 2015-03-22 14:42:18 +0200 | [diff] [blame] | 126 | |
koder aka kdanilov | 63e9c5a | 2015-04-28 23:06:07 +0300 | [diff] [blame] | 127 | ssize = ssize.lower() |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 128 | if ssize[-1] in SMAP: |
| 129 | return int(ssize[:-1]) * SMAP[ssize[-1]] |
koder aka kdanilov | 8ad6e81 | 2015-03-22 14:42:18 +0200 | [diff] [blame] | 130 | return int(ssize) |
| 131 | except (ValueError, TypeError, AttributeError): |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 132 | raise ValueError("Unknow size format {!r}".format(ssize)) |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 133 | |
| 134 | |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 135 | RSMAP = [('K', 1024), |
| 136 | ('M', 1024 ** 2), |
| 137 | ('G', 1024 ** 3), |
| 138 | ('T', 1024 ** 4)] |
| 139 | |
| 140 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 141 | def b2ssize(size: int) -> str: |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 142 | if size < 1024: |
| 143 | return str(size) |
| 144 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 145 | # make mypy happy |
| 146 | scale = 1 |
| 147 | name = "" |
| 148 | |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 149 | for name, scale in RSMAP: |
| 150 | if size < 1024 * scale: |
| 151 | if size % scale == 0: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 152 | return "{} {}i".format(size // scale, name) |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 153 | else: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 154 | return "{:.1f} {}i".format(float(size) / scale, name) |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 155 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 156 | return "{}{}i".format(size // scale, name) |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 157 | |
| 158 | |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 159 | RSMAP_10 = [('k', 1000), |
| 160 | ('m', 1000 ** 2), |
| 161 | ('g', 1000 ** 3), |
| 162 | ('t', 1000 ** 4)] |
| 163 | |
| 164 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 165 | def b2ssize_10(size: int) -> str: |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 166 | if size < 1000: |
| 167 | return str(size) |
| 168 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 169 | # make mypy happy |
| 170 | scale = 1 |
| 171 | name = "" |
| 172 | |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 173 | for name, scale in RSMAP_10: |
| 174 | if size < 1000 * scale: |
| 175 | if size % scale == 0: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 176 | return "{} {}".format(size // scale, name) |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 177 | else: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 178 | return "{:.1f} {}".format(float(size) / scale, name) |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 179 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 180 | return "{}{}".format(size // scale, name) |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 181 | |
| 182 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 183 | def run_locally(cmd: Union[str, List[str]], input_data: str="", timeout:int =20) -> str: |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 184 | if isinstance(cmd, str): |
| 185 | shell = True |
| 186 | cmd_str = cmd |
| 187 | else: |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 188 | shell = False |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 189 | cmd_str = " ".join(cmd) |
| 190 | |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 191 | proc = subprocess.Popen(cmd, |
| 192 | shell=shell, |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 193 | stdin=subprocess.PIPE, |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 194 | stdout=subprocess.PIPE, |
| 195 | stderr=subprocess.PIPE) |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 196 | res = [] # type: List[Tuple[bytes, bytes]] |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 197 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 198 | def thread_func() -> None: |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 199 | rr = proc.communicate(input_data.encode("utf8")) |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 200 | res.extend(rr) |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 201 | |
koder aka kdanilov | fd2cfa5 | 2015-05-20 03:17:42 +0300 | [diff] [blame] | 202 | thread = threading.Thread(target=thread_func, |
| 203 | name="Local cmd execution") |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 204 | thread.daemon = True |
| 205 | thread.start() |
| 206 | thread.join(timeout) |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 207 | |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 208 | if thread.is_alive(): |
koder aka kdanilov | bb5fe07 | 2015-05-21 02:50:23 +0300 | [diff] [blame] | 209 | if psutil is not None: |
| 210 | parent = psutil.Process(proc.pid) |
| 211 | for child in parent.children(recursive=True): |
| 212 | child.kill() |
| 213 | parent.kill() |
| 214 | else: |
| 215 | proc.kill() |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 216 | |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 217 | thread.join() |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 218 | raise RuntimeError("Local process timeout: " + cmd_str) |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 219 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 220 | stdout_data, stderr_data = zip(*res) # type: List[bytes], List[bytes] |
| 221 | |
| 222 | out = b"".join(stdout_data).decode("utf8") |
| 223 | err = b"".join(stderr_data).decode("utf8") |
| 224 | |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 225 | if 0 != proc.returncode: |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 226 | raise subprocess.CalledProcessError(proc.returncode, |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 227 | cmd_str, out + err) |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 228 | |
| 229 | return out |
| 230 | |
| 231 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 232 | def get_ip_for_target(target_ip: str) -> str: |
koder aka kdanilov | 209e85d | 2015-04-27 23:11:05 +0300 | [diff] [blame] | 233 | if not is_ip(target_ip): |
koder aka kdanilov | afd9874 | 2015-04-24 01:27:22 +0300 | [diff] [blame] | 234 | target_ip = socket.gethostbyname(target_ip) |
| 235 | |
koder aka kdanilov | 209e85d | 2015-04-27 23:11:05 +0300 | [diff] [blame] | 236 | first_dig = map(int, target_ip.split(".")) |
| 237 | if first_dig == 127: |
koder aka kdanilov | afd9874 | 2015-04-24 01:27:22 +0300 | [diff] [blame] | 238 | return '127.0.0.1' |
| 239 | |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 240 | data = run_locally('ip route get to'.split(" ") + [target_ip]) |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 241 | |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 242 | rr1 = r'{0} via [.0-9]+ dev (?P<dev>.*?) src (?P<ip>[.0-9]+)$' |
| 243 | rr1 = rr1.replace(" ", r'\s+') |
| 244 | rr1 = rr1.format(target_ip.replace('.', r'\.')) |
| 245 | |
| 246 | rr2 = r'{0} dev (?P<dev>.*?) src (?P<ip>[.0-9]+)$' |
| 247 | rr2 = rr2.replace(" ", r'\s+') |
| 248 | rr2 = rr2.format(target_ip.replace('.', r'\.')) |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 249 | |
| 250 | data_line = data.split("\n")[0].strip() |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 251 | res1 = re.match(rr1, data_line) |
| 252 | res2 = re.match(rr2, data_line) |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 253 | |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 254 | if res1 is not None: |
| 255 | return res1.group('ip') |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 256 | |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 257 | if res2 is not None: |
| 258 | return res2.group('ip') |
| 259 | |
| 260 | raise OSError("Can't define interface for {0}".format(target_ip)) |
| 261 | |
| 262 | |
koder aka kdanilov | 39e449e | 2016-12-17 15:15:26 +0200 | [diff] [blame^] | 263 | def open_for_append_or_create(fname: str) -> IO[str]: |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 264 | if not os.path.exists(fname): |
| 265 | return open(fname, "w") |
| 266 | |
| 267 | fd = open(fname, 'r+') |
| 268 | fd.seek(0, os.SEEK_END) |
| 269 | return fd |
| 270 | |
| 271 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 272 | def sec_to_str(seconds: int) -> str: |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 273 | h = seconds // 3600 |
| 274 | m = (seconds % 3600) // 60 |
| 275 | s = seconds % 60 |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 276 | return "{}:{:02d}:{:02d}".format(h, m, s) |
koder aka kdanilov | 168f609 | 2015-04-19 02:33:38 +0300 | [diff] [blame] | 277 | |
| 278 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 279 | def yamable(data: Any) -> Any: |
koder aka kdanilov | 168f609 | 2015-04-19 02:33:38 +0300 | [diff] [blame] | 280 | if isinstance(data, (tuple, list)): |
| 281 | return map(yamable, data) |
| 282 | |
koder aka kdanilov | 168f609 | 2015-04-19 02:33:38 +0300 | [diff] [blame] | 283 | if isinstance(data, dict): |
| 284 | res = {} |
| 285 | for k, v in data.items(): |
| 286 | res[yamable(k)] = yamable(v) |
| 287 | return res |
| 288 | |
| 289 | return data |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 290 | |
| 291 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 292 | def flatten(data: Iterable[Any]) -> List[Any]: |
koder aka kdanilov | 4af1c1d | 2015-05-18 15:48:58 +0300 | [diff] [blame] | 293 | res = [] |
| 294 | for i in data: |
| 295 | if isinstance(i, (list, tuple, set)): |
| 296 | res.extend(flatten(i)) |
| 297 | else: |
| 298 | res.append(i) |
| 299 | return res |
koder aka kdanilov | 89fb610 | 2015-06-13 02:58:08 +0300 | [diff] [blame] | 300 | |
| 301 | |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 302 | def get_creds_openrc(path: str) -> Tuple[str, str, str, str, bool]: |
koder aka kdanilov | 89fb610 | 2015-06-13 02:58:08 +0300 | [diff] [blame] | 303 | fc = open(path).read() |
| 304 | |
koder aka kdanilov | b719743 | 2015-07-15 00:40:43 +0300 | [diff] [blame] | 305 | echo = 'echo "$OS_INSECURE:$OS_TENANT_NAME:$OS_USERNAME:$OS_PASSWORD@$OS_AUTH_URL"' |
koder aka kdanilov | 89fb610 | 2015-06-13 02:58:08 +0300 | [diff] [blame] | 306 | |
| 307 | msg = "Failed to get creads from openrc file" |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 308 | with LogError(msg): |
koder aka kdanilov | 89fb610 | 2015-06-13 02:58:08 +0300 | [diff] [blame] | 309 | data = run_locally(['/bin/bash'], input_data=fc + "\n" + echo) |
| 310 | |
| 311 | msg = "Failed to get creads from openrc file: " + data |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 312 | with LogError(msg): |
koder aka kdanilov | 89fb610 | 2015-06-13 02:58:08 +0300 | [diff] [blame] | 313 | data = data.strip() |
koder aka kdanilov | b719743 | 2015-07-15 00:40:43 +0300 | [diff] [blame] | 314 | insecure_str, user, tenant, passwd_auth_url = data.split(':', 3) |
| 315 | insecure = (insecure_str in ('1', 'True', 'true')) |
koder aka kdanilov | 89fb610 | 2015-06-13 02:58:08 +0300 | [diff] [blame] | 316 | passwd, auth_url = passwd_auth_url.rsplit("@", 1) |
| 317 | assert (auth_url.startswith("https://") or |
| 318 | auth_url.startswith("http://")) |
| 319 | |
koder aka kdanilov | b719743 | 2015-07-15 00:40:43 +0300 | [diff] [blame] | 320 | return user, passwd, tenant, auth_url, insecure |
koder aka kdanilov | 89fb610 | 2015-06-13 02:58:08 +0300 | [diff] [blame] | 321 | |
| 322 | |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 323 | OSRelease = NamedTuple("OSRelease", |
| 324 | [("distro", str), |
| 325 | ("release", str), |
| 326 | ("arch", str)]) |
koder aka kdanilov | 6ab4d43 | 2015-06-22 00:26:28 +0300 | [diff] [blame] | 327 | |
| 328 | |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 329 | def get_os(node: IRPCNode) -> OSRelease: |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 330 | """return os type, release and architecture for node. |
| 331 | """ |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 332 | arch = node.run("arch", nolog=True).strip() |
koder aka kdanilov | 6ab4d43 | 2015-06-22 00:26:28 +0300 | [diff] [blame] | 333 | |
koder aka kdanilov | 89fb610 | 2015-06-13 02:58:08 +0300 | [diff] [blame] | 334 | try: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 335 | node.run("ls -l /etc/redhat-release", nolog=True) |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 336 | return OSRelease('redhat', None, arch) |
koder aka kdanilov | 89fb610 | 2015-06-13 02:58:08 +0300 | [diff] [blame] | 337 | except: |
| 338 | pass |
| 339 | |
| 340 | try: |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 341 | node.run("ls -l /etc/debian_version", nolog=True) |
koder aka kdanilov | 6ab4d43 | 2015-06-22 00:26:28 +0300 | [diff] [blame] | 342 | |
| 343 | release = None |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 344 | for line in node.run("lsb_release -a", nolog=True).split("\n"): |
koder aka kdanilov | 6ab4d43 | 2015-06-22 00:26:28 +0300 | [diff] [blame] | 345 | if ':' not in line: |
| 346 | continue |
| 347 | opt, val = line.split(":", 1) |
| 348 | |
| 349 | if opt == 'Codename': |
| 350 | release = val.strip() |
| 351 | |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 352 | return OSRelease('ubuntu', release, arch) |
koder aka kdanilov | 89fb610 | 2015-06-13 02:58:08 +0300 | [diff] [blame] | 353 | except: |
| 354 | pass |
| 355 | |
| 356 | raise RuntimeError("Unknown os") |
koder aka kdanilov | 0fdaaee | 2015-06-30 11:10:48 +0300 | [diff] [blame] | 357 | |
| 358 | |
| 359 | @contextlib.contextmanager |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 360 | def empty_ctx(val: Any = None) -> Iterator[Any]: |
koder aka kdanilov | 0fdaaee | 2015-06-30 11:10:48 +0300 | [diff] [blame] | 361 | yield val |
| 362 | |
| 363 | |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 364 | def log_nodes_statistic(nodes: Sequence[IRPCNode]) -> None: |
koder aka kdanilov | 0fdaaee | 2015-06-30 11:10:48 +0300 | [diff] [blame] | 365 | logger.info("Found {0} nodes total".format(len(nodes))) |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 366 | |
| 367 | per_role = collections.defaultdict(int) # type: Dict[str, int] |
koder aka kdanilov | 0fdaaee | 2015-06-30 11:10:48 +0300 | [diff] [blame] | 368 | for node in nodes: |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 369 | for role in node.info.roles: |
koder aka kdanilov | 0fdaaee | 2015-06-30 11:10:48 +0300 | [diff] [blame] | 370 | per_role[role] += 1 |
| 371 | |
| 372 | for role, count in sorted(per_role.items()): |
| 373 | logger.debug("Found {0} nodes with role {1}".format(count, role)) |
koder aka kdanilov | a94dfe1 | 2015-08-19 13:04:51 +0300 | [diff] [blame] | 374 | |
| 375 | |
koder aka kdanilov | 3b4da8b | 2016-10-17 00:17:53 +0300 | [diff] [blame] | 376 | def which(program: str) -> Optional[str]: |
koder aka kdanilov | a94dfe1 | 2015-08-19 13:04:51 +0300 | [diff] [blame] | 377 | def is_exe(fpath): |
| 378 | return os.path.isfile(fpath) and os.access(fpath, os.X_OK) |
| 379 | |
| 380 | for path in os.environ["PATH"].split(os.pathsep): |
| 381 | path = path.strip('"') |
| 382 | exe_file = os.path.join(path, program) |
| 383 | if is_exe(exe_file): |
| 384 | return exe_file |
| 385 | |
| 386 | return None |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 387 | |
| 388 | |
| 389 | def get_uniq_path_uuid(path: str, max_iter: int = 10) -> Tuple[str, str]: |
| 390 | for i in range(max_iter): |
| 391 | run_uuid = pet_generate(2, "_") |
| 392 | results_dir = os.path.join(path, run_uuid) |
| 393 | if not os.path.exists(results_dir): |
| 394 | break |
| 395 | else: |
| 396 | run_uuid = str(uuid.uuid4()) |
| 397 | results_dir = os.path.join(path, run_uuid) |
| 398 | |
| 399 | return results_dir, run_uuid |
| 400 | |
| 401 | |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 402 | class Timeout(Iterable[float]): |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame] | 403 | def __init__(self, timeout: int, message: str = None, min_tick: int = 1, no_exc: bool = False) -> None: |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 404 | self.end_time = time.time() + timeout |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 405 | self.message = message |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame] | 406 | self.min_tick = min_tick |
| 407 | self.prev_tick_at = time.time() |
| 408 | self.no_exc = no_exc |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 409 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame] | 410 | def tick(self) -> bool: |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 411 | current_time = time.time() |
| 412 | |
| 413 | if current_time > self.end_time: |
koder aka kdanilov | 22d134e | 2016-11-08 11:33:19 +0200 | [diff] [blame] | 414 | if self.message: |
| 415 | msg = "Timeout: {}".format(self.message) |
| 416 | else: |
| 417 | msg = "Timeout" |
| 418 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame] | 419 | if self.no_exc: |
| 420 | return False |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 421 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame] | 422 | raise TimeoutError(msg) |
| 423 | |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 424 | sleep_time = self.min_tick - (current_time - self.prev_tick_at) |
| 425 | if sleep_time > 0: |
| 426 | time.sleep(sleep_time) |
| 427 | self.prev_tick_at = time.time() |
| 428 | else: |
| 429 | self.prev_tick_at = current_time |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame] | 430 | |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame] | 431 | return True |
| 432 | |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 433 | def __iter__(self) -> Iterator[float]: |
| 434 | return cast(Iterator[float], self) |
koder aka kdanilov | 3d2bc4f | 2016-11-12 18:31:18 +0200 | [diff] [blame] | 435 | |
| 436 | def __next__(self) -> float: |
| 437 | if not self.tick(): |
| 438 | raise StopIteration() |
koder aka kdanilov | 7308462 | 2016-11-16 21:51:08 +0200 | [diff] [blame] | 439 | return self.end_time - time.time() |