cli.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. #!/usr/bin/env python
  2. # pylint: disable=C,R,W
  3. from datetime import datetime
  4. import logging
  5. from subprocess import Popen
  6. from sys import stdout
  7. import click
  8. from colorama import Fore, Style
  9. from pathlib2 import Path
  10. import werkzeug.serving
  11. import yaml
  12. from superset import (
  13. app, dashboard_import_export_util, data, db,
  14. dict_import_export_util, security_manager, utils,
  15. )
  16. config = app.config
  17. celery_app = utils.get_celery_app(config)
  18. def create_app(script_info=None):
  19. return app
  20. @app.shell_context_processor
  21. def make_shell_context():
  22. return dict(app=app, db=db)
  23. @app.cli.command()
  24. def init():
  25. """Inits the Superset application"""
  26. utils.get_or_create_main_db()
  27. security_manager.sync_role_definitions()
  28. def debug_run(app, port, use_reloader):
  29. return app.run(
  30. host='0.0.0.0',
  31. port=int(port),
  32. threaded=True,
  33. debug=True,
  34. use_reloader=use_reloader)
  35. def console_log_run(app, port, use_reloader):
  36. from console_log import ConsoleLog
  37. from gevent import pywsgi
  38. from geventwebsocket.handler import WebSocketHandler
  39. app.wsgi_app = ConsoleLog(app.wsgi_app, app.logger)
  40. def run():
  41. server = pywsgi.WSGIServer(
  42. ('0.0.0.0', int(port)),
  43. app,
  44. handler_class=WebSocketHandler)
  45. server.serve_forever()
  46. if use_reloader:
  47. from gevent import monkey
  48. monkey.patch_all()
  49. run = werkzeug.serving.run_with_reloader(run)
  50. run()
  51. @app.cli.command()
  52. @click.option('--debug', '-d', is_flag=True, help='Start the web server in debug mode')
  53. @click.option('--console-log', is_flag=True,
  54. help='Create logger that logs to the browser console (implies -d)')
  55. @click.option('--no-reload', '-n', 'use_reloader', flag_value=False,
  56. default=config.get('FLASK_USE_RELOAD'),
  57. help='Don\'t use the reloader in debug mode')
  58. @click.option('--address', '-a', default=config.get('SUPERSET_WEBSERVER_ADDRESS'),
  59. help='Specify the address to which to bind the web server')
  60. @click.option('--port', '-p', default=config.get('SUPERSET_WEBSERVER_PORT'),
  61. help='Specify the port on which to run the web server')
  62. @click.option('--workers', '-w', default=config.get('SUPERSET_WORKERS', 2),
  63. help='Number of gunicorn web server workers to fire up [DEPRECATED]')
  64. @click.option('--timeout', '-t', default=config.get('SUPERSET_WEBSERVER_TIMEOUT'),
  65. help='Specify the timeout (seconds) for the '
  66. 'gunicorn web server [DEPRECATED]')
  67. @click.option('--socket', '-s', default=config.get('SUPERSET_WEBSERVER_SOCKET'),
  68. help='Path to a UNIX socket as an alternative to address:port, e.g. '
  69. '/var/run/superset.sock. '
  70. 'Will override the address and port values. [DEPRECATED]')
  71. def runserver(debug, console_log, use_reloader, address, port, timeout, workers, socket):
  72. """Starts a Superset web server."""
  73. debug = debug or config.get('DEBUG') or console_log
  74. if debug:
  75. print(Fore.BLUE + '-=' * 20)
  76. print(
  77. Fore.YELLOW + 'Starting Superset server in ' +
  78. Fore.RED + 'DEBUG' +
  79. Fore.YELLOW + ' mode')
  80. print(Fore.BLUE + '-=' * 20)
  81. print(Style.RESET_ALL)
  82. if console_log:
  83. console_log_run(app, port, use_reloader)
  84. else:
  85. debug_run(app, port, use_reloader)
  86. else:
  87. logging.info(
  88. "The Gunicorn 'superset runserver' command is deprecated. Please "
  89. "use the 'gunicorn' command instead.")
  90. addr_str = ' unix:{socket} ' if socket else' {address}:{port} '
  91. cmd = (
  92. 'gunicorn '
  93. '-w {workers} '
  94. '--timeout {timeout} '
  95. '-b ' + addr_str +
  96. '--limit-request-line 0 '
  97. '--limit-request-field_size 0 '
  98. 'superset:app').format(**locals())
  99. print(Fore.GREEN + 'Starting server with command: ')
  100. print(Fore.YELLOW + cmd)
  101. print(Style.RESET_ALL)
  102. Popen(cmd, shell=True).wait()
  103. @app.cli.command()
  104. @click.option('--verbose', '-v', is_flag=True, help='Show extra information')
  105. def version(verbose):
  106. """Prints the current version number"""
  107. print(Fore.BLUE + '-=' * 15)
  108. print(Fore.YELLOW + 'Superset ' + Fore.CYAN + '{version}'.format(
  109. version=config.get('VERSION_STRING')))
  110. print(Fore.BLUE + '-=' * 15)
  111. if verbose:
  112. print('[DB] : ' + '{}'.format(db.engine))
  113. print(Style.RESET_ALL)
  114. def load_examples_run(load_test_data):
  115. print('Loading examples into {}'.format(db))
  116. data.load_css_templates()
  117. print('Loading energy related dataset')
  118. data.load_energy()
  119. print("Loading [World Bank's Health Nutrition and Population Stats]")
  120. data.load_world_bank_health_n_pop()
  121. print('Loading [Birth names]')
  122. data.load_birth_names()
  123. print('Loading [Random time series data]')
  124. data.load_random_time_series_data()
  125. print('Loading [Random long/lat data]')
  126. data.load_long_lat_data()
  127. print('Loading [Country Map data]')
  128. data.load_country_map_data()
  129. print('Loading [Multiformat time series]')
  130. data.load_multiformat_time_series_data()
  131. print('Loading [Paris GeoJson]')
  132. data.load_paris_iris_geojson()
  133. print('Loading [San Francisco population polygons]')
  134. data.load_sf_population_polygons()
  135. print('Loading [Flights data]')
  136. data.load_flights()
  137. print('Loading [BART lines]')
  138. data.load_bart_lines()
  139. print('Loading [Multi Line]')
  140. data.load_multi_line()
  141. print('Loading [Misc Charts] dashboard')
  142. data.load_misc_dashboard()
  143. if load_test_data:
  144. print('Loading [Unicode test data]')
  145. data.load_unicode_test_data()
  146. print('Loading DECK.gl demo')
  147. data.load_deck_dash()
  148. @app.cli.command()
  149. @click.option('--load-test-data', '-t', is_flag=True, help='Load additional test data')
  150. def load_examples(load_test_data):
  151. """Loads a set of Slices and Dashboards and a supporting dataset """
  152. load_examples_run(load_test_data)
  153. @app.cli.command()
  154. @click.option('--datasource', '-d', help='Specify which datasource name to load, if '
  155. 'omitted, all datasources will be refreshed')
  156. @click.option('--merge', '-m', is_flag=True, default=False,
  157. help='Specify using \'merge\' property during operation. '
  158. 'Default value is False.')
  159. def refresh_druid(datasource, merge):
  160. """Refresh druid datasources"""
  161. session = db.session()
  162. from superset.connectors.druid.models import DruidCluster
  163. for cluster in session.query(DruidCluster).all():
  164. try:
  165. cluster.refresh_datasources(datasource_name=datasource,
  166. merge_flag=merge)
  167. except Exception as e:
  168. print(
  169. "Error while processing cluster '{}'\n{}".format(
  170. cluster, str(e)))
  171. logging.exception(e)
  172. cluster.metadata_last_refreshed = datetime.now()
  173. print(
  174. 'Refreshed metadata from cluster '
  175. '[' + cluster.cluster_name + ']')
  176. session.commit()
  177. @app.cli.command()
  178. @click.option(
  179. '--path', '-p',
  180. help='Path to a single JSON file or path containing multiple JSON files'
  181. 'files to import (*.json)')
  182. @click.option(
  183. '--recursive', '-r',
  184. help='recursively search the path for json files')
  185. def import_dashboards(path, recursive=False):
  186. """Import dashboards from JSON"""
  187. p = Path(path)
  188. files = []
  189. if p.is_file():
  190. files.append(p)
  191. elif p.exists() and not recursive:
  192. files.extend(p.glob('*.json'))
  193. elif p.exists() and recursive:
  194. files.extend(p.rglob('*.json'))
  195. for f in files:
  196. logging.info('Importing dashboard from file %s', f)
  197. try:
  198. with f.open() as data_stream:
  199. dashboard_import_export_util.import_dashboards(
  200. db.session, data_stream)
  201. except Exception as e:
  202. logging.error('Error when importing dashboard from file %s', f)
  203. logging.error(e)
  204. @app.cli.command()
  205. @click.option(
  206. '--dashboard-file', '-f', default=None,
  207. help='Specify the the file to export to')
  208. @click.option(
  209. '--print_stdout', '-p',
  210. help='Print JSON to stdout')
  211. def export_dashboards(print_stdout, dashboard_file):
  212. """Export dashboards to JSON"""
  213. data = dashboard_import_export_util.export_dashboards(db.session)
  214. if print_stdout or not dashboard_file:
  215. print(data)
  216. if dashboard_file:
  217. logging.info('Exporting dashboards to %s', dashboard_file)
  218. with open(dashboard_file, 'w') as data_stream:
  219. data_stream.write(data)
  220. @app.cli.command()
  221. @click.option(
  222. '--path', '-p',
  223. help='Path to a single YAML file or path containing multiple YAML '
  224. 'files to import (*.yaml or *.yml)')
  225. @click.option(
  226. '--sync', '-s', 'sync', default='',
  227. help='comma seperated list of element types to synchronize '
  228. 'e.g. "metrics,columns" deletes metrics and columns in the DB '
  229. 'that are not specified in the YAML file')
  230. @click.option(
  231. '--recursive', '-r',
  232. help='recursively search the path for yaml files')
  233. def import_datasources(path, sync, recursive=False):
  234. """Import datasources from YAML"""
  235. sync_array = sync.split(',')
  236. p = Path(path)
  237. files = []
  238. if p.is_file():
  239. files.append(p)
  240. elif p.exists() and not recursive:
  241. files.extend(p.glob('*.yaml'))
  242. files.extend(p.glob('*.yml'))
  243. elif p.exists() and recursive:
  244. files.extend(p.rglob('*.yaml'))
  245. files.extend(p.rglob('*.yml'))
  246. for f in files:
  247. logging.info('Importing datasources from file %s', f)
  248. try:
  249. with f.open() as data_stream:
  250. dict_import_export_util.import_from_dict(
  251. db.session,
  252. yaml.safe_load(data_stream),
  253. sync=sync_array)
  254. except Exception as e:
  255. logging.error('Error when importing datasources from file %s', f)
  256. logging.error(e)
  257. @app.cli.command()
  258. @click.option(
  259. '--datasource-file', '-f', default=None,
  260. help='Specify the the file to export to')
  261. @click.option(
  262. '--print_stdout', '-p',
  263. help='Print YAML to stdout')
  264. @click.option(
  265. '--back-references', '-b',
  266. help='Include parent back references')
  267. @click.option(
  268. '--include-defaults', '-d',
  269. help='Include fields containing defaults')
  270. def export_datasources(print_stdout, datasource_file,
  271. back_references, include_defaults):
  272. """Export datasources to YAML"""
  273. data = dict_import_export_util.export_to_dict(
  274. session=db.session,
  275. recursive=True,
  276. back_references=back_references,
  277. include_defaults=include_defaults)
  278. if print_stdout or not datasource_file:
  279. yaml.safe_dump(data, stdout, default_flow_style=False)
  280. if datasource_file:
  281. logging.info('Exporting datasources to %s', datasource_file)
  282. with open(datasource_file, 'w') as data_stream:
  283. yaml.safe_dump(data, data_stream, default_flow_style=False)
  284. @app.cli.command()
  285. @click.option(
  286. '--back-references', '-b',
  287. help='Include parent back references')
  288. def export_datasource_schema(back_references):
  289. """Export datasource YAML schema to stdout"""
  290. data = dict_import_export_util.export_schema_to_dict(
  291. back_references=back_references)
  292. yaml.safe_dump(data, stdout, default_flow_style=False)
  293. @app.cli.command()
  294. def update_datasources_cache():
  295. """Refresh sqllab datasources cache"""
  296. from superset.models.core import Database
  297. for database in db.session.query(Database).all():
  298. print('Fetching {} datasources ...'.format(database.name))
  299. try:
  300. database.all_table_names(force=True)
  301. database.all_view_names(force=True)
  302. except Exception as e:
  303. print('{}'.format(str(e)))
  304. @app.cli.command()
  305. @click.option(
  306. '--workers', '-w',
  307. type=int,
  308. help='Number of celery server workers to fire up')
  309. def worker(workers):
  310. """Starts a Superset worker for async SQL query execution."""
  311. logging.info(
  312. "The 'superset worker' command is deprecated. Please use the 'celery "
  313. "worker' command instead.")
  314. if workers:
  315. celery_app.conf.update(CELERYD_CONCURRENCY=workers)
  316. elif config.get('SUPERSET_CELERY_WORKERS'):
  317. celery_app.conf.update(
  318. CELERYD_CONCURRENCY=config.get('SUPERSET_CELERY_WORKERS'))
  319. worker = celery_app.Worker(optimization='fair')
  320. worker.start()
  321. @app.cli.command()
  322. @click.option(
  323. '-p', '--port',
  324. default='5555',
  325. help='Port on which to start the Flower process')
  326. @click.option(
  327. '-a', '--address',
  328. default='localhost',
  329. help='Address on which to run the service')
  330. def flower(port, address):
  331. """Runs a Celery Flower web server
  332. Celery Flower is a UI to monitor the Celery operation on a given
  333. broker"""
  334. BROKER_URL = celery_app.conf.BROKER_URL
  335. cmd = (
  336. 'celery flower '
  337. '--broker={BROKER_URL} '
  338. '--port={port} '
  339. '--address={address} '
  340. ).format(**locals())
  341. logging.info(
  342. "The 'superset flower' command is deprecated. Please use the 'celery "
  343. "flower' command instead.")
  344. print(Fore.GREEN + 'Starting a Celery Flower instance')
  345. print(Fore.BLUE + '-=' * 40)
  346. print(Fore.YELLOW + cmd)
  347. print(Fore.BLUE + '-=' * 40)
  348. Popen(cmd, shell=True).wait()
  349. @app.cli.command()
  350. def load_test_users():
  351. """
  352. Loads admin, alpha, and gamma user for testing purposes
  353. Syncs permissions for those users/roles
  354. """
  355. load_test_users_run()
  356. def load_test_users_run():
  357. """
  358. Loads admin, alpha, and gamma user for testing purposes
  359. Syncs permissions for those users/roles
  360. """
  361. if config.get('TESTING'):
  362. security_manager.sync_role_definitions()
  363. gamma_sqllab_role = security_manager.add_role('gamma_sqllab')
  364. for perm in security_manager.find_role('Gamma').permissions:
  365. security_manager.add_permission_role(gamma_sqllab_role, perm)
  366. utils.get_or_create_main_db()
  367. db_perm = utils.get_main_database(security_manager.get_session).perm
  368. security_manager.merge_perm('database_access', db_perm)
  369. db_pvm = security_manager.find_permission_view_menu(
  370. view_menu_name=db_perm, permission_name='database_access')
  371. gamma_sqllab_role.permissions.append(db_pvm)
  372. for perm in security_manager.find_role('sql_lab').permissions:
  373. security_manager.add_permission_role(gamma_sqllab_role, perm)
  374. admin = security_manager.find_user('admin')
  375. if not admin:
  376. security_manager.add_user(
  377. 'admin', 'admin', ' user', 'admin@fab.org',
  378. security_manager.find_role('Admin'),
  379. password='general')
  380. gamma = security_manager.find_user('gamma')
  381. if not gamma:
  382. security_manager.add_user(
  383. 'gamma', 'gamma', 'user', 'gamma@fab.org',
  384. security_manager.find_role('Gamma'),
  385. password='general')
  386. gamma2 = security_manager.find_user('gamma2')
  387. if not gamma2:
  388. security_manager.add_user(
  389. 'gamma2', 'gamma2', 'user', 'gamma2@fab.org',
  390. security_manager.find_role('Gamma'),
  391. password='general')
  392. gamma_sqllab_user = security_manager.find_user('gamma_sqllab')
  393. if not gamma_sqllab_user:
  394. security_manager.add_user(
  395. 'gamma_sqllab', 'gamma_sqllab', 'user', 'gamma_sqllab@fab.org',
  396. gamma_sqllab_role, password='general')
  397. alpha = security_manager.find_user('alpha')
  398. if not alpha:
  399. security_manager.add_user(
  400. 'alpha', 'alpha', 'user', 'alpha@fab.org',
  401. security_manager.find_role('Alpha'),
  402. password='general')
  403. security_manager.get_session.commit()