commands.py 27 KB

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