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