service_registry.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 socket
  17. from pathlib import Path
  18. from fate_arch.common import file_utils, conf_utils
  19. from fate_arch.common.conf_utils import SERVICE_CONF
  20. from .db_models import DB, ServiceRegistryInfo, ServerRegistryInfo
  21. from .reload_config_base import ReloadConfigBase
  22. class ServiceRegistry(ReloadConfigBase):
  23. @classmethod
  24. @DB.connection_context()
  25. def load_service(cls, **kwargs) -> [ServiceRegistryInfo]:
  26. service_registry_list = ServiceRegistryInfo.query(**kwargs)
  27. return [service for service in service_registry_list]
  28. @classmethod
  29. @DB.connection_context()
  30. def save_service_info(cls, server_name, service_name, uri, method="POST", server_info=None, params=None, data=None, headers=None, protocol="http"):
  31. if not server_info:
  32. server_list = ServerRegistry.query_server_info_from_db(server_name=server_name)
  33. if not server_list:
  34. raise Exception(f"no found server {server_name}")
  35. server_info = server_list[0]
  36. url = f"{server_info.f_protocol}://{server_info.f_host}:{server_info.f_port}{uri}"
  37. else:
  38. url = f"{server_info.get('protocol', protocol)}://{server_info.get('host')}:{server_info.get('port')}{uri}"
  39. service_info = {
  40. "f_server_name": server_name,
  41. "f_service_name": service_name,
  42. "f_url": url,
  43. "f_method": method,
  44. "f_params": params if params else {},
  45. "f_data": data if data else {},
  46. "f_headers": headers if headers else {}
  47. }
  48. entity_model, status = ServiceRegistryInfo.get_or_create(
  49. f_server_name=server_name,
  50. f_service_name=service_name,
  51. defaults=service_info)
  52. if status is False:
  53. for key in service_info:
  54. setattr(entity_model, key, service_info[key])
  55. entity_model.save(force_insert=False)
  56. class ServerRegistry(ReloadConfigBase):
  57. FATEBOARD = None
  58. FATE_ON_STANDALONE = None
  59. FATE_ON_EGGROLL = None
  60. FATE_ON_SPARK = None
  61. MODEL_STORE_ADDRESS = None
  62. SERVINGS = None
  63. FATEMANAGER = None
  64. STUDIO = None
  65. @classmethod
  66. def load(cls):
  67. cls.load_server_info_from_conf()
  68. cls.load_server_info_from_db()
  69. @classmethod
  70. def load_server_info_from_conf(cls):
  71. path = Path(file_utils.get_project_base_directory()) / 'conf' / SERVICE_CONF
  72. conf = file_utils.load_yaml_conf(path)
  73. if not isinstance(conf, dict):
  74. raise ValueError('invalid config file')
  75. local_path = path.with_name(f'local.{SERVICE_CONF}')
  76. if local_path.exists():
  77. local_conf = file_utils.load_yaml_conf(local_path)
  78. if not isinstance(local_conf, dict):
  79. raise ValueError('invalid local config file')
  80. conf.update(local_conf)
  81. for k, v in conf.items():
  82. if isinstance(v, dict):
  83. setattr(cls, k.upper(), v)
  84. @classmethod
  85. def register(cls, server_name, server_info):
  86. cls.save_server_info_to_db(server_name, server_info.get("host"), server_info.get("port"), protocol=server_info.get("protocol", "http"))
  87. setattr(cls, server_name, server_info)
  88. @classmethod
  89. def save(cls, service_config):
  90. update_server = {}
  91. for server_name, server_info in service_config.items():
  92. cls.parameter_check(server_info)
  93. api_info = server_info.pop("api", {})
  94. for service_name, info in api_info.items():
  95. ServiceRegistry.save_service_info(server_name, service_name, uri=info.get('uri'), method=info.get('method', 'POST'), server_info=server_info)
  96. cls.save_server_info_to_db(server_name, server_info.get("host"), server_info.get("port"), protocol="http")
  97. setattr(cls, server_name.upper(), server_info)
  98. return update_server
  99. @classmethod
  100. def parameter_check(cls, service_info):
  101. if "host" in service_info and "port" in service_info:
  102. cls.connection_test(service_info.get("host"), service_info.get("port"))
  103. @classmethod
  104. def connection_test(cls, ip, port):
  105. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  106. result = s.connect_ex((ip, port))
  107. if result != 0:
  108. raise ConnectionRefusedError(f"connection refused: host {ip}, port {port}")
  109. @classmethod
  110. def query(cls, service_name, default=None):
  111. service_info = getattr(cls, service_name, default)
  112. if not service_info:
  113. service_info = conf_utils.get_base_config(service_name, default)
  114. return service_info
  115. @classmethod
  116. @DB.connection_context()
  117. def query_server_info_from_db(cls, server_name=None) -> [ServerRegistryInfo]:
  118. if server_name:
  119. server_list = ServerRegistryInfo.select().where(ServerRegistryInfo.f_server_name==server_name.upper())
  120. else:
  121. server_list = ServerRegistryInfo.select()
  122. return [server for server in server_list]
  123. @classmethod
  124. @DB.connection_context()
  125. def load_server_info_from_db(cls):
  126. for server in cls.query_server_info_from_db():
  127. server_info = {
  128. "host": server.f_host,
  129. "port": server.f_port,
  130. "protocol": server.f_protocol
  131. }
  132. setattr(cls, server.f_server_name.upper(), server_info)
  133. @classmethod
  134. @DB.connection_context()
  135. def save_server_info_to_db(cls, server_name, host, port, protocol="http"):
  136. server_info = {
  137. "f_server_name": server_name,
  138. "f_host": host,
  139. "f_port": port,
  140. "f_protocol": protocol
  141. }
  142. entity_model, status = ServerRegistryInfo.get_or_create(
  143. f_server_name=server_name,
  144. defaults=server_info)
  145. if status is False:
  146. for key in server_info:
  147. setattr(entity_model, key, server_info[key])
  148. entity_model.save(force_insert=False)