utils.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. # encoding: utf-8
  2. from datetime import datetime, tzinfo, timedelta
  3. import os
  4. import re
  5. import socket
  6. def ensure_ascii(s):
  7. if not isinstance(s, str):
  8. s = '%s' % s
  9. if isinstance(s, str):
  10. return s
  11. else:
  12. return s.encode('utf-8')
  13. def td_total_seconds(td):
  14. return td.days*86400 + td.seconds
  15. def parse_isotime(expires):
  16. return datetime.strptime(expires+"UTC", '%Y-%m-%dT%H:%M:%S.%fZ%Z')
  17. class simple_utc(tzinfo):
  18. def tzname(self, **kwargs):
  19. return 'UTC'
  20. def utcoffset(self, dt):
  21. return timedelta(0)
  22. def parse_k8s_time(time_str):
  23. # time_str: e.g., 2021-02-03T11:33:05Z
  24. ret = datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%SZ')
  25. return ret.replace(tzinfo=simple_utc())
  26. def get_major_version(ver):
  27. segs = ver.split('.')
  28. # 对于 master 版本,不做校验;对于 v3.6.x、v3.7.x这样的格式,做版本校验
  29. if ver.startswith('master'):
  30. return 'master'
  31. if (not ver.startswith('master-')) and len(segs) < 3:
  32. raise Exception("Invalid version %s", ver)
  33. return '%s_%s' % (segs[0], segs[1])
  34. def is_below_v3_9(ver):
  35. # 对于 master 版本,不做校验;对于 v3.6.x、v3.7.x这样的格式,做版本校验
  36. if ver.startswith('master'):
  37. return False
  38. segs = ver.split('.')
  39. v_1st = int(segs[0].strip('v'))
  40. v_2nd = int(segs[1])
  41. if v_1st > 3:
  42. return False
  43. elif v_1st < 3:
  44. return True
  45. else:
  46. if v_2nd < 9:
  47. return True
  48. return False
  49. def to_yaml(data):
  50. import yaml
  51. return yaml.dump(data, default_flow_style=False)
  52. def print_title(title):
  53. print('\n')
  54. print('=' * 80)
  55. print(title)
  56. print('=' * 80)
  57. def init_local_user_path():
  58. import os
  59. path = os.environ['PATH']
  60. user_bin = os.path.expanduser('~/.local/bin')
  61. if user_bin not in path.split(os.pathsep):
  62. path = f'{path}:{user_bin}'
  63. os.environ['PATH'] = path
  64. def pr_red(*skk):
  65. print("\033[31m{}\033[00m" .format(' '.join(skk)))
  66. def pr_green(skk):
  67. print("\033[1m\033[92m{}\033[00m" .format(skk))
  68. def regex_search(pattern, string, ignore_case=False):
  69. flags = re.IGNORECASE if ignore_case else 0
  70. match = re.search(pattern, string, flags)
  71. if match:
  72. return match.group(0)
  73. return None
  74. def is_valid_dns(dns):
  75. try:
  76. socket.gethostbyname(dns)
  77. return True
  78. except socket.gaierror:
  79. return False
  80. def generage_random_string(N=12):
  81. import random
  82. import string
  83. return ''.join(
  84. random.choice(string.ascii_uppercase + string.digits)
  85. for _ in range(N))
  86. def is_ipv4(addr):
  87. try:
  88. socket.inet_pton(socket.AF_INET, addr)
  89. return True
  90. except (OSError, AttributeError, socket.error):
  91. return False
  92. def is_ipv6(addr):
  93. try:
  94. socket.inet_pton(socket.AF_INET6, addr)
  95. return True
  96. except (OSError, AttributeError, socket.error):
  97. return False