reflex.py 26 KB

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