您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

commands.py 54KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. import base64
  2. import json
  3. import logging
  4. import operator
  5. import secrets
  6. from typing import Any
  7. import click
  8. import sqlalchemy as sa
  9. from flask import current_app
  10. from pydantic import TypeAdapter
  11. from sqlalchemy import select
  12. from sqlalchemy.exc import SQLAlchemyError
  13. from configs import dify_config
  14. from constants.languages import languages
  15. from core.plugin.entities.plugin import ToolProviderID
  16. from core.rag.datasource.vdb.vector_factory import Vector
  17. from core.rag.datasource.vdb.vector_type import VectorType
  18. from core.rag.index_processor.constant.built_in_field import BuiltInField
  19. from core.rag.models.document import Document
  20. from core.tools.utils.system_oauth_encryption import encrypt_system_oauth_params
  21. from events.app_event import app_was_created
  22. from extensions.ext_database import db
  23. from extensions.ext_redis import redis_client
  24. from extensions.ext_storage import storage
  25. from libs.helper import email as email_validate
  26. from libs.password import hash_password, password_pattern, valid_password
  27. from libs.rsa import generate_key_pair
  28. from models import Tenant
  29. from models.dataset import Dataset, DatasetCollectionBinding, DatasetMetadata, DatasetMetadataBinding, DocumentSegment
  30. from models.dataset import Document as DatasetDocument
  31. from models.model import Account, App, AppAnnotationSetting, AppMode, Conversation, MessageAnnotation
  32. from models.provider import Provider, ProviderModel
  33. from models.tools import ToolOAuthSystemClient
  34. from services.account_service import AccountService, RegisterService, TenantService
  35. from services.clear_free_plan_tenant_expired_logs import ClearFreePlanTenantExpiredLogs
  36. from services.plugin.data_migration import PluginDataMigration
  37. from services.plugin.plugin_migration import PluginMigration
  38. from tasks.remove_app_and_related_data_task import delete_draft_variables_batch
  39. logger = logging.getLogger(__name__)
  40. @click.command("reset-password", help="Reset the account password.")
  41. @click.option("--email", prompt=True, help="Account email to reset password for")
  42. @click.option("--new-password", prompt=True, help="New password")
  43. @click.option("--password-confirm", prompt=True, help="Confirm new password")
  44. def reset_password(email, new_password, password_confirm):
  45. """
  46. Reset password of owner account
  47. Only available in SELF_HOSTED mode
  48. """
  49. if str(new_password).strip() != str(password_confirm).strip():
  50. click.echo(click.style("Passwords do not match.", fg="red"))
  51. return
  52. account = db.session.query(Account).where(Account.email == email).one_or_none()
  53. if not account:
  54. click.echo(click.style(f"Account not found for email: {email}", fg="red"))
  55. return
  56. try:
  57. valid_password(new_password)
  58. except:
  59. click.echo(click.style(f"Invalid password. Must match {password_pattern}", fg="red"))
  60. return
  61. # generate password salt
  62. salt = secrets.token_bytes(16)
  63. base64_salt = base64.b64encode(salt).decode()
  64. # encrypt password with salt
  65. password_hashed = hash_password(new_password, salt)
  66. base64_password_hashed = base64.b64encode(password_hashed).decode()
  67. account.password = base64_password_hashed
  68. account.password_salt = base64_salt
  69. db.session.commit()
  70. AccountService.reset_login_error_rate_limit(email)
  71. click.echo(click.style("Password reset successfully.", fg="green"))
  72. @click.command("reset-email", help="Reset the account email.")
  73. @click.option("--email", prompt=True, help="Current account email")
  74. @click.option("--new-email", prompt=True, help="New email")
  75. @click.option("--email-confirm", prompt=True, help="Confirm new email")
  76. def reset_email(email, new_email, email_confirm):
  77. """
  78. Replace account email
  79. :return:
  80. """
  81. if str(new_email).strip() != str(email_confirm).strip():
  82. click.echo(click.style("New emails do not match.", fg="red"))
  83. return
  84. account = db.session.query(Account).where(Account.email == email).one_or_none()
  85. if not account:
  86. click.echo(click.style(f"Account not found for email: {email}", fg="red"))
  87. return
  88. try:
  89. email_validate(new_email)
  90. except:
  91. click.echo(click.style(f"Invalid email: {new_email}", fg="red"))
  92. return
  93. account.email = new_email
  94. db.session.commit()
  95. click.echo(click.style("Email updated successfully.", fg="green"))
  96. @click.command(
  97. "reset-encrypt-key-pair",
  98. help="Reset the asymmetric key pair of workspace for encrypt LLM credentials. "
  99. "After the reset, all LLM credentials will become invalid, "
  100. "requiring re-entry."
  101. "Only support SELF_HOSTED mode.",
  102. )
  103. @click.confirmation_option(
  104. prompt=click.style(
  105. "Are you sure you want to reset encrypt key pair? This operation cannot be rolled back!", fg="red"
  106. )
  107. )
  108. def reset_encrypt_key_pair():
  109. """
  110. Reset the encrypted key pair of workspace for encrypt LLM credentials.
  111. After the reset, all LLM credentials will become invalid, requiring re-entry.
  112. Only support SELF_HOSTED mode.
  113. """
  114. if dify_config.EDITION != "SELF_HOSTED":
  115. click.echo(click.style("This command is only for SELF_HOSTED installations.", fg="red"))
  116. return
  117. tenants = db.session.query(Tenant).all()
  118. for tenant in tenants:
  119. if not tenant:
  120. click.echo(click.style("No workspaces found. Run /install first.", fg="red"))
  121. return
  122. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  123. db.session.query(Provider).where(Provider.provider_type == "custom", Provider.tenant_id == tenant.id).delete()
  124. db.session.query(ProviderModel).where(ProviderModel.tenant_id == tenant.id).delete()
  125. db.session.commit()
  126. click.echo(
  127. click.style(
  128. f"Congratulations! The asymmetric key pair of workspace {tenant.id} has been reset.",
  129. fg="green",
  130. )
  131. )
  132. @click.command("vdb-migrate", help="Migrate vector db.")
  133. @click.option("--scope", default="all", prompt=False, help="The scope of vector database to migrate, Default is All.")
  134. def vdb_migrate(scope: str):
  135. if scope in {"knowledge", "all"}:
  136. migrate_knowledge_vector_database()
  137. if scope in {"annotation", "all"}:
  138. migrate_annotation_vector_database()
  139. def migrate_annotation_vector_database():
  140. """
  141. Migrate annotation datas to target vector database .
  142. """
  143. click.echo(click.style("Starting annotation data migration.", fg="green"))
  144. create_count = 0
  145. skipped_count = 0
  146. total_count = 0
  147. page = 1
  148. while True:
  149. try:
  150. # get apps info
  151. per_page = 50
  152. apps = (
  153. db.session.query(App)
  154. .where(App.status == "normal")
  155. .order_by(App.created_at.desc())
  156. .limit(per_page)
  157. .offset((page - 1) * per_page)
  158. .all()
  159. )
  160. if not apps:
  161. break
  162. except SQLAlchemyError:
  163. raise
  164. page += 1
  165. for app in apps:
  166. total_count = total_count + 1
  167. click.echo(
  168. f"Processing the {total_count} app {app.id}. " + f"{create_count} created, {skipped_count} skipped."
  169. )
  170. try:
  171. click.echo(f"Creating app annotation index: {app.id}")
  172. app_annotation_setting = (
  173. db.session.query(AppAnnotationSetting).where(AppAnnotationSetting.app_id == app.id).first()
  174. )
  175. if not app_annotation_setting:
  176. skipped_count = skipped_count + 1
  177. click.echo(f"App annotation setting disabled: {app.id}")
  178. continue
  179. # get dataset_collection_binding info
  180. dataset_collection_binding = (
  181. db.session.query(DatasetCollectionBinding)
  182. .where(DatasetCollectionBinding.id == app_annotation_setting.collection_binding_id)
  183. .first()
  184. )
  185. if not dataset_collection_binding:
  186. click.echo(f"App annotation collection binding not found: {app.id}")
  187. continue
  188. annotations = db.session.scalars(
  189. select(MessageAnnotation).where(MessageAnnotation.app_id == app.id)
  190. ).all()
  191. dataset = Dataset(
  192. id=app.id,
  193. tenant_id=app.tenant_id,
  194. indexing_technique="high_quality",
  195. embedding_model_provider=dataset_collection_binding.provider_name,
  196. embedding_model=dataset_collection_binding.model_name,
  197. collection_binding_id=dataset_collection_binding.id,
  198. )
  199. documents = []
  200. if annotations:
  201. for annotation in annotations:
  202. document = Document(
  203. page_content=annotation.question,
  204. metadata={"annotation_id": annotation.id, "app_id": app.id, "doc_id": annotation.id},
  205. )
  206. documents.append(document)
  207. vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"])
  208. click.echo(f"Migrating annotations for app: {app.id}.")
  209. try:
  210. vector.delete()
  211. click.echo(click.style(f"Deleted vector index for app {app.id}.", fg="green"))
  212. except Exception as e:
  213. click.echo(click.style(f"Failed to delete vector index for app {app.id}.", fg="red"))
  214. raise e
  215. if documents:
  216. try:
  217. click.echo(
  218. click.style(
  219. f"Creating vector index with {len(documents)} annotations for app {app.id}.",
  220. fg="green",
  221. )
  222. )
  223. vector.create(documents)
  224. click.echo(click.style(f"Created vector index for app {app.id}.", fg="green"))
  225. except Exception as e:
  226. click.echo(click.style(f"Failed to created vector index for app {app.id}.", fg="red"))
  227. raise e
  228. click.echo(f"Successfully migrated app annotation {app.id}.")
  229. create_count += 1
  230. except Exception as e:
  231. click.echo(
  232. click.style(f"Error creating app annotation index: {e.__class__.__name__} {str(e)}", fg="red")
  233. )
  234. continue
  235. click.echo(
  236. click.style(
  237. f"Migration complete. Created {create_count} app annotation indexes. Skipped {skipped_count} apps.",
  238. fg="green",
  239. )
  240. )
  241. def migrate_knowledge_vector_database():
  242. """
  243. Migrate vector database datas to target vector database .
  244. """
  245. click.echo(click.style("Starting vector database migration.", fg="green"))
  246. create_count = 0
  247. skipped_count = 0
  248. total_count = 0
  249. vector_type = dify_config.VECTOR_STORE
  250. upper_collection_vector_types = {
  251. VectorType.MILVUS,
  252. VectorType.PGVECTOR,
  253. VectorType.VASTBASE,
  254. VectorType.RELYT,
  255. VectorType.WEAVIATE,
  256. VectorType.ORACLE,
  257. VectorType.ELASTICSEARCH,
  258. VectorType.OPENGAUSS,
  259. VectorType.TABLESTORE,
  260. VectorType.MATRIXONE,
  261. }
  262. lower_collection_vector_types = {
  263. VectorType.ANALYTICDB,
  264. VectorType.CHROMA,
  265. VectorType.MYSCALE,
  266. VectorType.PGVECTO_RS,
  267. VectorType.TIDB_VECTOR,
  268. VectorType.OPENSEARCH,
  269. VectorType.TENCENT,
  270. VectorType.BAIDU,
  271. VectorType.VIKINGDB,
  272. VectorType.UPSTASH,
  273. VectorType.COUCHBASE,
  274. VectorType.OCEANBASE,
  275. }
  276. page = 1
  277. while True:
  278. try:
  279. stmt = (
  280. select(Dataset).where(Dataset.indexing_technique == "high_quality").order_by(Dataset.created_at.desc())
  281. )
  282. datasets = db.paginate(select=stmt, page=page, per_page=50, max_per_page=50, error_out=False)
  283. except SQLAlchemyError:
  284. raise
  285. page += 1
  286. for dataset in datasets:
  287. total_count = total_count + 1
  288. click.echo(
  289. f"Processing the {total_count} dataset {dataset.id}. {create_count} created, {skipped_count} skipped."
  290. )
  291. try:
  292. click.echo(f"Creating dataset vector database index: {dataset.id}")
  293. if dataset.index_struct_dict:
  294. if dataset.index_struct_dict["type"] == vector_type:
  295. skipped_count = skipped_count + 1
  296. continue
  297. collection_name = ""
  298. dataset_id = dataset.id
  299. if vector_type in upper_collection_vector_types:
  300. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  301. elif vector_type == VectorType.QDRANT:
  302. if dataset.collection_binding_id:
  303. dataset_collection_binding = (
  304. db.session.query(DatasetCollectionBinding)
  305. .where(DatasetCollectionBinding.id == dataset.collection_binding_id)
  306. .one_or_none()
  307. )
  308. if dataset_collection_binding:
  309. collection_name = dataset_collection_binding.collection_name
  310. else:
  311. raise ValueError("Dataset Collection Binding not found")
  312. else:
  313. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  314. elif vector_type in lower_collection_vector_types:
  315. collection_name = Dataset.gen_collection_name_by_id(dataset_id).lower()
  316. else:
  317. raise ValueError(f"Vector store {vector_type} is not supported.")
  318. index_struct_dict = {"type": vector_type, "vector_store": {"class_prefix": collection_name}}
  319. dataset.index_struct = json.dumps(index_struct_dict)
  320. vector = Vector(dataset)
  321. click.echo(f"Migrating dataset {dataset.id}.")
  322. try:
  323. vector.delete()
  324. click.echo(
  325. click.style(f"Deleted vector index {collection_name} for dataset {dataset.id}.", fg="green")
  326. )
  327. except Exception as e:
  328. click.echo(
  329. click.style(
  330. f"Failed to delete vector index {collection_name} for dataset {dataset.id}.", fg="red"
  331. )
  332. )
  333. raise e
  334. dataset_documents = db.session.scalars(
  335. select(DatasetDocument).where(
  336. DatasetDocument.dataset_id == dataset.id,
  337. DatasetDocument.indexing_status == "completed",
  338. DatasetDocument.enabled == True,
  339. DatasetDocument.archived == False,
  340. )
  341. ).all()
  342. documents = []
  343. segments_count = 0
  344. for dataset_document in dataset_documents:
  345. segments = db.session.scalars(
  346. select(DocumentSegment).where(
  347. DocumentSegment.document_id == dataset_document.id,
  348. DocumentSegment.status == "completed",
  349. DocumentSegment.enabled == True,
  350. )
  351. ).all()
  352. for segment in segments:
  353. document = Document(
  354. page_content=segment.content,
  355. metadata={
  356. "doc_id": segment.index_node_id,
  357. "doc_hash": segment.index_node_hash,
  358. "document_id": segment.document_id,
  359. "dataset_id": segment.dataset_id,
  360. },
  361. )
  362. documents.append(document)
  363. segments_count = segments_count + 1
  364. if documents:
  365. try:
  366. click.echo(
  367. click.style(
  368. f"Creating vector index with {len(documents)} documents of {segments_count}"
  369. f" segments for dataset {dataset.id}.",
  370. fg="green",
  371. )
  372. )
  373. vector.create(documents)
  374. click.echo(click.style(f"Created vector index for dataset {dataset.id}.", fg="green"))
  375. except Exception as e:
  376. click.echo(click.style(f"Failed to created vector index for dataset {dataset.id}.", fg="red"))
  377. raise e
  378. db.session.add(dataset)
  379. db.session.commit()
  380. click.echo(f"Successfully migrated dataset {dataset.id}.")
  381. create_count += 1
  382. except Exception as e:
  383. db.session.rollback()
  384. click.echo(click.style(f"Error creating dataset index: {e.__class__.__name__} {str(e)}", fg="red"))
  385. continue
  386. click.echo(
  387. click.style(
  388. f"Migration complete. Created {create_count} dataset indexes. Skipped {skipped_count} datasets.", fg="green"
  389. )
  390. )
  391. @click.command("convert-to-agent-apps", help="Convert Agent Assistant to Agent App.")
  392. def convert_to_agent_apps():
  393. """
  394. Convert Agent Assistant to Agent App.
  395. """
  396. click.echo(click.style("Starting convert to agent apps.", fg="green"))
  397. proceeded_app_ids = []
  398. while True:
  399. # fetch first 1000 apps
  400. sql_query = """SELECT a.id AS id FROM apps a
  401. INNER JOIN app_model_configs am ON a.app_model_config_id=am.id
  402. WHERE a.mode = 'chat'
  403. AND am.agent_mode is not null
  404. AND (
  405. am.agent_mode like '%"strategy": "function_call"%'
  406. OR am.agent_mode like '%"strategy": "react"%'
  407. )
  408. AND (
  409. am.agent_mode like '{"enabled": true%'
  410. OR am.agent_mode like '{"max_iteration": %'
  411. ) ORDER BY a.created_at DESC LIMIT 1000
  412. """
  413. with db.engine.begin() as conn:
  414. rs = conn.execute(sa.text(sql_query))
  415. apps = []
  416. for i in rs:
  417. app_id = str(i.id)
  418. if app_id not in proceeded_app_ids:
  419. proceeded_app_ids.append(app_id)
  420. app = db.session.query(App).where(App.id == app_id).first()
  421. if app is not None:
  422. apps.append(app)
  423. if len(apps) == 0:
  424. break
  425. for app in apps:
  426. click.echo(f"Converting app: {app.id}")
  427. try:
  428. app.mode = AppMode.AGENT_CHAT
  429. db.session.commit()
  430. # update conversation mode to agent
  431. db.session.query(Conversation).where(Conversation.app_id == app.id).update(
  432. {Conversation.mode: AppMode.AGENT_CHAT}
  433. )
  434. db.session.commit()
  435. click.echo(click.style(f"Converted app: {app.id}", fg="green"))
  436. except Exception as e:
  437. click.echo(click.style(f"Convert app error: {e.__class__.__name__} {str(e)}", fg="red"))
  438. click.echo(click.style(f"Conversion complete. Converted {len(proceeded_app_ids)} agent apps.", fg="green"))
  439. @click.command("add-qdrant-index", help="Add Qdrant index.")
  440. @click.option("--field", default="metadata.doc_id", prompt=False, help="Index field , default is metadata.doc_id.")
  441. def add_qdrant_index(field: str):
  442. click.echo(click.style("Starting Qdrant index creation.", fg="green"))
  443. create_count = 0
  444. try:
  445. bindings = db.session.query(DatasetCollectionBinding).all()
  446. if not bindings:
  447. click.echo(click.style("No dataset collection bindings found.", fg="red"))
  448. return
  449. import qdrant_client
  450. from qdrant_client.http.exceptions import UnexpectedResponse
  451. from qdrant_client.http.models import PayloadSchemaType
  452. from core.rag.datasource.vdb.qdrant.qdrant_vector import PathQdrantParams, QdrantConfig
  453. for binding in bindings:
  454. if dify_config.QDRANT_URL is None:
  455. raise ValueError("Qdrant URL is required.")
  456. qdrant_config = QdrantConfig(
  457. endpoint=dify_config.QDRANT_URL,
  458. api_key=dify_config.QDRANT_API_KEY,
  459. root_path=current_app.root_path,
  460. timeout=dify_config.QDRANT_CLIENT_TIMEOUT,
  461. grpc_port=dify_config.QDRANT_GRPC_PORT,
  462. prefer_grpc=dify_config.QDRANT_GRPC_ENABLED,
  463. )
  464. try:
  465. params = qdrant_config.to_qdrant_params()
  466. # Check the type before using
  467. if isinstance(params, PathQdrantParams):
  468. # PathQdrantParams case
  469. client = qdrant_client.QdrantClient(path=params.path)
  470. else:
  471. # UrlQdrantParams case - params is UrlQdrantParams
  472. client = qdrant_client.QdrantClient(
  473. url=params.url,
  474. api_key=params.api_key,
  475. timeout=int(params.timeout),
  476. verify=params.verify,
  477. grpc_port=params.grpc_port,
  478. prefer_grpc=params.prefer_grpc,
  479. )
  480. # create payload index
  481. client.create_payload_index(binding.collection_name, field, field_schema=PayloadSchemaType.KEYWORD)
  482. create_count += 1
  483. except UnexpectedResponse as e:
  484. # Collection does not exist, so return
  485. if e.status_code == 404:
  486. click.echo(click.style(f"Collection not found: {binding.collection_name}.", fg="red"))
  487. continue
  488. # Some other error occurred, so re-raise the exception
  489. else:
  490. click.echo(
  491. click.style(
  492. f"Failed to create Qdrant index for collection: {binding.collection_name}.", fg="red"
  493. )
  494. )
  495. except Exception:
  496. click.echo(click.style("Failed to create Qdrant client.", fg="red"))
  497. click.echo(click.style(f"Index creation complete. Created {create_count} collection indexes.", fg="green"))
  498. @click.command("old-metadata-migration", help="Old metadata migration.")
  499. def old_metadata_migration():
  500. """
  501. Old metadata migration.
  502. """
  503. click.echo(click.style("Starting old metadata migration.", fg="green"))
  504. page = 1
  505. while True:
  506. try:
  507. stmt = (
  508. select(DatasetDocument)
  509. .where(DatasetDocument.doc_metadata.is_not(None))
  510. .order_by(DatasetDocument.created_at.desc())
  511. )
  512. documents = db.paginate(select=stmt, page=page, per_page=50, max_per_page=50, error_out=False)
  513. except SQLAlchemyError:
  514. raise
  515. if not documents:
  516. break
  517. for document in documents:
  518. if document.doc_metadata:
  519. doc_metadata = document.doc_metadata
  520. for key in doc_metadata:
  521. for field in BuiltInField:
  522. if field.value == key:
  523. break
  524. else:
  525. dataset_metadata = (
  526. db.session.query(DatasetMetadata)
  527. .where(DatasetMetadata.dataset_id == document.dataset_id, DatasetMetadata.name == key)
  528. .first()
  529. )
  530. if not dataset_metadata:
  531. dataset_metadata = DatasetMetadata(
  532. tenant_id=document.tenant_id,
  533. dataset_id=document.dataset_id,
  534. name=key,
  535. type="string",
  536. created_by=document.created_by,
  537. )
  538. db.session.add(dataset_metadata)
  539. db.session.flush()
  540. dataset_metadata_binding = DatasetMetadataBinding(
  541. tenant_id=document.tenant_id,
  542. dataset_id=document.dataset_id,
  543. metadata_id=dataset_metadata.id,
  544. document_id=document.id,
  545. created_by=document.created_by,
  546. )
  547. db.session.add(dataset_metadata_binding)
  548. else:
  549. dataset_metadata_binding = (
  550. db.session.query(DatasetMetadataBinding) # type: ignore
  551. .where(
  552. DatasetMetadataBinding.dataset_id == document.dataset_id,
  553. DatasetMetadataBinding.document_id == document.id,
  554. DatasetMetadataBinding.metadata_id == dataset_metadata.id,
  555. )
  556. .first()
  557. )
  558. if not dataset_metadata_binding:
  559. dataset_metadata_binding = DatasetMetadataBinding(
  560. tenant_id=document.tenant_id,
  561. dataset_id=document.dataset_id,
  562. metadata_id=dataset_metadata.id,
  563. document_id=document.id,
  564. created_by=document.created_by,
  565. )
  566. db.session.add(dataset_metadata_binding)
  567. db.session.commit()
  568. page += 1
  569. click.echo(click.style("Old metadata migration completed.", fg="green"))
  570. @click.command("create-tenant", help="Create account and tenant.")
  571. @click.option("--email", prompt=True, help="Tenant account email.")
  572. @click.option("--name", prompt=True, help="Workspace name.")
  573. @click.option("--language", prompt=True, help="Account language, default: en-US.")
  574. def create_tenant(email: str, language: str | None = None, name: str | None = None):
  575. """
  576. Create tenant account
  577. """
  578. if not email:
  579. click.echo(click.style("Email is required.", fg="red"))
  580. return
  581. # Create account
  582. email = email.strip()
  583. if "@" not in email:
  584. click.echo(click.style("Invalid email address.", fg="red"))
  585. return
  586. account_name = email.split("@")[0]
  587. if language not in languages:
  588. language = "en-US"
  589. # Validates name encoding for non-Latin characters.
  590. name = name.strip().encode("utf-8").decode("utf-8") if name else None
  591. # generate random password
  592. new_password = secrets.token_urlsafe(16)
  593. # register account
  594. account = RegisterService.register(
  595. email=email,
  596. name=account_name,
  597. password=new_password,
  598. language=language,
  599. create_workspace_required=False,
  600. )
  601. TenantService.create_owner_tenant_if_not_exist(account, name)
  602. click.echo(
  603. click.style(
  604. f"Account and tenant created.\nAccount: {email}\nPassword: {new_password}",
  605. fg="green",
  606. )
  607. )
  608. @click.command("upgrade-db", help="Upgrade the database")
  609. def upgrade_db():
  610. click.echo("Preparing database migration...")
  611. lock = redis_client.lock(name="db_upgrade_lock", timeout=60)
  612. if lock.acquire(blocking=False):
  613. try:
  614. click.echo(click.style("Starting database migration.", fg="green"))
  615. # run db migration
  616. import flask_migrate
  617. flask_migrate.upgrade()
  618. click.echo(click.style("Database migration successful!", fg="green"))
  619. except Exception:
  620. logger.exception("Failed to execute database migration")
  621. finally:
  622. lock.release()
  623. else:
  624. click.echo("Database migration skipped")
  625. @click.command("fix-app-site-missing", help="Fix app related site missing issue.")
  626. def fix_app_site_missing():
  627. """
  628. Fix app related site missing issue.
  629. """
  630. click.echo(click.style("Starting fix for missing app-related sites.", fg="green"))
  631. failed_app_ids = []
  632. while True:
  633. sql = """select apps.id as id from apps left join sites on sites.app_id=apps.id
  634. where sites.id is null limit 1000"""
  635. with db.engine.begin() as conn:
  636. rs = conn.execute(sa.text(sql))
  637. processed_count = 0
  638. for i in rs:
  639. processed_count += 1
  640. app_id = str(i.id)
  641. if app_id in failed_app_ids:
  642. continue
  643. try:
  644. app = db.session.query(App).where(App.id == app_id).first()
  645. if not app:
  646. print(f"App {app_id} not found")
  647. continue
  648. tenant = app.tenant
  649. if tenant:
  650. accounts = tenant.get_accounts()
  651. if not accounts:
  652. print(f"Fix failed for app {app.id}")
  653. continue
  654. account = accounts[0]
  655. print(f"Fixing missing site for app {app.id}")
  656. app_was_created.send(app, account=account)
  657. except Exception:
  658. failed_app_ids.append(app_id)
  659. click.echo(click.style(f"Failed to fix missing site for app {app_id}", fg="red"))
  660. logger.exception("Failed to fix app related site missing issue, app_id: %s", app_id)
  661. continue
  662. if not processed_count:
  663. break
  664. click.echo(click.style("Fix for missing app-related sites completed successfully!", fg="green"))
  665. @click.command("migrate-data-for-plugin", help="Migrate data for plugin.")
  666. def migrate_data_for_plugin():
  667. """
  668. Migrate data for plugin.
  669. """
  670. click.echo(click.style("Starting migrate data for plugin.", fg="white"))
  671. PluginDataMigration.migrate()
  672. click.echo(click.style("Migrate data for plugin completed.", fg="green"))
  673. @click.command("extract-plugins", help="Extract plugins.")
  674. @click.option("--output_file", prompt=True, help="The file to store the extracted plugins.", default="plugins.jsonl")
  675. @click.option("--workers", prompt=True, help="The number of workers to extract plugins.", default=10)
  676. def extract_plugins(output_file: str, workers: int):
  677. """
  678. Extract plugins.
  679. """
  680. click.echo(click.style("Starting extract plugins.", fg="white"))
  681. PluginMigration.extract_plugins(output_file, workers)
  682. click.echo(click.style("Extract plugins completed.", fg="green"))
  683. @click.command("extract-unique-identifiers", help="Extract unique identifiers.")
  684. @click.option(
  685. "--output_file",
  686. prompt=True,
  687. help="The file to store the extracted unique identifiers.",
  688. default="unique_identifiers.json",
  689. )
  690. @click.option(
  691. "--input_file", prompt=True, help="The file to store the extracted unique identifiers.", default="plugins.jsonl"
  692. )
  693. def extract_unique_plugins(output_file: str, input_file: str):
  694. """
  695. Extract unique plugins.
  696. """
  697. click.echo(click.style("Starting extract unique plugins.", fg="white"))
  698. PluginMigration.extract_unique_plugins_to_file(input_file, output_file)
  699. click.echo(click.style("Extract unique plugins completed.", fg="green"))
  700. @click.command("install-plugins", help="Install plugins.")
  701. @click.option(
  702. "--input_file", prompt=True, help="The file to store the extracted unique identifiers.", default="plugins.jsonl"
  703. )
  704. @click.option(
  705. "--output_file", prompt=True, help="The file to store the installed plugins.", default="installed_plugins.jsonl"
  706. )
  707. @click.option("--workers", prompt=True, help="The number of workers to install plugins.", default=100)
  708. def install_plugins(input_file: str, output_file: str, workers: int):
  709. """
  710. Install plugins.
  711. """
  712. click.echo(click.style("Starting install plugins.", fg="white"))
  713. PluginMigration.install_plugins(input_file, output_file, workers)
  714. click.echo(click.style("Install plugins completed.", fg="green"))
  715. @click.command("clear-free-plan-tenant-expired-logs", help="Clear free plan tenant expired logs.")
  716. @click.option("--days", prompt=True, help="The days to clear free plan tenant expired logs.", default=30)
  717. @click.option("--batch", prompt=True, help="The batch size to clear free plan tenant expired logs.", default=100)
  718. @click.option(
  719. "--tenant_ids",
  720. prompt=True,
  721. multiple=True,
  722. help="The tenant ids to clear free plan tenant expired logs.",
  723. )
  724. def clear_free_plan_tenant_expired_logs(days: int, batch: int, tenant_ids: list[str]):
  725. """
  726. Clear free plan tenant expired logs.
  727. """
  728. click.echo(click.style("Starting clear free plan tenant expired logs.", fg="white"))
  729. ClearFreePlanTenantExpiredLogs.process(days, batch, tenant_ids)
  730. click.echo(click.style("Clear free plan tenant expired logs completed.", fg="green"))
  731. @click.option("-f", "--force", is_flag=True, help="Skip user confirmation and force the command to execute.")
  732. @click.command("clear-orphaned-file-records", help="Clear orphaned file records.")
  733. def clear_orphaned_file_records(force: bool):
  734. """
  735. Clear orphaned file records in the database.
  736. """
  737. # define tables and columns to process
  738. files_tables = [
  739. {"table": "upload_files", "id_column": "id", "key_column": "key"},
  740. {"table": "tool_files", "id_column": "id", "key_column": "file_key"},
  741. ]
  742. ids_tables = [
  743. {"type": "uuid", "table": "message_files", "column": "upload_file_id"},
  744. {"type": "text", "table": "documents", "column": "data_source_info"},
  745. {"type": "text", "table": "document_segments", "column": "content"},
  746. {"type": "text", "table": "messages", "column": "answer"},
  747. {"type": "text", "table": "workflow_node_executions", "column": "inputs"},
  748. {"type": "text", "table": "workflow_node_executions", "column": "process_data"},
  749. {"type": "text", "table": "workflow_node_executions", "column": "outputs"},
  750. {"type": "text", "table": "conversations", "column": "introduction"},
  751. {"type": "text", "table": "conversations", "column": "system_instruction"},
  752. {"type": "text", "table": "accounts", "column": "avatar"},
  753. {"type": "text", "table": "apps", "column": "icon"},
  754. {"type": "text", "table": "sites", "column": "icon"},
  755. {"type": "json", "table": "messages", "column": "inputs"},
  756. {"type": "json", "table": "messages", "column": "message"},
  757. ]
  758. # notify user and ask for confirmation
  759. click.echo(
  760. click.style(
  761. "This command will first find and delete orphaned file records from the message_files table,", fg="yellow"
  762. )
  763. )
  764. click.echo(
  765. click.style(
  766. "and then it will find and delete orphaned file records in the following tables:",
  767. fg="yellow",
  768. )
  769. )
  770. for files_table in files_tables:
  771. click.echo(click.style(f"- {files_table['table']}", fg="yellow"))
  772. click.echo(
  773. click.style("The following tables and columns will be scanned to find orphaned file records:", fg="yellow")
  774. )
  775. for ids_table in ids_tables:
  776. click.echo(click.style(f"- {ids_table['table']} ({ids_table['column']})", fg="yellow"))
  777. click.echo("")
  778. click.echo(click.style("!!! USE WITH CAUTION !!!", fg="red"))
  779. click.echo(
  780. click.style(
  781. (
  782. "Since not all patterns have been fully tested, "
  783. "please note that this command may delete unintended file records."
  784. ),
  785. fg="yellow",
  786. )
  787. )
  788. click.echo(
  789. click.style("This cannot be undone. Please make sure to back up your database before proceeding.", fg="yellow")
  790. )
  791. click.echo(
  792. click.style(
  793. (
  794. "It is also recommended to run this during the maintenance window, "
  795. "as this may cause high load on your instance."
  796. ),
  797. fg="yellow",
  798. )
  799. )
  800. if not force:
  801. click.confirm("Do you want to proceed?", abort=True)
  802. # start the cleanup process
  803. click.echo(click.style("Starting orphaned file records cleanup.", fg="white"))
  804. # clean up the orphaned records in the message_files table where message_id doesn't exist in messages table
  805. try:
  806. click.echo(
  807. click.style("- Listing message_files records where message_id doesn't exist in messages table", fg="white")
  808. )
  809. query = (
  810. "SELECT mf.id, mf.message_id "
  811. "FROM message_files mf LEFT JOIN messages m ON mf.message_id = m.id "
  812. "WHERE m.id IS NULL"
  813. )
  814. orphaned_message_files = []
  815. with db.engine.begin() as conn:
  816. rs = conn.execute(sa.text(query))
  817. for i in rs:
  818. orphaned_message_files.append({"id": str(i[0]), "message_id": str(i[1])})
  819. if orphaned_message_files:
  820. click.echo(click.style(f"Found {len(orphaned_message_files)} orphaned message_files records:", fg="white"))
  821. for record in orphaned_message_files:
  822. click.echo(click.style(f" - id: {record['id']}, message_id: {record['message_id']}", fg="black"))
  823. if not force:
  824. click.confirm(
  825. (
  826. f"Do you want to proceed "
  827. f"to delete all {len(orphaned_message_files)} orphaned message_files records?"
  828. ),
  829. abort=True,
  830. )
  831. click.echo(click.style("- Deleting orphaned message_files records", fg="white"))
  832. query = "DELETE FROM message_files WHERE id IN :ids"
  833. with db.engine.begin() as conn:
  834. conn.execute(sa.text(query), {"ids": tuple(record["id"] for record in orphaned_message_files)})
  835. click.echo(
  836. click.style(f"Removed {len(orphaned_message_files)} orphaned message_files records.", fg="green")
  837. )
  838. else:
  839. click.echo(click.style("No orphaned message_files records found. There is nothing to delete.", fg="green"))
  840. except Exception as e:
  841. click.echo(click.style(f"Error deleting orphaned message_files records: {str(e)}", fg="red"))
  842. # clean up the orphaned records in the rest of the *_files tables
  843. try:
  844. # fetch file id and keys from each table
  845. all_files_in_tables = []
  846. for files_table in files_tables:
  847. click.echo(click.style(f"- Listing file records in table {files_table['table']}", fg="white"))
  848. query = f"SELECT {files_table['id_column']}, {files_table['key_column']} FROM {files_table['table']}"
  849. with db.engine.begin() as conn:
  850. rs = conn.execute(sa.text(query))
  851. for i in rs:
  852. all_files_in_tables.append({"table": files_table["table"], "id": str(i[0]), "key": i[1]})
  853. click.echo(click.style(f"Found {len(all_files_in_tables)} files in tables.", fg="white"))
  854. # fetch referred table and columns
  855. guid_regexp = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"
  856. all_ids_in_tables = []
  857. for ids_table in ids_tables:
  858. query = ""
  859. if ids_table["type"] == "uuid":
  860. click.echo(
  861. click.style(
  862. f"- Listing file ids in column {ids_table['column']} in table {ids_table['table']}", fg="white"
  863. )
  864. )
  865. query = (
  866. f"SELECT {ids_table['column']} FROM {ids_table['table']} WHERE {ids_table['column']} IS NOT NULL"
  867. )
  868. with db.engine.begin() as conn:
  869. rs = conn.execute(sa.text(query))
  870. for i in rs:
  871. all_ids_in_tables.append({"table": ids_table["table"], "id": str(i[0])})
  872. elif ids_table["type"] == "text":
  873. click.echo(
  874. click.style(
  875. f"- Listing file-id-like strings in column {ids_table['column']} in table {ids_table['table']}",
  876. fg="white",
  877. )
  878. )
  879. query = (
  880. f"SELECT regexp_matches({ids_table['column']}, '{guid_regexp}', 'g') AS extracted_id "
  881. f"FROM {ids_table['table']}"
  882. )
  883. with db.engine.begin() as conn:
  884. rs = conn.execute(sa.text(query))
  885. for i in rs:
  886. for j in i[0]:
  887. all_ids_in_tables.append({"table": ids_table["table"], "id": j})
  888. elif ids_table["type"] == "json":
  889. click.echo(
  890. click.style(
  891. (
  892. f"- Listing file-id-like JSON string in column {ids_table['column']} "
  893. f"in table {ids_table['table']}"
  894. ),
  895. fg="white",
  896. )
  897. )
  898. query = (
  899. f"SELECT regexp_matches({ids_table['column']}::text, '{guid_regexp}', 'g') AS extracted_id "
  900. f"FROM {ids_table['table']}"
  901. )
  902. with db.engine.begin() as conn:
  903. rs = conn.execute(sa.text(query))
  904. for i in rs:
  905. for j in i[0]:
  906. all_ids_in_tables.append({"table": ids_table["table"], "id": j})
  907. click.echo(click.style(f"Found {len(all_ids_in_tables)} file ids in tables.", fg="white"))
  908. except Exception as e:
  909. click.echo(click.style(f"Error fetching keys: {str(e)}", fg="red"))
  910. return
  911. # find orphaned files
  912. all_files = [file["id"] for file in all_files_in_tables]
  913. all_ids = [file["id"] for file in all_ids_in_tables]
  914. orphaned_files = list(set(all_files) - set(all_ids))
  915. if not orphaned_files:
  916. click.echo(click.style("No orphaned file records found. There is nothing to delete.", fg="green"))
  917. return
  918. click.echo(click.style(f"Found {len(orphaned_files)} orphaned file records.", fg="white"))
  919. for file in orphaned_files:
  920. click.echo(click.style(f"- orphaned file id: {file}", fg="black"))
  921. if not force:
  922. click.confirm(f"Do you want to proceed to delete all {len(orphaned_files)} orphaned file records?", abort=True)
  923. # delete orphaned records for each file
  924. try:
  925. for files_table in files_tables:
  926. click.echo(click.style(f"- Deleting orphaned file records in table {files_table['table']}", fg="white"))
  927. query = f"DELETE FROM {files_table['table']} WHERE {files_table['id_column']} IN :ids"
  928. with db.engine.begin() as conn:
  929. conn.execute(sa.text(query), {"ids": tuple(orphaned_files)})
  930. except Exception as e:
  931. click.echo(click.style(f"Error deleting orphaned file records: {str(e)}", fg="red"))
  932. return
  933. click.echo(click.style(f"Removed {len(orphaned_files)} orphaned file records.", fg="green"))
  934. @click.option("-f", "--force", is_flag=True, help="Skip user confirmation and force the command to execute.")
  935. @click.command("remove-orphaned-files-on-storage", help="Remove orphaned files on the storage.")
  936. def remove_orphaned_files_on_storage(force: bool):
  937. """
  938. Remove orphaned files on the storage.
  939. """
  940. # define tables and columns to process
  941. files_tables = [
  942. {"table": "upload_files", "key_column": "key"},
  943. {"table": "tool_files", "key_column": "file_key"},
  944. ]
  945. storage_paths = ["image_files", "tools", "upload_files"]
  946. # notify user and ask for confirmation
  947. click.echo(click.style("This command will find and remove orphaned files on the storage,", fg="yellow"))
  948. click.echo(
  949. click.style("by comparing the files on the storage with the records in the following tables:", fg="yellow")
  950. )
  951. for files_table in files_tables:
  952. click.echo(click.style(f"- {files_table['table']}", fg="yellow"))
  953. click.echo(click.style("The following paths on the storage will be scanned to find orphaned files:", fg="yellow"))
  954. for storage_path in storage_paths:
  955. click.echo(click.style(f"- {storage_path}", fg="yellow"))
  956. click.echo("")
  957. click.echo(click.style("!!! USE WITH CAUTION !!!", fg="red"))
  958. click.echo(
  959. click.style(
  960. "Currently, this command will work only for opendal based storage (STORAGE_TYPE=opendal).", fg="yellow"
  961. )
  962. )
  963. click.echo(
  964. click.style(
  965. "Since not all patterns have been fully tested, please note that this command may delete unintended files.",
  966. fg="yellow",
  967. )
  968. )
  969. click.echo(
  970. click.style("This cannot be undone. Please make sure to back up your storage before proceeding.", fg="yellow")
  971. )
  972. click.echo(
  973. click.style(
  974. (
  975. "It is also recommended to run this during the maintenance window, "
  976. "as this may cause high load on your instance."
  977. ),
  978. fg="yellow",
  979. )
  980. )
  981. if not force:
  982. click.confirm("Do you want to proceed?", abort=True)
  983. # start the cleanup process
  984. click.echo(click.style("Starting orphaned files cleanup.", fg="white"))
  985. # fetch file id and keys from each table
  986. all_files_in_tables = []
  987. try:
  988. for files_table in files_tables:
  989. click.echo(click.style(f"- Listing files from table {files_table['table']}", fg="white"))
  990. query = f"SELECT {files_table['key_column']} FROM {files_table['table']}"
  991. with db.engine.begin() as conn:
  992. rs = conn.execute(sa.text(query))
  993. for i in rs:
  994. all_files_in_tables.append(str(i[0]))
  995. click.echo(click.style(f"Found {len(all_files_in_tables)} files in tables.", fg="white"))
  996. except Exception as e:
  997. click.echo(click.style(f"Error fetching keys: {str(e)}", fg="red"))
  998. all_files_on_storage = []
  999. for storage_path in storage_paths:
  1000. try:
  1001. click.echo(click.style(f"- Scanning files on storage path {storage_path}", fg="white"))
  1002. files = storage.scan(path=storage_path, files=True, directories=False)
  1003. all_files_on_storage.extend(files)
  1004. except FileNotFoundError as e:
  1005. click.echo(click.style(f" -> Skipping path {storage_path} as it does not exist.", fg="yellow"))
  1006. continue
  1007. except Exception as e:
  1008. click.echo(click.style(f" -> Error scanning files on storage path {storage_path}: {str(e)}", fg="red"))
  1009. continue
  1010. click.echo(click.style(f"Found {len(all_files_on_storage)} files on storage.", fg="white"))
  1011. # find orphaned files
  1012. orphaned_files = list(set(all_files_on_storage) - set(all_files_in_tables))
  1013. if not orphaned_files:
  1014. click.echo(click.style("No orphaned files found. There is nothing to remove.", fg="green"))
  1015. return
  1016. click.echo(click.style(f"Found {len(orphaned_files)} orphaned files.", fg="white"))
  1017. for file in orphaned_files:
  1018. click.echo(click.style(f"- orphaned file: {file}", fg="black"))
  1019. if not force:
  1020. click.confirm(f"Do you want to proceed to remove all {len(orphaned_files)} orphaned files?", abort=True)
  1021. # delete orphaned files
  1022. removed_files = 0
  1023. error_files = 0
  1024. for file in orphaned_files:
  1025. try:
  1026. storage.delete(file)
  1027. removed_files += 1
  1028. click.echo(click.style(f"- Removing orphaned file: {file}", fg="white"))
  1029. except Exception as e:
  1030. error_files += 1
  1031. click.echo(click.style(f"- Error deleting orphaned file {file}: {str(e)}", fg="red"))
  1032. continue
  1033. if error_files == 0:
  1034. click.echo(click.style(f"Removed {removed_files} orphaned files without errors.", fg="green"))
  1035. else:
  1036. click.echo(click.style(f"Removed {removed_files} orphaned files, with {error_files} errors.", fg="yellow"))
  1037. @click.command("setup-system-tool-oauth-client", help="Setup system tool oauth client.")
  1038. @click.option("--provider", prompt=True, help="Provider name")
  1039. @click.option("--client-params", prompt=True, help="Client Params")
  1040. def setup_system_tool_oauth_client(provider, client_params):
  1041. """
  1042. Setup system tool oauth client
  1043. """
  1044. provider_id = ToolProviderID(provider)
  1045. provider_name = provider_id.provider_name
  1046. plugin_id = provider_id.plugin_id
  1047. try:
  1048. # json validate
  1049. click.echo(click.style(f"Validating client params: {client_params}", fg="yellow"))
  1050. client_params_dict = TypeAdapter(dict[str, Any]).validate_json(client_params)
  1051. click.echo(click.style("Client params validated successfully.", fg="green"))
  1052. click.echo(click.style(f"Encrypting client params: {client_params}", fg="yellow"))
  1053. click.echo(click.style(f"Using SECRET_KEY: `{dify_config.SECRET_KEY}`", fg="yellow"))
  1054. oauth_client_params = encrypt_system_oauth_params(client_params_dict)
  1055. click.echo(click.style("Client params encrypted successfully.", fg="green"))
  1056. except Exception as e:
  1057. click.echo(click.style(f"Error parsing client params: {str(e)}", fg="red"))
  1058. return
  1059. deleted_count = (
  1060. db.session.query(ToolOAuthSystemClient)
  1061. .filter_by(
  1062. provider=provider_name,
  1063. plugin_id=plugin_id,
  1064. )
  1065. .delete()
  1066. )
  1067. if deleted_count > 0:
  1068. click.echo(click.style(f"Deleted {deleted_count} existing oauth client params.", fg="yellow"))
  1069. oauth_client = ToolOAuthSystemClient(
  1070. provider=provider_name,
  1071. plugin_id=plugin_id,
  1072. encrypted_oauth_params=oauth_client_params,
  1073. )
  1074. db.session.add(oauth_client)
  1075. db.session.commit()
  1076. click.echo(click.style(f"OAuth client params setup successfully. id: {oauth_client.id}", fg="green"))
  1077. def _find_orphaned_draft_variables(batch_size: int = 1000) -> list[str]:
  1078. """
  1079. Find draft variables that reference non-existent apps.
  1080. Args:
  1081. batch_size: Maximum number of orphaned app IDs to return
  1082. Returns:
  1083. List of app IDs that have draft variables but don't exist in the apps table
  1084. """
  1085. query = """
  1086. SELECT DISTINCT wdv.app_id
  1087. FROM workflow_draft_variables AS wdv
  1088. WHERE NOT EXISTS(
  1089. SELECT 1 FROM apps WHERE apps.id = wdv.app_id
  1090. )
  1091. LIMIT :batch_size
  1092. """
  1093. with db.engine.connect() as conn:
  1094. result = conn.execute(sa.text(query), {"batch_size": batch_size})
  1095. return [row[0] for row in result]
  1096. def _count_orphaned_draft_variables() -> dict[str, Any]:
  1097. """
  1098. Count orphaned draft variables by app.
  1099. Returns:
  1100. Dictionary with statistics about orphaned variables
  1101. """
  1102. query = """
  1103. SELECT
  1104. wdv.app_id,
  1105. COUNT(*) as variable_count
  1106. FROM workflow_draft_variables AS wdv
  1107. WHERE NOT EXISTS(
  1108. SELECT 1 FROM apps WHERE apps.id = wdv.app_id
  1109. )
  1110. GROUP BY wdv.app_id
  1111. ORDER BY variable_count DESC
  1112. """
  1113. with db.engine.connect() as conn:
  1114. result = conn.execute(sa.text(query))
  1115. orphaned_by_app = {row[0]: row[1] for row in result}
  1116. total_orphaned = sum(orphaned_by_app.values())
  1117. app_count = len(orphaned_by_app)
  1118. return {
  1119. "total_orphaned_variables": total_orphaned,
  1120. "orphaned_app_count": app_count,
  1121. "orphaned_by_app": orphaned_by_app,
  1122. }
  1123. @click.command()
  1124. @click.option("--dry-run", is_flag=True, help="Show what would be deleted without actually deleting")
  1125. @click.option("--batch-size", default=1000, help="Number of records to process per batch (default 1000)")
  1126. @click.option("--max-apps", default=None, type=int, help="Maximum number of apps to process (default: no limit)")
  1127. @click.option("-f", "--force", is_flag=True, help="Skip user confirmation and force the command to execute.")
  1128. def cleanup_orphaned_draft_variables(
  1129. dry_run: bool,
  1130. batch_size: int,
  1131. max_apps: int | None,
  1132. force: bool = False,
  1133. ):
  1134. """
  1135. Clean up orphaned draft variables from the database.
  1136. This script finds and removes draft variables that belong to apps
  1137. that no longer exist in the database.
  1138. """
  1139. logger = logging.getLogger(__name__)
  1140. # Get statistics
  1141. stats = _count_orphaned_draft_variables()
  1142. logger.info("Found %s orphaned draft variables", stats["total_orphaned_variables"])
  1143. logger.info("Across %s non-existent apps", stats["orphaned_app_count"])
  1144. if stats["total_orphaned_variables"] == 0:
  1145. logger.info("No orphaned draft variables found. Exiting.")
  1146. return
  1147. if dry_run:
  1148. logger.info("DRY RUN: Would delete the following:")
  1149. for app_id, count in sorted(stats["orphaned_by_app"].items(), key=operator.itemgetter(1), reverse=True)[
  1150. :10
  1151. ]: # Show top 10
  1152. logger.info(" App %s: %s variables", app_id, count)
  1153. if len(stats["orphaned_by_app"]) > 10:
  1154. logger.info(" ... and %s more apps", len(stats["orphaned_by_app"]) - 10)
  1155. return
  1156. # Confirm deletion
  1157. if not force:
  1158. click.confirm(
  1159. f"Are you sure you want to delete {stats['total_orphaned_variables']} "
  1160. f"orphaned draft variables from {stats['orphaned_app_count']} apps?",
  1161. abort=True,
  1162. )
  1163. total_deleted = 0
  1164. processed_apps = 0
  1165. while True:
  1166. if max_apps and processed_apps >= max_apps:
  1167. logger.info("Reached maximum app limit (%s). Stopping.", max_apps)
  1168. break
  1169. orphaned_app_ids = _find_orphaned_draft_variables(batch_size=10)
  1170. if not orphaned_app_ids:
  1171. logger.info("No more orphaned draft variables found.")
  1172. break
  1173. for app_id in orphaned_app_ids:
  1174. if max_apps and processed_apps >= max_apps:
  1175. break
  1176. try:
  1177. deleted_count = delete_draft_variables_batch(app_id, batch_size)
  1178. total_deleted += deleted_count
  1179. processed_apps += 1
  1180. logger.info("Deleted %s variables for app %s", deleted_count, app_id)
  1181. except Exception:
  1182. logger.exception("Error processing app %s", app_id)
  1183. continue
  1184. logger.info("Cleanup completed. Total deleted: %s variables across %s apps", total_deleted, processed_apps)