blob: 078a0194a77d62e7f4171d8c6df382b1571edf37 [file] [log] [blame]
koder aka kdanilov652cd802015-04-13 12:21:07 +03001import re
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +03002import os
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +03003import sys
koder aka kdanilovffaf48d2016-12-27 02:25:29 +02004import math
koder aka kdanilov22d134e2016-11-08 11:33:19 +02005import time
6import uuid
koder aka kdanilovafd98742015-04-24 01:27:22 +03007import socket
koder aka kdanilove21d7472015-02-14 19:02:04 -08008import logging
koder aka kdanilovf2865172016-12-30 03:35:11 +02009import datetime
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +030010import ipaddress
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -080011import threading
12import contextlib
koder aka kdanilov652cd802015-04-13 12:21:07 +030013import subprocess
koder aka kdanilov6ab4d432015-06-22 00:26:28 +030014import collections
koder aka kdanilov4643fd62015-02-10 16:20:13 -080015
koder aka kdanilov3d2bc4f2016-11-12 18:31:18 +020016from .node_interfaces import IRPCNode
koder aka kdanilovffaf48d2016-12-27 02:25:29 +020017from typing import (Any, Tuple, Union, List, Iterator, Dict, Iterable, Optional,
18 IO, Sequence, NamedTuple, cast, TypeVar)
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +030019
koder aka kdanilovbb5fe072015-05-21 02:50:23 +030020try:
21 import psutil
22except ImportError:
23 psutil = None
24
koder aka kdanilov22d134e2016-11-08 11:33:19 +020025try:
26 from petname import Generate as pet_generate
27except ImportError:
28 def pet_generate(x: str, y: str) -> str:
29 return str(uuid.uuid4())
30
koder aka kdanilove21d7472015-02-14 19:02:04 -080031
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030032logger = logging.getLogger("wally")
koder aka kdanilovffaf48d2016-12-27 02:25:29 +020033TNumber = TypeVar('TNumber', int, float)
34Number = Union[int, float]
koder aka kdanilov209e85d2015-04-27 23:11:05 +030035
36
koder aka kdanilovf86d7af2015-05-06 04:01:54 +030037class StopTestError(RuntimeError):
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +030038 pass
koder aka kdanilovf86d7af2015-05-06 04:01:54 +030039
40
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +030041class LogError:
koder aka kdanilov22d134e2016-11-08 11:33:19 +020042 def __init__(self, message: str, exc_logger: logging.Logger = None) -> None:
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +030043 self.message = message
44 self.exc_logger = exc_logger
45
koder aka kdanilov22d134e2016-11-08 11:33:19 +020046 def __enter__(self) -> 'LogError':
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +030047 return self
48
koder aka kdanilov22d134e2016-11-08 11:33:19 +020049 def __exit__(self, tp: type, value: Exception, traceback: Any) -> bool:
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +030050 if value is None or isinstance(value, StopTestError):
koder aka kdanilov22d134e2016-11-08 11:33:19 +020051 return False
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +030052
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 kdanilov22d134e2016-11-08 11:33:19 +020059 raise StopTestError(self.message) from value
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +030060
61
koder aka kdanilov22d134e2016-11-08 11:33:19 +020062class TaskFinished(Exception):
koder aka kdanilov2c473092015-03-29 17:12:13 +030063 pass
koder aka kdanilov4643fd62015-02-10 16:20:13 -080064
koder aka kdanilov2c473092015-03-29 17:12:13 +030065
koder aka kdanilovffaf48d2016-12-27 02:25:29 +020066class 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
106def greater_digit_pos(val: Number) -> int:
107 return int(math.floor(math.log10(val))) + 1
108
109
110def 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
115def is_ip(data: str) -> bool:
116 try:
117 ipaddress.ip_address(data)
118 return True
119 except ValueError:
120 return False
121
122
123def log_block(message: str, exc_logger:logging.Logger = None) -> LogError:
124 logger.debug("Starts : " + message)
125 return LogError(message, exc_logger)
126
127
128def check_input_param(is_ok: bool, message: str) -> None:
129 if not is_ok:
130 logger.error(message)
131 raise StopTestError(message)
132
133
134def 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 kdanilov2c473092015-03-29 17:12:13 +0300146SMAP = dict(k=1024, m=1024 ** 2, g=1024 ** 3, t=1024 ** 4)
koder aka kdanilov8ad6e812015-03-22 14:42:18 +0200147
148
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300149def ssize2b(ssize: Union[str, int]) -> int:
koder aka kdanilov8ad6e812015-03-22 14:42:18 +0200150 try:
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300151 if isinstance(ssize, int):
koder aka kdanilov63e9c5a2015-04-28 23:06:07 +0300152 return ssize
koder aka kdanilov8ad6e812015-03-22 14:42:18 +0200153
koder aka kdanilov63e9c5a2015-04-28 23:06:07 +0300154 ssize = ssize.lower()
koder aka kdanilov2c473092015-03-29 17:12:13 +0300155 if ssize[-1] in SMAP:
156 return int(ssize[:-1]) * SMAP[ssize[-1]]
koder aka kdanilov8ad6e812015-03-22 14:42:18 +0200157 return int(ssize)
158 except (ValueError, TypeError, AttributeError):
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300159 raise ValueError("Unknow size format {!r}".format(ssize))
koder aka kdanilov652cd802015-04-13 12:21:07 +0300160
161
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300162RSMAP = [('K', 1024),
163 ('M', 1024 ** 2),
164 ('G', 1024 ** 3),
165 ('T', 1024 ** 4)]
166
167
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300168def b2ssize(size: int) -> str:
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300169 if size < 1024:
170 return str(size)
171
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200172 # make mypy happy
173 scale = 1
174 name = ""
175
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300176 for name, scale in RSMAP:
177 if size < 1024 * scale:
178 if size % scale == 0:
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300179 return "{} {}i".format(size // scale, name)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300180 else:
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300181 return "{:.1f} {}i".format(float(size) / scale, name)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300182
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300183 return "{}{}i".format(size // scale, name)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300184
185
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300186RSMAP_10 = [('k', 1000),
187 ('m', 1000 ** 2),
188 ('g', 1000 ** 3),
189 ('t', 1000 ** 4)]
190
191
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300192def b2ssize_10(size: int) -> str:
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300193 if size < 1000:
194 return str(size)
195
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200196 # make mypy happy
197 scale = 1
198 name = ""
199
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300200 for name, scale in RSMAP_10:
201 if size < 1000 * scale:
202 if size % scale == 0:
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300203 return "{} {}".format(size // scale, name)
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300204 else:
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300205 return "{:.1f} {}".format(float(size) / scale, name)
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300206
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300207 return "{}{}".format(size // scale, name)
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300208
209
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300210def run_locally(cmd: Union[str, List[str]], input_data: str="", timeout:int =20) -> str:
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200211 if isinstance(cmd, str):
212 shell = True
213 cmd_str = cmd
214 else:
koder aka kdanilov73084622016-11-16 21:51:08 +0200215 shell = False
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200216 cmd_str = " ".join(cmd)
217
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300218 proc = subprocess.Popen(cmd,
219 shell=shell,
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300220 stdin=subprocess.PIPE,
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300221 stdout=subprocess.PIPE,
222 stderr=subprocess.PIPE)
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200223 res = [] # type: List[Tuple[bytes, bytes]]
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300224
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300225 def thread_func() -> None:
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200226 rr = proc.communicate(input_data.encode("utf8"))
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300227 res.extend(rr)
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300228
koder aka kdanilovfd2cfa52015-05-20 03:17:42 +0300229 thread = threading.Thread(target=thread_func,
230 name="Local cmd execution")
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300231 thread.daemon = True
232 thread.start()
233 thread.join(timeout)
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300234
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300235 if thread.is_alive():
koder aka kdanilovbb5fe072015-05-21 02:50:23 +0300236 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 kdanilovd5ed4da2015-05-07 23:33:23 +0300243
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300244 thread.join()
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200245 raise RuntimeError("Local process timeout: " + cmd_str)
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300246
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200247 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 kdanilovd5ed4da2015-05-07 23:33:23 +0300252 if 0 != proc.returncode:
koder aka kdanilov416b87a2015-05-12 00:26:04 +0300253 raise subprocess.CalledProcessError(proc.returncode,
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200254 cmd_str, out + err)
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300255
256 return out
257
258
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300259def get_ip_for_target(target_ip: str) -> str:
koder aka kdanilov209e85d2015-04-27 23:11:05 +0300260 if not is_ip(target_ip):
koder aka kdanilovafd98742015-04-24 01:27:22 +0300261 target_ip = socket.gethostbyname(target_ip)
262
koder aka kdanilov209e85d2015-04-27 23:11:05 +0300263 first_dig = map(int, target_ip.split("."))
264 if first_dig == 127:
koder aka kdanilovafd98742015-04-24 01:27:22 +0300265 return '127.0.0.1'
266
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300267 data = run_locally('ip route get to'.split(" ") + [target_ip])
koder aka kdanilov652cd802015-04-13 12:21:07 +0300268
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300269 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 kdanilov652cd802015-04-13 12:21:07 +0300276
277 data_line = data.split("\n")[0].strip()
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300278 res1 = re.match(rr1, data_line)
279 res2 = re.match(rr2, data_line)
koder aka kdanilov652cd802015-04-13 12:21:07 +0300280
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300281 if res1 is not None:
282 return res1.group('ip')
koder aka kdanilov652cd802015-04-13 12:21:07 +0300283
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300284 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 kdanilov39e449e2016-12-17 15:15:26 +0200290def open_for_append_or_create(fname: str) -> IO[str]:
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300291 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 kdanilov3b4da8b2016-10-17 00:17:53 +0300299def sec_to_str(seconds: int) -> str:
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300300 h = seconds // 3600
301 m = (seconds % 3600) // 60
302 s = seconds % 60
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300303 return "{}:{:02d}:{:02d}".format(h, m, s)
koder aka kdanilov168f6092015-04-19 02:33:38 +0300304
305
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300306def yamable(data: Any) -> Any:
koder aka kdanilov168f6092015-04-19 02:33:38 +0300307 if isinstance(data, (tuple, list)):
308 return map(yamable, data)
309
koder aka kdanilov168f6092015-04-19 02:33:38 +0300310 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 kdanilovf86d7af2015-05-06 04:01:54 +0300317
318
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300319def flatten(data: Iterable[Any]) -> List[Any]:
koder aka kdanilov4af1c1d2015-05-18 15:48:58 +0300320 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 kdanilov89fb6102015-06-13 02:58:08 +0300327
328
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200329def get_creds_openrc(path: str) -> Tuple[str, str, str, str, bool]:
koder aka kdanilov89fb6102015-06-13 02:58:08 +0300330 fc = open(path).read()
331
koder aka kdanilovb7197432015-07-15 00:40:43 +0300332 echo = 'echo "$OS_INSECURE:$OS_TENANT_NAME:$OS_USERNAME:$OS_PASSWORD@$OS_AUTH_URL"'
koder aka kdanilov89fb6102015-06-13 02:58:08 +0300333
334 msg = "Failed to get creads from openrc file"
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300335 with LogError(msg):
koder aka kdanilov89fb6102015-06-13 02:58:08 +0300336 data = run_locally(['/bin/bash'], input_data=fc + "\n" + echo)
337
338 msg = "Failed to get creads from openrc file: " + data
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300339 with LogError(msg):
koder aka kdanilov89fb6102015-06-13 02:58:08 +0300340 data = data.strip()
koder aka kdanilovb7197432015-07-15 00:40:43 +0300341 insecure_str, user, tenant, passwd_auth_url = data.split(':', 3)
342 insecure = (insecure_str in ('1', 'True', 'true'))
koder aka kdanilov89fb6102015-06-13 02:58:08 +0300343 passwd, auth_url = passwd_auth_url.rsplit("@", 1)
344 assert (auth_url.startswith("https://") or
345 auth_url.startswith("http://"))
346
koder aka kdanilovb7197432015-07-15 00:40:43 +0300347 return user, passwd, tenant, auth_url, insecure
koder aka kdanilov89fb6102015-06-13 02:58:08 +0300348
349
koder aka kdanilov73084622016-11-16 21:51:08 +0200350OSRelease = NamedTuple("OSRelease",
351 [("distro", str),
352 ("release", str),
353 ("arch", str)])
koder aka kdanilov6ab4d432015-06-22 00:26:28 +0300354
355
koder aka kdanilov73084622016-11-16 21:51:08 +0200356def get_os(node: IRPCNode) -> OSRelease:
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200357 """return os type, release and architecture for node.
358 """
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300359 arch = node.run("arch", nolog=True).strip()
koder aka kdanilov6ab4d432015-06-22 00:26:28 +0300360
koder aka kdanilov89fb6102015-06-13 02:58:08 +0300361 try:
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300362 node.run("ls -l /etc/redhat-release", nolog=True)
koder aka kdanilov73084622016-11-16 21:51:08 +0200363 return OSRelease('redhat', None, arch)
koder aka kdanilov89fb6102015-06-13 02:58:08 +0300364 except:
365 pass
366
367 try:
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300368 node.run("ls -l /etc/debian_version", nolog=True)
koder aka kdanilov6ab4d432015-06-22 00:26:28 +0300369
370 release = None
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300371 for line in node.run("lsb_release -a", nolog=True).split("\n"):
koder aka kdanilov6ab4d432015-06-22 00:26:28 +0300372 if ':' not in line:
373 continue
374 opt, val = line.split(":", 1)
375
376 if opt == 'Codename':
377 release = val.strip()
378
koder aka kdanilov73084622016-11-16 21:51:08 +0200379 return OSRelease('ubuntu', release, arch)
koder aka kdanilov89fb6102015-06-13 02:58:08 +0300380 except:
381 pass
382
383 raise RuntimeError("Unknown os")
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +0300384
385
386@contextlib.contextmanager
koder aka kdanilov73084622016-11-16 21:51:08 +0200387def empty_ctx(val: Any = None) -> Iterator[Any]:
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +0300388 yield val
389
390
koder aka kdanilov73084622016-11-16 21:51:08 +0200391def log_nodes_statistic(nodes: Sequence[IRPCNode]) -> None:
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +0300392 logger.info("Found {0} nodes total".format(len(nodes)))
koder aka kdanilov22d134e2016-11-08 11:33:19 +0200393
394 per_role = collections.defaultdict(int) # type: Dict[str, int]
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +0300395 for node in nodes:
koder aka kdanilov73084622016-11-16 21:51:08 +0200396 for role in node.info.roles:
koder aka kdanilov0fdaaee2015-06-30 11:10:48 +0300397 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 kdanilova94dfe12015-08-19 13:04:51 +0300401
402
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +0300403def which(program: str) -> Optional[str]:
koder aka kdanilova94dfe12015-08-19 13:04:51 +0300404 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 kdanilov22d134e2016-11-08 11:33:19 +0200414
415
416def 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 kdanilovbbbe1dc2016-12-20 01:19:56 +0200429def 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 kdanilovf2865172016-12-30 03:35:11 +0200438
439
440def 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)