db_models.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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 inspect
  17. import os
  18. import sys
  19. from peewee import CharField, IntegerField, BigIntegerField, TextField, CompositeKey, BooleanField
  20. from fate_arch.federation import FederationEngine
  21. from fate_arch.metastore.base_model import DateTimeField
  22. from fate_arch.common import file_utils, log, EngineType, conf_utils
  23. from fate_arch.common.conf_utils import decrypt_database_config
  24. from fate_arch.metastore.base_model import JSONField, SerializedField, BaseModel
  25. LOGGER = log.getLogger()
  26. DATABASE = decrypt_database_config()
  27. is_standalone = conf_utils.get_base_config("default_engines", {}).get(EngineType.FEDERATION).upper() == \
  28. FederationEngine.STANDALONE
  29. def singleton(cls, *args, **kw):
  30. instances = {}
  31. def _singleton():
  32. key = str(cls) + str(os.getpid())
  33. if key not in instances:
  34. instances[key] = cls(*args, **kw)
  35. return instances[key]
  36. return _singleton
  37. @singleton
  38. class BaseDataBase(object):
  39. def __init__(self):
  40. database_config = DATABASE.copy()
  41. db_name = database_config.pop("name")
  42. if is_standalone and not bool(int(os.environ.get("FORCE_USE_MYSQL", 0))):
  43. from playhouse.apsw_ext import APSWDatabase
  44. self.database_connection = APSWDatabase(file_utils.get_project_base_directory("fate_sqlite.db"))
  45. else:
  46. from playhouse.pool import PooledMySQLDatabase
  47. self.database_connection = PooledMySQLDatabase(db_name, **database_config)
  48. DB = BaseDataBase().database_connection
  49. def close_connection():
  50. try:
  51. if DB:
  52. DB.close()
  53. except Exception as e:
  54. LOGGER.exception(e)
  55. class DataBaseModel(BaseModel):
  56. class Meta:
  57. database = DB
  58. @DB.connection_context()
  59. def init_database_tables():
  60. members = inspect.getmembers(sys.modules[__name__], inspect.isclass)
  61. table_objs = []
  62. create_failed_list = []
  63. for name, obj in members:
  64. if obj != DataBaseModel and issubclass(obj, DataBaseModel):
  65. table_objs.append(obj)
  66. LOGGER.info(f"start create table {obj.__name__}")
  67. try:
  68. obj.create_table()
  69. LOGGER.info(f"create table success: {obj.__name__}")
  70. except Exception as e:
  71. LOGGER.exception(e)
  72. create_failed_list.append(obj.__name__)
  73. if create_failed_list:
  74. LOGGER.info(f"create tables failed: {create_failed_list}")
  75. raise Exception(f"create tables failed: {create_failed_list}")
  76. class StorageConnectorModel(DataBaseModel):
  77. f_name = CharField(max_length=100, primary_key=True)
  78. f_engine = CharField(max_length=100, index=True) # 'MYSQL'
  79. f_connector_info = JSONField()
  80. class Meta:
  81. db_table = "t_storage_connector"
  82. class StorageTableMetaModel(DataBaseModel):
  83. f_name = CharField(max_length=100, index=True)
  84. f_namespace = CharField(max_length=100, index=True)
  85. f_address = JSONField()
  86. f_engine = CharField(max_length=100) # 'EGGROLL', 'MYSQL'
  87. f_store_type = CharField(max_length=50, null=True) # store type
  88. f_options = JSONField()
  89. f_partitions = IntegerField(null=True)
  90. f_id_delimiter = CharField(null=True)
  91. f_in_serialized = BooleanField(default=True)
  92. f_have_head = BooleanField(default=True)
  93. f_extend_sid = BooleanField(default=False)
  94. f_auto_increasing_sid = BooleanField(default=False)
  95. f_schema = SerializedField()
  96. f_count = BigIntegerField(null=True)
  97. f_part_of_data = SerializedField()
  98. f_origin = CharField(max_length=50, default='')
  99. f_disable = BooleanField(default=False)
  100. f_description = TextField(default='')
  101. f_read_access_time = BigIntegerField(null=True)
  102. f_read_access_date = DateTimeField(null=True)
  103. f_write_access_time = BigIntegerField(null=True)
  104. f_write_access_date = DateTimeField(null=True)
  105. class Meta:
  106. db_table = "t_storage_table_meta"
  107. primary_key = CompositeKey('f_name', 'f_namespace')
  108. class SessionRecord(DataBaseModel):
  109. f_engine_session_id = CharField(max_length=150, null=False)
  110. f_manager_session_id = CharField(max_length=150, null=False)
  111. f_engine_type = CharField(max_length=10, index=True)
  112. f_engine_name = CharField(max_length=50, index=True)
  113. f_engine_address = JSONField()
  114. class Meta:
  115. db_table = "t_session_record"