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