plugin_migration.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. import datetime
  2. import json
  3. import logging
  4. from collections.abc import Sequence
  5. import click
  6. from flask import Flask, current_app
  7. from sqlalchemy.orm import Session
  8. from core.agent.entities import AgentToolEntity
  9. from core.entities import DEFAULT_PLUGIN_ID
  10. from core.tools.entities.tool_entities import ToolProviderType
  11. from models.account import Tenant
  12. from models.engine import db
  13. from models.model import App, AppMode, AppModelConfig
  14. from models.tools import BuiltinToolProvider
  15. from models.workflow import Workflow
  16. logger = logging.getLogger(__name__)
  17. excluded_providers = ["time", "audio", "code", "webscraper"]
  18. class PluginMigration:
  19. @classmethod
  20. def extract_plugins(cls, filepath: str, workers: int) -> None:
  21. """
  22. Migrate plugin.
  23. """
  24. import concurrent.futures
  25. from threading import Lock
  26. click.echo(click.style("Migrating models/tools to new plugin Mechanism", fg="white"))
  27. ended_at = datetime.datetime.now()
  28. started_at = datetime.datetime(2023, 4, 3, 8, 59, 24)
  29. current_time = started_at
  30. with Session(db.engine) as session:
  31. total_tenant_count = session.query(Tenant.id).count()
  32. click.echo(click.style(f"Total tenant count: {total_tenant_count}", fg="white"))
  33. handled_tenant_count = 0
  34. file_lock = Lock()
  35. counter_lock = Lock()
  36. thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=workers)
  37. def process_tenant(flask_app: Flask, tenant_id: str) -> None:
  38. with flask_app.app_context():
  39. nonlocal handled_tenant_count
  40. try:
  41. plugins = cls.extract_installed_plugin_ids(tenant_id)
  42. # Use lock when writing to file
  43. with file_lock:
  44. with open(filepath, "a") as f:
  45. f.write(json.dumps({"tenant_id": tenant_id, "plugins": plugins}) + "\n")
  46. # Use lock when updating counter
  47. with counter_lock:
  48. nonlocal handled_tenant_count
  49. handled_tenant_count += 1
  50. click.echo(
  51. click.style(
  52. f"[{datetime.datetime.now()}] "
  53. f"Processed {handled_tenant_count} tenants "
  54. f"({(handled_tenant_count / total_tenant_count) * 100:.1f}%), "
  55. f"{handled_tenant_count}/{total_tenant_count}",
  56. fg="green",
  57. )
  58. )
  59. except Exception:
  60. logger.exception(f"Failed to process tenant {tenant_id}")
  61. futures = []
  62. while current_time < ended_at:
  63. click.echo(click.style(f"Current time: {current_time}, Started at: {datetime.datetime.now()}", fg="white"))
  64. # Initial interval of 1 day, will be dynamically adjusted based on tenant count
  65. interval = datetime.timedelta(days=1)
  66. # Process tenants in this batch
  67. with Session(db.engine) as session:
  68. # Calculate tenant count in next batch with current interval
  69. # Try different intervals until we find one with a reasonable tenant count
  70. test_intervals = [
  71. datetime.timedelta(days=1),
  72. datetime.timedelta(hours=12),
  73. datetime.timedelta(hours=6),
  74. datetime.timedelta(hours=3),
  75. datetime.timedelta(hours=1),
  76. ]
  77. for test_interval in test_intervals:
  78. tenant_count = (
  79. session.query(Tenant.id)
  80. .filter(Tenant.created_at.between(current_time, current_time + test_interval))
  81. .count()
  82. )
  83. if tenant_count <= 100:
  84. interval = test_interval
  85. break
  86. else:
  87. # If all intervals have too many tenants, use minimum interval
  88. interval = datetime.timedelta(hours=1)
  89. # Adjust interval to target ~100 tenants per batch
  90. if tenant_count > 0:
  91. # Scale interval based on ratio to target count
  92. interval = min(
  93. datetime.timedelta(days=1), # Max 1 day
  94. max(
  95. datetime.timedelta(hours=1), # Min 1 hour
  96. interval * (100 / tenant_count), # Scale to target 100
  97. ),
  98. )
  99. batch_end = min(current_time + interval, ended_at)
  100. rs = (
  101. session.query(Tenant.id)
  102. .filter(Tenant.created_at.between(current_time, batch_end))
  103. .order_by(Tenant.created_at)
  104. )
  105. tenants = []
  106. for row in rs:
  107. tenant_id = str(row.id)
  108. try:
  109. tenants.append(tenant_id)
  110. except Exception:
  111. logger.exception(f"Failed to process tenant {tenant_id}")
  112. continue
  113. futures.append(
  114. thread_pool.submit(
  115. process_tenant,
  116. current_app._get_current_object(), # type: ignore[attr-defined]
  117. tenant_id,
  118. )
  119. )
  120. current_time = batch_end
  121. # wait for all threads to finish
  122. for future in futures:
  123. future.result()
  124. @classmethod
  125. def extract_installed_plugin_ids(cls, tenant_id: str) -> Sequence[str]:
  126. """
  127. Extract installed plugin ids.
  128. """
  129. tools = cls.extract_tool_tables(tenant_id)
  130. models = cls.extract_model_tables(tenant_id)
  131. workflows = cls.extract_workflow_tables(tenant_id)
  132. apps = cls.extract_app_tables(tenant_id)
  133. return list({*tools, *models, *workflows, *apps})
  134. @classmethod
  135. def extract_model_tables(cls, tenant_id: str) -> Sequence[str]:
  136. """
  137. Extract model tables.
  138. NOTE: rename google to gemini
  139. """
  140. models = []
  141. table_pairs = [
  142. ("providers", "provider_name"),
  143. ("provider_models", "provider_name"),
  144. ("provider_orders", "provider_name"),
  145. ("tenant_default_models", "provider_name"),
  146. ("tenant_preferred_model_providers", "provider_name"),
  147. ("provider_model_settings", "provider_name"),
  148. ("load_balancing_model_configs", "provider_name"),
  149. ]
  150. for table, column in table_pairs:
  151. models.extend(cls.extract_model_table(tenant_id, table, column))
  152. # duplicate models
  153. models = list(set(models))
  154. return models
  155. @classmethod
  156. def extract_model_table(cls, tenant_id: str, table: str, column: str) -> Sequence[str]:
  157. """
  158. Extract model table.
  159. """
  160. with Session(db.engine) as session:
  161. rs = session.execute(
  162. db.text(f"SELECT DISTINCT {column} FROM {table} WHERE tenant_id = :tenant_id"), {"tenant_id": tenant_id}
  163. )
  164. result = []
  165. for row in rs:
  166. provider_name = str(row[0])
  167. if provider_name and "/" not in provider_name:
  168. if provider_name == "google":
  169. provider_name = "gemini"
  170. result.append(DEFAULT_PLUGIN_ID + "/" + provider_name + "/" + provider_name)
  171. elif provider_name:
  172. result.append(provider_name)
  173. return result
  174. @classmethod
  175. def extract_tool_tables(cls, tenant_id: str) -> Sequence[str]:
  176. """
  177. Extract tool tables.
  178. """
  179. with Session(db.engine) as session:
  180. rs = session.query(BuiltinToolProvider).filter(BuiltinToolProvider.tenant_id == tenant_id).all()
  181. result = []
  182. for row in rs:
  183. if "/" not in row.provider:
  184. result.append(DEFAULT_PLUGIN_ID + "/" + row.provider + "/" + row.provider)
  185. else:
  186. result.append(row.provider)
  187. return result
  188. @classmethod
  189. def _handle_builtin_tool_provider(cls, provider_name: str) -> str:
  190. """
  191. Handle builtin tool provider.
  192. """
  193. if provider_name == "jina":
  194. provider_name = "jina_tool"
  195. elif provider_name == "siliconflow":
  196. provider_name = "siliconflow_tool"
  197. elif provider_name == "stepfun":
  198. provider_name = "stepfun_tool"
  199. if "/" not in provider_name:
  200. return DEFAULT_PLUGIN_ID + "/" + provider_name + "/" + provider_name
  201. else:
  202. return provider_name
  203. @classmethod
  204. def extract_workflow_tables(cls, tenant_id: str) -> Sequence[str]:
  205. """
  206. Extract workflow tables, only ToolNode is required.
  207. """
  208. with Session(db.engine) as session:
  209. rs = session.query(Workflow).filter(Workflow.tenant_id == tenant_id).all()
  210. result = []
  211. for row in rs:
  212. graph = row.graph_dict
  213. # get nodes
  214. nodes = graph.get("nodes", [])
  215. for node in nodes:
  216. data = node.get("data", {})
  217. if data.get("type") == "tool":
  218. provider_name = data.get("provider_name")
  219. provider_type = data.get("provider_type")
  220. if provider_name not in excluded_providers and provider_type == ToolProviderType.BUILT_IN.value:
  221. provider_name = cls._handle_builtin_tool_provider(provider_name)
  222. result.append(provider_name)
  223. return result
  224. @classmethod
  225. def extract_app_tables(cls, tenant_id: str) -> Sequence[str]:
  226. """
  227. Extract app tables.
  228. """
  229. with Session(db.engine) as session:
  230. apps = session.query(App).filter(App.tenant_id == tenant_id).all()
  231. if not apps:
  232. return []
  233. agent_app_model_config_ids = [
  234. app.app_model_config_id for app in apps if app.is_agent or app.mode == AppMode.AGENT_CHAT.value
  235. ]
  236. rs = session.query(AppModelConfig).filter(AppModelConfig.id.in_(agent_app_model_config_ids)).all()
  237. result = []
  238. for row in rs:
  239. agent_config = row.agent_mode_dict
  240. if "tools" in agent_config and isinstance(agent_config["tools"], list):
  241. for tool in agent_config["tools"]:
  242. if isinstance(tool, dict):
  243. try:
  244. tool_entity = AgentToolEntity(**tool)
  245. if (
  246. tool_entity.provider_type == ToolProviderType.BUILT_IN.value
  247. and tool_entity.provider_id not in excluded_providers
  248. ):
  249. result.append(cls._handle_builtin_tool_provider(tool_entity.provider_id))
  250. except Exception:
  251. logger.exception(f"Failed to process tool {tool}")
  252. continue
  253. return result