| 1 |
""" |
| 2 |
Utils for common funcs, such as setting up a log, composing functions. |
| 3 |
""" |
| 4 |
|
| 5 |
import argparse |
| 6 |
import functools |
| 7 |
import logging |
| 8 |
import logging.config |
| 9 |
import multiprocessing |
| 10 |
import resource |
| 11 |
import os |
| 12 |
import pprint |
| 13 |
import subprocess |
| 14 |
import sys |
| 15 |
import time |
| 16 |
import traceback |
| 17 |
import types |
| 18 |
import xml.etree.ElementTree as ET |
| 19 |
from contextlib import contextmanager |
| 20 |
|
| 21 |
from pbcommand.models import FileTypes, DataSetMetaData |
| 22 |
from pbcommand import to_ascii |
| 23 |
|
| 24 |
|
| 25 |
log = logging.getLogger(__name__) |
| 26 |
log.addHandler(logging.NullHandler()) |
| 27 |
|
| 28 |
|
| 29 |
class Constants: |
| 30 |
"""Log Level format strings""" |
| 31 |
LOG_FMT_ONLY_MSG = '%(message)s' |
| 32 |
LOG_FMT_ERR = '%(message)s' |
| 33 |
LOG_FMT_LVL = '[%(levelname)s] %(message)s' |
| 34 |
LOG_FMT_MIN = '[%(asctime)-15sZ] %(message)s' |
| 35 |
LOG_FMT_SIMPLE = '[%(levelname)s] %(asctime)-15sZ %(message)s' |
| 36 |
LOG_FMT_STD = '[%(levelname)s] %(asctime)-15sZ [%(name)s] %(message)s' |
| 37 |
LOG_FMT_FULL = '[%(levelname)s] %(asctime)-15sZ [%(name)s %(funcName)s %(lineno)d] %(message)s' |
| 38 |
|
| 39 |
|
| 40 |
class ExternalCommandNotFoundError(Exception): |
| 41 |
"""External command is not found in Path""" |
| 42 |
pass |
| 43 |
|
| 44 |
|
| 45 |
def _handler_stream_d(stream, level_str, formatter_id): |
| 46 |
d = {'level': level_str, |
| 47 |
'class': "logging.StreamHandler", |
| 48 |
'formatter': formatter_id, |
| 49 |
'stream': stream} |
| 50 |
return d |
| 51 |
|
| 52 |
|
| 53 |
_handler_stdout_stream_d = functools.partial( |
| 54 |
_handler_stream_d, "ext://sys.stdout") |
| 55 |
_handler_stderr_stream_d = functools.partial( |
| 56 |
_handler_stream_d, "ext://sys.stderr") |
| 57 |
|
| 58 |
|
| 59 |
def _handler_file(level_str, path, formatter_id): |
| 60 |
d = {'class': 'logging.FileHandler', |
| 61 |
'level': level_str, |
| 62 |
'formatter': formatter_id, |
| 63 |
'filename': path} |
| 64 |
return d |
| 65 |
|
| 66 |
|
| 67 |
def _get_default_logging_config_dict(level, file_name_or_none, formatter): |
| 68 |
""" |
| 69 |
Setup a logger to either a file or console. If file name is none, then |
| 70 |
a logger will be setup to stdout. |
| 71 |
|
| 72 |
:note: adds console |
| 73 |
|
| 74 |
Returns a dict configuration of the logger. |
| 75 |
""" |
| 76 |
|
| 77 |
level_str = logging.getLevelName(level) |
| 78 |
|
| 79 |
formatter_id = 'custom_logger_fmt' |
| 80 |
console_handler_id = "console_handler" |
| 81 |
|
| 82 |
error_fmt_id = "error_fmt_id" |
| 83 |
error_handler_id = "error_handler" |
| 84 |
error_handler_d = _handler_stderr_stream_d(logging.ERROR, error_fmt_id) |
| 85 |
|
| 86 |
if file_name_or_none is None: |
| 87 |
handler_d = _handler_stdout_stream_d(level_str, formatter_id) |
| 88 |
else: |
| 89 |
handler_d = _handler_file(level_str, file_name_or_none, formatter_id) |
| 90 |
|
| 91 |
formatters_d = {fid: {'format': fx} for fid, fx in [ |
| 92 |
(formatter_id, formatter), (error_fmt_id, Constants.LOG_FMT_ERR)]} |
| 93 |
|
| 94 |
handlers_d = {console_handler_id: handler_d, |
| 95 |
error_handler_id: error_handler_d} |
| 96 |
|
| 97 |
loggers_d = {"custom": {'handlers': [console_handler_id], |
| 98 |
'stderr': {'handlers': [error_handler_id]}}} |
| 99 |
|
| 100 |
d = { |
| 101 |
'version': 1, |
| 102 |
'disable_existing_loggers': False, |
| 103 |
'formatters': formatters_d, |
| 104 |
'handlers': handlers_d, |
| 105 |
'loggers': loggers_d, |
| 106 |
'root': {'handlers': [error_handler_id, console_handler_id], 'level': logging.NOTSET} |
| 107 |
} |
| 108 |
|
| 109 |
|
| 110 |
return d |
| 111 |
|
| 112 |
|
| 113 |
def _get_console_and_file_logging_config_dict( |
| 114 |
console_level, console_formatter, path, path_level, path_formatter): |
| 115 |
""" |
| 116 |
Get logging configuration that is both for console and a file. |
| 117 |
|
| 118 |
:note: A stderr logger handler is also added. |
| 119 |
|
| 120 |
""" |
| 121 |
|
| 122 |
def _to_handler_d(handlers_, level): |
| 123 |
return {"handlers": handlers_, "level": level, "propagate": True} |
| 124 |
|
| 125 |
console_handler_id = "console_handler" |
| 126 |
console_fmt_id = "console_fmt" |
| 127 |
console_handler_d = _handler_stdout_stream_d(console_level, console_fmt_id) |
| 128 |
|
| 129 |
stderr_handler_id = "stderr_handler" |
| 130 |
error_fmt_id = "error_fmt" |
| 131 |
stderr_handler_d = _handler_stderr_stream_d(logging.ERROR, console_fmt_id) |
| 132 |
|
| 133 |
file_handler_id = "file_handler" |
| 134 |
file_fmt_id = "file_fmt" |
| 135 |
file_handler_d = _handler_file(path_level, path, file_fmt_id) |
| 136 |
|
| 137 |
formatters = {console_fmt_id: {"format": console_formatter}, |
| 138 |
file_fmt_id: {"format": path_formatter}, |
| 139 |
error_fmt_id: {"format": Constants.LOG_FMT_ERR} |
| 140 |
} |
| 141 |
|
| 142 |
handlers = {console_handler_id: console_handler_d, |
| 143 |
file_handler_id: file_handler_d, |
| 144 |
stderr_handler_id: stderr_handler_d} |
| 145 |
|
| 146 |
loggers = {"console": _to_handler_d([console_handler_id], console_level), |
| 147 |
"custom_file": _to_handler_d([file_handler_id], path_level), |
| 148 |
"stderr_err": _to_handler_d([stderr_handler_id], logging.ERROR) |
| 149 |
} |
| 150 |
|
| 151 |
d = {'version': 1, |
| 152 |
'disable_existing_loggers': False, |
| 153 |
'formatters': formatters, |
| 154 |
'handlers': handlers, |
| 155 |
'loggers': loggers, |
| 156 |
'root': {'handlers': list(handlers.keys()), 'level': logging.DEBUG} |
| 157 |
} |
| 158 |
|
| 159 |
|
| 160 |
return d |
| 161 |
|
| 162 |
|
| 163 |
def _setup_logging_config_d(d): |
| 164 |
logging.config.dictConfig(d) |
| 165 |
logging.Formatter.converter = time.gmtime |
| 166 |
return d |
| 167 |
|
| 168 |
|
| 169 |
def setup_logger(file_name_or_none, level, formatter=Constants.LOG_FMT_FULL): |
| 170 |
""" |
| 171 |
|
| 172 |
:param file_name_or_none: Path to log file, None will default to stdout |
| 173 |
:param level: logging.LEVEL of |
| 174 |
:param formatter: Log Formatting string |
| 175 |
""" |
| 176 |
d = _get_default_logging_config_dict(level, file_name_or_none, formatter) |
| 177 |
return _setup_logging_config_d(d) |
| 178 |
|
| 179 |
|
| 180 |
def setup_console_and_file_logger( |
| 181 |
stdout_level, stdout_formatter, path, path_level, path_formatter): |
| 182 |
d = _get_console_and_file_logging_config_dict( |
| 183 |
stdout_level, stdout_formatter, path, path_level, path_formatter) |
| 184 |
return _setup_logging_config_d(d) |
| 185 |
|
| 186 |
|
| 187 |
def setup_log(alog, |
| 188 |
level=logging.INFO, |
| 189 |
file_name=None, |
| 190 |
log_filter=None, |
| 191 |
str_formatter=Constants.LOG_FMT_FULL): |
| 192 |
"""Core Util to setup log handler |
| 193 |
|
| 194 |
:param alog: a log instance |
| 195 |
:param level: (int) Level of logging debug |
| 196 |
:param file_name: (str, None) if None, stdout is used, str write to file |
| 197 |
:param log_filter: (LogFilter, None) |
| 198 |
:param str_formatter: (str) log formatting str |
| 199 |
|
| 200 |
.. warning:: THIS NEEDS TO BE DEPRECATED |
| 201 |
""" |
| 202 |
setup_logger(file_name, level, formatter=str_formatter) |
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
if log_filter is not None: |
| 207 |
alog.warn("log_filter kw is no longer supported") |
| 208 |
|
| 209 |
return alog |
| 210 |
|
| 211 |
|
| 212 |
def get_parsed_args_log_level(pargs, default_level=logging.INFO): |
| 213 |
""" |
| 214 |
Utility for handling logging setup flexibly in a variety of use cases, |
| 215 |
assuming standard command-line arguments. |
| 216 |
|
| 217 |
:param pargs: argparse namespace or equivalent |
| 218 |
:param default_level: logging level to use if the parsed arguments do not |
| 219 |
specify one |
| 220 |
""" |
| 221 |
level = default_level |
| 222 |
if isinstance(level, str): |
| 223 |
level = logging.getLevelName(level) |
| 224 |
verbosity = getattr(pargs, 'verbosity', None) |
| 225 |
if verbosity is not None and verbosity > 0: |
| 226 |
if verbosity >= 2: |
| 227 |
level = logging.DEBUG |
| 228 |
else: |
| 229 |
level = logging.INFO |
| 230 |
elif hasattr(pargs, 'debug') and pargs.debug: |
| 231 |
level = logging.DEBUG |
| 232 |
elif hasattr(pargs, 'quiet') and pargs.quiet: |
| 233 |
level = logging.ERROR |
| 234 |
elif hasattr(pargs, 'log_level'): |
| 235 |
level = logging.getLevelName(pargs.log_level) |
| 236 |
return level |
| 237 |
|
| 238 |
|
| 239 |
def log_traceback(alog, ex, ex_traceback): |
| 240 |
""" |
| 241 |
Log a python traceback in the log file |
| 242 |
|
| 243 |
:param ex: python Exception instance |
| 244 |
:param ex_traceback: exception traceback |
| 245 |
|
| 246 |
|
| 247 |
Example Usage (assuming you have a log instance in your scope) |
| 248 |
|
| 249 |
:Example: |
| 250 |
|
| 251 |
>>> value = 0 |
| 252 |
>>> try: |
| 253 |
>>> 1 / value |
| 254 |
>>> except Exception as e: |
| 255 |
>>> msg = "{i} failed validation. {e}".format(i=value, e=e) |
| 256 |
>>> log.error(msg) |
| 257 |
>>> _, _, ex_traceback = sys.exc_info() |
| 258 |
>>> log_traceback(log, e, ex_traceback) |
| 259 |
|
| 260 |
""" |
| 261 |
|
| 262 |
tb_lines = traceback.format_exception(ex.__class__, ex, ex_traceback) |
| 263 |
tb_text = ''.join(tb_lines) |
| 264 |
alog.error(tb_text) |
| 265 |
|
| 266 |
|
| 267 |
def validate_type_or_raise(instance, type_or_types, error_prefix=None): |
| 268 |
_d = dict(t=instance, x=type(instance), v=instance) |
| 269 |
e = error_prefix if error_prefix is not None else "" |
| 270 |
msg = e + "Expected type {t}. Got type {x} for {v}".format(**_d) |
| 271 |
if not isinstance(instance, type_or_types): |
| 272 |
raise TypeError(msg) |
| 273 |
else: |
| 274 |
return instance |
| 275 |
|
| 276 |
|
| 277 |
def _simple_validate_type(atype, instance): |
| 278 |
return validate_type_or_raise(instance, atype) |
| 279 |
|
| 280 |
|
| 281 |
_is_argparser_instance = functools.partial( |
| 282 |
_simple_validate_type, argparse.ArgumentParser) |
| 283 |
|
| 284 |
|
| 285 |
def is_argparser_instance(func): |
| 286 |
@functools.wraps |
| 287 |
def wrapper(*args, **kwargs): |
| 288 |
_is_argparser_instance(args[0]) |
| 289 |
return func(*args, **kwargs) |
| 290 |
return wrapper |
| 291 |
|
| 292 |
|
| 293 |
def compose(*funcs): |
| 294 |
""" |
| 295 |
Functional composition of a non-empty list |
| 296 |
|
| 297 |
[f, g, h] will be f(g(h(x))) |
| 298 |
|
| 299 |
:Example: |
| 300 |
|
| 301 |
>>> f = lambda x: x * x |
| 302 |
>>> g = lambda x: x + 1 |
| 303 |
>>> h = lambda x: x * 2 |
| 304 |
>>> funcs = [f, g, h] |
| 305 |
>>> fgh = compose(*funcs) |
| 306 |
>>> fgh(3) # 49 |
| 307 |
>>> compose(f, g, h)(3) |
| 308 |
|
| 309 |
""" |
| 310 |
if not funcs: |
| 311 |
raise ValueError("Compose only supports non-empty lists") |
| 312 |
for func in funcs: |
| 313 |
if not isinstance(func, (types.BuiltinMethodType, |
| 314 |
functools.partial, |
| 315 |
types.MethodType, |
| 316 |
types.BuiltinFunctionType, |
| 317 |
types.FunctionType)): |
| 318 |
raise TypeError("Only Function types are supported") |
| 319 |
|
| 320 |
def compose_two(f, g): |
| 321 |
def c(x): |
| 322 |
return f(g(x)) |
| 323 |
return c |
| 324 |
return functools.reduce(compose_two, funcs) |
| 325 |
|
| 326 |
|
| 327 |
def which(exe_str): |
| 328 |
"""walk the current PATH for exe_str to get the absolute path of the exe |
| 329 |
|
| 330 |
:param exe_str: Executable name |
| 331 |
|
| 332 |
:rtype: str | None |
| 333 |
:returns Absolute path to the executable or None if the exe is not found |
| 334 |
""" |
| 335 |
paths = os.environ.get('PATH', None) |
| 336 |
resolved_exe = None |
| 337 |
|
| 338 |
if paths is None: |
| 339 |
|
| 340 |
msg = "PATH env var is not defined." |
| 341 |
log.error(msg) |
| 342 |
return resolved_exe |
| 343 |
|
| 344 |
for path in paths.split(":"): |
| 345 |
exe_path = os.path.join(path, exe_str) |
| 346 |
|
| 347 |
if os.path.exists(exe_path): |
| 348 |
resolved_exe = exe_path |
| 349 |
break |
| 350 |
|
| 351 |
|
| 352 |
return resolved_exe |
| 353 |
|
| 354 |
|
| 355 |
def which_or_raise(cmd): |
| 356 |
"""Find exe in path or raise ExternalCommandNotFoundError""" |
| 357 |
resolved_cmd = which(cmd) |
| 358 |
if resolved_cmd is None: |
| 359 |
raise ExternalCommandNotFoundError( |
| 360 |
"Unable to find required cmd '{c}'".format(c=cmd)) |
| 361 |
else: |
| 362 |
return resolved_cmd |
| 363 |
|
| 364 |
|
| 365 |
class Singleton(type): |
| 366 |
|
| 367 |
""" |
| 368 |
General Purpose singleton class |
| 369 |
|
| 370 |
Usage: |
| 371 |
|
| 372 |
>>> class MyClass: |
| 373 |
>>> __metaclass__ = Singleton |
| 374 |
>>> def __init__(self): |
| 375 |
>>> self.name = 'name' |
| 376 |
|
| 377 |
""" |
| 378 |
|
| 379 |
def __init__(cls, name, bases, dct): |
| 380 |
super().__init__(name, bases, dct) |
| 381 |
cls.instance = None |
| 382 |
|
| 383 |
def __call__(cls, *args, **kw): |
| 384 |
if cls.instance is None: |
| 385 |
cls.instance = super().__call__(*args) |
| 386 |
return cls.instance |
| 387 |
|
| 388 |
|
| 389 |
def nfs_exists_check(ff): |
| 390 |
""" |
| 391 |
Central place for all NFS hackery |
| 392 |
|
| 393 |
Return whether a file or a dir ff exists or not. |
| 394 |
Call listdir() instead of os.path.exists() to eliminate NFS errors. |
| 395 |
|
| 396 |
Added try/catch black hole exception cases to help trigger an NFS refresh |
| 397 |
|
| 398 |
:rtype bool: |
| 399 |
""" |
| 400 |
try: |
| 401 |
|
| 402 |
os.listdir(os.path.dirname(os.path.realpath(ff))) |
| 403 |
|
| 404 |
|
| 405 |
if os.path.exists(ff): |
| 406 |
return True |
| 407 |
|
| 408 |
|
| 409 |
|
| 410 |
os.listdir(os.path.realpath(ff)) |
| 411 |
if os.path.exists(ff): |
| 412 |
return True |
| 413 |
except OSError: |
| 414 |
pass |
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
try: |
| 420 |
f = open(ff, 'r') |
| 421 |
f.close() |
| 422 |
except Exception: |
| 423 |
pass |
| 424 |
|
| 425 |
|
| 426 |
try: |
| 427 |
_ = os.stat(ff) |
| 428 |
_ = os.listdir(ff) |
| 429 |
except Exception: |
| 430 |
pass |
| 431 |
|
| 432 |
|
| 433 |
|
| 434 |
cmd = "ls %s" % ff |
| 435 |
rcode = 1 |
| 436 |
try: |
| 437 |
p = subprocess.Popen([cmd], shell=True) |
| 438 |
rcode = p.wait() |
| 439 |
except Exception: |
| 440 |
pass |
| 441 |
|
| 442 |
return rcode == 0 |
| 443 |
|
| 444 |
|
| 445 |
def nfs_refresh(path, ntimes=3, sleep_time=1.0): |
| 446 |
while True: |
| 447 |
if nfs_exists_check(path): |
| 448 |
return True |
| 449 |
ntimes -= 1 |
| 450 |
if ntimes <= 0: |
| 451 |
break |
| 452 |
time.sleep(sleep_time) |
| 453 |
log.warn("NFS refresh failed. unable to resolve {p}".format(p=path)) |
| 454 |
return False |
| 455 |
|
| 456 |
|
| 457 |
@contextmanager |
| 458 |
def ignored(*exceptions): |
| 459 |
try: |
| 460 |
yield |
| 461 |
except exceptions: |
| 462 |
pass |
| 463 |
|
| 464 |
|
| 465 |
def get_dataset_metadata(path): |
| 466 |
""" |
| 467 |
Returns DataSetMeta data or raises ValueError if dataset XML is missing |
| 468 |
the required UniqueId and MetaType values. |
| 469 |
|
| 470 |
:param path: Path to DataSet XML |
| 471 |
:raises: ValueError |
| 472 |
:return: DataSetMetaData |
| 473 |
""" |
| 474 |
uuid = mt = name = None |
| 475 |
for event, element in ET.iterparse(path, events=("start",)): |
| 476 |
uuid = element.get("UniqueId") |
| 477 |
mt = element.get("MetaType") |
| 478 |
name = element.get("Name") |
| 479 |
break |
| 480 |
else: |
| 481 |
raise ValueError( |
| 482 |
'Did not find events=("start",) in XML path={}'.format(path)) |
| 483 |
if mt in FileTypes.ALL_DATASET_TYPES().keys(): |
| 484 |
return DataSetMetaData(uuid, mt, name) |
| 485 |
else: |
| 486 |
raise ValueError("Unsupported dataset type '{t}'".format(t=mt)) |
| 487 |
|
| 488 |
|
| 489 |
def get_dataset_metadata_or_none(path): |
| 490 |
""" |
| 491 |
Returns DataSetMeta data, else None if the file doesn't exist or a |
| 492 |
processing of the XML raises. |
| 493 |
|
| 494 |
:param path: Path to DataSet XML |
| 495 |
:return: DataSetMetaData or None |
| 496 |
""" |
| 497 |
try: |
| 498 |
return get_dataset_metadata(path) |
| 499 |
except Exception: |
| 500 |
return None |
| 501 |
|
| 502 |
|
| 503 |
def is_dataset(path): |
| 504 |
"""peek into the XML to get the MetaType and verify that it's a valid dataset |
| 505 |
|
| 506 |
:param path: Path to DataSet XML |
| 507 |
""" |
| 508 |
return get_dataset_metadata_or_none(path) is not None |
| 509 |
|
| 510 |
|
| 511 |
def walker(root_dir, file_filter_func): |
| 512 |
""" |
| 513 |
Walk the file sytem and filter by the supplied filter function. |
| 514 |
|
| 515 |
Filter function F(path) -> bool |
| 516 |
""" |
| 517 |
for root, dnames, fnames in os.walk(root_dir): |
| 518 |
for fname in fnames: |
| 519 |
path = os.path.join(root, fname) |
| 520 |
if file_filter_func(path): |
| 521 |
yield path |
| 522 |
|
| 523 |
|
| 524 |
def pool_map(func, args, nproc): |
| 525 |
""" |
| 526 |
Wrapper for calling a function in parallel using the multiprocessing |
| 527 |
module and blocking until results are available. |
| 528 |
""" |
| 529 |
nargs = len(args) |
| 530 |
computed_nproc = min(nargs, nproc, multiprocessing.cpu_count()) |
| 531 |
if computed_nproc > 1: |
| 532 |
log.debug("Running on %d processors", computed_nproc) |
| 533 |
pool = multiprocessing.Pool(processes=computed_nproc) |
| 534 |
result = pool.map(func, args) |
| 535 |
pool.close() |
| 536 |
pool.join() |
| 537 |
else: |
| 538 |
log.debug("computed_nproc=1, running serially") |
| 539 |
result = list(map(func, args)) |
| 540 |
return result |
| 541 |
|
| 542 |
|
| 543 |
def get_peak_memory_usage(): |
| 544 |
try: |
| 545 |
return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss |
| 546 |
except Exception as e: |
| 547 |
log.error(f"Failed to get ru_maxrss: {e}") |
| 548 |
return None |