Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

561 righe
18 KiB

  1. from __future__ import unicode_literals, absolute_import, print_function
  2. import click
  3. import hashlib, os, sys
  4. import frappe
  5. from frappe import _
  6. from _mysql_exceptions import ProgrammingError
  7. from frappe.commands import pass_context, get_site
  8. from frappe.commands.scheduler import _is_scheduler_enabled
  9. from frappe.limits import update_limits, get_limits
  10. from frappe.installer import update_site_config
  11. from frappe.utils import touch_file, get_site_path
  12. from six import text_type
  13. @click.command('new-site')
  14. @click.argument('site')
  15. @click.option('--db-name', help='Database name')
  16. @click.option('--mariadb-root-username', default='root', help='Root username for MariaDB')
  17. @click.option('--mariadb-root-password', help='Root password for MariaDB')
  18. @click.option('--admin-password', help='Administrator password for new site', default=None)
  19. @click.option('--verbose', is_flag=True, default=False, help='Verbose')
  20. @click.option('--force', help='Force restore if site/database already exists', is_flag=True, default=False)
  21. @click.option('--source_sql', help='Initiate database with a SQL file')
  22. @click.option('--install-app', multiple=True, help='Install app after installation')
  23. def new_site(site, mariadb_root_username=None, mariadb_root_password=None, admin_password=None, verbose=False, install_apps=None, source_sql=None, force=None, install_app=None, db_name=None):
  24. "Create a new site"
  25. frappe.init(site=site, new_site=True)
  26. _new_site(db_name, site, mariadb_root_username=mariadb_root_username, mariadb_root_password=mariadb_root_password, admin_password=admin_password,
  27. verbose=verbose, install_apps=install_app, source_sql=source_sql, force=force)
  28. if len(frappe.utils.get_sites()) == 1:
  29. use(site)
  30. def _new_site(db_name, site, mariadb_root_username=None, mariadb_root_password=None, admin_password=None,
  31. verbose=False, install_apps=None, source_sql=None,force=False, reinstall=False):
  32. """Install a new Frappe site"""
  33. if not db_name:
  34. db_name = hashlib.sha1(site).hexdigest()[:16]
  35. from frappe.installer import install_db, make_site_dirs
  36. from frappe.installer import install_app as _install_app
  37. import frappe.utils.scheduler
  38. frappe.init(site=site)
  39. try:
  40. # enable scheduler post install?
  41. enable_scheduler = _is_scheduler_enabled()
  42. except Exception:
  43. enable_scheduler = False
  44. make_site_dirs()
  45. installing = None
  46. try:
  47. installing = touch_file(get_site_path('locks', 'installing.lock'))
  48. install_db(root_login=mariadb_root_username, root_password=mariadb_root_password, db_name=db_name,
  49. admin_password=admin_password, verbose=verbose, source_sql=source_sql,force=force, reinstall=reinstall)
  50. apps_to_install = ['frappe'] + (frappe.conf.get("install_apps") or []) + (list(install_apps) or [])
  51. for app in apps_to_install:
  52. _install_app(app, verbose=verbose, set_as_patched=not source_sql)
  53. frappe.utils.scheduler.toggle_scheduler(enable_scheduler)
  54. frappe.db.commit()
  55. scheduler_status = "disabled" if frappe.utils.scheduler.is_scheduler_disabled() else "enabled"
  56. print("*** Scheduler is", scheduler_status, "***")
  57. except frappe.exceptions.ImproperDBConfigurationError:
  58. _drop_site(site, mariadb_root_username, mariadb_root_password, force=True)
  59. finally:
  60. if installing and os.path.exists(installing):
  61. os.remove(installing)
  62. frappe.destroy()
  63. @click.command('restore')
  64. @click.argument('sql-file-path')
  65. @click.option('--mariadb-root-username', default='root', help='Root username for MariaDB')
  66. @click.option('--mariadb-root-password', help='Root password for MariaDB')
  67. @click.option('--db-name', help='Database name for site in case it is a new one')
  68. @click.option('--admin-password', help='Administrator password for new site')
  69. @click.option('--install-app', multiple=True, help='Install app after installation')
  70. @click.option('--with-public-files', help='Restores the public files of the site, given path to its tar file')
  71. @click.option('--with-private-files', help='Restores the private files of the site, given path to its tar file')
  72. @pass_context
  73. def restore(context, sql_file_path, mariadb_root_username=None, mariadb_root_password=None, db_name=None, verbose=None, install_app=None, admin_password=None, force=None, with_public_files=None, with_private_files=None):
  74. "Restore site database from an sql file"
  75. from frappe.installer import extract_sql_gzip, extract_tar_files
  76. # Extract the gzip file if user has passed *.sql.gz file instead of *.sql file
  77. if not os.path.exists(sql_file_path):
  78. sql_file_path = '../' + sql_file_path
  79. if not os.path.exists(sql_file_path):
  80. print('Invalid path {0}' + sql_file_path[3:])
  81. sys.exit(1)
  82. if sql_file_path.endswith('sql.gz'):
  83. sql_file_path = extract_sql_gzip(os.path.abspath(sql_file_path))
  84. site = get_site(context)
  85. frappe.init(site=site)
  86. _new_site(frappe.conf.db_name, site, mariadb_root_username=mariadb_root_username,
  87. mariadb_root_password=mariadb_root_password, admin_password=admin_password,
  88. verbose=context.verbose, install_apps=install_app, source_sql=sql_file_path,
  89. force=context.force)
  90. # Extract public and/or private files to the restored site, if user has given the path
  91. if with_public_files:
  92. public = extract_tar_files(site, with_public_files, 'public')
  93. os.remove(public)
  94. if with_private_files:
  95. private = extract_tar_files(site, with_private_files, 'private')
  96. os.remove(private)
  97. @click.command('reinstall')
  98. @click.option('--admin-password', help='Administrator Password for reinstalled site')
  99. @click.option('--yes', is_flag=True, default=False, help='Pass --yes to skip confirmation')
  100. @pass_context
  101. def reinstall(context, admin_password=None, yes=False):
  102. "Reinstall site ie. wipe all data and start over"
  103. site = get_site(context)
  104. _reinstall(site, admin_password, yes, verbose=context.verbose)
  105. def _reinstall(site, admin_password=None, yes=False, verbose=False):
  106. if not yes:
  107. click.confirm('This will wipe your database. Are you sure you want to reinstall?', abort=True)
  108. try:
  109. frappe.init(site=site)
  110. frappe.connect()
  111. frappe.clear_cache()
  112. installed = frappe.get_installed_apps()
  113. frappe.clear_cache()
  114. except Exception:
  115. installed = []
  116. finally:
  117. if frappe.db:
  118. frappe.db.close()
  119. frappe.destroy()
  120. frappe.init(site=site)
  121. _new_site(frappe.conf.db_name, site, verbose=verbose, force=True, reinstall=True,
  122. install_apps=installed, admin_password=admin_password)
  123. @click.command('install-app')
  124. @click.argument('app')
  125. @pass_context
  126. def install_app(context, app):
  127. "Install a new app to site"
  128. from frappe.installer import install_app as _install_app
  129. for site in context.sites:
  130. frappe.init(site=site)
  131. frappe.connect()
  132. try:
  133. _install_app(app, verbose=context.verbose)
  134. finally:
  135. frappe.destroy()
  136. @click.command('list-apps')
  137. @pass_context
  138. def list_apps(context):
  139. "List apps in site"
  140. site = get_site(context)
  141. frappe.init(site=site)
  142. frappe.connect()
  143. print("\n".join(frappe.get_installed_apps()))
  144. frappe.destroy()
  145. @click.command('add-system-manager')
  146. @click.argument('email')
  147. @click.option('--first-name')
  148. @click.option('--last-name')
  149. @click.option('--send-welcome-email', default=False, is_flag=True)
  150. @pass_context
  151. def add_system_manager(context, email, first_name, last_name, send_welcome_email):
  152. "Add a new system manager to a site"
  153. import frappe.utils.user
  154. for site in context.sites:
  155. frappe.connect(site=site)
  156. try:
  157. frappe.utils.user.add_system_manager(email, first_name, last_name, send_welcome_email)
  158. frappe.db.commit()
  159. finally:
  160. frappe.destroy()
  161. @click.command('disable-user')
  162. @click.argument('email')
  163. @pass_context
  164. def disable_user(context, email):
  165. site = get_site(context)
  166. with frappe.init_site(site):
  167. frappe.connect()
  168. user = frappe.get_doc("User", email)
  169. user.enabled = 0
  170. user.save(ignore_permissions=True)
  171. frappe.db.commit()
  172. @click.command('migrate')
  173. @click.option('--rebuild-website', help="Rebuild webpages after migration")
  174. @pass_context
  175. def migrate(context, rebuild_website=False):
  176. "Run patches, sync schema and rebuild files/translations"
  177. from frappe.migrate import migrate
  178. for site in context.sites:
  179. print('Migrating', site)
  180. frappe.init(site=site)
  181. frappe.connect()
  182. try:
  183. migrate(context.verbose, rebuild_website=rebuild_website)
  184. finally:
  185. frappe.destroy()
  186. @click.command('run-patch')
  187. @click.argument('module')
  188. @pass_context
  189. def run_patch(context, module):
  190. "Run a particular patch"
  191. import frappe.modules.patch_handler
  192. for site in context.sites:
  193. frappe.init(site=site)
  194. try:
  195. frappe.connect()
  196. frappe.modules.patch_handler.run_single(module, force=context.force)
  197. finally:
  198. frappe.destroy()
  199. @click.command('reload-doc')
  200. @click.argument('module')
  201. @click.argument('doctype')
  202. @click.argument('docname')
  203. @pass_context
  204. def reload_doc(context, module, doctype, docname):
  205. "Reload schema for a DocType"
  206. for site in context.sites:
  207. try:
  208. frappe.init(site=site)
  209. frappe.connect()
  210. frappe.reload_doc(module, doctype, docname, force=context.force)
  211. frappe.db.commit()
  212. finally:
  213. frappe.destroy()
  214. @click.command('reload-doctype')
  215. @click.argument('doctype')
  216. @pass_context
  217. def reload_doctype(context, doctype):
  218. "Reload schema for a DocType"
  219. for site in context.sites:
  220. try:
  221. frappe.init(site=site)
  222. frappe.connect()
  223. frappe.reload_doctype(doctype, force=context.force)
  224. frappe.db.commit()
  225. finally:
  226. frappe.destroy()
  227. @click.command('use')
  228. @click.argument('site')
  229. def _use(site, sites_path='.'):
  230. "Set a default site"
  231. use(site, sites_path=sites_path)
  232. def use(site, sites_path='.'):
  233. with open(os.path.join(sites_path, "currentsite.txt"), "w") as sitefile:
  234. sitefile.write(site)
  235. @click.command('backup')
  236. @click.option('--with-files', default=False, is_flag=True, help="Take backup with files")
  237. @pass_context
  238. def backup(context, with_files=False, backup_path_db=None, backup_path_files=None,
  239. backup_path_private_files=None, quiet=False):
  240. "Backup"
  241. from frappe.utils.backups import scheduled_backup
  242. verbose = context.verbose
  243. for site in context.sites:
  244. frappe.init(site=site)
  245. frappe.connect()
  246. odb = scheduled_backup(ignore_files=not with_files, backup_path_db=backup_path_db, backup_path_files=backup_path_files, backup_path_private_files=backup_path_private_files, force=True)
  247. if verbose:
  248. from frappe.utils import now
  249. print("database backup taken -", odb.backup_path_db, "- on", now())
  250. if with_files:
  251. print("files backup taken -", odb.backup_path_files, "- on", now())
  252. print("private files backup taken -", odb.backup_path_private_files, "- on", now())
  253. frappe.destroy()
  254. @click.command('remove-from-installed-apps')
  255. @click.argument('app')
  256. @pass_context
  257. def remove_from_installed_apps(context, app):
  258. "Remove app from site's installed-apps list"
  259. from frappe.installer import remove_from_installed_apps
  260. for site in context.sites:
  261. try:
  262. frappe.init(site=site)
  263. frappe.connect()
  264. remove_from_installed_apps(app)
  265. finally:
  266. frappe.destroy()
  267. @click.command('uninstall-app')
  268. @click.argument('app')
  269. @click.option('--yes', '-y', help='To bypass confirmation prompt for uninstalling the app', is_flag=True, default=False, multiple=True)
  270. @click.option('--dry-run', help='List all doctypes that will be deleted', is_flag=True, default=False)
  271. @pass_context
  272. def uninstall(context, app, dry_run=False, yes=False):
  273. "Remove app and linked modules from site"
  274. from frappe.installer import remove_app
  275. for site in context.sites:
  276. try:
  277. frappe.init(site=site)
  278. frappe.connect()
  279. remove_app(app, dry_run, yes)
  280. finally:
  281. frappe.destroy()
  282. @click.command('drop-site')
  283. @click.argument('site')
  284. @click.option('--root-login', default='root')
  285. @click.option('--root-password')
  286. @click.option('--archived-sites-path')
  287. @click.option('--force', help='Force drop-site even if an error is encountered', is_flag=True, default=False)
  288. def drop_site(site, root_login='root', root_password=None, archived_sites_path=None, force=False):
  289. _drop_site(site, root_login, root_password, archived_sites_path, force)
  290. def _drop_site(site, root_login='root', root_password=None, archived_sites_path=None, force=False):
  291. "Remove site from database and filesystem"
  292. from frappe.installer import get_root_connection
  293. from frappe.model.db_schema import DbManager
  294. from frappe.utils.backups import scheduled_backup
  295. frappe.init(site=site)
  296. frappe.connect()
  297. try:
  298. scheduled_backup(ignore_files=False, force=True)
  299. except ProgrammingError as err:
  300. if err[0] == 1146:
  301. if force:
  302. pass
  303. else:
  304. click.echo("="*80)
  305. click.echo("Error: The operation has stopped because backup of {s}'s database failed.".format(s=site))
  306. click.echo("Reason: {reason}{sep}".format(reason=err[1], sep="\n"))
  307. click.echo("Fix the issue and try again.")
  308. click.echo(
  309. "Hint: Use 'bench drop-site {s} --force' to force the removal of {s}".format(sep="\n", tab="\t", s=site)
  310. )
  311. sys.exit(1)
  312. db_name = frappe.local.conf.db_name
  313. frappe.local.db = get_root_connection(root_login, root_password)
  314. dbman = DbManager(frappe.local.db)
  315. dbman.delete_user(db_name)
  316. dbman.drop_database(db_name)
  317. if not archived_sites_path:
  318. archived_sites_path = os.path.join(frappe.get_app_path('frappe'), '..', '..', '..', 'archived_sites')
  319. if not os.path.exists(archived_sites_path):
  320. os.mkdir(archived_sites_path)
  321. move(archived_sites_path, site)
  322. def move(dest_dir, site):
  323. if not os.path.isdir(dest_dir):
  324. raise Exception("destination is not a directory or does not exist")
  325. frappe.init(site)
  326. old_path = frappe.utils.get_site_path()
  327. new_path = os.path.join(dest_dir, site)
  328. # check if site dump of same name already exists
  329. site_dump_exists = True
  330. count = 0
  331. while site_dump_exists:
  332. final_new_path = new_path + (count and str(count) or "")
  333. site_dump_exists = os.path.exists(final_new_path)
  334. count = int(count or 0) + 1
  335. os.rename(old_path, final_new_path)
  336. frappe.destroy()
  337. return final_new_path
  338. @click.command('set-admin-password')
  339. @click.argument('admin-password')
  340. @pass_context
  341. def set_admin_password(context, admin_password):
  342. "Set Administrator password for a site"
  343. import getpass
  344. from frappe.utils.password import update_password
  345. for site in context.sites:
  346. try:
  347. frappe.init(site=site)
  348. while not admin_password:
  349. admin_password = getpass.getpass("Administrator's password for {0}: ".format(site))
  350. frappe.connect()
  351. update_password('Administrator', admin_password)
  352. frappe.db.commit()
  353. admin_password = None
  354. finally:
  355. frappe.destroy()
  356. @click.command('set-limit')
  357. @click.option('--site', help='site name')
  358. @click.argument('limit')
  359. @click.argument('value')
  360. @pass_context
  361. def set_limit(context, site, limit, value):
  362. """Sets user / space / email limit for a site"""
  363. _set_limits(context, site, ((limit, value),))
  364. @click.command('set-limits')
  365. @click.option('--site', help='site name')
  366. @click.option('--limit', 'limits', type=(text_type, text_type), multiple=True)
  367. @pass_context
  368. def set_limits(context, site, limits):
  369. _set_limits(context, site, limits)
  370. def _set_limits(context, site, limits):
  371. import datetime
  372. if not limits:
  373. return
  374. if not site:
  375. site = get_site(context)
  376. with frappe.init_site(site):
  377. frappe.connect()
  378. new_limits = {}
  379. for limit, value in limits:
  380. if limit not in ('emails', 'space', 'users', 'email_group',
  381. 'expiry', 'support_email', 'support_chat', 'upgrade_url'):
  382. frappe.throw(_('Invalid limit {0}').format(limit))
  383. if limit=='expiry' and value:
  384. try:
  385. datetime.datetime.strptime(value, '%Y-%m-%d')
  386. except ValueError:
  387. raise ValueError("Incorrect data format, should be YYYY-MM-DD")
  388. elif limit=='space':
  389. value = float(value)
  390. elif limit in ('users', 'emails', 'email_group'):
  391. value = int(value)
  392. new_limits[limit] = value
  393. update_limits(new_limits)
  394. @click.command('clear-limits')
  395. @click.option('--site', help='site name')
  396. @click.argument('limits', nargs=-1, type=click.Choice(['emails', 'space', 'users', 'email_group',
  397. 'expiry', 'support_email', 'support_chat', 'upgrade_url']))
  398. @pass_context
  399. def clear_limits(context, site, limits):
  400. """Clears given limit from the site config, and removes limit from site config if its empty"""
  401. from frappe.limits import clear_limit as _clear_limit
  402. if not limits:
  403. return
  404. if not site:
  405. site = get_site(context)
  406. with frappe.init_site(site):
  407. _clear_limit(limits)
  408. # Remove limits from the site_config, if it's empty
  409. limits = get_limits()
  410. if not limits:
  411. update_site_config('limits', 'None', validate=False)
  412. @click.command('set-last-active-for-user')
  413. @click.option('--user', help="Setup last active date for user")
  414. @pass_context
  415. def set_last_active_for_user(context, user=None):
  416. "Set users last active date to current datetime"
  417. from frappe.core.doctype.user.user import get_system_users
  418. from frappe.utils.user import set_last_active_to_now
  419. site = get_site(context)
  420. with frappe.init_site(site):
  421. frappe.connect()
  422. if not user:
  423. user = get_system_users(limit=1)
  424. if len(user) > 0:
  425. user = user[0]
  426. else:
  427. return
  428. set_last_active_to_now(user)
  429. frappe.db.commit()
  430. @click.command('publish-realtime')
  431. @click.argument('event')
  432. @click.option('--message')
  433. @click.option('--room')
  434. @click.option('--user')
  435. @click.option('--doctype')
  436. @click.option('--docname')
  437. @click.option('--after-commit')
  438. @pass_context
  439. def publish_realtime(context, event, message, room, user, doctype, docname, after_commit):
  440. "Publish realtime event from bench"
  441. from frappe import publish_realtime
  442. for site in context.sites:
  443. try:
  444. frappe.init(site=site)
  445. frappe.connect()
  446. publish_realtime(event, message=message, room=room, user=user, doctype=doctype, docname=docname,
  447. after_commit=after_commit)
  448. frappe.db.commit()
  449. finally:
  450. frappe.destroy()
  451. commands = [
  452. add_system_manager,
  453. backup,
  454. drop_site,
  455. install_app,
  456. list_apps,
  457. migrate,
  458. new_site,
  459. reinstall,
  460. reload_doc,
  461. reload_doctype,
  462. remove_from_installed_apps,
  463. restore,
  464. run_patch,
  465. set_admin_password,
  466. uninstall,
  467. set_limit,
  468. set_limits,
  469. clear_limits,
  470. disable_user,
  471. _use,
  472. set_last_active_for_user,
  473. publish_realtime,
  474. ]