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 46KB

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