reflex.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. """Reflex CLI to create, run, and deploy apps."""
  2. import asyncio
  3. import atexit
  4. import json
  5. import os
  6. import shutil
  7. import tempfile
  8. import time
  9. from datetime import datetime
  10. from pathlib import Path
  11. from typing import List, Optional
  12. import httpx
  13. import typer
  14. from alembic.util.exc import CommandError
  15. from tabulate import tabulate
  16. from reflex import constants, model
  17. from reflex.config import get_config
  18. from reflex.utils import (
  19. build,
  20. console,
  21. exec,
  22. hosting,
  23. prerequisites,
  24. processes,
  25. telemetry,
  26. )
  27. # Create the app.
  28. cli = typer.Typer(add_completion=False)
  29. # Get the config.
  30. config = get_config()
  31. def version(value: bool):
  32. """Get the Reflex version.
  33. Args:
  34. value: Whether the version flag was passed.
  35. Raises:
  36. typer.Exit: If the version flag was passed.
  37. """
  38. if value:
  39. console.print(constants.Reflex.VERSION)
  40. raise typer.Exit()
  41. @cli.callback()
  42. def main(
  43. version: bool = typer.Option(
  44. None,
  45. "-v",
  46. "--version",
  47. callback=version,
  48. help="Get the Reflex version.",
  49. is_eager=True,
  50. ),
  51. ):
  52. """Reflex CLI to create, run, and deploy apps."""
  53. pass
  54. @cli.command()
  55. def init(
  56. name: str = typer.Option(
  57. None, metavar="APP_NAME", help="The name of the app to initialize."
  58. ),
  59. template: constants.Templates.Kind = typer.Option(
  60. constants.Templates.Kind.DEFAULT.value,
  61. help="The template to initialize the app with.",
  62. ),
  63. loglevel: constants.LogLevel = typer.Option(
  64. config.loglevel, help="The log level to use."
  65. ),
  66. ):
  67. """Initialize a new Reflex app in the current directory."""
  68. # Set the log level.
  69. console.set_log_level(loglevel)
  70. # Show system info
  71. exec.output_system_info()
  72. # Get the app name.
  73. app_name = prerequisites.get_default_app_name() if name is None else name
  74. console.rule(f"[bold]Initializing {app_name}")
  75. # Set up the web project.
  76. prerequisites.initialize_frontend_dependencies()
  77. # Migrate Pynecone projects to Reflex.
  78. prerequisites.migrate_to_reflex()
  79. # Set up the app directory, only if the config doesn't exist.
  80. if not os.path.exists(constants.Config.FILE):
  81. prerequisites.create_config(app_name)
  82. prerequisites.initialize_app_directory(app_name, template)
  83. telemetry.send("init")
  84. else:
  85. telemetry.send("reinit")
  86. # Initialize the .gitignore.
  87. prerequisites.initialize_gitignore()
  88. # Initialize the requirements.txt.
  89. prerequisites.initialize_requirements_txt()
  90. # Finish initializing the app.
  91. console.success(f"Initialized {app_name}")
  92. @cli.command()
  93. def run(
  94. env: constants.Env = typer.Option(
  95. constants.Env.DEV, help="The environment to run the app in."
  96. ),
  97. frontend: bool = typer.Option(
  98. False, "--frontend-only", help="Execute only frontend."
  99. ),
  100. backend: bool = typer.Option(False, "--backend-only", help="Execute only backend."),
  101. frontend_port: str = typer.Option(
  102. config.frontend_port, help="Specify a different frontend port."
  103. ),
  104. backend_port: str = typer.Option(
  105. config.backend_port, help="Specify a different backend port."
  106. ),
  107. backend_host: str = typer.Option(
  108. config.backend_host, help="Specify the backend host."
  109. ),
  110. loglevel: constants.LogLevel = typer.Option(
  111. config.loglevel, help="The log level to use."
  112. ),
  113. ):
  114. """Run the app in the current directory."""
  115. # Set the log level.
  116. console.set_log_level(loglevel)
  117. # Set env mode in the environment
  118. os.environ["REFLEX_ENV_MODE"] = env.value
  119. # Show system info
  120. exec.output_system_info()
  121. # If no --frontend-only and no --backend-only, then turn on frontend and backend both
  122. if not frontend and not backend:
  123. frontend = True
  124. backend = True
  125. if not frontend and backend:
  126. _skip_compile()
  127. # Check that the app is initialized.
  128. prerequisites.check_initialized(frontend=frontend)
  129. # If something is running on the ports, ask the user if they want to kill or change it.
  130. if frontend and processes.is_process_on_port(frontend_port):
  131. frontend_port = processes.change_or_terminate_port(frontend_port, "frontend")
  132. if backend and processes.is_process_on_port(backend_port):
  133. backend_port = processes.change_or_terminate_port(backend_port, "backend")
  134. # Apply the new ports to the config.
  135. if frontend_port != str(config.frontend_port):
  136. config._set_persistent(frontend_port=frontend_port)
  137. if backend_port != str(config.backend_port):
  138. config._set_persistent(backend_port=backend_port)
  139. console.rule("[bold]Starting Reflex App")
  140. if frontend:
  141. # Get the app module.
  142. prerequisites.get_app()
  143. # Warn if schema is not up to date.
  144. prerequisites.check_schema_up_to_date()
  145. # Get the frontend and backend commands, based on the environment.
  146. setup_frontend = frontend_cmd = backend_cmd = None
  147. if env == constants.Env.DEV:
  148. setup_frontend, frontend_cmd, backend_cmd = (
  149. build.setup_frontend,
  150. exec.run_frontend,
  151. exec.run_backend,
  152. )
  153. if env == constants.Env.PROD:
  154. setup_frontend, frontend_cmd, backend_cmd = (
  155. build.setup_frontend_prod,
  156. exec.run_frontend_prod,
  157. exec.run_backend_prod,
  158. )
  159. assert setup_frontend and frontend_cmd and backend_cmd, "Invalid env"
  160. # Post a telemetry event.
  161. telemetry.send(f"run-{env.value}")
  162. # Display custom message when there is a keyboard interrupt.
  163. atexit.register(processes.atexit_handler)
  164. # Run the frontend and backend together.
  165. commands = []
  166. # Run the frontend on a separate thread.
  167. if frontend:
  168. setup_frontend(Path.cwd())
  169. commands.append((frontend_cmd, Path.cwd(), frontend_port))
  170. # In prod mode, run the backend on a separate thread.
  171. if backend and env == constants.Env.PROD:
  172. commands.append((backend_cmd, backend_host, backend_port))
  173. # Start the frontend and backend.
  174. with processes.run_concurrently_context(*commands):
  175. # In dev mode, run the backend on the main thread.
  176. if backend and env == constants.Env.DEV:
  177. backend_cmd(backend_host, int(backend_port))
  178. @cli.command()
  179. def deploy_legacy(
  180. dry_run: bool = typer.Option(False, help="Whether to run a dry run."),
  181. loglevel: constants.LogLevel = typer.Option(
  182. console._LOG_LEVEL, help="The log level to use."
  183. ),
  184. ):
  185. """Deploy the app to the Reflex hosting service."""
  186. # Set the log level.
  187. console.set_log_level(loglevel)
  188. # Show system info
  189. exec.output_system_info()
  190. # Check if the deploy url is set.
  191. if config.rxdeploy_url is None:
  192. console.info("This feature is coming soon!")
  193. return
  194. # Compile the app in production mode.
  195. export(loglevel=loglevel)
  196. # Exit early if this is a dry run.
  197. if dry_run:
  198. return
  199. # Deploy the app.
  200. data = {"userId": config.username, "projectId": config.app_name}
  201. original_response = httpx.get(config.rxdeploy_url, params=data)
  202. response = original_response.json()
  203. frontend = response["frontend_resources_url"]
  204. backend = response["backend_resources_url"]
  205. # Upload the frontend and backend.
  206. with open(constants.ComponentName.FRONTEND.zip(), "rb") as f:
  207. httpx.put(frontend, data=f) # type: ignore
  208. with open(constants.ComponentName.BACKEND.zip(), "rb") as f:
  209. httpx.put(backend, data=f) # type: ignore
  210. @cli.command()
  211. def export(
  212. zipping: bool = typer.Option(
  213. True, "--no-zip", help="Disable zip for backend and frontend exports."
  214. ),
  215. frontend: bool = typer.Option(
  216. True, "--backend-only", help="Export only backend.", show_default=False
  217. ),
  218. backend: bool = typer.Option(
  219. True, "--frontend-only", help="Export only frontend.", show_default=False
  220. ),
  221. zip_dest_dir: str = typer.Option(
  222. os.getcwd(),
  223. help="The directory to export the zip files to.",
  224. show_default=False,
  225. ),
  226. upload_db_file: bool = typer.Option(
  227. False,
  228. help="Whether to exclude sqlite db files when exporting backend.",
  229. hidden=True,
  230. ),
  231. loglevel: constants.LogLevel = typer.Option(
  232. console._LOG_LEVEL, help="The log level to use."
  233. ),
  234. ):
  235. """Export the app to a zip file."""
  236. # Set the log level.
  237. console.set_log_level(loglevel)
  238. # Show system info
  239. exec.output_system_info()
  240. # Check that the app is initialized.
  241. prerequisites.check_initialized(frontend=frontend)
  242. # Compile the app in production mode and export it.
  243. console.rule("[bold]Compiling production app and preparing for export.")
  244. if frontend:
  245. # Ensure module can be imported and app.compile() is called.
  246. prerequisites.get_app()
  247. # Set up .web directory and install frontend dependencies.
  248. build.setup_frontend(Path.cwd())
  249. # Export the app.
  250. build.export(
  251. backend=backend,
  252. frontend=frontend,
  253. zip=zipping,
  254. zip_dest_dir=zip_dest_dir,
  255. deploy_url=config.deploy_url,
  256. upload_db_file=upload_db_file,
  257. )
  258. # Post a telemetry event.
  259. telemetry.send("export")
  260. @cli.command()
  261. def login(
  262. loglevel: constants.LogLevel = typer.Option(
  263. config.loglevel, help="The log level to use."
  264. ),
  265. ):
  266. """Authenticate with Reflex hosting service."""
  267. # Set the log level.
  268. console.set_log_level(loglevel)
  269. access_token, invitation_code = hosting.authenticated_token()
  270. if access_token:
  271. console.print("You already logged in.")
  272. return
  273. # If not already logged in, open a browser window/tab to the login page.
  274. access_token = hosting.authenticate_on_browser(invitation_code)
  275. if not access_token:
  276. console.error(f"Unable to authenticate. Please try again or contact support.")
  277. raise typer.Exit(1)
  278. console.print("Successfully logged in.")
  279. @cli.command()
  280. def logout(
  281. loglevel: constants.LogLevel = typer.Option(
  282. config.loglevel, help="The log level to use."
  283. ),
  284. ):
  285. """Log out of access to Reflex hosting service."""
  286. console.set_log_level(loglevel)
  287. hosting.log_out_on_browser()
  288. console.debug("Deleting access token from config locally")
  289. hosting.delete_token_from_config(include_invitation_code=True)
  290. db_cli = typer.Typer()
  291. def _skip_compile():
  292. """Skip the compile step."""
  293. os.environ[constants.SKIP_COMPILE_ENV_VAR] = "yes"
  294. @db_cli.command(name="init")
  295. def db_init():
  296. """Create database schema and migration configuration."""
  297. # Check the database url.
  298. if config.db_url is None:
  299. console.error("db_url is not configured, cannot initialize.")
  300. return
  301. # Check the alembic config.
  302. if Path(constants.ALEMBIC_CONFIG).exists():
  303. console.error(
  304. "Database is already initialized. Use "
  305. "[bold]reflex db makemigrations[/bold] to create schema change "
  306. "scripts and [bold]reflex db migrate[/bold] to apply migrations "
  307. "to a new or existing database.",
  308. )
  309. return
  310. # Initialize the database.
  311. _skip_compile()
  312. prerequisites.get_app()
  313. model.Model.alembic_init()
  314. model.Model.migrate(autogenerate=True)
  315. @db_cli.command()
  316. def migrate():
  317. """Create or update database schema from migration scripts."""
  318. _skip_compile()
  319. prerequisites.get_app()
  320. if not prerequisites.check_db_initialized():
  321. return
  322. model.Model.migrate()
  323. prerequisites.check_schema_up_to_date()
  324. @db_cli.command()
  325. def makemigrations(
  326. message: str = typer.Option(
  327. None, help="Human readable identifier for the generated revision."
  328. ),
  329. ):
  330. """Create autogenerated alembic migration scripts."""
  331. _skip_compile()
  332. prerequisites.get_app()
  333. if not prerequisites.check_db_initialized():
  334. return
  335. with model.Model.get_db_engine().connect() as connection:
  336. try:
  337. model.Model.alembic_autogenerate(connection=connection, message=message)
  338. except CommandError as command_error:
  339. if "Target database is not up to date." not in str(command_error):
  340. raise
  341. console.error(
  342. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  343. )
  344. @cli.command()
  345. def deploy(
  346. key: Optional[str] = typer.Option(
  347. None, "-k", "--deployment-key", help="The name of the deployment."
  348. ),
  349. app_name: str = typer.Option(
  350. config.app_name,
  351. "--app-name",
  352. help="The name of the App to deploy under.",
  353. hidden=True,
  354. ),
  355. regions: List[str] = typer.Option(
  356. list(),
  357. "-r",
  358. "--region",
  359. help="The regions to deploy to.",
  360. ),
  361. envs: List[str] = typer.Option(
  362. list(),
  363. "--env",
  364. help="The environment variables to set: <key>=<value>. For multiple envs, repeat this option, e.g. --env k1=v2 --env k2=v2.",
  365. ),
  366. cpus: Optional[int] = typer.Option(
  367. None, help="The number of CPUs to allocate.", hidden=True
  368. ),
  369. memory_mb: Optional[int] = typer.Option(
  370. None, help="The amount of memory to allocate.", hidden=True
  371. ),
  372. auto_start: Optional[bool] = typer.Option(
  373. True,
  374. help="Whether to auto start the instance.",
  375. hidden=True,
  376. ),
  377. auto_stop: Optional[bool] = typer.Option(
  378. True,
  379. help="Whether to auto stop the instance.",
  380. hidden=True,
  381. ),
  382. frontend_hostname: Optional[str] = typer.Option(
  383. None,
  384. "--frontend-hostname",
  385. help="The hostname of the frontend.",
  386. hidden=True,
  387. ),
  388. interactive: Optional[bool] = typer.Option(
  389. True,
  390. help="Whether to list configuration options and ask for confirmation.",
  391. ),
  392. with_metrics: Optional[str] = typer.Option(
  393. None,
  394. help="Setting for metrics scraping for the deployment. Setup required in user code.",
  395. hidden=True,
  396. ),
  397. with_tracing: Optional[str] = typer.Option(
  398. None,
  399. help="Setting to export tracing for the deployment. Setup required in user code.",
  400. hidden=True,
  401. ),
  402. upload_db_file: bool = typer.Option(
  403. False,
  404. help="Whether to include local sqlite db files when uploading to hosting service.",
  405. hidden=True,
  406. ),
  407. loglevel: constants.LogLevel = typer.Option(
  408. config.loglevel, help="The log level to use."
  409. ),
  410. ):
  411. """Deploy the app to the Reflex hosting service."""
  412. # Set the log level.
  413. console.set_log_level(loglevel)
  414. if not interactive and not key:
  415. console.error("Please provide a deployment key when not in interactive mode.")
  416. raise typer.Exit(1)
  417. try:
  418. hosting.check_requirements_txt_exist()
  419. except Exception as ex:
  420. console.error(f"{constants.RequirementsTxt.FILE} required for deployment")
  421. raise typer.Exit(1) from ex
  422. # Check if we are set up.
  423. prerequisites.check_initialized(frontend=True)
  424. try:
  425. # Send a request to server to obtain necessary information
  426. # in preparation of a deployment. For example,
  427. # server can return confirmation of a particular deployment key,
  428. # is available, or suggest a new key, or return an existing deployment.
  429. # Some of these are used in the interactive mode.
  430. pre_deploy_response = hosting.prepare_deploy(
  431. app_name, key=key, frontend_hostname=frontend_hostname
  432. )
  433. except Exception as ex:
  434. console.error(f"Unable to prepare deployment due to: {ex}")
  435. raise typer.Exit(1) from ex
  436. # The app prefix should not change during the time of preparation
  437. app_prefix = pre_deploy_response.app_prefix
  438. if not interactive:
  439. # in this case, the key was supplied for the pre_deploy call, at this point the reply is expected
  440. if (reply := pre_deploy_response.reply) is None:
  441. console.error(f"Unable to deploy at this name {key}.")
  442. raise typer.Exit(1)
  443. api_url = reply.api_url
  444. deploy_url = reply.deploy_url
  445. else:
  446. (
  447. key_candidate,
  448. api_url,
  449. deploy_url,
  450. ) = hosting.interactive_get_deployment_key_from_user_input(
  451. pre_deploy_response, app_name, frontend_hostname=frontend_hostname
  452. )
  453. if not key_candidate or not api_url or not deploy_url:
  454. console.error("Unable to find a suitable deployment key.")
  455. raise typer.Exit(1)
  456. # Now copy over the candidate to the key
  457. key = key_candidate
  458. # Then CP needs to know the user's location, which requires user permission
  459. region_input = console.ask(
  460. "Region to deploy to", default=regions[0] if regions else "sjc"
  461. )
  462. regions = regions or [region_input]
  463. # process the envs
  464. envs = hosting.interactive_prompt_for_envs()
  465. # Check the required params are valid
  466. console.debug(f"{key=}, {regions=}, {app_name=}, {app_prefix=}, {api_url}")
  467. if not key or not regions or not app_name or not app_prefix or not api_url:
  468. console.error("Please provide all the required parameters.")
  469. raise typer.Exit(1)
  470. processed_envs = hosting.process_envs(envs) if envs else None
  471. # Compile the app in production mode.
  472. config.api_url = api_url
  473. config.deploy_url = deploy_url
  474. tmp_dir = tempfile.mkdtemp()
  475. try:
  476. export(
  477. frontend=True,
  478. backend=True,
  479. zipping=True,
  480. zip_dest_dir=tmp_dir,
  481. loglevel=loglevel,
  482. upload_db_file=upload_db_file,
  483. )
  484. except ImportError as ie:
  485. console.error(
  486. f"Encountered ImportError, did you install all the dependencies? {ie}"
  487. )
  488. if os.path.exists(tmp_dir):
  489. shutil.rmtree(tmp_dir)
  490. raise typer.Exit(1) from ie
  491. frontend_file_name = constants.ComponentName.FRONTEND.zip()
  492. backend_file_name = constants.ComponentName.BACKEND.zip()
  493. console.print("Uploading code and sending request ...")
  494. deploy_requested_at = datetime.now().astimezone()
  495. try:
  496. deploy_response = hosting.deploy(
  497. frontend_file_name=frontend_file_name,
  498. backend_file_name=backend_file_name,
  499. export_dir=tmp_dir,
  500. key=key,
  501. app_name=app_name,
  502. regions=regions,
  503. app_prefix=app_prefix,
  504. cpus=cpus,
  505. memory_mb=memory_mb,
  506. auto_start=auto_start,
  507. auto_stop=auto_stop,
  508. frontend_hostname=frontend_hostname,
  509. envs=processed_envs,
  510. with_metrics=with_metrics,
  511. with_tracing=with_tracing,
  512. )
  513. except Exception as ex:
  514. console.error(f"Unable to deploy due to: {ex}")
  515. raise typer.Exit(1) from ex
  516. finally:
  517. if os.path.exists(tmp_dir):
  518. shutil.rmtree(tmp_dir)
  519. # Deployment will actually start when data plane reconciles this request
  520. console.debug(f"deploy_response: {deploy_response}")
  521. console.rule("[bold]Deploying production app.")
  522. console.print(
  523. "[bold]Deployment will start shortly. Closing this command now will not affect your deployment."
  524. )
  525. # It takes a few seconds for the deployment request to be picked up by server
  526. hosting.wait_for_server_to_pick_up_request()
  527. console.print("Waiting for server to report progress ...")
  528. # Display the key events such as build, deploy, etc
  529. asyncio.get_event_loop().run_until_complete(
  530. hosting.display_deploy_milestones(key, from_iso_timestamp=deploy_requested_at)
  531. )
  532. console.print("Waiting for the new deployment to come up")
  533. backend_up = frontend_up = False
  534. with console.status("Checking backend ..."):
  535. for _ in range(constants.Hosting.BACKEND_POLL_RETRIES):
  536. if backend_up := hosting.poll_backend(deploy_response.backend_url):
  537. break
  538. time.sleep(1)
  539. if not backend_up:
  540. console.print("Backend unreachable")
  541. else:
  542. console.print("Backend is up")
  543. with console.status("Checking frontend ..."):
  544. for _ in range(constants.Hosting.FRONTEND_POLL_RETRIES):
  545. if frontend_up := hosting.poll_frontend(deploy_response.frontend_url):
  546. break
  547. time.sleep(1)
  548. if not frontend_up:
  549. console.print("frontend is unreachable")
  550. else:
  551. console.print("frontend is up")
  552. if frontend_up and backend_up:
  553. console.print(
  554. f"Your site [ {key} ] at {regions} is up: {deploy_response.frontend_url}"
  555. )
  556. return
  557. console.warn(
  558. f"Your deployment is taking unusually long. Check back later on its status: `reflex deployments status {key}`"
  559. )
  560. deployments_cli = typer.Typer()
  561. @deployments_cli.command(name="list")
  562. def list_deployments(
  563. loglevel: constants.LogLevel = typer.Option(
  564. config.loglevel, help="The log level to use."
  565. ),
  566. as_json: bool = typer.Option(
  567. False, "-j", "--json", help="Whether to output the result in json format."
  568. ),
  569. ):
  570. """List all the hosted deployments of the authenticated user."""
  571. console.set_log_level(loglevel)
  572. try:
  573. deployments = hosting.list_deployments()
  574. except Exception as ex:
  575. console.error(f"Unable to list deployments due to: {ex}")
  576. raise typer.Exit(1) from ex
  577. if as_json:
  578. console.print(json.dumps(deployments))
  579. return
  580. if deployments:
  581. headers = list(deployments[0].keys())
  582. table = [list(deployment.values()) for deployment in deployments]
  583. console.print(tabulate(table, headers=headers))
  584. else:
  585. # If returned empty list, print the empty
  586. console.print(str(deployments))
  587. @deployments_cli.command(name="delete")
  588. def delete_deployment(
  589. key: str = typer.Argument(..., help="The name of the deployment."),
  590. loglevel: constants.LogLevel = typer.Option(
  591. config.loglevel, help="The log level to use."
  592. ),
  593. ):
  594. """Delete a hosted instance."""
  595. console.set_log_level(loglevel)
  596. try:
  597. hosting.delete_deployment(key)
  598. except Exception as ex:
  599. console.error(f"Unable to delete deployment due to: {ex}")
  600. raise typer.Exit(1) from ex
  601. console.print(f"Successfully deleted [ {key} ].")
  602. @deployments_cli.command(name="status")
  603. def get_deployment_status(
  604. key: str = typer.Argument(..., help="The name of the deployment."),
  605. loglevel: constants.LogLevel = typer.Option(
  606. config.loglevel, help="The log level to use."
  607. ),
  608. ):
  609. """Check the status of a deployment."""
  610. console.set_log_level(loglevel)
  611. try:
  612. console.print(f"Getting status for [ {key} ] ...\n")
  613. status = hosting.get_deployment_status(key)
  614. # TODO: refactor all these tabulate calls
  615. status.backend.updated_at = hosting.convert_to_local_time(
  616. status.backend.updated_at or "N/A"
  617. )
  618. backend_status = status.backend.dict(exclude_none=True)
  619. headers = list(backend_status.keys())
  620. table = list(backend_status.values())
  621. console.print(tabulate([table], headers=headers))
  622. # Add a new line in console
  623. console.print("\n")
  624. status.frontend.updated_at = hosting.convert_to_local_time(
  625. status.frontend.updated_at or "N/A"
  626. )
  627. frontend_status = status.frontend.dict(exclude_none=True)
  628. headers = list(frontend_status.keys())
  629. table = list(frontend_status.values())
  630. console.print(tabulate([table], headers=headers))
  631. except Exception as ex:
  632. console.error(f"Unable to get deployment status due to: {ex}")
  633. raise typer.Exit(1) from ex
  634. @deployments_cli.command(name="logs")
  635. def get_deployment_logs(
  636. key: str = typer.Argument(..., help="The name of the deployment."),
  637. loglevel: constants.LogLevel = typer.Option(
  638. config.loglevel, help="The log level to use."
  639. ),
  640. ):
  641. """Get the logs for a deployment."""
  642. console.set_log_level(loglevel)
  643. console.print("Note: there is a few seconds delay for logs to be available.")
  644. try:
  645. asyncio.get_event_loop().run_until_complete(hosting.get_logs(key))
  646. except Exception as ex:
  647. console.error(f"Unable to get deployment logs due to: {ex}")
  648. raise typer.Exit(1) from ex
  649. @deployments_cli.command(name="regions")
  650. def get_deployment_regions(
  651. loglevel: constants.LogLevel = typer.Option(
  652. config.loglevel, help="The log level to use."
  653. ),
  654. as_json: bool = typer.Option(
  655. False, "-j", "--json", help="Whether to output the result in json format."
  656. ),
  657. ):
  658. """List all the regions of the hosting service."""
  659. console.set_log_level(loglevel)
  660. list_regions_info = hosting.get_regions()
  661. if as_json:
  662. console.print(json.dumps(list_regions_info))
  663. return
  664. if list_regions_info:
  665. headers = list(list_regions_info[0].keys())
  666. table = [list(deployment.values()) for deployment in list_regions_info]
  667. console.print(tabulate(table, headers=headers))
  668. cli.add_typer(db_cli, name="db", help="Subcommands for managing the database schema.")
  669. cli.add_typer(
  670. deployments_cli,
  671. name="deployments",
  672. help="Subcommands for managing the Deployments.",
  673. )
  674. if __name__ == "__main__":
  675. cli()