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