base_utils.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import base64
  17. import datetime
  18. import io
  19. import json
  20. import os
  21. import pickle
  22. import socket
  23. import time
  24. import uuid
  25. from enum import Enum, IntEnum
  26. from fate_arch.common.conf_utils import get_base_config
  27. from fate_arch.common import BaseType
  28. use_deserialize_safe_module = get_base_config('use_deserialize_safe_module', False)
  29. class CustomJSONEncoder(json.JSONEncoder):
  30. def __init__(self, **kwargs):
  31. self._with_type = kwargs.pop("with_type", False)
  32. super().__init__(**kwargs)
  33. def default(self, obj):
  34. if isinstance(obj, datetime.datetime):
  35. return obj.strftime('%Y-%m-%d %H:%M:%S')
  36. elif isinstance(obj, datetime.date):
  37. return obj.strftime('%Y-%m-%d')
  38. elif isinstance(obj, datetime.timedelta):
  39. return str(obj)
  40. elif issubclass(type(obj), Enum) or issubclass(type(obj), IntEnum):
  41. return obj.value
  42. elif isinstance(obj, set):
  43. return list(obj)
  44. elif issubclass(type(obj), BaseType):
  45. if not self._with_type:
  46. return obj.to_dict()
  47. else:
  48. return obj.to_dict_with_type()
  49. elif isinstance(obj, type):
  50. return obj.__name__
  51. else:
  52. return json.JSONEncoder.default(self, obj)
  53. def fate_uuid():
  54. return uuid.uuid1().hex
  55. def string_to_bytes(string):
  56. return string if isinstance(string, bytes) else string.encode(encoding="utf-8")
  57. def bytes_to_string(byte):
  58. return byte.decode(encoding="utf-8")
  59. def json_dumps(src, byte=False, indent=None, with_type=False):
  60. dest = json.dumps(src, indent=indent, cls=CustomJSONEncoder, with_type=with_type)
  61. if byte:
  62. dest = string_to_bytes(dest)
  63. return dest
  64. def json_loads(src, object_hook=None, object_pairs_hook=None):
  65. if isinstance(src, bytes):
  66. src = bytes_to_string(src)
  67. return json.loads(src, object_hook=object_hook, object_pairs_hook=object_pairs_hook)
  68. def current_timestamp():
  69. return int(time.time() * 1000)
  70. def timestamp_to_date(timestamp, format_string="%Y-%m-%d %H:%M:%S"):
  71. if not timestamp:
  72. timestamp = time.time()
  73. timestamp = int(timestamp) / 1000
  74. time_array = time.localtime(timestamp)
  75. str_date = time.strftime(format_string, time_array)
  76. return str_date
  77. def date_string_to_timestamp(time_str, format_string="%Y-%m-%d %H:%M:%S"):
  78. time_array = time.strptime(time_str, format_string)
  79. time_stamp = int(time.mktime(time_array) * 1000)
  80. return time_stamp
  81. def serialize_b64(src, to_str=False):
  82. dest = base64.b64encode(pickle.dumps(src))
  83. if not to_str:
  84. return dest
  85. else:
  86. return bytes_to_string(dest)
  87. def deserialize_b64(src):
  88. src = base64.b64decode(string_to_bytes(src) if isinstance(src, str) else src)
  89. if use_deserialize_safe_module:
  90. return restricted_loads(src)
  91. return pickle.loads(src)
  92. safe_module = {
  93. 'federatedml',
  94. 'numpy',
  95. 'fate_flow'
  96. }
  97. class RestrictedUnpickler(pickle.Unpickler):
  98. def find_class(self, module, name):
  99. import importlib
  100. if module.split('.')[0] in safe_module:
  101. _module = importlib.import_module(module)
  102. return getattr(_module, name)
  103. # Forbid everything else.
  104. raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
  105. (module, name))
  106. def restricted_loads(src):
  107. """Helper function analogous to pickle.loads()."""
  108. return RestrictedUnpickler(io.BytesIO(src)).load()
  109. def get_lan_ip():
  110. if os.name != "nt":
  111. import fcntl
  112. import struct
  113. def get_interface_ip(ifname):
  114. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  115. return socket.inet_ntoa(
  116. fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', string_to_bytes(ifname[:15])))[20:24])
  117. ip = socket.gethostbyname(socket.getfqdn())
  118. if ip.startswith("127.") and os.name != "nt":
  119. interfaces = [
  120. "bond1",
  121. "eth0",
  122. "eth1",
  123. "eth2",
  124. "wlan0",
  125. "wlan1",
  126. "wifi0",
  127. "ath0",
  128. "ath1",
  129. "ppp0",
  130. ]
  131. for ifname in interfaces:
  132. try:
  133. ip = get_interface_ip(ifname)
  134. break
  135. except IOError as e:
  136. pass
  137. return ip or ''