You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

commands.py 49KB

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