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 | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 4 | import time |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 5 | import psutil |
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 | 7acd6bd | 2015-02-12 14:28:30 -0800 | [diff] [blame] | 8 | import threading |
| 9 | import contextlib |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 10 | import subprocess |
koder aka kdanilov | 4643fd6 | 2015-02-10 16:20:13 -0800 | [diff] [blame] | 11 | |
koder aka kdanilov | e21d747 | 2015-02-14 19:02:04 -0800 | [diff] [blame] | 12 | |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 13 | logger = logging.getLogger("wally") |
koder aka kdanilov | 7acd6bd | 2015-02-12 14:28:30 -0800 | [diff] [blame] | 14 | |
| 15 | |
koder aka kdanilov | 209e85d | 2015-04-27 23:11:05 +0300 | [diff] [blame] | 16 | def is_ip(data): |
| 17 | if data.count('.') != 3: |
| 18 | return False |
| 19 | |
| 20 | try: |
| 21 | for part in map(int, data.split('.')): |
| 22 | if part > 255 or part < 0: |
| 23 | raise ValueError() |
| 24 | except ValueError: |
| 25 | return False |
| 26 | return True |
| 27 | |
| 28 | |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 29 | class StopTestError(RuntimeError): |
| 30 | def __init__(self, reason, orig_exc=None): |
| 31 | RuntimeError.__init__(self, reason) |
| 32 | self.orig_exc = orig_exc |
| 33 | |
| 34 | |
koder aka kdanilov | 4af1c1d | 2015-05-18 15:48:58 +0300 | [diff] [blame^] | 35 | @contextlib.contextmanager |
| 36 | def log_block(message, exc_logger=None): |
| 37 | logger.debug("Starts : " + message) |
| 38 | with log_error(message, exc_logger): |
| 39 | yield |
| 40 | # try: |
| 41 | # yield |
| 42 | # except Exception as exc: |
| 43 | # if isinstance(exc, types) and not isinstance(exc, StopIteration): |
| 44 | # templ = "Error during {0} stage: {1!s}" |
| 45 | # logger.debug(templ.format(action, exc)) |
| 46 | # raise |
| 47 | |
| 48 | |
| 49 | class log_error(object): |
| 50 | def __init__(self, message, exc_logger=None): |
| 51 | self.message = message |
| 52 | self.exc_logger = exc_logger |
| 53 | |
| 54 | def __enter__(self): |
| 55 | return self |
| 56 | |
| 57 | def __exit__(self, tp, value, traceback): |
| 58 | if value is None or isinstance(value, StopTestError): |
| 59 | return |
| 60 | |
| 61 | if self.exc_logger is None: |
| 62 | exc_logger = sys._getframe(1).f_globals.get('logger', logger) |
| 63 | else: |
| 64 | exc_logger = self.exc_logger |
| 65 | |
| 66 | exc_logger.exception(self.message, exc_info=(tp, value, traceback)) |
| 67 | raise StopTestError(self.message, value) |
| 68 | |
| 69 | |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 70 | def check_input_param(is_ok, message): |
| 71 | if not is_ok: |
| 72 | logger.error(message) |
| 73 | raise StopTestError(message) |
| 74 | |
| 75 | |
koder aka kdanilov | e06762a | 2015-03-22 23:32:09 +0200 | [diff] [blame] | 76 | def parse_creds(creds): |
| 77 | # parse user:passwd@host |
| 78 | user, passwd_host = creds.split(":", 1) |
| 79 | |
| 80 | if '@' not in passwd_host: |
| 81 | passwd, host = passwd_host, None |
| 82 | else: |
| 83 | passwd, host = passwd_host.rsplit('@', 1) |
| 84 | |
| 85 | return user, passwd, host |
| 86 | |
| 87 | |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 88 | class TaksFinished(Exception): |
| 89 | pass |
koder aka kdanilov | 4643fd6 | 2015-02-10 16:20:13 -0800 | [diff] [blame] | 90 | |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 91 | |
| 92 | class Barrier(object): |
| 93 | def __init__(self, count): |
| 94 | self.count = count |
| 95 | self.curr_count = 0 |
| 96 | self.cond = threading.Condition() |
| 97 | self.exited = False |
| 98 | |
| 99 | def wait(self, timeout=None): |
| 100 | with self.cond: |
| 101 | if self.exited: |
| 102 | raise TaksFinished() |
| 103 | |
| 104 | self.curr_count += 1 |
| 105 | if self.curr_count == self.count: |
| 106 | self.curr_count = 0 |
| 107 | self.cond.notify_all() |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 108 | return True |
koder aka kdanilov | 4643fd6 | 2015-02-10 16:20:13 -0800 | [diff] [blame] | 109 | else: |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 110 | self.cond.wait(timeout=timeout) |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 111 | return False |
koder aka kdanilov | 4643fd6 | 2015-02-10 16:20:13 -0800 | [diff] [blame] | 112 | |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 113 | def exit(self): |
| 114 | with self.cond: |
| 115 | self.exited = True |
koder aka kdanilov | 7acd6bd | 2015-02-12 14:28:30 -0800 | [diff] [blame] | 116 | |
| 117 | |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 118 | 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] | 119 | |
| 120 | |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 121 | def ssize2b(ssize): |
koder aka kdanilov | 8ad6e81 | 2015-03-22 14:42:18 +0200 | [diff] [blame] | 122 | try: |
koder aka kdanilov | 63e9c5a | 2015-04-28 23:06:07 +0300 | [diff] [blame] | 123 | if isinstance(ssize, (int, long)): |
| 124 | return ssize |
koder aka kdanilov | 8ad6e81 | 2015-03-22 14:42:18 +0200 | [diff] [blame] | 125 | |
koder aka kdanilov | 63e9c5a | 2015-04-28 23:06:07 +0300 | [diff] [blame] | 126 | ssize = ssize.lower() |
koder aka kdanilov | 2c47309 | 2015-03-29 17:12:13 +0300 | [diff] [blame] | 127 | if ssize[-1] in SMAP: |
| 128 | return int(ssize[:-1]) * SMAP[ssize[-1]] |
koder aka kdanilov | 8ad6e81 | 2015-03-22 14:42:18 +0200 | [diff] [blame] | 129 | return int(ssize) |
| 130 | except (ValueError, TypeError, AttributeError): |
koder aka kdanilov | 2e92802 | 2015-04-08 13:47:15 +0300 | [diff] [blame] | 131 | raise ValueError("Unknow size format {0!r}".format(ssize)) |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 132 | |
| 133 | |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 134 | RSMAP = [('K', 1024), |
| 135 | ('M', 1024 ** 2), |
| 136 | ('G', 1024 ** 3), |
| 137 | ('T', 1024 ** 4)] |
| 138 | |
| 139 | |
| 140 | def b2ssize(size): |
| 141 | if size < 1024: |
| 142 | return str(size) |
| 143 | |
| 144 | for name, scale in RSMAP: |
| 145 | if size < 1024 * scale: |
| 146 | if size % scale == 0: |
| 147 | return "{0} {1}i".format(size // scale, name) |
| 148 | else: |
| 149 | return "{0:.1f} {1}i".format(float(size) / scale, name) |
| 150 | |
| 151 | return "{0}{1}i".format(size // scale, name) |
| 152 | |
| 153 | |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 154 | RSMAP_10 = [('k', 1000), |
| 155 | ('m', 1000 ** 2), |
| 156 | ('g', 1000 ** 3), |
| 157 | ('t', 1000 ** 4)] |
| 158 | |
| 159 | |
| 160 | def b2ssize_10(size): |
| 161 | if size < 1000: |
| 162 | return str(size) |
| 163 | |
| 164 | for name, scale in RSMAP_10: |
| 165 | if size < 1000 * scale: |
| 166 | if size % scale == 0: |
| 167 | return "{0} {1}".format(size // scale, name) |
| 168 | else: |
| 169 | return "{0:.1f} {1}".format(float(size) / scale, name) |
| 170 | |
| 171 | return "{0}{1}".format(size // scale, name) |
| 172 | |
| 173 | |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 174 | def run_locally(cmd, input_data="", timeout=20): |
| 175 | shell = isinstance(cmd, basestring) |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 176 | proc = subprocess.Popen(cmd, |
| 177 | shell=shell, |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 178 | stdin=subprocess.PIPE, |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 179 | stdout=subprocess.PIPE, |
| 180 | stderr=subprocess.PIPE) |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 181 | res = [] |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 182 | |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 183 | def thread_func(): |
| 184 | rr = proc.communicate(input_data) |
| 185 | res.extend(rr) |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 186 | |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 187 | thread = threading.Thread(target=thread_func) |
| 188 | thread.daemon = True |
| 189 | thread.start() |
| 190 | thread.join(timeout) |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 191 | |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 192 | if thread.is_alive(): |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 193 | |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 194 | parent = psutil.Process(proc.pid) |
| 195 | for child in parent.children(recursive=True): |
| 196 | child.kill() |
| 197 | parent.kill() |
| 198 | thread.join() |
| 199 | raise RuntimeError("Local process timeout: " + str(cmd)) |
| 200 | |
| 201 | out, err = res |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 202 | if 0 != proc.returncode: |
koder aka kdanilov | 416b87a | 2015-05-12 00:26:04 +0300 | [diff] [blame] | 203 | raise subprocess.CalledProcessError(proc.returncode, |
| 204 | cmd, out + err) |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 205 | |
| 206 | return out |
| 207 | |
| 208 | |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 209 | def get_ip_for_target(target_ip): |
koder aka kdanilov | 209e85d | 2015-04-27 23:11:05 +0300 | [diff] [blame] | 210 | if not is_ip(target_ip): |
koder aka kdanilov | afd9874 | 2015-04-24 01:27:22 +0300 | [diff] [blame] | 211 | target_ip = socket.gethostbyname(target_ip) |
| 212 | |
koder aka kdanilov | 209e85d | 2015-04-27 23:11:05 +0300 | [diff] [blame] | 213 | first_dig = map(int, target_ip.split(".")) |
| 214 | if first_dig == 127: |
koder aka kdanilov | afd9874 | 2015-04-24 01:27:22 +0300 | [diff] [blame] | 215 | return '127.0.0.1' |
| 216 | |
koder aka kdanilov | d5ed4da | 2015-05-07 23:33:23 +0300 | [diff] [blame] | 217 | data = run_locally('ip route get to'.split(" ") + [target_ip]) |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 218 | |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 219 | rr1 = r'{0} via [.0-9]+ dev (?P<dev>.*?) src (?P<ip>[.0-9]+)$' |
| 220 | rr1 = rr1.replace(" ", r'\s+') |
| 221 | rr1 = rr1.format(target_ip.replace('.', r'\.')) |
| 222 | |
| 223 | rr2 = r'{0} dev (?P<dev>.*?) src (?P<ip>[.0-9]+)$' |
| 224 | rr2 = rr2.replace(" ", r'\s+') |
| 225 | rr2 = rr2.format(target_ip.replace('.', r'\.')) |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 226 | |
| 227 | data_line = data.split("\n")[0].strip() |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 228 | res1 = re.match(rr1, data_line) |
| 229 | res2 = re.match(rr2, data_line) |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 230 | |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 231 | if res1 is not None: |
| 232 | return res1.group('ip') |
koder aka kdanilov | 652cd80 | 2015-04-13 12:21:07 +0300 | [diff] [blame] | 233 | |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 234 | if res2 is not None: |
| 235 | return res2.group('ip') |
| 236 | |
| 237 | raise OSError("Can't define interface for {0}".format(target_ip)) |
| 238 | |
| 239 | |
| 240 | def open_for_append_or_create(fname): |
| 241 | if not os.path.exists(fname): |
| 242 | return open(fname, "w") |
| 243 | |
| 244 | fd = open(fname, 'r+') |
| 245 | fd.seek(0, os.SEEK_END) |
| 246 | return fd |
| 247 | |
| 248 | |
| 249 | def sec_to_str(seconds): |
| 250 | h = seconds // 3600 |
| 251 | m = (seconds % 3600) // 60 |
| 252 | s = seconds % 60 |
| 253 | return "{0}:{1:02d}:{2:02d}".format(h, m, s) |
koder aka kdanilov | 168f609 | 2015-04-19 02:33:38 +0300 | [diff] [blame] | 254 | |
| 255 | |
| 256 | def yamable(data): |
| 257 | if isinstance(data, (tuple, list)): |
| 258 | return map(yamable, data) |
| 259 | |
| 260 | if isinstance(data, unicode): |
| 261 | return str(data) |
| 262 | |
| 263 | if isinstance(data, dict): |
| 264 | res = {} |
| 265 | for k, v in data.items(): |
| 266 | res[yamable(k)] = yamable(v) |
| 267 | return res |
| 268 | |
| 269 | return data |
koder aka kdanilov | f86d7af | 2015-05-06 04:01:54 +0300 | [diff] [blame] | 270 | |
| 271 | |
| 272 | CLEANING = [] |
| 273 | |
| 274 | |
| 275 | def clean_resource(func, *args, **kwargs): |
| 276 | CLEANING.append((func, args, kwargs)) |
| 277 | |
| 278 | |
| 279 | def iter_clean_func(): |
| 280 | while CLEANING != []: |
| 281 | yield CLEANING.pop() |
koder aka kdanilov | 4af1c1d | 2015-05-18 15:48:58 +0300 | [diff] [blame^] | 282 | |
| 283 | |
| 284 | def flatten(data): |
| 285 | res = [] |
| 286 | for i in data: |
| 287 | if isinstance(i, (list, tuple, set)): |
| 288 | res.extend(flatten(i)) |
| 289 | else: |
| 290 | res.append(i) |
| 291 | return res |