lib.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import os
  2. import sys
  3. import locale
  4. import random
  5. import time
  6. import signal
  7. from contextlib import contextmanager
  8. @contextmanager
  9. def default_sigint():
  10. original_sigint_handler = signal.getsignal(signal.SIGINT)
  11. signal.signal(signal.SIGINT, signal.SIG_DFL)
  12. try:
  13. yield
  14. finally:
  15. signal.signal(signal.SIGINT, original_sigint_handler)
  16. def to_utf8(s):
  17. """Re-encode string from the default system encoding to UTF-8."""
  18. current = locale.getpreferredencoding()
  19. return s.decode(current).encode("UTF-8") if s and current != "UTF-8" else s
  20. def debug(obj, fd=sys.stderr):
  21. """Write obj to standard error."""
  22. string = str(obj.encode(get_encoding(fd), "backslashreplace")
  23. if isinstance(obj, unicode) else obj)
  24. fd.write(string + "\n")
  25. def catch_exceptions(exit_codes, fun, *args, **kwargs):
  26. """
  27. Catch exceptions on fun(*args, **kwargs) and return the exit code specified
  28. in the exit_codes dictionary. Return 0 if no exception is raised.
  29. """
  30. try:
  31. fun(*args, **kwargs)
  32. return 0
  33. except tuple(exit_codes.keys()) as exc:
  34. debug("[%s] %s" % (exc.__class__.__name__, exc))
  35. return exit_codes[exc.__class__]
  36. def get_encoding(fd):
  37. """Guess terminal encoding."""
  38. return fd.encoding or locale.getpreferredencoding()
  39. def first(it):
  40. """Return first element in iterable."""
  41. return it.next()
  42. def string_to_dict(string):
  43. """Return dictionary from string "key1=value1, key2=value2"."""
  44. if string:
  45. pairs = [s.strip() for s in string.split(",")]
  46. return dict(pair.split("=") for pair in pairs)
  47. def get_first_existing_filename(prefixes, relative_path):
  48. """Get the first existing filename of relative_path seeking on prefixes directories."""
  49. for prefix in prefixes:
  50. path = os.path.join(prefix, relative_path)
  51. if os.path.exists(path):
  52. return path
  53. def retriable_exceptions(fun, retriable_exceptions, max_retries=None):
  54. """Run function and retry on some exceptions (with exponential backoff)."""
  55. retry = 0
  56. while 1:
  57. try:
  58. return fun()
  59. except tuple(retriable_exceptions) as exc:
  60. retry += 1
  61. if type(exc) not in retriable_exceptions:
  62. raise exc
  63. elif max_retries is not None and retry > max_retries:
  64. debug("[Retryable errors] Retry limit reached")
  65. raise exc
  66. else:
  67. seconds = random.uniform(0, 2**retry)
  68. message = ("[Retryable error {current_retry}/{total_retries}] " +
  69. "{error_type} ({error_msg}). Wait {wait_time} seconds").format(
  70. current_retry=retry,
  71. total_retries=max_retries or "-",
  72. error_type=type(exc).__name__,
  73. error_msg=str(exc) or "-",
  74. wait_time="%.1f" % seconds,
  75. )
  76. debug(message)
  77. time.sleep(seconds)