commands.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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.models.document import Document
  14. from events.app_event import app_was_created
  15. from extensions.ext_database import db
  16. from extensions.ext_redis import redis_client
  17. from libs.helper import email as email_validate
  18. from libs.password import hash_password, password_pattern, valid_password
  19. from libs.rsa import generate_key_pair
  20. from models.account import Tenant
  21. from models.dataset import Dataset, DatasetCollectionBinding, DocumentSegment
  22. from models.dataset import Document as DatasetDocument
  23. from models.model import Account, App, AppAnnotationSetting, AppMode, Conversation, MessageAnnotation
  24. from models.provider import Provider, ProviderModel
  25. from services.account_service import RegisterService, TenantService
  26. @click.command("reset-password", help="Reset the account password.")
  27. @click.option("--email", prompt=True, help="The email address of the account whose password you need to reset")
  28. @click.option("--new-password", prompt=True, help="the new password.")
  29. @click.option("--password-confirm", prompt=True, help="the new password confirm.")
  30. def reset_password(email, new_password, password_confirm):
  31. """
  32. Reset password of owner account
  33. Only available in SELF_HOSTED mode
  34. """
  35. if str(new_password).strip() != str(password_confirm).strip():
  36. click.echo(click.style("sorry. The two passwords do not match.", fg="red"))
  37. return
  38. account = db.session.query(Account).filter(Account.email == email).one_or_none()
  39. if not account:
  40. click.echo(click.style("sorry. the account: [{}] not exist .".format(email), fg="red"))
  41. return
  42. try:
  43. valid_password(new_password)
  44. except:
  45. click.echo(click.style("sorry. The passwords must match {} ".format(password_pattern), fg="red"))
  46. return
  47. # generate password salt
  48. salt = secrets.token_bytes(16)
  49. base64_salt = base64.b64encode(salt).decode()
  50. # encrypt password with salt
  51. password_hashed = hash_password(new_password, salt)
  52. base64_password_hashed = base64.b64encode(password_hashed).decode()
  53. account.password = base64_password_hashed
  54. account.password_salt = base64_salt
  55. db.session.commit()
  56. click.echo(click.style("Congratulations! Password has been reset.", fg="green"))
  57. @click.command("reset-email", help="Reset the account email.")
  58. @click.option("--email", prompt=True, help="The old email address of the account whose email you need to reset")
  59. @click.option("--new-email", prompt=True, help="the new email.")
  60. @click.option("--email-confirm", prompt=True, help="the new email confirm.")
  61. def reset_email(email, new_email, email_confirm):
  62. """
  63. Replace account email
  64. :return:
  65. """
  66. if str(new_email).strip() != str(email_confirm).strip():
  67. click.echo(click.style("Sorry, new email and confirm email do not match.", fg="red"))
  68. return
  69. account = db.session.query(Account).filter(Account.email == email).one_or_none()
  70. if not account:
  71. click.echo(click.style("sorry. the account: [{}] not exist .".format(email), fg="red"))
  72. return
  73. try:
  74. email_validate(new_email)
  75. except:
  76. click.echo(click.style("sorry. {} is not a valid email. ".format(email), fg="red"))
  77. return
  78. account.email = new_email
  79. db.session.commit()
  80. click.echo(click.style("Congratulations!, email has been reset.", fg="green"))
  81. @click.command(
  82. "reset-encrypt-key-pair",
  83. help="Reset the asymmetric key pair of workspace for encrypt LLM credentials. "
  84. "After the reset, all LLM credentials will become invalid, "
  85. "requiring re-entry."
  86. "Only support SELF_HOSTED mode.",
  87. )
  88. @click.confirmation_option(
  89. prompt=click.style(
  90. "Are you sure you want to reset encrypt key pair?" " this operation cannot be rolled back!", fg="red"
  91. )
  92. )
  93. def reset_encrypt_key_pair():
  94. """
  95. Reset the encrypted key pair of workspace for encrypt LLM credentials.
  96. After the reset, all LLM credentials will become invalid, requiring re-entry.
  97. Only support SELF_HOSTED mode.
  98. """
  99. if dify_config.EDITION != "SELF_HOSTED":
  100. click.echo(click.style("Sorry, only support SELF_HOSTED mode.", fg="red"))
  101. return
  102. tenants = db.session.query(Tenant).all()
  103. for tenant in tenants:
  104. if not tenant:
  105. click.echo(click.style("Sorry, no workspace found. Please enter /install to initialize.", fg="red"))
  106. return
  107. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  108. db.session.query(Provider).filter(Provider.provider_type == "custom", Provider.tenant_id == tenant.id).delete()
  109. db.session.query(ProviderModel).filter(ProviderModel.tenant_id == tenant.id).delete()
  110. db.session.commit()
  111. click.echo(
  112. click.style(
  113. "Congratulations! " "the asymmetric key pair of workspace {} has been reset.".format(tenant.id),
  114. fg="green",
  115. )
  116. )
  117. @click.command("vdb-migrate", help="migrate vector db.")
  118. @click.option("--scope", default="all", prompt=False, help="The scope of vector database to migrate, Default is All.")
  119. def vdb_migrate(scope: str):
  120. if scope in ["knowledge", "all"]:
  121. migrate_knowledge_vector_database()
  122. if scope in ["annotation", "all"]:
  123. migrate_annotation_vector_database()
  124. def migrate_annotation_vector_database():
  125. """
  126. Migrate annotation datas to target vector database .
  127. """
  128. click.echo(click.style("Start migrate annotation data.", fg="green"))
  129. create_count = 0
  130. skipped_count = 0
  131. total_count = 0
  132. page = 1
  133. while True:
  134. try:
  135. # get apps info
  136. apps = (
  137. db.session.query(App)
  138. .filter(App.status == "normal")
  139. .order_by(App.created_at.desc())
  140. .paginate(page=page, per_page=50)
  141. )
  142. except NotFound:
  143. break
  144. page += 1
  145. for app in apps:
  146. total_count = total_count + 1
  147. click.echo(
  148. f"Processing the {total_count} app {app.id}. " + f"{create_count} created, {skipped_count} skipped."
  149. )
  150. try:
  151. click.echo("Create app annotation index: {}".format(app.id))
  152. app_annotation_setting = (
  153. db.session.query(AppAnnotationSetting).filter(AppAnnotationSetting.app_id == app.id).first()
  154. )
  155. if not app_annotation_setting:
  156. skipped_count = skipped_count + 1
  157. click.echo("App annotation setting is disabled: {}".format(app.id))
  158. continue
  159. # get dataset_collection_binding info
  160. dataset_collection_binding = (
  161. db.session.query(DatasetCollectionBinding)
  162. .filter(DatasetCollectionBinding.id == app_annotation_setting.collection_binding_id)
  163. .first()
  164. )
  165. if not dataset_collection_binding:
  166. click.echo("App annotation collection binding is not exist: {}".format(app.id))
  167. continue
  168. annotations = db.session.query(MessageAnnotation).filter(MessageAnnotation.app_id == app.id).all()
  169. dataset = Dataset(
  170. id=app.id,
  171. tenant_id=app.tenant_id,
  172. indexing_technique="high_quality",
  173. embedding_model_provider=dataset_collection_binding.provider_name,
  174. embedding_model=dataset_collection_binding.model_name,
  175. collection_binding_id=dataset_collection_binding.id,
  176. )
  177. documents = []
  178. if annotations:
  179. for annotation in annotations:
  180. document = Document(
  181. page_content=annotation.question,
  182. metadata={"annotation_id": annotation.id, "app_id": app.id, "doc_id": annotation.id},
  183. )
  184. documents.append(document)
  185. vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"])
  186. click.echo(f"Start to migrate annotation, app_id: {app.id}.")
  187. try:
  188. vector.delete()
  189. click.echo(click.style(f"Successfully delete vector index for app: {app.id}.", fg="green"))
  190. except Exception as e:
  191. click.echo(click.style(f"Failed to delete vector index for app {app.id}.", fg="red"))
  192. raise e
  193. if documents:
  194. try:
  195. click.echo(
  196. click.style(
  197. f"Start to created vector index with {len(documents)} annotations for app {app.id}.",
  198. fg="green",
  199. )
  200. )
  201. vector.create(documents)
  202. click.echo(click.style(f"Successfully created vector index for app {app.id}.", fg="green"))
  203. except Exception as e:
  204. click.echo(click.style(f"Failed to created vector index for app {app.id}.", fg="red"))
  205. raise e
  206. click.echo(f"Successfully migrated app annotation {app.id}.")
  207. create_count += 1
  208. except Exception as e:
  209. click.echo(
  210. click.style(
  211. "Create app annotation index error: {} {}".format(e.__class__.__name__, str(e)), fg="red"
  212. )
  213. )
  214. continue
  215. click.echo(
  216. click.style(
  217. f"Congratulations! Create {create_count} app annotation indexes, and skipped {skipped_count} apps.",
  218. fg="green",
  219. )
  220. )
  221. def migrate_knowledge_vector_database():
  222. """
  223. Migrate vector database datas to target vector database .
  224. """
  225. click.echo(click.style("Start migrate vector db.", fg="green"))
  226. create_count = 0
  227. skipped_count = 0
  228. total_count = 0
  229. vector_type = dify_config.VECTOR_STORE
  230. page = 1
  231. while True:
  232. try:
  233. datasets = (
  234. db.session.query(Dataset)
  235. .filter(Dataset.indexing_technique == "high_quality")
  236. .order_by(Dataset.created_at.desc())
  237. .paginate(page=page, per_page=50)
  238. )
  239. except NotFound:
  240. break
  241. page += 1
  242. for dataset in datasets:
  243. total_count = total_count + 1
  244. click.echo(
  245. f"Processing the {total_count} dataset {dataset.id}. "
  246. + f"{create_count} created, {skipped_count} skipped."
  247. )
  248. try:
  249. click.echo("Create dataset vdb index: {}".format(dataset.id))
  250. if dataset.index_struct_dict:
  251. if dataset.index_struct_dict["type"] == vector_type:
  252. skipped_count = skipped_count + 1
  253. continue
  254. collection_name = ""
  255. if vector_type == VectorType.WEAVIATE:
  256. dataset_id = dataset.id
  257. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  258. index_struct_dict = {"type": VectorType.WEAVIATE, "vector_store": {"class_prefix": collection_name}}
  259. dataset.index_struct = json.dumps(index_struct_dict)
  260. elif vector_type == VectorType.QDRANT:
  261. if dataset.collection_binding_id:
  262. dataset_collection_binding = (
  263. db.session.query(DatasetCollectionBinding)
  264. .filter(DatasetCollectionBinding.id == dataset.collection_binding_id)
  265. .one_or_none()
  266. )
  267. if dataset_collection_binding:
  268. collection_name = dataset_collection_binding.collection_name
  269. else:
  270. raise ValueError("Dataset Collection Bindings is not exist!")
  271. else:
  272. dataset_id = dataset.id
  273. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  274. index_struct_dict = {"type": VectorType.QDRANT, "vector_store": {"class_prefix": collection_name}}
  275. dataset.index_struct = json.dumps(index_struct_dict)
  276. elif vector_type == VectorType.MILVUS:
  277. dataset_id = dataset.id
  278. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  279. index_struct_dict = {"type": VectorType.MILVUS, "vector_store": {"class_prefix": collection_name}}
  280. dataset.index_struct = json.dumps(index_struct_dict)
  281. elif vector_type == VectorType.RELYT:
  282. dataset_id = dataset.id
  283. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  284. index_struct_dict = {"type": "relyt", "vector_store": {"class_prefix": collection_name}}
  285. dataset.index_struct = json.dumps(index_struct_dict)
  286. elif vector_type == VectorType.TENCENT:
  287. dataset_id = dataset.id
  288. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  289. index_struct_dict = {"type": VectorType.TENCENT, "vector_store": {"class_prefix": collection_name}}
  290. dataset.index_struct = json.dumps(index_struct_dict)
  291. elif vector_type == VectorType.PGVECTOR:
  292. dataset_id = dataset.id
  293. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  294. index_struct_dict = {"type": VectorType.PGVECTOR, "vector_store": {"class_prefix": collection_name}}
  295. dataset.index_struct = json.dumps(index_struct_dict)
  296. elif vector_type == VectorType.OPENSEARCH:
  297. dataset_id = dataset.id
  298. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  299. index_struct_dict = {
  300. "type": VectorType.OPENSEARCH,
  301. "vector_store": {"class_prefix": collection_name},
  302. }
  303. dataset.index_struct = json.dumps(index_struct_dict)
  304. elif vector_type == VectorType.ANALYTICDB:
  305. dataset_id = dataset.id
  306. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  307. index_struct_dict = {
  308. "type": VectorType.ANALYTICDB,
  309. "vector_store": {"class_prefix": collection_name},
  310. }
  311. dataset.index_struct = json.dumps(index_struct_dict)
  312. elif vector_type == VectorType.ELASTICSEARCH:
  313. dataset_id = dataset.id
  314. index_name = Dataset.gen_collection_name_by_id(dataset_id)
  315. index_struct_dict = {"type": "elasticsearch", "vector_store": {"class_prefix": index_name}}
  316. dataset.index_struct = json.dumps(index_struct_dict)
  317. else:
  318. raise ValueError(f"Vector store {vector_type} is not supported.")
  319. vector = Vector(dataset)
  320. click.echo(f"Start to migrate dataset {dataset.id}.")
  321. try:
  322. vector.delete()
  323. click.echo(
  324. click.style(
  325. f"Successfully delete vector index {collection_name} for dataset {dataset.id}.", fg="green"
  326. )
  327. )
  328. except Exception as e:
  329. click.echo(
  330. click.style(
  331. f"Failed to delete vector index {collection_name} for dataset {dataset.id}.", fg="red"
  332. )
  333. )
  334. raise e
  335. dataset_documents = (
  336. db.session.query(DatasetDocument)
  337. .filter(
  338. DatasetDocument.dataset_id == dataset.id,
  339. DatasetDocument.indexing_status == "completed",
  340. DatasetDocument.enabled == True,
  341. DatasetDocument.archived == False,
  342. )
  343. .all()
  344. )
  345. documents = []
  346. segments_count = 0
  347. for dataset_document in dataset_documents:
  348. segments = (
  349. db.session.query(DocumentSegment)
  350. .filter(
  351. DocumentSegment.document_id == dataset_document.id,
  352. DocumentSegment.status == "completed",
  353. DocumentSegment.enabled == True,
  354. )
  355. .all()
  356. )
  357. for segment in segments:
  358. document = Document(
  359. page_content=segment.content,
  360. metadata={
  361. "doc_id": segment.index_node_id,
  362. "doc_hash": segment.index_node_hash,
  363. "document_id": segment.document_id,
  364. "dataset_id": segment.dataset_id,
  365. },
  366. )
  367. documents.append(document)
  368. segments_count = segments_count + 1
  369. if documents:
  370. try:
  371. click.echo(
  372. click.style(
  373. f"Start to created vector index with {len(documents)} documents of {segments_count} segments for dataset {dataset.id}.",
  374. fg="green",
  375. )
  376. )
  377. vector.create(documents)
  378. click.echo(
  379. click.style(f"Successfully created vector index for dataset {dataset.id}.", fg="green")
  380. )
  381. except Exception as e:
  382. click.echo(click.style(f"Failed to created vector index for dataset {dataset.id}.", fg="red"))
  383. raise e
  384. db.session.add(dataset)
  385. db.session.commit()
  386. click.echo(f"Successfully migrated dataset {dataset.id}.")
  387. create_count += 1
  388. except Exception as e:
  389. db.session.rollback()
  390. click.echo(
  391. click.style("Create dataset index error: {} {}".format(e.__class__.__name__, str(e)), fg="red")
  392. )
  393. continue
  394. click.echo(
  395. click.style(
  396. f"Congratulations! Create {create_count} dataset indexes, and skipped {skipped_count} datasets.", fg="green"
  397. )
  398. )
  399. @click.command("convert-to-agent-apps", help="Convert Agent Assistant to Agent App.")
  400. def convert_to_agent_apps():
  401. """
  402. Convert Agent Assistant to Agent App.
  403. """
  404. click.echo(click.style("Start convert to agent apps.", fg="green"))
  405. proceeded_app_ids = []
  406. while True:
  407. # fetch first 1000 apps
  408. sql_query = """SELECT a.id AS id FROM apps a
  409. INNER JOIN app_model_configs am ON a.app_model_config_id=am.id
  410. WHERE a.mode = 'chat'
  411. AND am.agent_mode is not null
  412. AND (
  413. am.agent_mode like '%"strategy": "function_call"%'
  414. OR am.agent_mode like '%"strategy": "react"%'
  415. )
  416. AND (
  417. am.agent_mode like '{"enabled": true%'
  418. OR am.agent_mode like '{"max_iteration": %'
  419. ) ORDER BY a.created_at DESC LIMIT 1000
  420. """
  421. with db.engine.begin() as conn:
  422. rs = conn.execute(db.text(sql_query))
  423. apps = []
  424. for i in rs:
  425. app_id = str(i.id)
  426. if app_id not in proceeded_app_ids:
  427. proceeded_app_ids.append(app_id)
  428. app = db.session.query(App).filter(App.id == app_id).first()
  429. apps.append(app)
  430. if len(apps) == 0:
  431. break
  432. for app in apps:
  433. click.echo("Converting app: {}".format(app.id))
  434. try:
  435. app.mode = AppMode.AGENT_CHAT.value
  436. db.session.commit()
  437. # update conversation mode to agent
  438. db.session.query(Conversation).filter(Conversation.app_id == app.id).update(
  439. {Conversation.mode: AppMode.AGENT_CHAT.value}
  440. )
  441. db.session.commit()
  442. click.echo(click.style("Converted app: {}".format(app.id), fg="green"))
  443. except Exception as e:
  444. click.echo(click.style("Convert app error: {} {}".format(e.__class__.__name__, str(e)), fg="red"))
  445. click.echo(click.style("Congratulations! Converted {} agent apps.".format(len(proceeded_app_ids)), fg="green"))
  446. @click.command("add-qdrant-doc-id-index", help="add qdrant doc_id index.")
  447. @click.option("--field", default="metadata.doc_id", prompt=False, help="index field , default is metadata.doc_id.")
  448. def add_qdrant_doc_id_index(field: str):
  449. click.echo(click.style("Start add qdrant doc_id index.", fg="green"))
  450. vector_type = dify_config.VECTOR_STORE
  451. if vector_type != "qdrant":
  452. click.echo(click.style("Sorry, only support qdrant vector store.", fg="red"))
  453. return
  454. create_count = 0
  455. try:
  456. bindings = db.session.query(DatasetCollectionBinding).all()
  457. if not bindings:
  458. click.echo(click.style("Sorry, no dataset collection bindings found.", fg="red"))
  459. return
  460. import qdrant_client
  461. from qdrant_client.http.exceptions import UnexpectedResponse
  462. from qdrant_client.http.models import PayloadSchemaType
  463. from core.rag.datasource.vdb.qdrant.qdrant_vector import QdrantConfig
  464. for binding in bindings:
  465. if dify_config.QDRANT_URL is None:
  466. raise ValueError("Qdrant url is required.")
  467. qdrant_config = QdrantConfig(
  468. endpoint=dify_config.QDRANT_URL,
  469. api_key=dify_config.QDRANT_API_KEY,
  470. root_path=current_app.root_path,
  471. timeout=dify_config.QDRANT_CLIENT_TIMEOUT,
  472. grpc_port=dify_config.QDRANT_GRPC_PORT,
  473. prefer_grpc=dify_config.QDRANT_GRPC_ENABLED,
  474. )
  475. try:
  476. client = qdrant_client.QdrantClient(**qdrant_config.to_qdrant_params())
  477. # create payload index
  478. client.create_payload_index(binding.collection_name, field, field_schema=PayloadSchemaType.KEYWORD)
  479. create_count += 1
  480. except UnexpectedResponse as e:
  481. # Collection does not exist, so return
  482. if e.status_code == 404:
  483. click.echo(
  484. click.style(f"Collection not found, collection_name:{binding.collection_name}.", fg="red")
  485. )
  486. continue
  487. # Some other error occurred, so re-raise the exception
  488. else:
  489. click.echo(
  490. click.style(
  491. f"Failed to create qdrant index, collection_name:{binding.collection_name}.", fg="red"
  492. )
  493. )
  494. except Exception as e:
  495. click.echo(click.style("Failed to create qdrant client.", fg="red"))
  496. click.echo(click.style(f"Congratulations! Create {create_count} collection indexes.", fg="green"))
  497. @click.command("create-tenant", help="Create account and tenant.")
  498. @click.option("--email", prompt=True, help="The email address of the tenant account.")
  499. @click.option("--language", prompt=True, help="Account language, default: en-US.")
  500. def create_tenant(email: str, language: Optional[str] = None):
  501. """
  502. Create tenant account
  503. """
  504. if not email:
  505. click.echo(click.style("Sorry, email is required.", fg="red"))
  506. return
  507. # Create account
  508. email = email.strip()
  509. if "@" not in email:
  510. click.echo(click.style("Sorry, invalid email address.", fg="red"))
  511. return
  512. account_name = email.split("@")[0]
  513. if language not in languages:
  514. language = "en-US"
  515. # generate random password
  516. new_password = secrets.token_urlsafe(16)
  517. # register account
  518. account = RegisterService.register(email=email, name=account_name, password=new_password, language=language)
  519. TenantService.create_owner_tenant_if_not_exist(account)
  520. click.echo(
  521. click.style(
  522. "Congratulations! Account and tenant created.\n" "Account: {}\nPassword: {}".format(email, new_password),
  523. fg="green",
  524. )
  525. )
  526. @click.command("upgrade-db", help="upgrade the database")
  527. def upgrade_db():
  528. click.echo("Preparing database migration...")
  529. lock = redis_client.lock(name="db_upgrade_lock", timeout=60)
  530. if lock.acquire(blocking=False):
  531. try:
  532. click.echo(click.style("Start database migration.", fg="green"))
  533. # run db migration
  534. import flask_migrate
  535. flask_migrate.upgrade()
  536. click.echo(click.style("Database migration successful!", fg="green"))
  537. except Exception as e:
  538. logging.exception(f"Database migration failed, error: {e}")
  539. finally:
  540. lock.release()
  541. else:
  542. click.echo("Database migration skipped")
  543. @click.command("fix-app-site-missing", help="Fix app related site missing issue.")
  544. def fix_app_site_missing():
  545. """
  546. Fix app related site missing issue.
  547. """
  548. click.echo(click.style("Start fix app related site missing issue.", fg="green"))
  549. failed_app_ids = []
  550. while True:
  551. sql = """select apps.id as id from apps left join sites on sites.app_id=apps.id
  552. where sites.id is null limit 1000"""
  553. with db.engine.begin() as conn:
  554. rs = conn.execute(db.text(sql))
  555. processed_count = 0
  556. for i in rs:
  557. processed_count += 1
  558. app_id = str(i.id)
  559. if app_id in failed_app_ids:
  560. continue
  561. try:
  562. app = db.session.query(App).filter(App.id == app_id).first()
  563. tenant = app.tenant
  564. if tenant:
  565. accounts = tenant.get_accounts()
  566. if not accounts:
  567. print("Fix app {} failed.".format(app.id))
  568. continue
  569. account = accounts[0]
  570. print("Fix app {} related site missing issue.".format(app.id))
  571. app_was_created.send(app, account=account)
  572. except Exception as e:
  573. failed_app_ids.append(app_id)
  574. click.echo(click.style("Fix app {} related site missing issue failed!".format(app_id), fg="red"))
  575. logging.exception(f"Fix app related site missing issue failed, error: {e}")
  576. continue
  577. if not processed_count:
  578. break
  579. click.echo(click.style("Congratulations! Fix app related site missing issue successful!", fg="green"))
  580. def register_commands(app):
  581. app.cli.add_command(reset_password)
  582. app.cli.add_command(reset_email)
  583. app.cli.add_command(reset_encrypt_key_pair)
  584. app.cli.add_command(vdb_migrate)
  585. app.cli.add_command(convert_to_agent_apps)
  586. app.cli.add_command(add_qdrant_doc_id_index)
  587. app.cli.add_command(create_tenant)
  588. app.cli.add_command(upgrade_db)
  589. app.cli.add_command(fix_app_site_missing)