PageRenderTime 177ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 0ms

/ee/cli/plugins/site.py

https://gitlab.com/Symons/easyengine
Python | 1564 lines | 1552 code | 8 blank | 4 comment | 15 complexity | c078a9ec67574300ef581c2f4bd1d025 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. # """EasyEngine site controller."""
  2. from cement.core.controller import CementBaseController, expose
  3. from cement.core import handler, hook
  4. from ee.core.variables import EEVariables
  5. from ee.core.domainvalidate import ValidateDomain
  6. from ee.core.fileutils import EEFileUtils
  7. from ee.cli.plugins.site_functions import *
  8. from ee.core.services import EEService
  9. from ee.cli.plugins.sitedb import *
  10. from ee.core.git import EEGit
  11. from subprocess import Popen
  12. from ee.core.nginxhashbucket import hashbucket
  13. import sys
  14. import os
  15. import glob
  16. import subprocess
  17. def ee_site_hook(app):
  18. # do something with the ``app`` object here.
  19. from ee.core.database import init_db
  20. import ee.cli.plugins.models
  21. init_db(app)
  22. class EESiteController(CementBaseController):
  23. class Meta:
  24. label = 'site'
  25. stacked_on = 'base'
  26. stacked_type = 'nested'
  27. description = ('Performs website specific operations')
  28. arguments = [
  29. (['site_name'],
  30. dict(help='Website name', nargs='?')),
  31. ]
  32. usage = "ee site (command) <site_name> [options]"
  33. @expose(hide=True)
  34. def default(self):
  35. self.app.args.print_help()
  36. @expose(help="Enable site example.com")
  37. def enable(self):
  38. if not self.app.pargs.site_name:
  39. try:
  40. while not self.app.pargs.site_name:
  41. self.app.pargs.site_name = (input('Enter site name : ')
  42. .strip())
  43. except IOError as e:
  44. Log.error(self, 'could not input site name')
  45. self.app.pargs.site_name = self.app.pargs.site_name.strip()
  46. # validate domain name
  47. (ee_domain, ee_www_domain) = ValidateDomain(self.app.pargs.site_name)
  48. # check if site exists
  49. if not check_domain_exists(self, ee_domain):
  50. Log.error(self, "site {0} does not exist".format(ee_domain))
  51. if os.path.isfile('/etc/nginx/sites-available/{0}'
  52. .format(ee_domain)):
  53. Log.info(self, "Enable domain {0:10} \t".format(ee_domain), end='')
  54. EEFileUtils.create_symlink(self,
  55. ['/etc/nginx/sites-available/{0}'
  56. .format(ee_domain),
  57. '/etc/nginx/sites-enabled/{0}'
  58. .format(ee_domain)])
  59. EEGit.add(self, ["/etc/nginx"],
  60. msg="Enabled {0} "
  61. .format(ee_domain))
  62. updateSiteInfo(self, ee_domain, enabled=True)
  63. Log.info(self, "[" + Log.ENDC + "OK" + Log.OKBLUE + "]")
  64. if not EEService.reload_service(self, 'nginx'):
  65. Log.error(self, "service nginx reload failed. "
  66. "check issues with `nginx -t` command")
  67. else:
  68. Log.error(self, "nginx configuration file does not exist"
  69. .format(ee_domain))
  70. @expose(help="Disable site example.com")
  71. def disable(self):
  72. if not self.app.pargs.site_name:
  73. try:
  74. while not self.app.pargs.site_name:
  75. self.app.pargs.site_name = (input('Enter site name : ')
  76. .strip())
  77. except IOError as e:
  78. Log.error(self, 'could not input site name')
  79. self.app.pargs.site_name = self.app.pargs.site_name.strip()
  80. (ee_domain, ee_www_domain) = ValidateDomain(self.app.pargs.site_name)
  81. # check if site exists
  82. if not check_domain_exists(self, ee_domain):
  83. Log.error(self, "site {0} does not exist".format(ee_domain))
  84. if os.path.isfile('/etc/nginx/sites-available/{0}'
  85. .format(ee_domain)):
  86. Log.info(self, "Disable domain {0:10} \t"
  87. .format(ee_domain), end='')
  88. if not os.path.isfile('/etc/nginx/sites-enabled/{0}'
  89. .format(ee_domain)):
  90. Log.debug(self, "Site {0} already disabled".format(ee_domain))
  91. Log.info(self, "[" + Log.FAIL + "Failed" + Log.OKBLUE+"]")
  92. else:
  93. EEFileUtils.remove_symlink(self,
  94. '/etc/nginx/sites-enabled/{0}'
  95. .format(ee_domain))
  96. EEGit.add(self, ["/etc/nginx"],
  97. msg="Disabled {0} "
  98. .format(ee_domain))
  99. updateSiteInfo(self, ee_domain, enabled=False)
  100. Log.info(self, "[" + Log.ENDC + "OK" + Log.OKBLUE + "]")
  101. if not EEService.reload_service(self, 'nginx'):
  102. Log.error(self, "service nginx reload failed. "
  103. "check issues with `nginx -t` command")
  104. else:
  105. Log.error(self, "nginx configuration file does not exist"
  106. .format(ee_domain))
  107. @expose(help="Get example.com information")
  108. def info(self):
  109. if not self.app.pargs.site_name:
  110. try:
  111. while not self.app.pargs.site_name:
  112. self.app.pargs.site_name = (input('Enter site name : ')
  113. .strip())
  114. except IOError as e:
  115. Log.error(self, 'could not input site name')
  116. self.app.pargs.site_name = self.app.pargs.site_name.strip()
  117. (ee_domain, ee_www_domain) = ValidateDomain(self.app.pargs.site_name)
  118. ee_db_name = ''
  119. ee_db_user = ''
  120. ee_db_pass = ''
  121. hhvm = ''
  122. if not check_domain_exists(self, ee_domain):
  123. Log.error(self, "site {0} does not exist".format(ee_domain))
  124. if os.path.isfile('/etc/nginx/sites-available/{0}'
  125. .format(ee_domain)):
  126. siteinfo = getSiteInfo(self, ee_domain)
  127. sitetype = siteinfo.site_type
  128. cachetype = siteinfo.cache_type
  129. ee_site_webroot = siteinfo.site_path
  130. access_log = (ee_site_webroot + '/logs/access.log')
  131. error_log = (ee_site_webroot + '/logs/error.log')
  132. ee_db_name = siteinfo.db_name
  133. ee_db_user = siteinfo.db_user
  134. ee_db_pass = siteinfo.db_password
  135. ee_db_host = siteinfo.db_host
  136. if sitetype != "html":
  137. hhvm = ("enabled" if siteinfo.is_hhvm else "disabled")
  138. if sitetype == "proxy":
  139. access_log = "/var/log/nginx/{0}.access.log".format(ee_domain)
  140. error_log = "/var/log/nginx/{0}.error.log".format(ee_domain)
  141. ee_site_webroot = ''
  142. pagespeed = ("enabled" if siteinfo.is_pagespeed else "disabled")
  143. data = dict(domain=ee_domain, webroot=ee_site_webroot,
  144. accesslog=access_log, errorlog=error_log,
  145. dbname=ee_db_name, dbuser=ee_db_user,
  146. dbpass=ee_db_pass, hhvm=hhvm, pagespeed=pagespeed,
  147. type=sitetype + " " + cachetype + " ({0})"
  148. .format("enabled" if siteinfo.is_enabled else
  149. "disabled"))
  150. self.app.render((data), 'siteinfo.mustache')
  151. else:
  152. Log.error(self, "nginx configuration file does not exist"
  153. .format(ee_domain))
  154. @expose(help="Monitor example.com logs")
  155. def log(self):
  156. self.app.pargs.site_name = self.app.pargs.site_name.strip()
  157. (ee_domain, ee_www_domain) = ValidateDomain(self.app.pargs.site_name)
  158. ee_site_webroot = getSiteInfo(self, ee_domain).site_path
  159. if not check_domain_exists(self, ee_domain):
  160. Log.error(self, "site {0} does not exist".format(ee_domain))
  161. logfiles = glob.glob(ee_site_webroot + '/logs/*.log')
  162. if logfiles:
  163. logwatch(self, logfiles)
  164. @expose(help="Display Nginx configuration of example.com")
  165. def show(self):
  166. if not self.app.pargs.site_name:
  167. try:
  168. while not self.app.pargs.site_name:
  169. self.app.pargs.site_name = (input('Enter site name : ')
  170. .strip())
  171. except IOError as e:
  172. Log.error(self, 'could not input site name')
  173. # TODO Write code for ee site edit command here
  174. self.app.pargs.site_name = self.app.pargs.site_name.strip()
  175. (ee_domain, ee_www_domain) = ValidateDomain(self.app.pargs.site_name)
  176. if not check_domain_exists(self, ee_domain):
  177. Log.error(self, "site {0} does not exist".format(ee_domain))
  178. if os.path.isfile('/etc/nginx/sites-available/{0}'
  179. .format(ee_domain)):
  180. Log.info(self, "Display NGINX configuration for {0}"
  181. .format(ee_domain))
  182. f = open('/etc/nginx/sites-available/{0}'.format(ee_domain),
  183. encoding='utf-8', mode='r')
  184. text = f.read()
  185. Log.info(self, Log.ENDC + text)
  186. f.close()
  187. else:
  188. Log.error(self, "nginx configuration file does not exists"
  189. .format(ee_domain))
  190. @expose(help="Change directory to site webroot")
  191. def cd(self):
  192. if not self.app.pargs.site_name:
  193. try:
  194. while not self.app.pargs.site_name:
  195. self.app.pargs.site_name = (input('Enter site name : ')
  196. .strip())
  197. except IOError as e:
  198. Log.error(self, 'Unable to read input, please try again')
  199. self.app.pargs.site_name = self.app.pargs.site_name.strip()
  200. (ee_domain, ee_www_domain) = ValidateDomain(self.app.pargs.site_name)
  201. if not check_domain_exists(self, ee_domain):
  202. Log.error(self, "site {0} does not exist".format(ee_domain))
  203. ee_site_webroot = getSiteInfo(self, ee_domain).site_path
  204. EEFileUtils.chdir(self, ee_site_webroot)
  205. try:
  206. subprocess.call(['bash'])
  207. except OSError as e:
  208. Log.debug(self, "{0}{1}".format(e.errno, e.strerror))
  209. Log.error(self, "unable to change directory")
  210. class EESiteEditController(CementBaseController):
  211. class Meta:
  212. label = 'edit'
  213. stacked_on = 'site'
  214. stacked_type = 'nested'
  215. description = ('Edit Nginx configuration of site')
  216. arguments = [
  217. (['site_name'],
  218. dict(help='domain name for the site',
  219. nargs='?')),
  220. (['--pagespeed'],
  221. dict(help="edit pagespeed configuration for site",
  222. action='store_true')),
  223. ]
  224. @expose(hide=True)
  225. def default(self):
  226. if not self.app.pargs.site_name:
  227. try:
  228. while not self.app.pargs.site_name:
  229. self.app.pargs.site_name = (input('Enter site name : ')
  230. .strip())
  231. except IOError as e:
  232. Log.error(self, 'Unable to read input, Please try again')
  233. self.app.pargs.site_name = self.app.pargs.site_name.strip()
  234. (ee_domain, ee_www_domain) = ValidateDomain(self.app.pargs.site_name)
  235. if not check_domain_exists(self, ee_domain):
  236. Log.error(self, "site {0} does not exist".format(ee_domain))
  237. ee_site_webroot = EEVariables.ee_webroot + ee_domain
  238. if not self.app.pargs.pagespeed:
  239. if os.path.isfile('/etc/nginx/sites-available/{0}'
  240. .format(ee_domain)):
  241. try:
  242. EEShellExec.invoke_editor(self, '/etc/nginx/sites-availa'
  243. 'ble/{0}'.format(ee_domain))
  244. except CommandExecutionError as e:
  245. Log.error(self, "Failed invoke editor")
  246. if (EEGit.checkfilestatus(self, "/etc/nginx",
  247. '/etc/nginx/sites-available/{0}'.format(ee_domain))):
  248. EEGit.add(self, ["/etc/nginx"], msg="Edit website: {0}"
  249. .format(ee_domain))
  250. # Reload NGINX
  251. if not EEService.reload_service(self, 'nginx'):
  252. Log.error(self, "service nginx reload failed. "
  253. "check issues with `nginx -t` command")
  254. else:
  255. Log.error(self, "nginx configuration file does not exists"
  256. .format(ee_domain))
  257. elif self.app.pargs.pagespeed:
  258. if os.path.isfile('{0}/conf/nginx/pagespeed.conf'
  259. .format(ee_site_webroot)):
  260. try:
  261. EEShellExec.invoke_editor(self, '{0}/conf/nginx/'
  262. 'pagespeed.conf'
  263. .format(ee_site_webroot))
  264. except CommandExecutionError as e:
  265. Log.error(self, "Failed invoke editor")
  266. if (EEGit.checkfilestatus(self, "{0}/conf/nginx"
  267. .format(ee_site_webroot),
  268. '{0}/conf/nginx/pagespeed.conf'.format(ee_site_webroot))):
  269. EEGit.add(self, ["{0}/conf/nginx".format(ee_site_webroot)],
  270. msg="Edit Pagespped config of site: {0}"
  271. .format(ee_domain))
  272. # Reload NGINX
  273. if not EEService.reload_service(self, 'nginx'):
  274. Log.error(self, "service nginx reload failed. "
  275. "check issues with `nginx -t` command")
  276. else:
  277. Log.error(self, "Pagespeed configuration file does not exists"
  278. .format(ee_domain))
  279. class EESiteCreateController(CementBaseController):
  280. class Meta:
  281. label = 'create'
  282. stacked_on = 'site'
  283. stacked_type = 'nested'
  284. description = ('this commands set up configuration and installs '
  285. 'required files as options are provided')
  286. arguments = [
  287. (['site_name'],
  288. dict(help='domain name for the site to be created.',
  289. nargs='?')),
  290. (['--html'],
  291. dict(help="create html site", action='store_true')),
  292. (['--php'],
  293. dict(help="create php site", action='store_true')),
  294. (['--mysql'],
  295. dict(help="create mysql site", action='store_true')),
  296. (['--wp'],
  297. dict(help="create wordpress single site",
  298. action='store_true')),
  299. (['--wpsubdir'],
  300. dict(help="create wordpress multisite with subdirectory setup",
  301. action='store_true')),
  302. (['--wpsubdomain'],
  303. dict(help="create wordpress multisite with subdomain setup",
  304. action='store_true')),
  305. (['--w3tc'],
  306. dict(help="create wordpress single/multi site with w3tc cache",
  307. action='store_true')),
  308. (['--wpfc'],
  309. dict(help="create wordpress single/multi site with wpfc cache",
  310. action='store_true')),
  311. (['--wpsc'],
  312. dict(help="create wordpress single/multi site with wpsc cache",
  313. action='store_true')),
  314. (['--wpredis'],
  315. dict(help="create wordpress single/multi site with redis cache",
  316. action='store_true')),
  317. (['--hhvm'],
  318. dict(help="create HHVM site", action='store_true')),
  319. (['--pagespeed'],
  320. dict(help="create pagespeed site", action='store_true')),
  321. (['--user'],
  322. dict(help="provide user for wordpress site")),
  323. (['--email'],
  324. dict(help="provide email address for wordpress site")),
  325. (['--pass'],
  326. dict(help="provide password for wordpress user",
  327. dest='wppass')),
  328. (['--proxy'],
  329. dict(help="create proxy for site", nargs='+')),
  330. (['--experimental'],
  331. dict(help="Enable Experimenal packages without prompt",
  332. action='store_true')),
  333. ]
  334. @expose(hide=True)
  335. def default(self):
  336. # self.app.render((data), 'default.mustache')
  337. # Check domain name validation
  338. data = dict()
  339. host, port = None, None
  340. try:
  341. stype, cache = detSitePar(vars(self.app.pargs))
  342. except RuntimeError as e:
  343. Log.debug(self, str(e))
  344. Log.error(self, "Please provide valid options to creating site")
  345. if stype is None and self.app.pargs.proxy:
  346. stype, cache = 'proxy', ''
  347. proxyinfo = self.app.pargs.proxy[0].strip()
  348. if not proxyinfo:
  349. Log.error(self, "Please provide proxy server host information")
  350. proxyinfo = proxyinfo.split(':')
  351. host = proxyinfo[0].strip()
  352. port = '80' if len(proxyinfo) < 2 else proxyinfo[1].strip()
  353. elif stype is None and not self.app.pargs.proxy:
  354. stype, cache = 'html', 'basic'
  355. elif stype and self.app.pargs.proxy:
  356. Log.error(self, "proxy should not be used with other site types")
  357. if (self.app.pargs.proxy and (self.app.pargs.pagespeed
  358. or self.app.pargs.hhvm)):
  359. Log.error(self, "Proxy site can not run on pagespeed or hhvm")
  360. if not self.app.pargs.site_name:
  361. try:
  362. while not self.app.pargs.site_name:
  363. # preprocessing before finalize site name
  364. self.app.pargs.site_name = (input('Enter site name : ')
  365. .strip())
  366. except IOError as e:
  367. Log.debug(self, str(e))
  368. Log.error(self, "Unable to input site name, Please try again!")
  369. self.app.pargs.site_name = self.app.pargs.site_name.strip()
  370. (ee_domain, ee_www_domain) = ValidateDomain(self.app.pargs.site_name)
  371. if not ee_domain.strip():
  372. Log.error("Invalid domain name, "
  373. "Provide valid domain name")
  374. ee_site_webroot = EEVariables.ee_webroot + ee_domain
  375. if check_domain_exists(self, ee_domain):
  376. Log.error(self, "site {0} already exists".format(ee_domain))
  377. elif os.path.isfile('/etc/nginx/sites-available/{0}'
  378. .format(ee_domain)):
  379. Log.error(self, "Nginx configuration /etc/nginx/sites-available/"
  380. "{0} already exists".format(ee_domain))
  381. if stype == 'proxy':
  382. data['site_name'] = ee_domain
  383. data['www_domain'] = ee_www_domain
  384. data['proxy'] = True
  385. data['host'] = host
  386. data['port'] = port
  387. ee_site_webroot = ""
  388. if stype in ['html', 'php']:
  389. data = dict(site_name=ee_domain, www_domain=ee_www_domain,
  390. static=True, basic=False, wp=False, w3tc=False,
  391. wpfc=False, wpsc=False, multisite=False,
  392. wpsubdir=False, webroot=ee_site_webroot)
  393. if stype == 'php':
  394. data['static'] = False
  395. data['basic'] = True
  396. elif stype in ['mysql', 'wp', 'wpsubdir', 'wpsubdomain']:
  397. data = dict(site_name=ee_domain, www_domain=ee_www_domain,
  398. static=False, basic=True, wp=False, w3tc=False,
  399. wpfc=False, wpsc=False, wpredis=False, multisite=False,
  400. wpsubdir=False, webroot=ee_site_webroot,
  401. ee_db_name='', ee_db_user='', ee_db_pass='',
  402. ee_db_host='')
  403. if stype in ['wp', 'wpsubdir', 'wpsubdomain']:
  404. data['wp'] = True
  405. data['basic'] = False
  406. data[cache] = True
  407. data['wp-user'] = self.app.pargs.user
  408. data['wp-email'] = self.app.pargs.email
  409. data['wp-pass'] = self.app.pargs.wppass
  410. if stype in ['wpsubdir', 'wpsubdomain']:
  411. data['multisite'] = True
  412. if stype == 'wpsubdir':
  413. data['wpsubdir'] = True
  414. else:
  415. pass
  416. if stype == "html" and self.app.pargs.hhvm:
  417. Log.error(self, "Can not create HTML site with HHVM")
  418. if data and self.app.pargs.hhvm:
  419. if (not self.app.pargs.experimental):
  420. Log.info(self, "HHVM is experimental feature and it may not "
  421. "work with all plugins of your site.\nYou can "
  422. "disable it by passing --hhvm=off later.\nDo you wish"
  423. " to enable HHVM now for {0}?".format(ee_domain))
  424. # Check prompt
  425. check_prompt = input("Type \"y\" to continue [n]:")
  426. if check_prompt != "Y" and check_prompt != "y":
  427. Log.info(self, "Not using HHVM for site.")
  428. data['hhvm'] = False
  429. hhvm = 0
  430. self.app.pargs.hhvm = False
  431. else:
  432. data['hhvm'] = True
  433. hhvm = 1
  434. else:
  435. data['hhvm'] = True
  436. hhvm = 1
  437. elif data:
  438. data['hhvm'] = False
  439. hhvm = 0
  440. if data and self.app.pargs.pagespeed:
  441. if (not self.app.pargs.experimental):
  442. Log.info(self, "PageSpeed is experimental feature and it may not "
  443. "work with all CSS/JS/Cache of your site.\nYou can "
  444. "disable it by passing --pagespeed=off later.\nDo you wish"
  445. " to enable PageSpeed now for {0}?".format(ee_domain))
  446. # Check prompt
  447. check_prompt = input("Type \"y\" to continue [n]:")
  448. if check_prompt != "Y" and check_prompt != "y":
  449. Log.info(self, "Not using PageSpeed for site.")
  450. data['pagespeed'] = False
  451. pagespeed = 0
  452. self.app.pargs.pagespeed = False
  453. else:
  454. data['pagespeed'] = True
  455. pagespeed = 1
  456. else:
  457. data['pagespeed'] = True
  458. pagespeed = 1
  459. elif data:
  460. data['pagespeed'] = False
  461. pagespeed = 0
  462. if (cache == 'wpredis' and (not self.app.pargs.experimental)):
  463. Log.info(self, "Redis is experimental feature and it may not "
  464. "work with all CSS/JS/Cache of your site.\nYou can "
  465. "disable it by changing cache later.\nDo you wish"
  466. " to enable Redis now for {0}?".format(ee_domain))
  467. # Check prompt
  468. check_prompt = input("Type \"y\" to continue [n]:")
  469. if check_prompt != "Y" and check_prompt != "y":
  470. Log.error(self, "Not using Redis for site")
  471. cache = 'basic'
  472. data['wpredis'] = False
  473. data['basic'] = True
  474. self.app.pargs.wpredis = False
  475. # self.app.args.print_help()
  476. # if not data:
  477. # self.app.close(1)
  478. # Check rerequired packages are installed or not
  479. ee_auth = site_package_check(self, stype)
  480. try:
  481. pre_run_checks(self)
  482. except SiteError as e:
  483. Log.debug(self, str(e))
  484. Log.error(self, "NGINX configuration check failed.")
  485. try:
  486. try:
  487. # setup NGINX configuration, and webroot
  488. setupdomain(self, data)
  489. # Fix Nginx Hashbucket size error
  490. hashbucket(self)
  491. except SiteError as e:
  492. # call cleanup actions on failure
  493. Log.info(self, Log.FAIL + "Oops Something went wrong !!")
  494. Log.info(self, Log.FAIL + "Calling cleanup actions ...")
  495. doCleanupAction(self, domain=ee_domain,
  496. webroot=data['webroot'])
  497. Log.debug(self, str(e))
  498. Log.error(self, "Check logs for reason "
  499. "`tail /var/log/ee/ee.log` & Try Again!!!")
  500. if 'proxy' in data.keys() and data['proxy']:
  501. addNewSite(self, ee_domain, stype, cache, ee_site_webroot)
  502. # Service Nginx Reload
  503. if not EEService.reload_service(self, 'nginx'):
  504. Log.info(self, Log.FAIL + "Oops Something went wrong !!")
  505. Log.info(self, Log.FAIL + "Calling cleanup actions ...")
  506. doCleanupAction(self, domain=ee_domain)
  507. Log.debug(self, str(e))
  508. Log.error(self, "service nginx reload failed. "
  509. "check issues with `nginx -t` command")
  510. Log.error(self, "Check logs for reason "
  511. "`tail /var/log/ee/ee.log` & Try Again!!!")
  512. if ee_auth and len(ee_auth):
  513. for msg in ee_auth:
  514. Log.info(self, Log.ENDC + msg, log=False)
  515. Log.info(self, "Successfully created site"
  516. " http://{0}".format(ee_domain))
  517. return
  518. # Update pagespeed config
  519. if self.app.pargs.pagespeed:
  520. operateOnPagespeed(self, data)
  521. addNewSite(self, ee_domain, stype, cache, ee_site_webroot,
  522. hhvm=hhvm, pagespeed=pagespeed)
  523. # Setup database for MySQL site
  524. if 'ee_db_name' in data.keys() and not data['wp']:
  525. try:
  526. data = setupdatabase(self, data)
  527. # Add database information for site into database
  528. updateSiteInfo(self, ee_domain, db_name=data['ee_db_name'],
  529. db_user=data['ee_db_user'],
  530. db_password=data['ee_db_pass'],
  531. db_host=data['ee_db_host'])
  532. except SiteError as e:
  533. # call cleanup actions on failure
  534. Log.debug(self, str(e))
  535. Log.info(self, Log.FAIL + "Oops Something went wrong !!")
  536. Log.info(self, Log.FAIL + "Calling cleanup actions ...")
  537. doCleanupAction(self, domain=ee_domain,
  538. webroot=data['webroot'],
  539. dbname=data['ee_db_name'],
  540. dbuser=data['ee_db_user'],
  541. dbhost=data['ee_db_host'])
  542. deleteSiteInfo(self, ee_domain)
  543. Log.error(self, "Check logs for reason "
  544. "`tail /var/log/ee/ee.log` & Try Again!!!")
  545. try:
  546. eedbconfig = open("{0}/ee-config.php"
  547. .format(ee_site_webroot),
  548. encoding='utf-8', mode='w')
  549. eedbconfig.write("<?php \ndefine('DB_NAME', '{0}');"
  550. "\ndefine('DB_USER', '{1}'); "
  551. "\ndefine('DB_PASSWORD', '{2}');"
  552. "\ndefine('DB_HOST', '{3}');\n?>"
  553. .format(data['ee_db_name'],
  554. data['ee_db_user'],
  555. data['ee_db_pass'],
  556. data['ee_db_host']))
  557. eedbconfig.close()
  558. stype = 'mysql'
  559. except IOError as e:
  560. Log.debug(self, str(e))
  561. Log.debug(self, "Error occured while generating "
  562. "ee-config.php")
  563. Log.info(self, Log.FAIL + "Oops Something went wrong !!")
  564. Log.info(self, Log.FAIL + "Calling cleanup actions ...")
  565. doCleanupAction(self, domain=ee_domain,
  566. webroot=data['webroot'],
  567. dbname=data['ee_db_name'],
  568. dbuser=data['ee_db_user'],
  569. dbhost=data['ee_db_host'])
  570. deleteSiteInfo(self, ee_domain)
  571. Log.error(self, "Check logs for reason "
  572. "`tail /var/log/ee/ee.log` & Try Again!!!")
  573. # Setup WordPress if Wordpress site
  574. if data['wp']:
  575. try:
  576. ee_wp_creds = setupwordpress(self, data)
  577. # Add database information for site into database
  578. updateSiteInfo(self, ee_domain, db_name=data['ee_db_name'],
  579. db_user=data['ee_db_user'],
  580. db_password=data['ee_db_pass'],
  581. db_host=data['ee_db_host'])
  582. except SiteError as e:
  583. # call cleanup actions on failure
  584. Log.debug(self, str(e))
  585. Log.info(self, Log.FAIL + "Oops Something went wrong !!")
  586. Log.info(self, Log.FAIL + "Calling cleanup actions ...")
  587. doCleanupAction(self, domain=ee_domain,
  588. webroot=data['webroot'],
  589. dbname=data['ee_db_name'],
  590. dbuser=data['ee_db_user'],
  591. dbhost=data['ee_mysql_grant_host'])
  592. deleteSiteInfo(self, ee_domain)
  593. Log.error(self, "Check logs for reason "
  594. "`tail /var/log/ee/ee.log` & Try Again!!!")
  595. # Service Nginx Reload call cleanup if failed to reload nginx
  596. if not EEService.reload_service(self, 'nginx'):
  597. Log.info(self, Log.FAIL + "Oops Something went wrong !!")
  598. Log.info(self, Log.FAIL + "Calling cleanup actions ...")
  599. doCleanupAction(self, domain=ee_domain,
  600. webroot=data['webroot'])
  601. if 'ee_db_name' in data.keys():
  602. doCleanupAction(self, domain=ee_domain,
  603. dbname=data['ee_db_name'],
  604. dbuser=data['ee_db_user'],
  605. dbhost=data['ee_mysql_grant_host'])
  606. deleteSiteInfo(self, ee_domain)
  607. Log.info(self, Log.FAIL + "service nginx reload failed."
  608. " check issues with `nginx -t` command.")
  609. Log.error(self, "Check logs for reason "
  610. "`tail /var/log/ee/ee.log` & Try Again!!!")
  611. EEGit.add(self, ["/etc/nginx"],
  612. msg="{0} created with {1} {2}"
  613. .format(ee_www_domain, stype, cache))
  614. # Setup Permissions for webroot
  615. try:
  616. setwebrootpermissions(self, data['webroot'])
  617. except SiteError as e:
  618. Log.debug(self, str(e))
  619. Log.info(self, Log.FAIL + "Oops Something went wrong !!")
  620. Log.info(self, Log.FAIL + "Calling cleanup actions ...")
  621. doCleanupAction(self, domain=ee_domain,
  622. webroot=data['webroot'])
  623. if 'ee_db_name' in data.keys():
  624. print("Inside db cleanup")
  625. doCleanupAction(self, domain=ee_domain,
  626. dbname=data['ee_db_name'],
  627. dbuser=data['ee_db_user'],
  628. dbhost=data['ee_mysql_grant_host'])
  629. deleteSiteInfo(self, ee_domain)
  630. Log.error(self, "Check logs for reason "
  631. "`tail /var/log/ee/ee.log` & Try Again!!!")
  632. if ee_auth and len(ee_auth):
  633. for msg in ee_auth:
  634. Log.info(self, Log.ENDC + msg, log=False)
  635. if data['wp']:
  636. Log.info(self, Log.ENDC + "WordPress admin user :"
  637. " {0}".format(ee_wp_creds['wp_user']), log=False)
  638. Log.info(self, Log.ENDC + "WordPress admin user password : {0}"
  639. .format(ee_wp_creds['wp_pass']), log=False)
  640. display_cache_settings(self, data)
  641. Log.info(self, "Successfully created site"
  642. " http://{0}".format(ee_domain))
  643. except SiteError as e:
  644. Log.error(self, "Check logs for reason "
  645. "`tail /var/log/ee/ee.log` & Try Again!!!")
  646. class EESiteUpdateController(CementBaseController):
  647. class Meta:
  648. label = 'update'
  649. stacked_on = 'site'
  650. stacked_type = 'nested'
  651. description = ('This command updates websites configuration to '
  652. 'another as per the options are provided')
  653. arguments = [
  654. (['site_name'],
  655. dict(help='domain name for the site to be updated',
  656. nargs='?')),
  657. (['--password'],
  658. dict(help="update to password for wordpress site user",
  659. action='store_true')),
  660. (['--html'],
  661. dict(help="update to html site", action='store_true')),
  662. (['--php'],
  663. dict(help="update to php site", action='store_true')),
  664. (['--mysql'],
  665. dict(help="update to mysql site", action='store_true')),
  666. (['--wp'],
  667. dict(help="update to wordpress single site",
  668. action='store_true')),
  669. (['--wpsubdir'],
  670. dict(help="update to wpsubdir site", action='store_true')),
  671. (['--wpsubdomain'],
  672. dict(help="update to wpsubdomain site", action='store_true')),
  673. (['--w3tc'],
  674. dict(help="update to w3tc cache", action='store_true')),
  675. (['--wpfc'],
  676. dict(help="update to wpfc cache", action='store_true')),
  677. (['--wpsc'],
  678. dict(help="update to wpsc cache", action='store_true')),
  679. (['--wpredis'],
  680. dict(help="update to redis cache", action='store_true')),
  681. (['--hhvm'],
  682. dict(help='Use HHVM for site',
  683. action='store' or 'store_const',
  684. choices=('on', 'off'), const='on', nargs='?')),
  685. (['--pagespeed'],
  686. dict(help='Use PageSpeed for site',
  687. action='store' or 'store_const',
  688. choices=('on', 'off'), const='on', nargs='?')),
  689. (['--proxy'],
  690. dict(help="update to proxy site", nargs='+')),
  691. (['--experimental'],
  692. dict(help="Enable Experimenal packages without prompt",
  693. action='store_true')),
  694. (['--all'],
  695. dict(help="update all sites", action='store_true')),
  696. ]
  697. @expose(help="Update site type or cache")
  698. def default(self):
  699. pargs = self.app.pargs
  700. if pargs.all:
  701. if pargs.site_name:
  702. Log.error(self, "`--all` option cannot be used with site name"
  703. " provided")
  704. if pargs.html:
  705. Log.error(self, "No site can be updated to html")
  706. if not (pargs.php or
  707. pargs.mysql or pargs.wp or pargs.wpsubdir or
  708. pargs.wpsubdomain or pargs.w3tc or pargs.wpfc or
  709. pargs.wpsc or pargs.hhvm or pargs.pagespeed or pargs.wpredis):
  710. Log.error(self, "Please provide options to update sites.")
  711. if pargs.all:
  712. if pargs.site_name:
  713. Log.error(self, "`--all` option cannot be used with site name"
  714. " provided")
  715. sites = getAllsites(self)
  716. if not sites:
  717. pass
  718. else:
  719. for site in sites:
  720. pargs.site_name = site.sitename
  721. Log.info(self, Log.ENDC + Log.BOLD + "Updating site {0},"
  722. " please wait..."
  723. .format(pargs.site_name))
  724. self.doupdatesite(pargs)
  725. print("\n")
  726. else:
  727. self.doupdatesite(pargs)
  728. def doupdatesite(self, pargs):
  729. hhvm = None
  730. pagespeed = None
  731. data = dict()
  732. try:
  733. stype, cache = detSitePar(vars(pargs))
  734. except RuntimeError as e:
  735. Log.debug(self, str(e))
  736. Log.error(self, "Please provide valid options combination for"
  737. " site update")
  738. if stype is None and pargs.proxy:
  739. stype, cache = 'proxy', ''
  740. proxyinfo = pargs.proxy[0].strip()
  741. if not proxyinfo:
  742. Log.error(self, "Please provide proxy server host information")
  743. proxyinfo = proxyinfo.split(':')
  744. host = proxyinfo[0].strip()
  745. port = '80' if len(proxyinfo) < 2 else proxyinfo[1].strip()
  746. elif stype is None and not pargs.proxy:
  747. stype, cache = 'html', 'basic'
  748. elif stype and pargs.proxy:
  749. Log.error(self, "--proxy can not be used with other site types")
  750. if (pargs.proxy and (pargs.pagespeed or pargs.hhvm)):
  751. Log.error(self, "Proxy site can not run on pagespeed or hhvm")
  752. if not pargs.site_name:
  753. try:
  754. while not pargs.site_name:
  755. pargs.site_name = (input('Enter site name : ').strip())
  756. except IOError as e:
  757. Log.error(self, 'Unable to input site name, Please try again!')
  758. pargs.site_name = pargs.site_name.strip()
  759. (ee_domain,
  760. ee_www_domain, ) = ValidateDomain(pargs.site_name)
  761. ee_site_webroot = EEVariables.ee_webroot + ee_domain
  762. check_site = getSiteInfo(self, ee_domain)
  763. if check_site is None:
  764. Log.error(self, " Site {0} does not exist.".format(ee_domain))
  765. else:
  766. oldsitetype = check_site.site_type
  767. oldcachetype = check_site.cache_type
  768. old_hhvm = check_site.is_hhvm
  769. old_pagespeed = check_site.is_pagespeed
  770. if (pargs.password and not (pargs.html or
  771. pargs.php or pargs.mysql or pargs.wp or
  772. pargs.w3tc or pargs.wpfc or pargs.wpsc
  773. or pargs.wpsubdir or pargs.wpsubdomain)):
  774. try:
  775. updatewpuserpassword(self, ee_domain, ee_site_webroot)
  776. except SiteError as e:
  777. Log.debug(self, str(e))
  778. Log.info(self, "\nPassword Unchanged.")
  779. return 0
  780. if ((stype == "proxy" and stype == oldsitetype and self.app.pargs.hhvm)
  781. or (stype == "proxy" and
  782. stype == oldsitetype and self.app.pargs.pagespeed)):
  783. Log.info(self, Log.FAIL +
  784. "Can not update proxy site to HHVM or Pagespeed")
  785. return 1
  786. if stype == "html" and stype == oldsitetype and self.app.pargs.hhvm:
  787. Log.info(self, Log.FAIL + "Can not update HTML site to HHVM")
  788. return 1
  789. if ((stype == 'php' and oldsitetype not in ['html', 'proxy']) or
  790. (stype == 'mysql' and oldsitetype not in ['html', 'php',
  791. 'proxy']) or
  792. (stype == 'wp' and oldsitetype not in ['html', 'php', 'mysql',
  793. 'proxy', 'wp']) or
  794. (stype == 'wpsubdir' and oldsitetype in ['wpsubdomain']) or
  795. (stype == 'wpsubdomain' and oldsitetype in ['wpsubdir']) or
  796. (stype == oldsitetype and cache == oldcachetype) and
  797. not pargs.pagespeed):
  798. Log.info(self, Log.FAIL + "can not update {0} {1} to {2} {3}".
  799. format(oldsitetype, oldcachetype, stype, cache))
  800. return 1
  801. if stype == 'proxy':
  802. data['site_name'] = ee_domain
  803. data['www_domain'] = ee_www_domain
  804. data['proxy'] = True
  805. data['host'] = host
  806. data['port'] = port
  807. pagespeed = False
  808. hhvm = False
  809. data['webroot'] = ee_site_webroot
  810. data['currsitetype'] = oldsitetype
  811. data['currcachetype'] = oldcachetype
  812. if stype == 'php':
  813. data = dict(site_name=ee_domain, www_domain=ee_www_domain,
  814. static=False, basic=True, wp=False, w3tc=False,
  815. wpfc=False, wpsc=False, wpredis=False, multisite=False,
  816. wpsubdir=False, webroot=ee_site_webroot,
  817. currsitetype=oldsitetype, currcachetype=oldcachetype)
  818. elif stype in ['mysql', 'wp', 'wpsubdir', 'wpsubdomain']:
  819. data = dict(site_name=ee_domain, www_domain=ee_www_domain,
  820. static=False, basic=True, wp=False, w3tc=False,
  821. wpfc=False, wpsc=False, wpredis=False, multisite=False,
  822. wpsubdir=False, webroot=ee_site_webroot,
  823. ee_db_name='', ee_db_user='', ee_db_pass='',
  824. ee_db_host='',
  825. currsitetype=oldsitetype, currcachetype=oldcachetype)
  826. if stype in ['wp', 'wpsubdir', 'wpsubdomain']:
  827. data['wp'] = True
  828. data['basic'] = False
  829. data[cache] = True
  830. if stype in ['wpsubdir', 'wpsubdomain']:
  831. data['multisite'] = True
  832. if stype == 'wpsubdir':
  833. data['wpsubdir'] = True
  834. if pargs.pagespeed or pargs.hhvm:
  835. if not data:
  836. data = dict(site_name=ee_domain, www_domain=ee_www_domain,
  837. currsitetype=oldsitetype,
  838. currcachetype=oldcachetype,
  839. webroot=ee_site_webroot)
  840. stype = oldsitetype
  841. cache = oldcachetype
  842. if oldsitetype == 'html' or oldsitetype == 'proxy':
  843. data['static'] = True
  844. data['wp'] = False
  845. data['multisite'] = False
  846. data['wpsubdir'] = False
  847. elif oldsitetype == 'php' or oldsitetype == 'mysql':
  848. data['static'] = False
  849. data['wp'] = False
  850. data['multisite'] = False
  851. data['wpsubdir'] = False
  852. elif oldsitetype == 'wp':
  853. data['static'] = False
  854. data['wp'] = True
  855. data['multisite'] = False
  856. data['wpsubdir'] = False
  857. elif oldsitetype == 'wpsubdir':
  858. data['static'] = False
  859. data['wp'] = True
  860. data['multisite'] = True
  861. data['wpsubdir'] = True
  862. elif oldsitetype == 'wpsubdomain':
  863. data['static'] = False
  864. data['wp'] = True
  865. data['multisite'] = True
  866. data['wpsubdir'] = False
  867. if oldcachetype == 'basic':
  868. data['basic'] = True
  869. data['w3tc'] = False
  870. data['wpfc'] = False
  871. data['wpsc'] = False
  872. data['wpredis'] = False
  873. elif oldcachetype == 'w3tc':
  874. data['basic'] = False
  875. data['w3tc'] = True
  876. data['wpfc'] = False
  877. data['wpsc'] = False
  878. data['wpredis'] = False
  879. elif oldcachetype == 'wpfc':
  880. data['basic'] = False
  881. data['w3tc'] = False
  882. data['wpfc'] = True
  883. data['wpsc'] = False
  884. data['wpredis'] = False
  885. elif oldcachetype == 'wpsc':
  886. data['basic'] = False
  887. data['w3tc'] = False
  888. data['wpfc'] = False
  889. data['wpsc'] = True
  890. data['wpredis'] = False
  891. elif oldcachetype == 'wpredis':
  892. data['basic'] = False
  893. data['w3tc'] = False
  894. data['wpfc'] = False
  895. data['wpsc'] = False
  896. data['wpredis'] = True
  897. if pargs.hhvm != 'off':
  898. data['hhvm'] = True
  899. hhvm = True
  900. elif pargs.hhvm == 'off':
  901. data['hhvm'] = False
  902. hhvm = False
  903. if pargs.pagespeed != 'off':
  904. data['pagespeed'] = True
  905. pagespeed = True
  906. elif pargs.pagespeed == 'off':
  907. data['pagespeed'] = False
  908. pagespeed = False
  909. if pargs.pagespeed:
  910. if pagespeed is old_pagespeed:
  911. if pagespeed is False:
  912. Log.info(self, "Pagespeed is already disabled for given "
  913. "site")
  914. elif pagespeed is True:
  915. Log.info(self, "Pagespeed is already enabled for given "
  916. "site")
  917. pargs.pagespeed = False
  918. if pargs.hhvm:
  919. if hhvm is old_hhvm:
  920. if hhvm is False:
  921. Log.info(self, "HHVM is allready disabled for given "
  922. "site")
  923. elif hhvm is True:
  924. Log.info(self, "HHVM is allready enabled for given "
  925. "site")
  926. pargs.hhvm = False
  927. if data and (not pargs.hhvm):
  928. if old_hhvm is True:
  929. data['hhvm'] = True
  930. hhvm = True
  931. else:
  932. data['hhvm'] = False
  933. hhvm = False
  934. if data and (not pargs.pagespeed):
  935. if old_pagespeed is True:
  936. data['pagespeed'] = True
  937. pagespeed = True
  938. else:
  939. data['pagespeed'] = False
  940. pagespeed = False
  941. if pargs.pagespeed=="on" or pargs.hhvm=="on":
  942. if pargs.hhvm == "on":
  943. if (not pargs.experimental):
  944. Log.info(self, "HHVM is experimental feature and it may not"
  945. " work with all plugins of your site.\nYou can "
  946. "disable it by passing --hhvm=off later.\nDo you wish"
  947. " to enable HHVM now for {0}?".format(ee_domain))
  948. # Check prompt
  949. check_prompt = input("Type \"y\" to continue [n]:")
  950. if check_prompt != "Y" and check_prompt != "y":
  951. Log.info(self, "Not using HHVM for site")
  952. data['hhvm'] = False
  953. hhvm = False
  954. else:
  955. data['hhvm'] = True
  956. hhvm = True
  957. else:
  958. data['hhvm'] = True
  959. hhvm = True
  960. if pargs.pagespeed=="on":
  961. if (not pargs.experimental):
  962. Log.info(self, "PageSpeed is experimental feature and it may not"
  963. " work with all CSS/JS/Cache of your site.\nYou can "
  964. "disable it by passing --pagespeed=off later.\nDo you wish"
  965. " to enable PageSpeed now for {0}?".format(ee_domain))
  966. # Check prompt
  967. check_prompt = input("Type \"y\" to continue [n]:")
  968. if check_prompt != "Y" and check_prompt != "y":
  969. Log.info(self, "Not using Pagespeed for given site")
  970. data['pagespeed'] = False
  971. pagespeed = False
  972. else:
  973. data['pagespeed'] = True
  974. pagespeed = True
  975. else:
  976. data['pagespeed'] = True
  977. pagespeed = True
  978. if data['currcachetype'] != 'wpredis' and pargs.wpredis:
  979. if (not pargs.experimental):
  980. Log.info(self, "Redis is experimental feature and it may not"
  981. " work with all plugins of your site.\nYou can "
  982. "disable it by changing cache type later.\nDo you wish"
  983. " to enable Redis now for {0}?".format(ee_domain))
  984. # Check prompt
  985. check_prompt = input("Type \"y\" to continue [n]: ")
  986. if check_prompt != "Y" and check_prompt != "y":
  987. Log.error(self, "Not using Redis for site")
  988. data['wpredis'] = False
  989. data['basic'] = True
  990. cache = 'basic'
  991. if ((hhvm is old_hhvm) and (pagespeed is old_pagespeed) and
  992. (stype == oldsitetype and cache == oldcachetype)):
  993. return 1
  994. if not data:
  995. Log.error(self, "Cannot update {0}, Invalid Options"
  996. .format(ee_domain))
  997. ee_auth = site_package_check(self, stype)
  998. data['ee_db_name'] = check_site.db_name
  999. data['ee_db_user'] = check_site.db_user
  1000. data['ee_db_pass'] = check_site.db_password
  1001. data['ee_db_host'] = check_site.db_host
  1002. try:
  1003. pre_run_checks(self)
  1004. except SiteError as e:
  1005. Log.debug(self, str(e))
  1006. Log.error(self

Large files files are truncated, but you can click here to view the full file