選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

opendal_conn.py 4.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import opendal
  2. import logging
  3. import pymysql
  4. import yaml
  5. from rag.utils import singleton
  6. SERVICE_CONF_PATH = "conf/service_conf.yaml"
  7. CREATE_TABLE_SQL = """
  8. CREATE TABLE IF NOT EXISTS `{}` (
  9. `key` VARCHAR(255) PRIMARY KEY,
  10. `value` LONGBLOB,
  11. `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  12. `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
  13. );
  14. """
  15. SET_MAX_ALLOWED_PACKET_SQL = """
  16. SET GLOBAL max_allowed_packet={}
  17. """
  18. def get_opendal_config_from_yaml(yaml_path=SERVICE_CONF_PATH):
  19. try:
  20. with open(yaml_path, 'r') as f:
  21. config = yaml.safe_load(f)
  22. opendal_config = config.get('opendal', {})
  23. kwargs = {}
  24. if opendal_config.get("scheme") == 'mysql':
  25. mysql_config = config.get('mysql', {})
  26. kwargs = {
  27. "scheme": "mysql",
  28. "host": mysql_config.get("host", "127.0.0.1"),
  29. "port": str(mysql_config.get("port", 3306)),
  30. "user": mysql_config.get("user", "root"),
  31. "password": mysql_config.get("password", ""),
  32. "database": mysql_config.get("name", "test_open_dal"),
  33. "table": opendal_config.get("config").get("table", "opendal_storage")
  34. }
  35. kwargs["connection_string"] = f"mysql://{kwargs['user']}:{kwargs['password']}@{kwargs['host']}:{kwargs['port']}/{kwargs['database']}"
  36. else:
  37. scheme = opendal_config.get("scheme")
  38. config_data = opendal_config.get("config", {})
  39. kwargs = {"scheme": scheme, **config_data}
  40. logging.info("Loaded OpenDAL configuration from yaml: %s", kwargs)
  41. return kwargs
  42. except Exception as e:
  43. logging.error("Failed to load OpenDAL configuration from yaml: %s", str(e))
  44. raise
  45. @singleton
  46. class OpenDALStorage:
  47. def __init__(self):
  48. self._kwargs = get_opendal_config_from_yaml()
  49. self._scheme = self._kwargs.get('scheme', 'mysql')
  50. if self._scheme == 'mysql':
  51. self.init_db_config()
  52. self.init_opendal_mysql_table()
  53. self._operator = opendal.Operator(**self._kwargs)
  54. logging.info("OpenDALStorage initialized successfully")
  55. def health(self):
  56. bucket, fnm, binary = "txtxtxtxt1", "txtxtxtxt1", b"_t@@@1"
  57. r = self._operator.write(f"{bucket}/{fnm}", binary)
  58. return r
  59. def put(self, bucket, fnm, binary):
  60. self._operator.write(f"{bucket}/{fnm}", binary)
  61. def get(self, bucket, fnm):
  62. return self._operator.read(f"{bucket}/{fnm}")
  63. def rm(self, bucket, fnm):
  64. self._operator.delete(f"{bucket}/{fnm}")
  65. self._operator.__init__()
  66. def scan(self, bucket, fnm):
  67. return self._operator.scan(f"{bucket}/{fnm}")
  68. def obj_exist(self, bucket, fnm):
  69. return self._operator.exists(f"{bucket}/{fnm}")
  70. def init_db_config(self):
  71. try:
  72. conn = pymysql.connect(
  73. host=self._kwargs['host'],
  74. port=int(self._kwargs['port']),
  75. user=self._kwargs['user'],
  76. password=self._kwargs['password'],
  77. database=self._kwargs['database']
  78. )
  79. cursor = conn.cursor()
  80. max_packet = self._kwargs.get('max_allowed_packet', 4194304) # Default to 4MB if not specified
  81. cursor.execute(SET_MAX_ALLOWED_PACKET_SQL, (max_packet,))
  82. conn.commit()
  83. cursor.close()
  84. conn.close()
  85. logging.info(f"Database configuration initialized with max_allowed_packet={max_packet}")
  86. except Exception as e:
  87. logging.error(f"Failed to initialize database configuration: {str(e)}")
  88. raise
  89. def init_opendal_mysql_table(self):
  90. conn = pymysql.connect(
  91. host=self._kwargs['host'],
  92. port=int(self._kwargs['port']),
  93. user=self._kwargs['user'],
  94. password=self._kwargs['password'],
  95. database=self._kwargs['database']
  96. )
  97. cursor = conn.cursor()
  98. cursor.execute(CREATE_TABLE_SQL.format(self._kwargs['table']))
  99. conn.commit()
  100. cursor.close()
  101. conn.close()
  102. logging.info(f"Table `{self._kwargs['table']}` initialized.")