def clean_fastcgi(self): """This function clears Fastcgi cache""" if(os.path.isdir("/var/run/nginx-cache")): Log.info(self, "Cleaning NGINX FastCGI cache") EEShellExec.cmd_exec(self, "rm -rf /var/run/nginx-cache/*") else: Log.error(self, "Unable to clean FastCGI cache", False)
def secure_auth(self): """This function Secures authentication""" passwd = ''.join([random.choice (string.ascii_letters + string.digits) for n in range(6)]) if not self.app.pargs.user_input: username = input("Provide HTTP authentication user " "name [{0}] :".format(EEVariables.ee_user)) self.app.pargs.user_input = username if username == "": self.app.pargs.user_input = EEVariables.ee_user if not self.app.pargs.user_pass: password = getpass.getpass("Provide HTTP authentication " "password [{0}] :".format(passwd)) self.app.pargs.user_pass = password if password == "": self.app.pargs.user_pass = passwd Log.debug(self, "printf username:"******"$(openssl passwd -crypt " "password 2> /dev/null)\n\"" "> /etc/nginx/htpasswd-ee 2>/dev/null") EEShellExec.cmd_exec(self, "printf \"{username}:" "$(openssl passwd -crypt " "{password} 2> /dev/null)\n\"" "> /etc/nginx/htpasswd-ee 2>/dev/null" .format(username=self.app.pargs.user_input, password=self.app.pargs.user_pass), log=False) EEGit.add(self, ["/etc/nginx"], msg="Adding changed secure auth into Git")
def setwebrootpermissions(self, webroot): Log.debug(self, "Setting up permissions") try: EEFileUtils.chown(self, webroot, EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True) except Exception as e: Log.debug(self, str(e)) raise SiteError("problem occured while settingup webroot permissions")
def removeNginxConf(self, domain): if os.path.isfile("/etc/nginx/sites-available/{0}".format(domain)): Log.debug(self, "Removing Nginx configuration") EEFileUtils.rm(self, "/etc/nginx/sites-enabled/{0}".format(domain)) EEFileUtils.rm(self, "/etc/nginx/sites-available/{0}".format(domain)) EEService.reload_service(self, "nginx") EEGit.add(self, ["/etc/nginx"], msg="Deleted {0} ".format(domain))
def clean_pagespeed(self): """This function clears Pagespeed cache""" if (os.path.isdir("/var/ngx_pagespeed_cache")): Log.info(self, "Cleaning PageSpeed cache") EEShellExec.cmd_exec(self, "rm -rf /var/ngx_pagespeed_cache/*") else: Log.error(self, "Unable to clean Pagespeed cache")
def add(self): """Swap addition with EasyEngine""" if EEVariables.ee_ram < 512: if EEVariables.ee_swap < 1000: Log.info(self, "Adding SWAP") # Install dphys-swapfile EEAptGet.update(self) EEAptGet.install(self, ["dphys-swapfile"]) # Stop service EEShellExec.cmd_exec(self, "service dphys-swapfile stop") # Remove Default swap created EEShellExec.cmd_exec(self, "/sbin/dphys-swapfile uninstall") # Modify Swap configuration if os.path.isfile("/etc/dphys-swapfile"): EEFileUtils.searchreplace(self, "/etc/dphys-swapfile", "#CONF_SWAPFILE=/var/swap", "CONF_SWAPFILE=/ee-swapfile") EEFileUtils.searchreplace(self, "/etc/dphys-swapfile", "#CONF_MAXSWAP=2048", "CONF_MAXSWAP=1024") EEFileUtils.searchreplace(self, "/etc/dphys-swapfile", "#CONF_SWAPSIZE=", "CONF_SWAPSIZE=1024") else: with open("/etc/dphys-swapfile", 'w') as conffile: conffile.write("CONF_SWAPFILE=/ee-swapfile\n" "CONF_SWAPSIZE=1024\n" "CONF_MAXSWAP=1024\n") # Create swap file EEShellExec.cmd_exec(self, "service dphys-swapfile start")
def sitebackup(self, data): ee_site_webroot = data['webroot'] backup_path = ee_site_webroot + '/backup/{0}'.format(EEVariables.ee_date) if not EEFileUtils.isexist(self, backup_path): EEFileUtils.mkdir(self, backup_path) Log.info(self, "Backup location : {0}".format(backup_path)) EEFileUtils.copyfile( self, '/etc/nginx/sites-available/{0}'.format(data['site_name']), backup_path) if data['currsitetype'] in ['html', 'php', 'mysql']: Log.info(self, "Backing up Webroot \t\t", end='') EEFileUtils.mvfile(self, ee_site_webroot + '/htdocs', backup_path) Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]") configfiles = glob.glob(ee_site_webroot + '/*-config.php') if configfiles and EEFileUtils.isexist(self, configfiles[0]): ee_db_name = (EEFileUtils.grep( self, configfiles[0], 'DB_NAME').split(',')[1].split(')')[0].strip().replace('\'', '')) Log.info(self, 'Backing up database \t\t', end='') EEShellExec.cmd_exec(self, "mysqldump {0} > {1}/{0}.sql".format( ee_db_name, backup_path), errormsg="\nFailed: Backup Database") Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]") # move wp-config.php/ee-config.php to backup if data['currsitetype'] in ['mysql']: EEFileUtils.mvfile(self, configfiles[0], backup_path) else: EEFileUtils.copyfile(self, configfiles[0], backup_path)
def chown(self, path, user, group, recursive=False): """ Change Owner for files change owner for file with path specified user: username of owner group: group of owner recursive: if recursive is True change owner for all files in directory """ userid = pwd.getpwnam(user)[2] groupid = pwd.getpwnam(user)[3] try: Log.debug( self, "Changing ownership of {0}, Userid:{1},Groupid:{2}".format( path, userid, groupid)) # Change inside files/directory permissions only if recursive flag # is set if recursive: for root, dirs, files in os.walk(path): for d in dirs: os.chown(os.path.join(root, d), userid, groupid) for f in files: os.chown(os.path.join(root, f), userid, groupid) os.chown(path, userid, groupid) except shutil.Error as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to change owner : {0}".format(path)) except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to change owner : {0} ".format(path))
def clean_fastcgi(self): """This function clears Fastcgi cache""" if (os.path.isdir("/var/run/nginx-cache")): Log.info(self, "Cleaning NGINX FastCGI cache") EEShellExec.cmd_exec(self, "rm -rf /var/run/nginx-cache/*") else: Log.error(self, "Unable to clean FastCGI cache", False)
def secure_auth(self): """This function Secures authentication""" passwd = ''.join([ random.choice(string.ascii_letters + string.digits) for n in range(6) ]) if not self.app.pargs.user_input: username = input("Provide HTTP authentication user " "name [{0}] :".format(EEVariables.ee_user)) self.app.pargs.user_input = username if username == "": self.app.pargs.user_input = EEVariables.ee_user if not self.app.pargs.user_pass: password = getpass.getpass("Provide HTTP authentication " "password [{0}] :".format(passwd)) self.app.pargs.user_pass = password if password == "": self.app.pargs.user_pass = passwd Log.debug( self, "printf username:"******"$(openssl passwd -crypt " "password 2> /dev/null)\n\"" "> /etc/nginx/htpasswd-ee 2>/dev/null") EEShellExec.cmd_exec(self, "printf \"{username}:" "$(openssl passwd -crypt " "{password} 2> /dev/null)\n\"" "> /etc/nginx/htpasswd-ee 2>/dev/null".format( username=self.app.pargs.user_input, password=self.app.pargs.user_pass), log=False) EEGit.add(self, ["/etc/nginx"], msg="Adding changed secure auth into Git")
def download_only(self,package_name,repo_url=None,repo_key=None): """ Similar to `apt-get install --download-only PACKAGE_NAME` """ packages = ' '.join(package_name) try: with open('/var/log/ee/ee.log', 'a') as f: if repo_url is not None: EERepo.add(self, repo_url=repo_url) if repo_key is not None: EERepo.add_key(self, repo_key) proc = subprocess.Popen("apt-get update && DEBIAN_FRONTEND=noninteractive " "apt-get install -o " "Dpkg::Options::=\"--force-confdef\"" " -o " "Dpkg::Options::=\"--force-confold\"" " -y --download-only {0}" .format(packages), shell=True, stdin=None, stdout=f, stderr=f, executable="/bin/bash") proc.wait() if proc.returncode == 0: return True else: Log.error(self,"Error in fetching dpkg package.\nReverting changes ..",False) if repo_url is not None: EERepo.remove(self, repo_url=repo_url) return False except Exception as e: Log.error(self, "Error while downloading packages, " "apt-get exited with error")
def site_package_check(self, stype): apt_packages = [] packages = [] stack = EEStackController() stack.app = self.app if stype in ['html', 'php', 'mysql', 'wp', 'wpsubdir', 'wpsubdomain']: Log.debug(self, "Setting apt_packages variable for Nginx") if not EEAptGet.is_installed(self, 'nginx-common'): apt_packages = apt_packages + EEVariables.ee_nginx if stype in ['php', 'mysql', 'wp', 'wpsubdir', 'wpsubdomain']: Log.debug(self, "Setting apt_packages variable for PHP") if not EEAptGet.is_installed(self, 'php5-fpm'): apt_packages = apt_packages + EEVariables.ee_php if stype in ['mysql', 'wp', 'wpsubdir', 'wpsubdomain']: Log.debug(self, "Setting apt_packages variable for MySQL") if not EEShellExec.cmd_exec(self, "mysqladmin ping"): apt_packages = apt_packages + EEVariables.ee_mysql if stype in ['php', 'mysql', 'wp', 'wpsubdir', 'wpsubdomain']: Log.debug(self, "Setting apt_packages variable for Postfix") if not EEAptGet.is_installed(self, 'postfix'): apt_packages = apt_packages + EEVariables.ee_postfix if stype in ['wp', 'wpsubdir', 'wpsubdomain']: Log.debug(self, "Setting packages variable for WP-CLI") if not EEShellExec.cmd_exec(self, "which wp"): packages = packages + [["https://github.com/wp-cli/wp-cli/" "releases/download/v{0}/" "wp-cli-{0}.phar" .format(EEVariables.ee_wp_cli), "/usr/bin/wp", "WP-CLI"]] return(stack.install(apt_packages=apt_packages, packages=packages, disp_msg=False))
def sitebackup(self, data): ee_site_webroot = data['webroot'] backup_path = ee_site_webroot + '/backup/{0}'.format(EEVariables.ee_date) if not EEFileUtils.isexist(self, backup_path): EEFileUtils.mkdir(self, backup_path) Log.info(self, "Backup location : {0}".format(backup_path)) EEFileUtils.copyfile(self, '/etc/nginx/sites-available/{0}' .format(data['site_name']), backup_path) if data['currsitetype'] in ['html', 'php', 'mysql']: Log.info(self, "Backing up Webroot \t\t", end='') EEFileUtils.mvfile(self, ee_site_webroot + '/htdocs', backup_path) Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]") configfiles = glob.glob(ee_site_webroot + '/*-config.php') if configfiles and EEFileUtils.isexist(self, configfiles[0]): ee_db_name = (EEFileUtils.grep(self, configfiles[0], 'DB_NAME').split(',')[1] .split(')')[0].strip().replace('\'', '')) Log.info(self, 'Backing up database \t\t', end='') EEShellExec.cmd_exec(self, "mysqldump {0} > {1}/{0}.sql" .format(ee_db_name, backup_path), errormsg="\nFailed: Backup Database") Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]") # move wp-config.php/ee-config.php to backup if data['currsitetype'] in ['mysql']: EEFileUtils.mvfile(self, configfiles[0], backup_path) else: EEFileUtils.copyfile(self, configfiles[0], backup_path)
def clean_redis(self): """This function clears Redis cache""" if (EEAptGet.is_installed(self, "redis-server")): Log.info(self, "Cleaning Redis cache") EEShellExec.cmd_exec(self, "redis-cli flushall") else: Log.info(self, "Redis is not installed")
def getExpirationDays(self, domain, returnonerror=False): # check if exist if not os.path.isfile( '/etc/letsencrypt/live/{0}/cert.pem'.format(domain)): Log.error( self, 'File Not Found : /etc/letsencrypt/live/{0}/cert.pem'.format( domain), False) if returnonerror: return -1 Log.error( self, "Check logs for reason " "`tail /var/log/ee/ee.log` & Try Again!!!") current_date = EEShellExec.cmd_exec_stdout(self, "date -d \"now\" +%s") expiration_date = EEShellExec.cmd_exec_stdout( self, "date -d \"`openssl x509 -in /etc/letsencrypt/live/{0}/cert.pem" " -text -noout|grep \"Not After\"|cut -c 25-`\" +%s".format( domain)) days_left = int((int(expiration_date) - int(current_date)) / 86400) if (days_left > 0): return days_left else: # return "Certificate Already Expired ! Please Renew soon." return -1
def addNewSite(self, site, stype, cache, path, enabled=True, ssl=False, fs='ext4', db='mysql', db_name=None, db_user=None, db_password=None, db_host='localhost', hhvm=0, pagespeed=0): """ Add New Site record information into ee database. """ try: newRec = SiteDB(site, stype, cache, path, enabled, ssl, fs, db, db_name, db_user, db_password, db_host, hhvm, pagespeed) db_session.add(newRec) db_session.commit() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to add site to database")
def add(self): """Swap addition with EasyEngine""" if EEVariables.ee_ram < 512: if EEVariables.ee_swap < 1000: Log.info(self, "Adding SWAP file, please wait...") # Install dphys-swapfile EEAptGet.update(self) EEAptGet.install(self, ["dphys-swapfile"]) # Stop service EEShellExec.cmd_exec(self, "service dphys-swapfile stop") # Remove Default swap created EEShellExec.cmd_exec(self, "/sbin/dphys-swapfile uninstall") # Modify Swap configuration if os.path.isfile("/etc/dphys-swapfile"): EEFileUtils.searchreplace(self, "/etc/dphys-swapfile", "#CONF_SWAPFILE=/var/swap", "CONF_SWAPFILE=/ee-swapfile") EEFileUtils.searchreplace(self, "/etc/dphys-swapfile", "#CONF_MAXSWAP=2048", "CONF_MAXSWAP=1024") EEFileUtils.searchreplace(self, "/etc/dphys-swapfile", "#CONF_SWAPSIZE=", "CONF_SWAPSIZE=1024") else: with open("/etc/dphys-swapfile", 'w') as conffile: conffile.write("CONF_SWAPFILE=/ee-swapfile\n" "CONF_SWAPSIZE=1024\n" "CONF_MAXSWAP=1024\n") # Create swap file EEShellExec.cmd_exec(self, "service dphys-swapfile start")
def removeNginxConf(self, domain): if os.path.isfile('/etc/nginx/sites-available/{0}'.format(domain)): Log.debug(self, "Removing Nginx configuration") EEFileUtils.rm(self, '/etc/nginx/sites-enabled/{0}'.format(domain)) EEFileUtils.rm(self, '/etc/nginx/sites-available/{0}'.format(domain)) EEService.reload_service(self, 'nginx') EEGit.add(self, ["/etc/nginx"], msg="Deleted {0} ".format(domain))
def signal_handler(self, signal, frame): """Handle Ctrl+c hevent for -i option of debug""" self.start = False if self.app.pargs.nginx: self.debug_nginx() if self.app.pargs.php: self.debug_php() if self.app.pargs.fpm: self.debug_fpm() if self.app.pargs.mysql: # MySQL debug will not work for remote MySQL if EEVariables.ee_mysql_host is "localhost": self.debug_mysql() else: Log.warn(self, "Remote MySQL found, EasyEngine will not " "enable remote debug") if self.app.pargs.wp: self.debug_wp() if self.app.pargs.rewrite: self.debug_rewrite() # Reload Nginx if self.trigger_nginx: EEService.reload_service(self, 'nginx') # Reload PHP if self.trigger_php: EEService.reload_service(self, 'php5-fpm') self.app.close(0)
def clean_redis(self): """This function clears Redis cache""" if(EEAptGet.is_installed(self, "redis-server")): Log.info(self, "Cleaning Redis cache") EEShellExec.cmd_exec(self, "redis-cli flushall") else: Log.info(self, "Redis is not installed")
def updateSiteInfo(self, site, stype="", cache="", enabled=True, ssl=False, fs="", db=""): """updates site record in database""" try: q = SiteDB.query.filter(SiteDB.sitename == site).first() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to query database for site info") if not q: Log.error(self, "{0} does not exist in database".format(site)) # Check if new record matches old if not then only update database if stype and q.site_type != stype: q.site_type = stype if cache and q.cache_type != cache: q.cache_type = cache if q.is_enabled != enabled: q.is_enabled = enabled if ssl and q.is_ssl != ssl: q.is_ssl = ssl try: q.created_on = func.now() db_session.commit() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to update site info in application database.")
def default(self): if ((not self.app.pargs.mariadb)): self.app.args.print_help() if self.app.pargs.mariadb: if EEVariables.ee_mysql_host is not "localhost": Log.error( self, "Remote MySQL found, EasyEngine will not " "install MariaDB") if EEShellExec.cmd_exec(self, "mysqladmin ping") and ( not EEAptGet.is_installed(self, 'mariadb-server')): Log.info( self, "If your database size is big, " "migration may take some time.") Log.info( self, "During migration non nginx-cached parts of " "your site may remain down") start_migrate = input("Type \"mariadb\" to continue:") if start_migrate != "mariadb": Log.error(self, "Not starting migration") self.migrate_mariadb() else: Log.error( self, "Your current MySQL is not alive or " "you allready installed MariaDB")
def clean_pagespeed(self): """This function clears Pagespeed cache""" if(os.path.isdir("/var/ngx_pagespeed_cache")): Log.info(self, "Cleaning PageSpeed cache") EEShellExec.cmd_exec(self, "rm -rf /var/ngx_pagespeed_cache/*") else: Log.error(self, "Unable to clean Pagespeed cache")
def operateOnPagespeed(self, data): ee_domain_name = data['site_name'] ee_site_webroot = data['webroot'] if data['pagespeed'] is True: if not os.path.isfile("{0}/conf/nginx/pagespeed.conf.disabled" .format(ee_site_webroot)): Log.debug(self, 'Writting the Pagespeed common ' 'configuration to file {0}/conf/nginx/pagespeed.conf' 'pagespeed.conf'.format(ee_site_webroot)) ee_nginx = open('{0}/conf/nginx/pagespeed.conf' .format(ee_site_webroot), encoding='utf-8', mode='w') self.app.render((data), 'pagespeed-common.mustache', out=ee_nginx) ee_nginx.close() else: EEFileUtils.mvfile(self, "{0}/conf/nginx/pagespeed.conf.disabled" .format(ee_site_webroot), '{0}/conf/nginx/pagespeed.conf' .format(ee_site_webroot)) elif data['pagespeed'] is False: if os.path.isfile("{0}/conf/nginx/pagespeed.conf" .format(ee_site_webroot)): EEFileUtils.mvfile(self, "{0}/conf/nginx/pagespeed.conf" .format(ee_site_webroot), '{0}/conf/nginx/pagespeed.conf.disabled' .format(ee_site_webroot)) # Add nginx conf folder into GIT EEGit.add(self, ["{0}/conf/nginx".format(ee_site_webroot)], msg="Adding Pagespeed config of site: {0}" .format(ee_domain_name))
def chown(self, path, user, group, recursive=False): """ Change Owner for files change owner for file with path specified user: username of owner group: group of owner recursive: if recursive is True change owner for all files in directory """ userid = pwd.getpwnam(user)[2] groupid = pwd.getpwnam(user)[3] try: Log.debug(self, "Changing ownership of {0}, Userid:{1},Groupid:{2}" .format(path, userid, groupid)) # Change inside files/directory permissions only if recursive flag # is set if recursive: for root, dirs, files in os.walk(path): for d in dirs: os.chown(os.path.join(root, d), userid, groupid) for f in files: os.chown(os.path.join(root, f), userid, groupid) os.chown(path, userid, groupid) except shutil.Error as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to change owner : {0}".format(path)) except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to change owner : {0} ".format(path))
def setwebrootpermissions(self, webroot): Log.debug(self, "Setting up permissions") EEFileUtils.chown(self, webroot, EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True)
def uninstallwp_plugin(self, plugin_name, data): ee_site_webroot = data['webroot'] Log.debug(self, "Uninstalling plugin {0}".format(plugin_name)) EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot)) EEShellExec.cmd_exec(self, "php /usr/bin/wp plugin --allow-root uninstall " "{0}".format(plugin_name), errormsg="Unable to UnInstall plugin {0}" .format(plugin_name))
def getAllsites(self): try: q = SiteDB.query.all() return q except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to query database")
def debug_wp(self): """Start/Stop WordPress debug""" if self.start and self.app.pargs.site_name: wp_config = "{0}/{1}/wp-config.php".format(EEVariables.ee_webroot, self.app.pargs.site_name) webroot = "{0}{1}".format(EEVariables.ee_webroot, self.app.pargs.site_name) if os.path.isfile(wp_config): if not EEShellExec.cmd_exec(self, "grep \"'WP_DEBUG'\" {0} |" " grep true".format(wp_config)): Log.info(self, "Starting WordPress debug") open("{0}/htdocs/wp-content/debug.log".format(webroot), encoding="utf-8", mode="a").close() EEShellExec.cmd_exec( self, "chown {1}: {0}/htdocs/wp-" "content/debug.log" "".format(webroot, EEVariables.ee_php_user), ) EEShellExec.cmd_exec( self, "sed -i \"s/define('WP_DEBUG'" ".*/define('WP_DEBUG', true);\\n" "define('WP_DEBUG_DISPLAY', false);" "\\ndefine('WP_DEBUG_LOG', true);" "\\ndefine('SAVEQUERIES', true);/\"" " {0}".format(wp_config), ) EEShellExec.cmd_exec( self, "cd {0}/htdocs/ && wp" " plugin --allow-root install " "developer query-monitor".format(webroot), ) EEShellExec.cmd_exec( self, "chown -R {1}: {0}/htdocs/" "wp-content/plugins".format(webroot, EEVariables.ee_php_user) ) self.msg = self.msg + [ "{0}{1}/htdocs/wp-content" "/debug.log".format(EEVariables.ee_webroot, self.app.pargs.site_name) ] else: Log.info(self, "{0} domain not valid".format(self.app.pargs.site_name)) elif not self.start and self.app.pargs.site_name: wp_config = "{0}{1}/wp-config.php".format(EEVariables.ee_webroot, self.app.pargs.site_name) webroot = "{0}{1}".format(EEVariables.ee_webroot, self.app.pargs.site_name) if os.path.isfile(wp_config): if EEShellExec.cmd_exec(self, "grep \"'WP_DEBUG'\" {0} | " "grep true".format(wp_config)): Log.info(self, "Disabling WordPress debug") EEShellExec.cmd_exec( self, "sed -i \"s/define('WP_DEBUG'" ", true);/define('WP_DEBUG', " 'false);/" {0}'.format(wp_config), ) EEShellExec.cmd_exec( self, "sed -i \"/define('" "WP_DEBUG_DISPLAY', false);/d\" {0}".format(wp_config) ) EEShellExec.cmd_exec(self, "sed -i \"/define('" "WP_DEBUG_LOG', true);/d\" {0}".format(wp_config)) EEShellExec.cmd_exec(self, "sed -i \"/define('" "SAVEQUERIES', " 'true);/d" {0}'.format(wp_config)) else: Log.info(self, "WordPress debug all already disabled") else: Log.error(self, "Missing argument site name")
def setupwordpressnetwork(self, data): ee_site_webroot = data['webroot'] EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot)) Log.info(self, "Setting up WordPress Network \t", end='') EEShellExec.cmd_exec(self, 'wp --allow-root core multisite-convert' ' --title=\'{0}\' {subdomains}' .format(data['www_domain'], subdomains='--subdomains' if not data['wpsubdir'] else '')) Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]")
def uninstallwp_plugin(self, plugin_name, data): ee_site_webroot = data['webroot'] Log.debug(self, "Uninstalling plugin {0}".format(plugin_name)) EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot)) EEShellExec.cmd_exec( self, "php /usr/bin/wp plugin --allow-root uninstall " "{0}".format(plugin_name), errormsg="Unable to UnInstall plugin {0}".format(plugin_name))
def invoke_editor(self, filepath, errormsg=''): """ Open files using sensible editor """ try: subprocess.call(['sensible-editor', filepath]) except OSError as e: Log.debug(self, "{0}{1}".format(e.errno, e.strerror)) raise CommandExecutionError
def updateSiteInfo(self, site, stype='', cache='', webroot='', enabled=True, ssl=False, fs='', db='', db_name=None, db_user=None, db_password=None, db_host=None, hhvm=None, pagespeed=None, php_version=''): """updates site record in database""" try: q = SiteDB.query.filter(SiteDB.sitename == site).first() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to query database for site info") if not q: Log.error(self, "{0} does not exist in database".format(site)) # Check if new record matches old if not then only update database if stype and q.site_type != stype: q.site_type = stype if cache and q.cache_type != cache: q.cache_type = cache if q.is_enabled != enabled: q.is_enabled = enabled if q.is_ssl != ssl: q.is_ssl = ssl if db_name and q.db_name != db_name: q.db_name = db_name if db_user and q.db_user != db_user: q.db_user = db_user if db_user and q.db_password != db_password: q.db_password = db_password if db_host and q.db_host != db_host: q.db_host = db_host if webroot and q.site_path != webroot: q.site_path = webroot if (hhvm is not None) and (q.is_hhvm is not hhvm): q.is_hhvm = hhvm if (pagespeed is not None) and (q.is_pagespeed is not pagespeed): q.is_pagespeed = pagespeed if php_version and q.php_version != php_version: q.php_version = php_version try: q.created_on = func.now() db_session.commit() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to update site info in application database.")
def getSiteInfo(self, site): """ Retrieves site record from ee databse """ try: q = SiteDB.query.filter(SiteDB.sitename == site).first() return q except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to query database for site info")
def getAllsites(self): """ 1. returns all records from ee database """ try: q = SiteDB.query.all() return q except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to query database")
def callback(filename, lines): for line in lines: if line.find(":::") == -1: print(line) else: data = line.split(":::") try: print(data[0], data[1], zlib.decompress(base64.decodestring(data[2]))) except Exception as e: Log.info(time.time(), "caught exception rendering a new log line in %s" % filename)
def remove_cron(self,cmd): if EEShellExec.cmd_exec(self, "crontab -l | grep -q \'{0}\'".format(cmd)): if not EEShellExec.cmd_exec(self, "/bin/bash -c " "\"crontab " "-l | sed '/{0}/d'" "| crontab -\"" .format(cmd)): Log.error(self, "Failed to remove crontab entry",False) else: Log.debug(self, "Cron not found")
def setupwordpressnetwork(self, data): ee_site_webroot = data['webroot'] EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot)) Log.info(self, "Setting up WordPress Network \t", end='') EEShellExec.cmd_exec( self, 'wp --allow-root core multisite-convert' ' --title={0} {subdomains}'.format( data['www_domain'], subdomains='--subdomains' if not data['wpsubdir'] else '')) Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]")
def check_db_exists(self, db_name): try: if EEMysql.dbConnection(self, db_name): return True except DatabaseNotExistsError as e: Log.debug(self, str(e)) return False except MySQLConnectionError as e: Log.debug(self, str(e)) return False
def check_db_exists(self, db_name): try: if EEMysql.dbConnection(self, db_name): return True except DatabaseNotExistsError as e: Log.debug(self, str(e)) return False except MySQLConnectionError as e: Log.debug(self, str(e)) raise MySQLConnectionError
def cmd_exec_stdout(self, command, errormsg='', log=True): """Run shell command from Python""" try: log and Log.debug(self, "Running command: {0}".format(command)) with subprocess.Popen([command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) as proc: (cmd_stdout_bytes, cmd_stderr_bytes) = proc.communicate() (cmd_stdout, cmd_stderr) = (cmd_stdout_bytes.decode('utf-8', "replace"), cmd_stderr_bytes.decode('utf-8', "replace")) if proc.returncode == 0: Log.debug( self, "Command Output: {0}, \nCommand Error: {1}".format( cmd_stdout, cmd_stderr)) return cmd_stdout else: Log.debug( self, "Command Output: {0}, \nCommand Error: {1}".format( cmd_stdout, cmd_stderr)) return cmd_stdout except OSError as e: Log.debug(self, str(e)) raise CommandExecutionError except Exception as e: Log.debug(self, str(e)) raise CommandExecutionError
def cmd_exec_stdout(self, command, errormsg='', log=True): """Run shell command from Python""" try: log and Log.debug(self, "Running command: {0}".format(command)) with subprocess.Popen([command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) as proc: (cmd_stdout_bytes, cmd_stderr_bytes) = proc.communicate() (cmd_stdout, cmd_stderr) = (cmd_stdout_bytes.decode('utf-8', "replace"), cmd_stderr_bytes.decode('utf-8', "replace")) if proc.returncode == 0: Log.debug(self, "Command Output: {0}, \nCommand Error: {1}" .format(cmd_stdout, cmd_stderr)) return cmd_stdout else: Log.debug(self, "Command Output: {0}, \nCommand Error: {1}" .format(cmd_stdout, cmd_stderr)) return cmd_stdout except OSError as e: Log.debug(self, str(e)) raise CommandExecutionError except Exception as e: Log.debug(self, str(e)) raise CommandExecutionError
def setcron_daily(self,cmd,comment='Cron set by EasyEngine',user='******',min=0,hour=12): if not EEShellExec.cmd_exec(self, "crontab -l | grep -q \'{0}\'".format(cmd)): EEShellExec.cmd_exec(self, "/bin/bash -c \"crontab -l " "2> /dev/null | {{ cat; echo -e" " \\\"" "\\n0 12 * * * " "{0}".format(cmd) + " # {0}".format(comment)+ "\\\"; } | crontab -\"") Log.debug(self, "Cron set")
def setcron_weekly(self,cmd,comment='Cron set by EasyEngine',user='******',min=0,hour=12): if not EEShellExec.cmd_exec(self, "crontab -l | grep -q \'{0}\'".format(cmd)): EEShellExec.cmd_exec(self, "/bin/bash -c \"crontab -l " "2> /dev/null | {{ cat; echo -e" " \\\"" "\\n0 0 * * 0 " "{0}".format(cmd) + " # {0}".format(comment)+ "\\\"; } | crontab -\"") Log.debug(self, "Cron set")
def addNewSite(self, site, stype, cache, path, enabled=True, ssl=False, fs="ext4", db="mysql"): """ Add New Site record information into ee database. """ try: newRec = SiteDB(site, stype, cache, path, enabled, ssl, fs, db) db_session.add(newRec) db_session.commit() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to add site to database")
def uninstallwp_plugin(self, plugin_name, data): ee_site_webroot = data['webroot'] Log.debug(self, "Uninstalling plugin {0}, please wait..." .format(plugin_name)) EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot)) try: EEShellExec.cmd_exec(self, "php /usr/bin/wp plugin " "--allow-root uninstall " "{0}".format(plugin_name)) except CommandExecutionError as e: raise SiteError("plugin uninstall failed")
def connect(self): """Makes connection with MySQL server""" try: connection = pymysql.connect(read_default_file='~/.my.cnf') return connection except ValueError as e: Log.debug(self, str(e)) raise MySQLConnectionError except pymysql.err.InternalError as e: Log.debug(self, str(e)) raise MySQLConnectionError
def isexist(self, path): """ Check if file exist on given path """ try: if os.path.exists(path): return (True) else: return (False) except OSError as e: Log.debug(self, "{0}".format(e.strerror)) Log.error(self, "Unable to check path {0}".format(path))
def extract(self, file, path): """Function to extract tar.gz file""" try: tar = tarfile.open(file) tar.extractall(path=path) tar.close() os.remove(file) return True except tarfile.TarError as e: Log.debug(self, "{0}{1}".format(e.errno, e.strerror)) Log.error(self, 'Unable to extract file \{0}'.format(file)) return False