lib.py 3.2 KB

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