desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Similar to `apt-get update`'
| def update(self):
| try:
with open('/var/log/ee/ee.log', 'a') as f:
proc = subprocess.Popen('apt-get update', shell=True, stdin=None, stdout=f, stderr=subprocess.PIPE, executable='/bin/bash')
proc.wait()
(output, error_output) = proc.communicate()
if ('NO_PUBKEY' in str(error_output)):
Log.info(self, 'Fixing missing GPG keys, please wait...')
error_list = str(error_output).split('\\n')
for single_error in error_list:
if ('NO_PUBKEY' in single_error):
key = single_error.rsplit(None, 1)[(-1)]
EERepo.add_key(self, key, keyserver='hkp://pgp.mit.edu')
proc = subprocess.Popen('apt-get update', shell=True, stdin=None, stdout=f, stderr=f, executable='/bin/bash')
proc.wait()
if (proc.returncode == 0):
return True
else:
Log.info(self, (Log.FAIL + 'Oops Something went wrong!!'))
Log.error(self, 'Check logs for reason `tail /var/log/ee/ee.log` & Try Again!!!')
except Exception as e:
Log.error(self, 'apt-get update exited with error')
|
'Similar to `apt-get upgrade`'
| def check_upgrade(self):
| try:
check_update = subprocess.Popen(['apt-get upgrade -s | grep "^Inst" | wc -l'], stdout=subprocess.PIPE, shell=True).communicate()[0]
if (check_update == '0\n'):
Log.error(self, 'No package updates available')
Log.info(self, 'Following package updates are available:')
subprocess.Popen('apt-get -s dist-upgrade | grep "^Inst"', shell=True, executable='/bin/bash', stdout=sys.stdout).communicate()
except Exception as e:
Log.error(self, 'Unable to check for packages upgrades')
|
'Similar to `apt-get upgrade`'
| def dist_upgrade(self):
| try:
with open('/var/log/ee/ee.log', 'a') as f:
proc = subprocess.Popen('DEBIAN_FRONTEND=noninteractive apt-get dist-upgrade -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" -y ', shell=True, stdin=None, stdout=f, stderr=f, executable='/bin/bash')
proc.wait()
if (proc.returncode == 0):
return True
else:
Log.info(self, (Log.FAIL + 'Oops Something went wrong!!'))
Log.error(self, 'Check logs for reason `tail /var/log/ee/ee.log` & Try Again!!!')
except Exception as e:
Log.error(self, 'Error while installing packages, apt-get exited with error')
|
'Similar to `apt-get autoclean`'
| def auto_clean(self):
| try:
orig_out = sys.stdout
sys.stdout = open(self.app.config.get('log.logging', 'file'), encoding='utf-8', mode='a')
apt_get.autoclean('-y')
sys.stdout = orig_out
except ErrorReturnCode as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, 'Unable to apt-get autoclean')
|
'Similar to `apt-get autoremove`'
| def auto_remove(self):
| try:
Log.debug(self, 'Running apt-get autoremove')
apt_get.autoremove('-y')
except ErrorReturnCode as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, 'Unable to apt-get autoremove')
|
'Checks if package is available in cache and is installed or not
returns True if installed otherwise returns False'
| def is_installed(self, package_name):
| apt_cache = apt.cache.Cache()
apt_cache.open()
if ((package_name.strip() in apt_cache) and apt_cache[package_name.strip()].is_installed):
return True
return False
|
'Similar to `apt-get install --download-only PACKAGE_NAME`'
| def download_only(self, package_name, repo_url=None, repo_key=None):
| 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')
|
'Function to extract tar.gz file'
| def extract(self, file, path):
| 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}'.format(e))
Log.error(self, 'Unable to extract file \\{0}'.format(file))
return False
|
'Makes connection with MySQL server'
| def connect(self):
| try:
if os.path.exists('/etc/mysql/conf.d/my.cnf'):
connection = pymysql.connect(read_default_file='/etc/mysql/conf.d/my.cnf')
else:
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
|
'Get login details from /etc/mysql/conf.d/my.cnf & Execute MySQL query'
| def execute(self, statement, errormsg='', log=True):
| connection = EEMysql.connect(self)
(log and Log.debug(self, 'Exceuting MySQL Statement : {0}'.format(statement)))
try:
cursor = connection.cursor()
sql = statement
cursor.execute(sql)
connection.commit()
except AttributeError as e:
Log.debug(self, str(e))
raise StatementExcecutionError
except Error as e:
Log.debug(self, str(e))
raise StatementExcecutionError
finally:
connection.close()
|
'Initialize'
| def __init__(self):
| pass
|
'This function used to add apt repositories and or ppa\'s
If repo_url is provided adds repo file to
/etc/apt/sources.list.d/
If ppa is provided add apt-repository using
add-apt-repository
command.'
| def add(self, repo_url=None, ppa=None):
| if (repo_url is not None):
repo_file_path = ('/etc/apt/sources.list.d/' + EEVariables().ee_repo_file)
try:
if (not os.path.isfile(repo_file_path)):
with open(repo_file_path, encoding='utf-8', mode='a') as repofile:
repofile.write(repo_url)
repofile.write('\n')
repofile.close()
elif (repo_url not in open(repo_file_path, encoding='utf-8').read()):
with open(repo_file_path, encoding='utf-8', mode='a') as repofile:
repofile.write(repo_url)
repofile.write('\n')
repofile.close()
return True
except IOError as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, 'File I/O error.')
except Exception as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, 'Unable to add repo')
if (ppa is not None):
EEShellExec.cmd_exec(self, "add-apt-repository -y '{ppa_name}'".format(ppa_name=ppa))
|
'This function used to remove ppa\'s
If ppa is provided adds repo file to
/etc/apt/sources.list.d/
command.'
| def remove(self, ppa=None, repo_url=None):
| if ppa:
EEShellExec.cmd_exec(self, "add-apt-repository -y --remove '{ppa_name}'".format(ppa_name=ppa))
elif repo_url:
repo_file_path = ('/etc/apt/sources.list.d/' + EEVariables().ee_repo_file)
try:
repofile = open(repo_file_path, 'w+')
repofile.write(repofile.read().replace(repo_url, ''))
repofile.close()
except IOError as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, 'File I/O error.')
except Exception as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, 'Unable to remove repo')
|
'This function adds imports repository keys from keyserver.
default keyserver is hkp://keys.gnupg.net
user can provide other keyserver with keyserver="hkp://xyz"'
| def add_key(self, keyids, keyserver=None):
| EEShellExec.cmd_exec(self, ('gpg --keyserver {serv}'.format(serv=(keyserver or 'hkp://keys.gnupg.net')) + ' --recv-keys {key}'.format(key=keyids)))
EEShellExec.cmd_exec(self, ('gpg -a --export --armor {0}'.format(keyids) + ' | apt-key add - '))
|
'Arguments:
(str) @folder:
the folder to watch
(callable) @callback:
a function which is called every time a new line in a
file being watched is found;
this is called with "filename" and "lines" arguments.
(list) @extensions:
only watch files with these extensions
(int) @tail_lines:
read last N lines from files being watched before starting'
| def __init__(self, filelist, callback, extensions=['log'], tail_lines=0):
| self.files_map = {}
self.filelist = filelist
self.callback = callback
self.extensions = extensions
for file in self.filelist:
assert os.path.isfile(file)
assert callable(callback)
self.update_files()
for (id, file) in list(iter(self.files_map.items())):
file.seek(os.path.getsize(file.name))
if tail_lines:
lines = self.tail(file.name, tail_lines)
if lines:
self.callback(file.name, lines)
|
'Start the loop.
If async is True make one loop then return.'
| def loop(self, interval=0.1, async=False):
| while 1:
self.update_files()
for (fid, file) in list(iter(self.files_map.items())):
self.readfile(file)
if async:
return
time.sleep(interval)
|
'Log when a file is un/watched'
| def log(self, line):
| print line
|
'Read last N lines from file fname.'
| @staticmethod
def tail(fname, window):
| try:
f = open(fname, encoding='utf-8', mode='r')
except IOError as err:
if (err.errno == errno.ENOENT):
return []
else:
raise
else:
BUFSIZ = 1024
f.seek(0, os.SEEK_END)
fsize = f.tell()
block = (-1)
data = ''
exit = False
while (not exit):
step = (block * BUFSIZ)
if (abs(step) >= fsize):
f.seek(0)
exit = True
else:
f.seek(step, os.SEEK_END)
data = f.read().strip()
if (data.count('\n') >= window):
break
else:
block -= 1
return data.splitlines()[(- window):]
|
'Initialize'
| def __init__():
| pass
|
'Swap addition with EasyEngine'
| def add(self):
| if (EEVariables.ee_ram < 512):
if (EEVariables.ee_swap < 1000):
Log.info(self, 'Adding SWAP file, please wait...')
EEAptGet.update(self)
EEAptGet.install(self, ['dphys-swapfile'])
EEShellExec.cmd_exec(self, 'service dphys-swapfile stop')
EEShellExec.cmd_exec(self, '/sbin/dphys-swapfile uninstall')
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\nCONF_SWAPSIZE=1024\nCONF_MAXSWAP=1024\n')
EEShellExec.cmd_exec(self, 'service dphys-swapfile start')
|
'Run shell command from Python'
| def cmd_exec(self, command, errormsg='', log=True):
| 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 True
else:
Log.debug(self, 'Command Output: {0}, \nCommand Error: {1}'.format(cmd_stdout, cmd_stderr))
return False
except OSError as e:
Log.debug(self, str(e))
raise CommandExecutionError
except Exception as e:
Log.debug(self, str(e))
raise CommandExecutionError
|
'Open files using sensible editor'
| def invoke_editor(self, filepath, errormsg=''):
| try:
subprocess.call(['sensible-editor', filepath])
except OSError as e:
Log.debug(self, '{0}{1}'.format(e.errno, e.strerror))
raise CommandExecutionError
|
'Run shell command from Python'
| def cmd_exec_stdout(self, command, errormsg='', log=True):
| 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
|
'start service
Similar to `service xyz start`'
| def start_service(self, service_name):
| try:
if (service_name in ['nginx', 'php5-fpm']):
service_cmd = '{0} -t && service {0} start'.format(service_name)
else:
service_cmd = 'service {0} start'.format(service_name)
Log.info(self, 'Start : {0:10}'.format(service_name), end='')
retcode = subprocess.getstatusoutput(service_cmd)
if (retcode[0] == 0):
Log.info(self, (((('[' + Log.ENDC) + 'OK') + Log.OKBLUE) + ']'))
return True
else:
Log.debug(self, '{0}'.format(retcode[1]))
Log.info(self, (((('[' + Log.FAIL) + 'Failed') + Log.OKBLUE) + ']'))
return False
except OSError as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, '\nFailed to start service {0}'.format(service_name))
|
'Stop service
Similar to `service xyz stop`'
| def stop_service(self, service_name):
| try:
Log.info(self, 'Stop : {0:10}'.format(service_name), end='')
retcode = subprocess.getstatusoutput('service {0} stop'.format(service_name))
if (retcode[0] == 0):
Log.info(self, (((('[' + Log.ENDC) + 'OK') + Log.OKBLUE) + ']'))
return True
else:
Log.debug(self, '{0}'.format(retcode[1]))
Log.info(self, (((('[' + Log.FAIL) + 'Failed') + Log.OKBLUE) + ']'))
return False
except OSError as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, '\nFailed to stop service : {0}'.format(service_name))
|
'Restart service
Similar to `service xyz restart`'
| def restart_service(self, service_name):
| try:
if (service_name in ['nginx', 'php5-fpm']):
service_cmd = '{0} -t && service {0} restart'.format(service_name)
else:
service_cmd = 'service {0} restart'.format(service_name)
Log.info(self, 'Restart : {0:10}'.format(service_name), end='')
retcode = subprocess.getstatusoutput(service_cmd)
if (retcode[0] == 0):
Log.info(self, (((('[' + Log.ENDC) + 'OK') + Log.OKBLUE) + ']'))
return True
else:
Log.debug(self, '{0}'.format(retcode[1]))
Log.info(self, (((('[' + Log.FAIL) + 'Failed') + Log.OKBLUE) + ']'))
return False
except OSError as e:
Log.debug(self, '{0} {1}'.format(e.errno, e.strerror))
Log.error(self, '\nFailed to restart service : {0}'.format(service_name))
|
'Stop service
Similar to `service xyz stop`'
| def reload_service(self, service_name):
| try:
if (service_name in ['nginx', 'php5-fpm']):
service_cmd = '{0} -t && service {0} reload'.format(service_name)
else:
service_cmd = 'service {0} reload'.format(service_name)
Log.info(self, 'Reload : {0:10}'.format(service_name), end='')
retcode = subprocess.getstatusoutput(service_cmd)
if (retcode[0] == 0):
Log.info(self, (((('[' + Log.ENDC) + 'OK') + Log.OKBLUE) + ']'))
return True
else:
Log.debug(self, '{0}'.format(retcode[1]))
Log.info(self, (((('[' + Log.FAIL) + 'Failed') + Log.OKBLUE) + ']'))
return False
except OSError as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, '\nFailed to reload service {0}'.format(service_name))
|
'Initializes Directory as repository if not already git repo.
and adds uncommited changes automatically'
| def add(self, paths, msg='Intializating'):
| for path in paths:
global git
git = git.bake('--git-dir={0}/.git'.format(path), '--work-tree={0}'.format(path))
if os.path.isdir(path):
if (not os.path.isdir((path + '/.git'))):
try:
Log.debug(self, 'EEGit: git init at {0}'.format(path))
git.init(path)
except ErrorReturnCode as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, 'Unable to git init at {0}'.format(path))
status = git.status('-s')
if (len(status.splitlines()) > 0):
try:
Log.debug(self, 'EEGit: git commit at {0}'.format(path))
git.add('--all')
git.commit('-am {0}'.format(msg))
except ErrorReturnCode as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, 'Unable to git commit at {0} '.format(path))
else:
Log.debug(self, 'EEGit: Path {0} not present'.format(path))
|
'Checks status of file, If its tracked or untracked.'
| def checkfilestatus(self, repo, filepath):
| global git
git = git.bake('--git-dir={0}/.git'.format(repo), '--work-tree={0}'.format(repo))
status = git.status('-s', '{0}'.format(filepath))
if (len(status.splitlines()) > 0):
return True
else:
return False
|
'Default function of log show'
| @expose(hide=True)
def default(self):
| self.msg = []
if self.app.pargs.php:
self.app.pargs.nginx = True
if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm) and (not self.app.pargs.mysql) and (not self.app.pargs.access) and (not self.app.pargs.wp) and (not self.app.pargs.site_name)):
self.app.pargs.nginx = True
self.app.pargs.fpm = True
self.app.pargs.mysql = True
self.app.pargs.access = True
if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm) and (not self.app.pargs.mysql) and (not self.app.pargs.access) and (not self.app.pargs.wp) and self.app.pargs.site_name):
self.app.pargs.nginx = True
self.app.pargs.wp = True
self.app.pargs.access = True
self.app.pargs.mysql = True
if (self.app.pargs.nginx and (not self.app.pargs.site_name)):
self.msg = (self.msg + ['/var/log/nginx/*error.log'])
if (self.app.pargs.access and (not self.app.pargs.site_name)):
self.msg = (self.msg + ['/var/log/nginx/*access.log'])
if self.app.pargs.fpm:
open('/var/log/php5/slow.log', 'a').close()
open('/var/log/php5/fpm.log', 'a').close()
self.msg = (self.msg + ['/var/log/php5/slow.log', '/var/log/php5/fpm.log'])
if self.app.pargs.mysql:
if (EEVariables.ee_mysql_host is 'localhost'):
if os.path.isfile('/var/log/mysql/mysql-slow.log'):
self.msg = (self.msg + ['/var/log/mysql/mysql-slow.log'])
else:
Log.info(self, 'MySQL slow-log not found, skipped')
else:
Log.warn(self, 'Remote MySQL found, EasyEngine is not able toshow MySQL log file')
if self.app.pargs.site_name:
webroot = '{0}{1}'.format(EEVariables.ee_webroot, self.app.pargs.site_name)
if (not os.path.isdir(webroot)):
Log.error(self, 'Site not present, quitting')
if self.app.pargs.access:
self.msg = (self.msg + ['{0}/{1}/logs/access.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
if self.app.pargs.nginx:
self.msg = (self.msg + ['{0}/{1}/logs/error.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
if self.app.pargs.wp:
if os.path.isdir('{0}/htdocs/wp-content'.format(webroot)):
if (not os.path.isfile('{0}/logs/debug.log'.format(webroot))):
if (not os.path.isfile('{0}/htdocs/wp-content/debug.log'.format(webroot))):
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))
EEFileUtils.create_symlink(self, ['{0}/htdocs/wp-content/debug.log'.format(webroot), '{0}/logs/debug.log'.format(webroot)])
self.msg = (self.msg + ['{0}/{1}/logs/debug.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
else:
Log.info(self, 'Site is not WordPress site, skipping WordPress logs')
watch_list = []
for w_list in self.msg:
watch_list = (watch_list + glob.glob(w_list))
logwatch(self, watch_list)
|
'Default function of log reset'
| @expose(hide=True)
def default(self):
| self.msg = []
if self.app.pargs.php:
self.app.pargs.nginx = True
if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm) and (not self.app.pargs.mysql) and (not self.app.pargs.access) and (not self.app.pargs.wp) and (not self.app.pargs.site_name) and (not self.app.pargs.slow_log_db)):
self.app.pargs.nginx = True
self.app.pargs.fpm = True
self.app.pargs.mysql = True
self.app.pargs.access = True
self.app.pargs.slow_log_db = True
if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm) and (not self.app.pargs.mysql) and (not self.app.pargs.access) and (not self.app.pargs.wp) and self.app.pargs.site_name and (not ((self.app.pargs.slow - log) - db))):
self.app.pargs.nginx = True
self.app.pargs.wp = True
self.app.pargs.access = True
self.app.pargs.mysql = True
if self.app.pargs.slow_log_db:
if os.path.isdir('/var/www/22222/htdocs/db/anemometer'):
Log.info(self, 'Resetting MySQL slow_query_log database table')
EEMysql.execute(self, 'TRUNCATE TABLE slow_query_log.global_query_review_history')
EEMysql.execute(self, 'TRUNCATE TABLE slow_query_log.global_query_review')
if (self.app.pargs.nginx and (not self.app.pargs.site_name)):
self.msg = (self.msg + ['/var/log/nginx/*error.log'])
if (self.app.pargs.access and (not self.app.pargs.site_name)):
self.msg = (self.msg + ['/var/log/nginx/*access.log'])
if self.app.pargs.fpm:
open('/var/log/php5/slow.log', 'a').close()
open('/var/log/php5/fpm.log', 'a').close()
self.msg = (self.msg + ['/var/log/php5/slow.log', '/var/log/php5/fpm.log'])
if self.app.pargs.mysql:
if (EEVariables.ee_mysql_host is 'localhost'):
if os.path.isfile('/var/log/mysql/mysql-slow.log'):
self.msg = (self.msg + ['/var/log/mysql/mysql-slow.log'])
else:
Log.info(self, 'MySQL slow-log not found, skipped')
else:
Log.warn(self, 'Remote MySQL found, EasyEngine is not able toshow MySQL log file')
if self.app.pargs.site_name:
webroot = '{0}{1}'.format(EEVariables.ee_webroot, self.app.pargs.site_name)
if (not os.path.isdir(webroot)):
Log.error(self, 'Site not present, quitting')
if self.app.pargs.access:
self.msg = (self.msg + ['{0}/{1}/logs/access.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
if self.app.pargs.nginx:
self.msg = (self.msg + ['{0}/{1}/logs/error.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
if self.app.pargs.wp:
if os.path.isdir('{0}/htdocs/wp-content'.format(webroot)):
if (not os.path.isfile('{0}/logs/debug.log'.format(webroot))):
if (not os.path.isfile('{0}/htdocs/wp-content/debug.log'.format(webroot))):
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))
EEFileUtils.create_symlink(self, ['{0}/htdocs/wp-content/debug.log'.format(webroot), '{0}/logs/debug.log'.format(webroot)])
self.msg = (self.msg + ['{0}/{1}/logs/debug.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
else:
Log.info(self, 'Site is not WordPress site, skipping WordPress logs')
reset_list = []
for r_list in self.msg:
reset_list = (reset_list + glob.glob(r_list))
for r_list in reset_list:
Log.info(self, 'Resetting file {file}'.format(file=r_list))
open(r_list, 'w').close()
|
'Default function of log GZip'
| @expose(hide=True)
def default(self):
| self.msg = []
if self.app.pargs.php:
self.app.pargs.nginx = True
if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm) and (not self.app.pargs.mysql) and (not self.app.pargs.access) and (not self.app.pargs.wp) and (not self.app.pargs.site_name)):
self.app.pargs.nginx = True
self.app.pargs.fpm = True
self.app.pargs.mysql = True
self.app.pargs.access = True
if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm) and (not self.app.pargs.mysql) and (not self.app.pargs.access) and (not self.app.pargs.wp) and self.app.pargs.site_name):
self.app.pargs.nginx = True
self.app.pargs.wp = True
self.app.pargs.access = True
self.app.pargs.mysql = True
if (self.app.pargs.nginx and (not self.app.pargs.site_name)):
self.msg = (self.msg + ['/var/log/nginx/*error.log'])
if (self.app.pargs.access and (not self.app.pargs.site_name)):
self.msg = (self.msg + ['/var/log/nginx/*access.log'])
if self.app.pargs.fpm:
open('/var/log/php5/slow.log', 'a').close()
open('/var/log/php5/fpm.log', 'a').close()
self.msg = (self.msg + ['/var/log/php5/slow.log', '/var/log/php5/fpm.log'])
if self.app.pargs.mysql:
if (EEVariables.ee_mysql_host is 'localhost'):
if os.path.isfile('/var/log/mysql/mysql-slow.log'):
self.msg = (self.msg + ['/var/log/mysql/mysql-slow.log'])
else:
Log.info(self, 'MySQL slow-log not found, skipped')
else:
Log.warn(self, 'Remote MySQL found, EasyEngine is not able toshow MySQL log file')
if self.app.pargs.site_name:
webroot = '{0}{1}'.format(EEVariables.ee_webroot, self.app.pargs.site_name)
if (not os.path.isdir(webroot)):
Log.error(self, 'Site not present, quitting')
if self.app.pargs.access:
self.msg = (self.msg + ['{0}/{1}/logs/access.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
if self.app.pargs.nginx:
self.msg = (self.msg + ['{0}/{1}/logs/error.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
if self.app.pargs.wp:
if os.path.isdir('{0}/htdocs/wp-content'.format(webroot)):
if (not os.path.isfile('{0}/logs/debug.log'.format(webroot))):
if (not os.path.isfile('{0}/htdocs/wp-content/debug.log'.format(webroot))):
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))
EEFileUtils.create_symlink(self, ['{0}/htdocs/wp-content/debug.log'.format(webroot), '{0}/logs/debug.log'.format(webroot)])
self.msg = (self.msg + ['{0}/{1}/logs/debug.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
else:
Log.info(self, 'Site is not WordPress site, skipping WordPress logs')
gzip_list = []
for g_list in self.msg:
gzip_list = (gzip_list + glob.glob(g_list))
for g_list in gzip_list:
Log.info(self, 'Gzipping file {file}'.format(file=g_list))
in_file = g_list
in_data = open(in_file, 'rb').read()
out_gz = (g_list + '.gz')
gzf = gzip.open(out_gz, 'wb')
gzf.write(in_data)
gzf.close()
|
'Default function of log Mail'
| @expose(hide=True)
def default(self):
| self.msg = []
if self.app.pargs.php:
self.app.pargs.nginx = True
if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm) and (not self.app.pargs.mysql) and (not self.app.pargs.access) and (not self.app.pargs.wp) and (not self.app.pargs.site_name)):
self.app.pargs.nginx = True
self.app.pargs.fpm = True
self.app.pargs.mysql = True
self.app.pargs.access = True
if ((not self.app.pargs.nginx) and (not self.app.pargs.fpm) and (not self.app.pargs.mysql) and (not self.app.pargs.access) and (not self.app.pargs.wp) and self.app.pargs.site_name):
self.app.pargs.nginx = True
self.app.pargs.wp = True
self.app.pargs.access = True
self.app.pargs.mysql = True
if (self.app.pargs.nginx and (not self.app.pargs.site_name)):
self.msg = (self.msg + ['/var/log/nginx/*error.log'])
if (self.app.pargs.access and (not self.app.pargs.site_name)):
self.msg = (self.msg + ['/var/log/nginx/*access.log'])
if self.app.pargs.fpm:
open('/var/log/php5/slow.log', 'a').close()
open('/var/log/php5/fpm.log', 'a').close()
self.msg = (self.msg + ['/var/log/php5/slow.log', '/var/log/php5/fpm.log'])
if self.app.pargs.mysql:
if (EEVariables.ee_mysql_host is 'localhost'):
if os.path.isfile('/var/log/mysql/mysql-slow.log'):
self.msg = (self.msg + ['/var/log/mysql/mysql-slow.log'])
else:
Log.info(self, 'MySQL slow-log not found, skipped')
else:
Log.warn(self, 'Remote MySQL found, EasyEngine is not able toshow MySQL log file')
if self.app.pargs.site_name:
webroot = '{0}{1}'.format(EEVariables.ee_webroot, self.app.pargs.site_name)
if (not os.path.isdir(webroot)):
Log.error(self, 'Site not present, quitting')
if self.app.pargs.access:
self.msg = (self.msg + ['{0}/{1}/logs/access.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
if self.app.pargs.nginx:
self.msg = (self.msg + ['{0}/{1}/logs/error.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
if self.app.pargs.wp:
if os.path.isdir('{0}/htdocs/wp-content'.format(webroot)):
if (not os.path.isfile('{0}/logs/debug.log'.format(webroot))):
if (not os.path.isfile('{0}/htdocs/wp-content/debug.log'.format(webroot))):
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))
EEFileUtils.create_symlink(self, ['{0}/htdocs/wp-content/debug.log'.format(webroot), '{0}/logs/debug.log'.format(webroot)])
self.msg = (self.msg + ['{0}/{1}/logs/debug.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
else:
Log.info(self, 'Site is not WordPress site, skipping WordPress logs')
mail_list = []
for m_list in self.msg:
mail_list = (mail_list + glob.glob(m_list))
for tomail in self.app.pargs.to:
Log.info(self, 'Sending mail to {0}'.format(tomail[0]))
EESendMail('easyengine', tomail[0], '{0} Log Files'.format(EEVariables.ee_fqdn), "Hey Hi,\n Please find attached server log files\n\n\nYour's faithfully,\nEasyEngine", files=mail_list, port=25, isTls=False)
|
'This function Secures authentication'
| @expose(hide=True)
def secure_auth(self):
| 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')
|
'This function Secures port'
| @expose(hide=True)
def secure_port(self):
| if self.app.pargs.user_input:
while (not self.app.pargs.user_input.isdigit()):
Log.info(self, 'Please Enter valid port number ')
self.app.pargs.user_input = input('EasyEngine admin port [22222]:')
if (not self.app.pargs.user_input):
port = input('EasyEngine admin port [22222]:')
if (port == ''):
self.app.pargs.user_input = 22222
while ((not port.isdigit()) and (port != '')):
Log.info(self, 'Please Enter valid port number :')
port = input('EasyEngine admin port [22222]:')
self.app.pargs.user_input = port
if (EEVariables.ee_platform_distro == 'ubuntu'):
EEShellExec.cmd_exec(self, 'sed -i "s/listen.*/listen {port} default_server ssl http2;/" /etc/nginx/sites-available/22222'.format(port=self.app.pargs.user_input))
if (EEVariables.ee_platform_distro == 'debian'):
EEShellExec.cmd_exec(self, 'sed -i "s/listen.*/listen {port} default_server ssl http2;/" /etc/nginx/sites-available/22222'.format(port=self.app.pargs.user_input))
EEGit.add(self, ['/etc/nginx'], msg='Adding changed secure port into Git')
if (not EEService.reload_service(self, 'nginx')):
Log.error(self, 'service nginx reload failed. check issues with `nginx -t` command')
Log.info(self, 'Successfully port changed {port}'.format(port=self.app.pargs.user_input))
|
'This function Secures IP'
| @expose(hide=True)
def secure_ip(self):
| newlist = []
if (not self.app.pargs.user_input):
ip = input('Enter the comma separated IP addresses to white list [127.0.0.1]:')
self.app.pargs.user_input = ip
try:
user_ip = self.app.pargs.user_input.split(',')
except Exception as e:
user_ip = ['127.0.0.1']
for ip_addr in user_ip:
if (not (('exist_ip_address ' + ip_addr) in open('/etc/nginx/common/acl.conf').read())):
EEShellExec.cmd_exec(self, 'sed -i "/deny/i allow {whitelist_adre}\\;" /etc/nginx/common/acl.conf'.format(whitelist_adre=ip_addr))
EEGit.add(self, ['/etc/nginx'], msg='Adding changed secure ip into Git')
Log.info(self, 'Successfully added IP address in acl.conf file')
|
'Display Nginx information'
| @expose(hide=True)
def info_nginx(self):
| version = os.popen("nginx -v 2>&1 | cut -d':' -f2 | cut -d' ' -f2 | cut -d'/' -f2 | tr -d '\n'").read()
allow = os.popen("grep ^allow /etc/nginx/common/acl.conf | cut -d' ' -f2 | cut -d';' -f1 | tr '\n' ' '").read()
nc = NginxConfig()
nc.loadf('/etc/nginx/nginx.conf')
user = nc.get('user')[1]
worker_processes = nc.get('worker_processes')[1]
worker_connections = nc.get([('events',), 'worker_connections'])[1]
keepalive_timeout = nc.get([('http',), 'keepalive_timeout'])[1]
fastcgi_read_timeout = nc.get([('http',), 'fastcgi_read_timeout'])[1]
client_max_body_size = nc.get([('http',), 'client_max_body_size'])[1]
data = dict(version=version, allow=allow, user=user, worker_processes=worker_processes, keepalive_timeout=keepalive_timeout, worker_connections=worker_connections, fastcgi_read_timeout=fastcgi_read_timeout, client_max_body_size=client_max_body_size)
self.app.render(data, 'info_nginx.mustache')
|
'Display PHP information'
| @expose(hide=True)
def info_php(self):
| version = os.popen(("{0} -v 2>/dev/null | head -n1 | cut -d' ' -f2 |".format(('php5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php')) + " cut -d'+' -f1 | tr -d '\n'")).read
config = configparser.ConfigParser()
config.read('/etc/{0}/fpm/php.ini'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')))
expose_php = config['PHP']['expose_php']
memory_limit = config['PHP']['memory_limit']
post_max_size = config['PHP']['post_max_size']
upload_max_filesize = config['PHP']['upload_max_filesize']
max_execution_time = config['PHP']['max_execution_time']
config.read('/etc/{0}/fpm/pool.d/www.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')))
www_listen = config['www']['listen']
www_ping_path = config['www']['ping.path']
www_pm_status_path = config['www']['pm.status_path']
www_pm = config['www']['pm']
www_pm_max_requests = config['www']['pm.max_requests']
www_pm_max_children = config['www']['pm.max_children']
www_pm_start_servers = config['www']['pm.start_servers']
www_pm_min_spare_servers = config['www']['pm.min_spare_servers']
www_pm_max_spare_servers = config['www']['pm.max_spare_servers']
www_request_terminate_time = config['www']['request_terminate_timeout']
try:
www_xdebug = config['www']['php_admin_flag[xdebug.profiler_enable_trigger]']
except Exception as e:
www_xdebug = 'off'
config.read('/etc/{0}/fpm/pool.d/debug.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')))
debug_listen = config['debug']['listen']
debug_ping_path = config['debug']['ping.path']
debug_pm_status_path = config['debug']['pm.status_path']
debug_pm = config['debug']['pm']
debug_pm_max_requests = config['debug']['pm.max_requests']
debug_pm_max_children = config['debug']['pm.max_children']
debug_pm_start_servers = config['debug']['pm.start_servers']
debug_pm_min_spare_servers = config['debug']['pm.min_spare_servers']
debug_pm_max_spare_servers = config['debug']['pm.max_spare_servers']
debug_request_terminate = config['debug']['request_terminate_timeout']
try:
debug_xdebug = config['debug']['php_admin_flag[xdebug.profiler_enable_trigger]']
except Exception as e:
debug_xdebug = 'off'
data = dict(version=version, expose_php=expose_php, memory_limit=memory_limit, post_max_size=post_max_size, upload_max_filesize=upload_max_filesize, max_execution_time=max_execution_time, www_listen=www_listen, www_ping_path=www_ping_path, www_pm_status_path=www_pm_status_path, www_pm=www_pm, www_pm_max_requests=www_pm_max_requests, www_pm_max_children=www_pm_max_children, www_pm_start_servers=www_pm_start_servers, www_pm_min_spare_servers=www_pm_min_spare_servers, www_pm_max_spare_servers=www_pm_max_spare_servers, www_request_terminate_timeout=www_request_terminate_time, www_xdebug_profiler_enable_trigger=www_xdebug, debug_listen=debug_listen, debug_ping_path=debug_ping_path, debug_pm_status_path=debug_pm_status_path, debug_pm=debug_pm, debug_pm_max_requests=debug_pm_max_requests, debug_pm_max_children=debug_pm_max_children, debug_pm_start_servers=debug_pm_start_servers, debug_pm_min_spare_servers=debug_pm_min_spare_servers, debug_pm_max_spare_servers=debug_pm_max_spare_servers, debug_request_terminate_timeout=debug_request_terminate, debug_xdebug_profiler_enable_trigger=debug_xdebug)
self.app.render(data, 'info_php.mustache')
|
'Display PHP information'
| @expose(hide=True)
def info_php7(self):
| version = os.popen("php7.0 -v 2>/dev/null | head -n1 | cut -d' ' -f2 | cut -d'+' -f1 | tr -d '\n'").read
config = configparser.ConfigParser()
config.read('/etc/php/7.0/fpm/php.ini')
expose_php = config['PHP']['expose_php']
memory_limit = config['PHP']['memory_limit']
post_max_size = config['PHP']['post_max_size']
upload_max_filesize = config['PHP']['upload_max_filesize']
max_execution_time = config['PHP']['max_execution_time']
config.read('/etc/php/7.0/fpm/pool.d/www.conf')
www_listen = config['www']['listen']
www_ping_path = config['www']['ping.path']
www_pm_status_path = config['www']['pm.status_path']
www_pm = config['www']['pm']
www_pm_max_requests = config['www']['pm.max_requests']
www_pm_max_children = config['www']['pm.max_children']
www_pm_start_servers = config['www']['pm.start_servers']
www_pm_min_spare_servers = config['www']['pm.min_spare_servers']
www_pm_max_spare_servers = config['www']['pm.max_spare_servers']
www_request_terminate_time = config['www']['request_terminate_timeout']
try:
www_xdebug = config['www']['php_admin_flag[xdebug.profiler_enable_trigger]']
except Exception as e:
www_xdebug = 'off'
config.read('/etc/php/7.0/fpm/pool.d/debug.conf')
debug_listen = config['debug']['listen']
debug_ping_path = config['debug']['ping.path']
debug_pm_status_path = config['debug']['pm.status_path']
debug_pm = config['debug']['pm']
debug_pm_max_requests = config['debug']['pm.max_requests']
debug_pm_max_children = config['debug']['pm.max_children']
debug_pm_start_servers = config['debug']['pm.start_servers']
debug_pm_min_spare_servers = config['debug']['pm.min_spare_servers']
debug_pm_max_spare_servers = config['debug']['pm.max_spare_servers']
debug_request_terminate = config['debug']['request_terminate_timeout']
try:
debug_xdebug = config['debug']['php_admin_flag[xdebug.profiler_enable_trigger]']
except Exception as e:
debug_xdebug = 'off'
data = dict(version=version, expose_php=expose_php, memory_limit=memory_limit, post_max_size=post_max_size, upload_max_filesize=upload_max_filesize, max_execution_time=max_execution_time, www_listen=www_listen, www_ping_path=www_ping_path, www_pm_status_path=www_pm_status_path, www_pm=www_pm, www_pm_max_requests=www_pm_max_requests, www_pm_max_children=www_pm_max_children, www_pm_start_servers=www_pm_start_servers, www_pm_min_spare_servers=www_pm_min_spare_servers, www_pm_max_spare_servers=www_pm_max_spare_servers, www_request_terminate_timeout=www_request_terminate_time, www_xdebug_profiler_enable_trigger=www_xdebug, debug_listen=debug_listen, debug_ping_path=debug_ping_path, debug_pm_status_path=debug_pm_status_path, debug_pm=debug_pm, debug_pm_max_requests=debug_pm_max_requests, debug_pm_max_children=debug_pm_max_children, debug_pm_start_servers=debug_pm_start_servers, debug_pm_min_spare_servers=debug_pm_min_spare_servers, debug_pm_max_spare_servers=debug_pm_max_spare_servers, debug_request_terminate_timeout=debug_request_terminate, debug_xdebug_profiler_enable_trigger=debug_xdebug)
self.app.render(data, 'info_php.mustache')
|
'Display MySQL information'
| @expose(hide=True)
def info_mysql(self):
| version = os.popen("mysql -V | awk '{print($5)}' | cut -d ',' -f1 | tr -d '\n'").read()
host = 'localhost'
port = os.popen('mysql -e "show variables" | grep ^port | awk \'{print($2)}\' | tr -d \'\n\'').read()
wait_timeout = os.popen('mysql -e "show variables" | grep ^wait_timeout | awk \'{print($2)}\' | tr -d \'\n\'').read()
interactive_timeout = os.popen('mysql -e "show variables" | grep ^interactive_timeout | awk \'{print($2)}\' | tr -d \'\n\'').read()
max_used_connections = os.popen('mysql -e "show global status" | grep Max_used_connections | awk \'{print($2)}\' | tr -d \'\n\'').read()
datadir = os.popen('mysql -e "show variables" | grep datadir | awk \'{print($2)}\' | tr -d \'\n\'').read()
socket = os.popen('mysql -e "show variables" | grep "^socket" | awk \'{print($2)}\' | tr -d \'\n\'').read()
data = dict(version=version, host=host, port=port, wait_timeout=wait_timeout, interactive_timeout=interactive_timeout, max_used_connections=max_used_connections, datadir=datadir, socket=socket)
self.app.render(data, 'info_mysql.mustache')
|
'default function for info'
| @expose(hide=True)
def default(self):
| if ((not self.app.pargs.nginx) and (not self.app.pargs.php) and (not self.app.pargs.mysql) and (not self.app.pargs.php7)):
self.app.pargs.nginx = True
self.app.pargs.php = True
self.app.pargs.mysql = True
if EEAptGet.is_installed(self, 'php7.0-fpm'):
self.app.pargs.php = True
if self.app.pargs.nginx:
if (EEAptGet.is_installed(self, 'nginx-custom') or EEAptGet.is_installed(self, 'nginx-common')):
self.info_nginx()
else:
Log.error(self, 'Nginx is not installed')
if self.app.pargs.php:
if ((EEVariables.ee_platform_distro == 'debian') or (EEVariables.ee_platform_codename == 'precise')):
if EEAptGet.is_installed(self, 'php5-fpm'):
self.info_php()
else:
Log.error(self, 'PHP5 is not installed')
elif EEAptGet.is_installed(self, 'php5.6-fpm'):
self.info_php()
else:
Log.error(self, 'PHP5.6 is not installed')
if self.app.pargs.php7:
if EEAptGet.is_installed(self, 'php7.0-fpm'):
self.info_php7()
else:
Log.error(self, 'PHP 7.0 is not installed')
if self.app.pargs.mysql:
if EEShellExec.cmd_exec(self, 'mysqladmin ping'):
self.info_mysql()
else:
Log.error(self, 'MySQL is not installed')
|
'Start services'
| @expose(help='Start stack services')
def start(self):
| services = []
if (not (self.app.pargs.nginx or self.app.pargs.php or self.app.pargs.php7 or self.app.pargs.mysql or self.app.pargs.postfix or self.app.pargs.hhvm or self.app.pargs.memcache or self.app.pargs.dovecot or self.app.pargs.redis)):
self.app.pargs.nginx = True
self.app.pargs.php = True
self.app.pargs.mysql = True
self.app.pargs.postfix = True
if self.app.pargs.nginx:
if (EEAptGet.is_installed(self, 'nginx-custom') or EEAptGet.is_installed(self, 'nginx-mainline')):
services = (services + ['nginx'])
else:
Log.info(self, 'Nginx is not installed')
if self.app.pargs.php:
if ((EEVariables.ee_platform_distro == 'debian') or (EEVariables.ee_platform_codename == 'precise')):
if EEAptGet.is_installed(self, 'php5-fpm'):
services = (services + ['php5-fpm'])
else:
Log.info(self, 'PHP5-FPM is not installed')
else:
if EEAptGet.is_installed(self, 'php5.6-fpm'):
services = (services + ['php5.6-fpm'])
else:
Log.info(self, 'PHP5.6-FPM is not installed')
if EEAptGet.is_installed(self, 'php7.0-fpm'):
services = (services + ['php7.0-fpm'])
else:
Log.info(self, 'PHP7.0-FPM is not installed')
if self.app.pargs.php7:
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
if EEAptGet.is_installed(self, 'php7.0-fpm'):
services = (services + ['php7.0-fpm'])
else:
Log.info(self, 'PHP7.0-FPM is not installed')
else:
Log.info(self, 'Your platform does not support PHP 7')
if self.app.pargs.mysql:
if ((EEVariables.ee_mysql_host is 'localhost') or (EEVariables.ee_mysql_host is '127.0.0.1')):
if (EEAptGet.is_installed(self, 'mysql-server') or EEAptGet.is_installed(self, 'percona-server-server-5.6') or EEAptGet.is_installed(self, 'mariadb-server')):
services = (services + ['mysql'])
else:
Log.info(self, 'MySQL is not installed')
else:
Log.warn(self, 'Remote MySQL found, Unable to check MySQL service status')
if self.app.pargs.postfix:
if EEAptGet.is_installed(self, 'postfix'):
services = (services + ['postfix'])
else:
Log.info(self, 'Postfix is not installed')
if self.app.pargs.hhvm:
if EEAptGet.is_installed(self, 'hhvm'):
services = (services + ['hhvm'])
else:
Log.info(self, 'HHVM is not installed')
if self.app.pargs.memcache:
if EEAptGet.is_installed(self, 'memcached'):
services = (services + ['memcached'])
else:
Log.info(self, 'Memcache is not installed')
if self.app.pargs.dovecot:
if EEAptGet.is_installed(self, 'dovecot-core'):
services = (services + ['dovecot'])
else:
Log.info(self, 'Mail server is not installed')
if self.app.pargs.redis:
if EEAptGet.is_installed(self, 'redis-server'):
services = (services + ['redis-server'])
else:
Log.info(self, 'Redis server is not installed')
for service in services:
Log.debug(self, 'Starting service: {0}'.format(service))
EEService.start_service(self, service)
|
'Stop services'
| @expose(help='Stop stack services')
def stop(self):
| services = []
if (not (self.app.pargs.nginx or self.app.pargs.php or self.app.pargs.php7 or self.app.pargs.mysql or self.app.pargs.postfix or self.app.pargs.hhvm or self.app.pargs.memcache or self.app.pargs.dovecot or self.app.pargs.redis)):
self.app.pargs.nginx = True
self.app.pargs.php = True
self.app.pargs.mysql = True
self.app.pargs.postfix = True
if self.app.pargs.nginx:
if (EEAptGet.is_installed(self, 'nginx-custom') or EEAptGet.is_installed(self, 'nginx-mainline')):
services = (services + ['nginx'])
else:
Log.info(self, 'Nginx is not installed')
if self.app.pargs.php:
if ((EEVariables.ee_platform_distro == 'debian') or (EEVariables.ee_platform_codename == 'precise')):
if EEAptGet.is_installed(self, 'php5-fpm'):
services = (services + ['php5-fpm'])
else:
Log.info(self, 'PHP5-FPM is not installed')
else:
if EEAptGet.is_installed(self, 'php5.6-fpm'):
services = (services + ['php5.6-fpm'])
else:
Log.info(self, 'PHP5.6-FPM is not installed')
if EEAptGet.is_installed(self, 'php7.0-fpm'):
services = (services + ['php7.0-fpm'])
else:
Log.info(self, 'PHP7.0-FPM is not installed')
if self.app.pargs.php7:
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
if EEAptGet.is_installed(self, 'php7.0-fpm'):
services = (services + ['php7.0-fpm'])
else:
Log.info(self, 'PHP7.0-FPM is not installed')
else:
Log.info(self, 'Your platform does not support PHP 7')
if self.app.pargs.mysql:
if ((EEVariables.ee_mysql_host is 'localhost') or (EEVariables.ee_mysql_host is '127.0.0.1')):
if (EEAptGet.is_installed(self, 'mysql-server') or EEAptGet.is_installed(self, 'percona-server-server-5.6') or EEAptGet.is_installed(self, 'mariadb-server')):
services = (services + ['mysql'])
else:
Log.info(self, 'MySQL is not installed')
else:
Log.warn(self, 'Remote MySQL found, Unable to check MySQL service status')
if self.app.pargs.postfix:
if EEAptGet.is_installed(self, 'postfix'):
services = (services + ['postfix'])
else:
Log.info(self, 'Postfix is not installed')
if self.app.pargs.hhvm:
if EEAptGet.is_installed(self, 'hhvm'):
services = (services + ['hhvm'])
else:
Log.info(self, 'HHVM is not installed')
if self.app.pargs.memcache:
if EEAptGet.is_installed(self, 'memcached'):
services = (services + ['memcached'])
else:
Log.info(self, 'Memcache is not installed')
if self.app.pargs.dovecot:
if EEAptGet.is_installed(self, 'dovecot-core'):
services = (services + ['dovecot'])
else:
Log.info(self, 'Mail server is not installed')
if self.app.pargs.redis:
if EEAptGet.is_installed(self, 'redis-server'):
services = (services + ['redis-server'])
else:
Log.info(self, 'Redis server is not installed')
for service in services:
Log.debug(self, 'Stopping service: {0}'.format(service))
EEService.stop_service(self, service)
|
'Restart services'
| @expose(help='Restart stack services')
def restart(self):
| services = []
if (not (self.app.pargs.nginx or self.app.pargs.php or self.app.pargs.php7 or self.app.pargs.mysql or self.app.pargs.postfix or self.app.pargs.hhvm or self.app.pargs.memcache or self.app.pargs.dovecot or self.app.pargs.redis)):
self.app.pargs.nginx = True
self.app.pargs.php = True
self.app.pargs.mysql = True
self.app.pargs.postfix = True
if self.app.pargs.nginx:
if (EEAptGet.is_installed(self, 'nginx-custom') or EEAptGet.is_installed(self, 'nginx-mainline')):
services = (services + ['nginx'])
else:
Log.info(self, 'Nginx is not installed')
if self.app.pargs.php:
if ((EEVariables.ee_platform_distro == 'debian') or (EEVariables.ee_platform_codename == 'precise')):
if EEAptGet.is_installed(self, 'php5-fpm'):
services = (services + ['php5-fpm'])
else:
Log.info(self, 'PHP5-FPM is not installed')
else:
if EEAptGet.is_installed(self, 'php5.6-fpm'):
services = (services + ['php5.6-fpm'])
else:
Log.info(self, 'PHP5.6-FPM is not installed')
if EEAptGet.is_installed(self, 'php7.0-fpm'):
services = (services + ['php7.0-fpm'])
else:
Log.info(self, 'PHP7.0-FPM is not installed')
if self.app.pargs.php7:
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
if EEAptGet.is_installed(self, 'php7.0-fpm'):
services = (services + ['php7.0-fpm'])
else:
Log.info(self, 'PHP7.0-FPM is not installed')
else:
Log.info(self, 'Your platform does not support PHP 7')
if self.app.pargs.mysql:
if ((EEVariables.ee_mysql_host is 'localhost') or (EEVariables.ee_mysql_host is '127.0.0.1')):
if (EEAptGet.is_installed(self, 'mysql-server') or EEAptGet.is_installed(self, 'percona-server-server-5.6') or EEAptGet.is_installed(self, 'mariadb-server')):
services = (services + ['mysql'])
else:
Log.info(self, 'MySQL is not installed')
else:
Log.warn(self, 'Remote MySQL found, Unable to check MySQL service status')
if self.app.pargs.postfix:
if EEAptGet.is_installed(self, 'postfix'):
services = (services + ['postfix'])
else:
Log.info(self, 'Postfix is not installed')
if self.app.pargs.hhvm:
if EEAptGet.is_installed(self, 'hhvm'):
services = (services + ['hhvm'])
else:
Log.info(self, 'HHVM is not installed')
if self.app.pargs.memcache:
if EEAptGet.is_installed(self, 'memcached'):
services = (services + ['memcached'])
else:
Log.info(self, 'Memcache is not installed')
if self.app.pargs.dovecot:
if EEAptGet.is_installed(self, 'dovecot-core'):
services = (services + ['dovecot'])
else:
Log.info(self, 'Mail server is not installed')
if self.app.pargs.redis:
if EEAptGet.is_installed(self, 'redis-server'):
services = (services + ['redis-server'])
else:
Log.info(self, 'Redis server is not installed')
for service in services:
Log.debug(self, 'Restarting service: {0}'.format(service))
EEService.restart_service(self, service)
|
'Status of services'
| @expose(help='Get stack status')
def status(self):
| services = []
if (not (self.app.pargs.nginx or self.app.pargs.php or self.app.pargs.php7 or self.app.pargs.mysql or self.app.pargs.postfix or self.app.pargs.hhvm or self.app.pargs.memcache or self.app.pargs.dovecot or self.app.pargs.redis)):
self.app.pargs.nginx = True
self.app.pargs.php = True
self.app.pargs.mysql = True
self.app.pargs.postfix = True
self.app.pargs.hhvm = True
if self.app.pargs.nginx:
if (EEAptGet.is_installed(self, 'nginx-custom') or EEAptGet.is_installed(self, 'nginx-mainline')):
services = (services + ['nginx'])
else:
Log.info(self, 'Nginx is not installed')
if self.app.pargs.php:
if ((EEVariables.ee_platform_distro == 'debian') or (EEVariables.ee_platform_codename == 'precise')):
if EEAptGet.is_installed(self, 'php5-fpm'):
services = (services + ['php5-fpm'])
else:
Log.info(self, 'PHP5-FPM is not installed')
else:
if EEAptGet.is_installed(self, 'php5.6-fpm'):
services = (services + ['php5.6-fpm'])
else:
Log.info(self, 'PHP5.6-FPM is not installed')
if EEAptGet.is_installed(self, 'php7.0-fpm'):
services = (services + ['php7.0-fpm'])
else:
Log.info(self, 'PHP7.0-FPM is not installed')
if self.app.pargs.php7:
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
if EEAptGet.is_installed(self, 'php7.0-fpm'):
services = (services + ['php7.0-fpm'])
else:
Log.info(self, 'PHP7.0-FPM is not installed')
else:
Log.info(self, 'Your platform does not support PHP 7')
if self.app.pargs.mysql:
if ((EEVariables.ee_mysql_host is 'localhost') or (EEVariables.ee_mysql_host is '127.0.0.1')):
if (EEAptGet.is_installed(self, 'mysql-server') or EEAptGet.is_installed(self, 'percona-server-server-5.6') or EEAptGet.is_installed(self, 'mariadb-server')):
services = (services + ['mysql'])
else:
Log.info(self, 'MySQL is not installed')
else:
Log.warn(self, 'Remote MySQL found, Unable to check MySQL service status')
if self.app.pargs.postfix:
if EEAptGet.is_installed(self, 'postfix'):
services = (services + ['postfix'])
else:
Log.info(self, 'Postfix is not installed')
if self.app.pargs.hhvm:
if EEAptGet.is_installed(self, 'hhvm'):
services = (services + ['hhvm'])
else:
Log.info(self, 'HHVM is not installed')
if self.app.pargs.memcache:
if EEAptGet.is_installed(self, 'memcached'):
services = (services + ['memcached'])
else:
Log.info(self, 'Memcache is not installed')
if self.app.pargs.dovecot:
if EEAptGet.is_installed(self, 'dovecot-core'):
services = (services + ['dovecot'])
else:
Log.info(self, 'Mail server is not installed')
if self.app.pargs.redis:
if EEAptGet.is_installed(self, 'redis-server'):
services = (services + ['redis-server'])
else:
Log.info(self, 'Redis server is not installed')
for service in services:
if EEService.get_service_status(self, service):
Log.info(self, '{0:10}: {1}'.format(service, 'Running'))
|
'Reload service'
| @expose(help='Reload stack services')
def reload(self):
| services = []
if (not (self.app.pargs.nginx or self.app.pargs.php or self.app.pargs.php7 or self.app.pargs.mysql or self.app.pargs.postfix or self.app.pargs.hhvm or self.app.pargs.memcache or self.app.pargs.dovecot or self.app.pargs.redis)):
self.app.pargs.nginx = True
self.app.pargs.php = True
self.app.pargs.mysql = True
self.app.pargs.postfix = True
if self.app.pargs.nginx:
if (EEAptGet.is_installed(self, 'nginx-custom') or EEAptGet.is_installed(self, 'nginx-mainline')):
services = (services + ['nginx'])
else:
Log.info(self, 'Nginx is not installed')
if self.app.pargs.php:
if ((EEVariables.ee_platform_distro == 'debian') or (EEVariables.ee_platform_codename == 'precise')):
if EEAptGet.is_installed(self, 'php5-fpm'):
services = (services + ['php5-fpm'])
else:
Log.info(self, 'PHP5-FPM is not installed')
else:
if EEAptGet.is_installed(self, 'php5.6-fpm'):
services = (services + ['php5.6-fpm'])
else:
Log.info(self, 'PHP5.6-FPM is not installed')
if EEAptGet.is_installed(self, 'php7.0-fpm'):
services = (services + ['php7.0-fpm'])
else:
Log.info(self, 'PHP7.0-FPM is not installed')
if self.app.pargs.php7:
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
if EEAptGet.is_installed(self, 'php7.0-fpm'):
services = (services + ['php7.0-fpm'])
else:
Log.info(self, 'PHP7.0-FPM is not installed')
else:
Log.info(self, 'Your platform does not support PHP 7')
if self.app.pargs.mysql:
if ((EEVariables.ee_mysql_host is 'localhost') or (EEVariables.ee_mysql_host is '127.0.0.1')):
if (EEAptGet.is_installed(self, 'mysql-server') or EEAptGet.is_installed(self, 'percona-server-server-5.6') or EEAptGet.is_installed(self, 'mariadb-server')):
services = (services + ['mysql'])
else:
Log.info(self, 'MySQL is not installed')
else:
Log.warn(self, 'Remote MySQL found, Unable to check MySQL service status')
if self.app.pargs.postfix:
if EEAptGet.is_installed(self, 'postfix'):
services = (services + ['postfix'])
else:
Log.info(self, 'Postfix is not installed')
if self.app.pargs.hhvm:
Log.info(self, 'HHVM does not support to reload')
if self.app.pargs.memcache:
if EEAptGet.is_installed(self, 'memcached'):
services = (services + ['memcached'])
else:
Log.info(self, 'Memcache is not installed')
if self.app.pargs.dovecot:
if EEAptGet.is_installed(self, 'dovecot-core'):
services = (services + ['dovecot'])
else:
Log.info(self, 'Mail server is not installed')
if self.app.pargs.redis:
if EEAptGet.is_installed(self, 'redis-server'):
services = (services + ['redis-server'])
else:
Log.info(self, 'Redis server is not installed')
for service in services:
Log.debug(self, 'Reloading service: {0}'.format(service))
EEService.reload_service(self, service)
|
'default action of ee stack command'
| @expose(hide=True)
def default(self):
| if self.app.pargs.pagespeed:
Log.error(self, 'Pagespeed support has been dropped since EasyEngine v3.6.0', False)
Log.error(self, 'Please run command again without `--pagespeed`', False)
Log.error(self, 'For more details, read - https://easyengine.io/blog/disabling-pagespeed/')
else:
self.app.args.print_help()
|
'Pre settings to do before installation packages'
| @expose(hide=True)
def pre_pref(self, apt_packages):
| if set(EEVariables.ee_postfix).issubset(set(apt_packages)):
Log.debug(self, 'Pre-seeding Postfix')
try:
EEShellExec.cmd_exec(self, 'echo "postfix postfix/main_mailer_type string \'Internet Site\'" | debconf-set-selections')
EEShellExec.cmd_exec(self, 'echo "postfix postfix/mailname string $(hostname -f)" | debconf-set-selections')
except CommandExecutionError as e:
Log.error(self, 'Failed to intialize postfix package')
if set(EEVariables.ee_mysql).issubset(set(apt_packages)):
Log.info(self, 'Adding repository for MySQL, please wait...')
mysql_pref = 'Package: *\nPin: origin sfo1.mirrors.digitalocean.com\nPin-Priority: 1000\n'
with open('/etc/apt/preferences.d/MariaDB.pref', 'w') as mysql_pref_file:
mysql_pref_file.write(mysql_pref)
EERepo.add(self, repo_url=EEVariables.ee_mysql_repo)
Log.debug(self, 'Adding key for {0}'.format(EEVariables.ee_mysql_repo))
if (EEVariables.ee_platform_codename != 'xenial'):
EERepo.add_key(self, '0xcbcb082a1bb943db', keyserver='keyserver.ubuntu.com')
else:
EERepo.add_key(self, '0xF1656F24C74CD1D8', keyserver='keyserver.ubuntu.com')
chars = ''.join(random.sample(string.ascii_letters, 8))
Log.debug(self, 'Pre-seeding MySQL')
Log.debug(self, 'echo "mariadb-server-10.1 mysql-server/root_password password " | debconf-set-selections')
try:
EEShellExec.cmd_exec(self, 'echo "mariadb-server-10.1 mysql-server/root_password password {chars}" | debconf-set-selections'.format(chars=chars), log=False)
except CommandExecutionError as e:
Log.error('Failed to initialize MySQL package')
Log.debug(self, 'echo "mariadb-server-10.1 mysql-server/root_password_again password " | debconf-set-selections')
try:
EEShellExec.cmd_exec(self, 'echo "mariadb-server-10.1 mysql-server/root_password_again password {chars}" | debconf-set-selections'.format(chars=chars), log=False)
except CommandExecutionError as e:
Log.error('Failed to initialize MySQL package')
mysql_config = '\n [client]\n user = root\n password = {chars}\n '.format(chars=chars)
config = configparser.ConfigParser()
config.read_string(mysql_config)
Log.debug(self, 'Writting configuration into MySQL file')
conf_path = '/etc/mysql/conf.d/my.cnf'
os.makedirs(os.path.dirname(conf_path), exist_ok=True)
with open(conf_path, encoding='utf-8', mode='w') as configfile:
config.write(configfile)
Log.debug(self, 'Setting my.cnf permission')
EEFileUtils.chmod(self, '/etc/mysql/conf.d/my.cnf', 384)
if set(EEVariables.ee_nginx).issubset(set(apt_packages)):
Log.info(self, 'Adding repository for NGINX, please wait...')
EERepo.add(self, repo_url=EEVariables.ee_nginx_repo)
Log.debug(self, 'Adding ppa of Nginx')
EERepo.add_key(self, EEVariables.ee_nginx_key)
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
if (set(EEVariables.ee_php7_0).issubset(set(apt_packages)) or set(EEVariables.ee_php5_6).issubset(set(apt_packages))):
Log.info(self, 'Adding repository for PHP, please wait...')
Log.debug(self, 'Adding ppa for PHP')
EERepo.add(self, ppa=EEVariables.ee_php_repo)
else:
if set(EEVariables.ee_php).issubset(set(apt_packages)):
Log.info(self, 'Adding repository for PHP, please wait...')
if (EEVariables.ee_platform_distro == 'debian'):
if (EEVariables.ee_platform_codename != 'jessie'):
Log.debug(self, 'Adding repo_url of php for debian')
EERepo.add(self, repo_url=EEVariables.ee_php_repo)
Log.debug(self, 'Adding Dotdeb/php GPG key')
EERepo.add_key(self, '89DF5277')
else:
Log.debug(self, 'Adding ppa for PHP')
EERepo.add(self, ppa=EEVariables.ee_php_repo)
if (EEVariables.ee_platform_codename == 'jessie'):
if set(EEVariables.ee_php7_0).issubset(set(apt_packages)):
Log.debug(self, 'Adding repo_url of php 7.0 for debian')
EERepo.add(self, repo_url=EEVariables.ee_php_repo)
Log.debug(self, 'Adding Dotdeb/php GPG key')
EERepo.add_key(self, '89DF5277')
if set(EEVariables.ee_hhvm).issubset(set(apt_packages)):
if (EEVariables.ee_platform_codename != 'xenial'):
Log.info(self, 'Adding repository for HHVM, please wait...')
if (EEVariables.ee_platform_codename == 'precise'):
Log.debug(self, 'Adding PPA for Boost')
EERepo.add(self, ppa=EEVariables.ee_boost_repo)
Log.debug(self, 'Adding ppa repo for HHVM')
EERepo.add(self, repo_url=EEVariables.ee_hhvm_repo)
Log.debug(self, 'Adding HHVM GPG Key')
EERepo.add_key(self, '0x5a16e7281be7a449')
else:
Log.info(self, 'Using default Ubuntu repository for HHVM')
if set(EEVariables.ee_mail).issubset(set(apt_packages)):
Log.debug(self, 'Executing the command debconf-set-selections.')
try:
EEShellExec.cmd_exec(self, 'echo "dovecot-core dovecot-core/create-ssl-cert boolean yes" | debconf-set-selections')
EEShellExec.cmd_exec(self, 'echo "dovecot-core dovecot-core/ssl-cert-name string $(hostname -f)" | debconf-set-selections')
except CommandExecutionError as e:
Log.error('Failed to initialize dovecot packages')
if set(EEVariables.ee_redis).issubset(set(apt_packages)):
Log.info(self, 'Adding repository for Redis, please wait...')
if (EEVariables.ee_platform_distro == 'debian'):
Log.debug(self, 'Adding repo_url of redis for debian')
EERepo.add(self, repo_url=EEVariables.ee_redis_repo)
Log.debug(self, 'Adding Dotdeb GPG key')
EERepo.add_key(self, '89DF5277')
else:
Log.debug(self, 'Adding ppa for redis')
EERepo.add(self, ppa=EEVariables.ee_redis_repo)
|
'Post activity after installation of packages'
| @expose(hide=True)
def post_pref(self, apt_packages, packages):
| if len(apt_packages):
if set(EEVariables.ee_postfix).issubset(set(apt_packages)):
EEGit.add(self, ['/etc/postfix'], msg='Adding Postfix into Git')
EEService.reload_service(self, 'postfix')
if set(EEVariables.ee_nginx).issubset(set(apt_packages)):
if (set(['nginx-plus']).issubset(set(apt_packages)) or set(['nginx']).issubset(set(apt_packages))):
if (not EEFileUtils.grep(self, '/etc/nginx/fastcgi_params', 'SCRIPT_FILENAME')):
with open('/etc/nginx/fastcgi_params', encoding='utf-8', mode='a') as ee_nginx:
ee_nginx.write('fastcgi_param DCTB SCRIPT_FILENAME DCTB $request_filename;\n')
if (not os.path.isfile('/etc/nginx/common/wpfc.conf')):
EEFileUtils.searchreplace(self, '/etc/nginx/nginx.conf', '# add_header', 'add_header')
EEFileUtils.searchreplace(self, '/etc/nginx/nginx.conf', '"EasyEngine"', '"EasyEngine {0}"'.format(EEVariables.ee_version))
data = dict()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/conf.d/blockips.conf')
ee_nginx = open('/etc/nginx/conf.d/blockips.conf', encoding='utf-8', mode='w')
self.app.render(data, 'blockips.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/conf.d/fastcgi.conf')
ee_nginx = open('/etc/nginx/conf.d/fastcgi.conf', encoding='utf-8', mode='w')
self.app.render(data, 'fastcgi.mustache', out=ee_nginx)
ee_nginx.close()
data = dict(php='9000', debug='9001', hhvm='8000', php7='9070', debug7='9170', hhvmconf=False, php7conf=(True if EEAptGet.is_installed(self, 'php7.0-fpm') else False))
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/conf.d/upstream.conf')
ee_nginx = open('/etc/nginx/conf.d/upstream.conf', encoding='utf-8', mode='w')
self.app.render(data, 'upstream.mustache', out=ee_nginx)
ee_nginx.close()
if (not os.path.exists('/etc/nginx/common')):
Log.debug(self, 'Creating directory/etc/nginx/common')
os.makedirs('/etc/nginx/common')
data = dict(webroot=EEVariables.ee_webroot)
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/acl.conf')
ee_nginx = open('/etc/nginx/common/acl.conf', encoding='utf-8', mode='w')
self.app.render(data, 'acl.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/locations.conf')
ee_nginx = open('/etc/nginx/common/locations.conf', encoding='utf-8', mode='w')
self.app.render(data, 'locations.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/php.conf')
ee_nginx = open('/etc/nginx/common/php.conf', encoding='utf-8', mode='w')
self.app.render(data, 'php.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/w3tc.conf')
ee_nginx = open('/etc/nginx/common/w3tc.conf', encoding='utf-8', mode='w')
self.app.render(data, 'w3tc.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpcommon.conf')
ee_nginx = open('/etc/nginx/common/wpcommon.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpcommon.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpfc.conf')
ee_nginx = open('/etc/nginx/common/wpfc.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpfc.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpsc.conf')
ee_nginx = open('/etc/nginx/common/wpsc.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpsc.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpsubdir.conf')
ee_nginx = open('/etc/nginx/common/wpsubdir.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpsubdir.mustache', out=ee_nginx)
ee_nginx.close()
if (((EEVariables.ee_platform_codename == 'jessie') or (EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) and (not os.path.isfile('/etc/nginx/common/php7.conf'))):
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/locations-php7.conf')
ee_nginx = open('/etc/nginx/common/locations-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'locations-php7.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/php7.conf')
ee_nginx = open('/etc/nginx/common/php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'php7.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/w3tc-php7.conf')
ee_nginx = open('/etc/nginx/common/w3tc-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'w3tc-php7.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpcommon-php7.conf')
ee_nginx = open('/etc/nginx/common/wpcommon-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpcommon-php7.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpfc-php7.conf')
ee_nginx = open('/etc/nginx/common/wpfc-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpfc-php7.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpsc-php7.conf')
ee_nginx = open('/etc/nginx/common/wpsc-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpsc-php7.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/redis-php7.conf')
ee_nginx = open('/etc/nginx/common/redis-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'redis-php7.mustache', out=ee_nginx)
ee_nginx.close()
if (set(['nginx-plus']).issubset(set(apt_packages)) or set(['nginx']).issubset(set(apt_packages))):
Log.info(self, 'Installing EasyEngine Configurations forNGINX')
if (not os.path.exists('/etc/nginx/sites-available')):
Log.debug(self, 'Creating directory/etc/nginx/sites-available')
os.makedirs('/etc/nginx/sites-available')
if (not os.path.exists('/etc/nginx/sites-enabled')):
Log.debug(self, 'Creating directory/etc/nginx/sites-available')
os.makedirs('/etc/nginx/sites-enabled')
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/sites-available/22222')
ee_nginx = open('/etc/nginx/sites-available/22222', encoding='utf-8', mode='w')
self.app.render(data, '22222.mustache', out=ee_nginx)
ee_nginx.close()
passwd = ''.join([random.choice((string.ascii_letters + string.digits)) for n in range(6)])
try:
EEShellExec.cmd_exec(self, 'printf "easyengine:$(openssl passwd -crypt {password} 2> /dev/null)\n"> /etc/nginx/htpasswd-ee 2>/dev/null'.format(password=passwd))
except CommandExecutionError as e:
Log.error(self, 'Failed to save HTTP Auth')
EEFileUtils.create_symlink(self, ['/etc/nginx/sites-available/22222', '/etc/nginx/sites-enabled/22222'])
if (not os.path.exists('{0}22222/logs'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory {0}22222/logs '.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/logs'.format(EEVariables.ee_webroot))
if (not os.path.exists('{0}22222/cert'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory {0}22222/cert'.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/cert'.format(EEVariables.ee_webroot))
EEFileUtils.create_symlink(self, ['/var/log/nginx/22222.access.log', '{0}22222/logs/access.log'.format(EEVariables.ee_webroot)])
EEFileUtils.create_symlink(self, ['/var/log/nginx/22222.error.log', '{0}22222/logs/error.log'.format(EEVariables.ee_webroot)])
try:
EEShellExec.cmd_exec(self, 'openssl genrsa -out {0}22222/cert/22222.key 2048'.format(EEVariables.ee_webroot))
EEShellExec.cmd_exec(self, 'openssl req -new -batch -subj /commonName=127.0.0.1/ -key {0}22222/cert/22222.key -out {0}22222/cert/22222.csr'.format(EEVariables.ee_webroot))
EEFileUtils.mvfile(self, '{0}22222/cert/22222.key'.format(EEVariables.ee_webroot), '{0}22222/cert/22222.key.org'.format(EEVariables.ee_webroot))
EEShellExec.cmd_exec(self, 'openssl rsa -in {0}22222/cert/22222.key.org -out {0}22222/cert/22222.key'.format(EEVariables.ee_webroot))
EEShellExec.cmd_exec(self, 'openssl x509 -req -days 3652 -in {0}22222/cert/22222.csr -signkey {0}22222/cert/22222.key -out {0}22222/cert/22222.crt'.format(EEVariables.ee_webroot))
except CommandExecutionError as e:
Log.error(self, 'Failed to generate SSL for 22222')
EEGit.add(self, ['/etc/nginx'], msg='Adding Nginx into Git')
EEService.reload_service(self, 'nginx')
if (set(['nginx-plus']).issubset(set(apt_packages)) or set(['nginx']).issubset(set(apt_packages))):
EEShellExec.cmd_exec(self, "sed -i -e 's/^user/#user/' -e '/^#user/a user\\ www-data\\;' /etc/nginx/nginx.conf")
if (not EEShellExec.cmd_exec(self, "cat /etc/nginx/nginx.conf | grep -q '/etc/nginx/sites-enabled'")):
EEShellExec.cmd_exec(self, "sed -i '/\\/etc\\/nginx\\/conf\\.d\\/\\*\\.conf/a \\ include\\ \\/etc\\/nginx\\/sites-enabled\\/*;' /etc/nginx/nginx.conf")
data['version'] = EEVariables.ee_version
Log.debug(self, 'Writting for nginx plus configuration to file /etc/nginx/conf.d/ee-plus.conf')
ee_nginx = open('/etc/nginx/conf.d/ee-plus.conf', encoding='utf-8', mode='w')
self.app.render(data, 'ee-plus.mustache', out=ee_nginx)
ee_nginx.close()
print ('HTTP Auth User Name: easyengine' + '\nHTTP Auth Password : {0}'.format(passwd))
EEService.reload_service(self, 'nginx')
else:
self.msg = ((self.msg + ['HTTP Auth User Name: easyengine']) + ['HTTP Auth Password : {0}'.format(passwd)])
else:
EEService.restart_service(self, 'nginx')
if EEAptGet.is_installed(self, 'redis-server'):
if (os.path.isfile('/etc/nginx/nginx.conf') and (not os.path.isfile('/etc/nginx/common/redis.conf'))):
data = dict()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/redis.conf')
ee_nginx = open('/etc/nginx/common/redis.conf', encoding='utf-8', mode='w')
self.app.render(data, 'redis.mustache', out=ee_nginx)
ee_nginx.close()
if (os.path.isfile('/etc/nginx/nginx.conf') and (not os.path.isfile('/etc/nginx/common/redis-hhvm.conf'))):
data = dict()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/redis-hhvm.conf')
ee_nginx = open('/etc/nginx/common/redis-hhvm.conf', encoding='utf-8', mode='w')
self.app.render(data, 'redis-hhvm.mustache', out=ee_nginx)
ee_nginx.close()
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
if (os.path.isfile('/etc/nginx/nginx.conf') and (not os.path.isfile('/etc/nginx/common/redis-php7.conf'))):
data = dict()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/redis-php7.conf')
ee_nginx = open('/etc/nginx/common/redis-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'redis-php7.mustache', out=ee_nginx)
ee_nginx.close()
if os.path.isfile('/etc/nginx/conf.d/upstream.conf'):
if (not EEFileUtils.grep(self, '/etc/nginx/conf.d/upstream.conf', 'redis')):
with open('/etc/nginx/conf.d/upstream.conf', 'a') as redis_file:
redis_file.write('upstream redis {\n server 127.0.0.1:6379;\n keepalive 10;\n}\n')
if (os.path.isfile('/etc/nginx/nginx.conf') and (not os.path.isfile('/etc/nginx/conf.d/redis.conf'))):
with open('/etc/nginx/conf.d/redis.conf', 'a') as redis_file:
redis_file.write('# Log format Settings\nlog_format rt_cache_redis \'$remote_addr $upstream_response_time $srcache_fetch_status [$time_local] \'\n\'$http_host "$request" $status $body_bytes_sent \'\n\'"$http_referer" "$http_user_agent"\';\n')
if self.app.pargs.php7:
if (os.path.isdir('/etc/nginx/common') and (not os.path.isfile('/etc/nginx/common/php7.conf'))):
data = dict()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/locations-php7.conf')
ee_nginx = open('/etc/nginx/common/locations-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'locations-php7.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/php7.conf')
ee_nginx = open('/etc/nginx/common/php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'php7.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/w3tc-php7.conf')
ee_nginx = open('/etc/nginx/common/w3tc-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'w3tc-php7.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpcommon-php7.conf')
ee_nginx = open('/etc/nginx/common/wpcommon-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpcommon-php7.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpfc-php7.conf')
ee_nginx = open('/etc/nginx/common/wpfc-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpfc-php7.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpsc-php7.conf')
ee_nginx = open('/etc/nginx/common/wpsc-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpsc-php7.mustache', out=ee_nginx)
ee_nginx.close()
if (os.path.isdir('/etc/nginx/common') and (not os.path.isfile('/etc/nginx/common/redis-php7.conf'))):
data = dict()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/redis-php7.conf')
ee_nginx = open('/etc/nginx/common/redis-php7.conf', encoding='utf-8', mode='w')
self.app.render(data, 'redis-php7.mustache', out=ee_nginx)
ee_nginx.close()
if os.path.isfile('/etc/nginx/conf.d/upstream.conf'):
if (not EEFileUtils.grep(self, '/etc/nginx/conf.d/upstream.conf', 'php7')):
with open('/etc/nginx/conf.d/upstream.conf', 'a') as php_file:
php_file.write('upstream php7 {\nserver 127.0.0.1:9070;\n}\nupstream debug7 {\nserver 127.0.0.1:9170;\n}\n')
if self.app.pargs.pagespeed:
if (os.path.isfile('/etc/nginx/nginx.conf') and (not os.path.isfile('/etc/nginx/conf.d/pagespeed.conf'))):
data = dict()
Log.debug(self, 'Writting the Pagespeed Global configuration to file /etc/nginx/conf.d/pagespeed.conf')
ee_nginx = open('/etc/nginx/conf.d/pagespeed.conf', encoding='utf-8', mode='w')
self.app.render(data, 'pagespeed-global.mustache', out=ee_nginx)
ee_nginx.close()
if set(EEVariables.ee_hhvm).issubset(set(apt_packages)):
EEShellExec.cmd_exec(self, 'update-rc.d hhvm defaults')
EEFileUtils.searchreplace(self, '/etc/hhvm/server.ini', '9000', '8000')
if (not (EEVariables.ee_platform_codename == 'xenial')):
EEFileUtils.searchreplace(self, '/etc/nginx/hhvm.conf', '9000', '8000')
with open('/etc/hhvm/php.ini', 'a') as hhvm_file:
hhvm_file.write('hhvm.log.header = true\nhhvm.log.natives_stack_trace = true\nhhvm.mysql.socket = /var/run/mysqld/mysqld.sock\nhhvm.pdo_mysql.socket = /var/run/mysqld/mysqld.sock\nhhvm.mysqli.socket = /var/run/mysqld/mysqld.sock\n')
with open('/etc/hhvm/server.ini', 'a') as hhvm_file:
hhvm_file.write('hhvm.server.ip = 127.0.0.1\n')
if os.path.isfile('/etc/nginx/conf.d/fastcgi.conf'):
if (not EEFileUtils.grep(self, '/etc/nginx/conf.d/fastcgi.conf', 'fastcgi_keep_conn')):
with open('/etc/nginx/conf.d/fastcgi.conf', 'a') as hhvm_file:
hhvm_file.write('fastcgi_keep_conn on;\n')
if os.path.isfile('/etc/nginx/conf.d/upstream.conf'):
if (not EEFileUtils.grep(self, '/etc/nginx/conf.d/upstream.conf', 'hhvm')):
with open('/etc/nginx/conf.d/upstream.conf', 'a') as hhvm_file:
hhvm_file.write('upstream hhvm {\nserver 127.0.0.1:8000;\nserver 127.0.0.1:9000 backup;\n}\n')
EEGit.add(self, ['/etc/hhvm'], msg='Adding HHVM into Git')
EEService.restart_service(self, 'hhvm')
if (os.path.isfile('/etc/nginx/nginx.conf') and (not os.path.isfile('/etc/nginx/common/php-hhvm.conf'))):
data = dict()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/php-hhvm.conf')
ee_nginx = open('/etc/nginx/common/php-hhvm.conf', encoding='utf-8', mode='w')
self.app.render(data, 'php-hhvm.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/w3tc-hhvm.conf')
ee_nginx = open('/etc/nginx/common/w3tc-hhvm.conf', encoding='utf-8', mode='w')
self.app.render(data, 'w3tc-hhvm.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpfc-hhvm.conf')
ee_nginx = open('/etc/nginx/common/wpfc-hhvm.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpfc-hhvm.mustache', out=ee_nginx)
ee_nginx.close()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/wpsc-hhvm.conf')
ee_nginx = open('/etc/nginx/common/wpsc-hhvm.conf', encoding='utf-8', mode='w')
self.app.render(data, 'wpsc-hhvm.mustache', out=ee_nginx)
ee_nginx.close()
if (not EEService.reload_service(self, 'nginx')):
Log.error(self, 'Failed to reload Nginx, please check output of `nginx -t`')
if set(EEVariables.ee_redis).issubset(set(apt_packages)):
if (os.path.isfile('/etc/nginx/nginx.conf') and (not os.path.isfile('/etc/nginx/common/redis.conf'))):
data = dict()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/redis.conf')
ee_nginx = open('/etc/nginx/common/redis.conf', encoding='utf-8', mode='w')
self.app.render(data, 'redis.mustache', out=ee_nginx)
ee_nginx.close()
if (os.path.isfile('/etc/nginx/nginx.conf') and (not os.path.isfile('/etc/nginx/common/redis-hhvm.conf'))):
data = dict()
Log.debug(self, 'Writting the nginx configuration to file /etc/nginx/common/redis-hhvm.conf')
ee_nginx = open('/etc/nginx/common/redis-hhvm.conf', encoding='utf-8', mode='w')
self.app.render(data, 'redis-hhvm.mustache', out=ee_nginx)
ee_nginx.close()
if os.path.isfile('/etc/nginx/conf.d/upstream.conf'):
if (not EEFileUtils.grep(self, '/etc/nginx/conf.d/upstream.conf', 'redis')):
with open('/etc/nginx/conf.d/upstream.conf', 'a') as redis_file:
redis_file.write('upstream redis {\n server 127.0.0.1:6379;\n keepalive 10;\n}\n')
if (os.path.isfile('/etc/nginx/nginx.conf') and (not os.path.isfile('/etc/nginx/conf.d/redis.conf'))):
with open('/etc/nginx/conf.d/redis.conf', 'a') as redis_file:
redis_file.write('# Log format Settings\nlog_format rt_cache_redis \'$remote_addr $upstream_response_time $srcache_fetch_status [$time_local] \'\n\'$http_host "$request" $status $body_bytes_sent \'\n\'"$http_referer" "$http_user_agent"\';\n')
if (((EEVariables.ee_platform_distro == 'debian') or (EEVariables.ee_platform_codename == 'precise')) and set(EEVariables.ee_php).issubset(set(apt_packages))):
if (not os.path.exists('/var/log/php5/')):
Log.debug(self, 'Creating directory /var/log/php5/')
os.makedirs('/var/log/php5/')
if ((EEVariables.ee_platform_distro == 'debian') and (EEVariables.ee_platform_codename == 'wheezy')):
EEShellExec.cmd_exec(self, 'pecl install xdebug')
with open('/etc/php5/mods-available/xdebug.ini', encoding='utf-8', mode='a') as myfile:
myfile.write('zend_extension=/usr/lib/php5/20131226/xdebug.so\n')
EEFileUtils.create_symlink(self, ['/etc/php5/mods-available/xdebug.ini', '/etc/php5/fpm/conf.d/20-xedbug.ini'])
config = configparser.ConfigParser()
Log.debug(self, 'configuring php file /etc/php5/fpm/php.ini')
config.read('/etc/php5/fpm/php.ini')
config['PHP']['expose_php'] = 'Off'
config['PHP']['post_max_size'] = '100M'
config['PHP']['upload_max_filesize'] = '100M'
config['PHP']['max_execution_time'] = '300'
config['PHP']['date.timezone'] = EEVariables.ee_timezone
with open('/etc/php5/fpm/php.ini', encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'Writting php configuration into /etc/php5/fpm/php.ini')
config.write(configfile)
'\n #Code depreciated. Mustache version applied\n # Parse /etc/php5/fpm/php-fpm.conf\n config = configparser.ConfigParser()\n Log.debug(self, "configuring php file"\n "/etc/php5/fpm/php-fpm.conf")\n config.read_file(codecs.open("/etc/php5/fpm/php-fpm.conf",\n "r", "utf8"))\n config[\'global\'][\'error_log\'] = \'/var/log/php5/fpm.log\'\n config.remove_option(\'global\', \'include\')\n config[\'global\'][\'log_level\'] = \'notice\'\n config[\'global\'][\'include\'] = \'/etc/php5/fpm/pool.d/*.conf\'\n with codecs.open(\'/etc/php5/fpm/php-fpm.conf\',\n encoding=\'utf-8\', mode=\'w\') as configfile:\n Log.debug(self, "writting php5 configuration into "\n "/etc/php5/fpm/php-fpm.conf")\n config.write(configfile)\n '
data = dict(pid='/run/php5-fpm.pid', error_log='/var/log/php5/fpm.log', include='/etc/php5/fpm/pool.d/*.conf')
Log.debug(self, 'writting php configuration into /etc/php5/fpm/php-fpm.conf')
ee_php_fpm = open('/etc/php5/fpm/php-fpm.conf', encoding='utf-8', mode='w')
self.app.render(data, 'php-fpm.mustache', out=ee_php_fpm)
ee_php_fpm.close()
config = configparser.ConfigParser()
config.read_file(codecs.open('/etc/php5/fpm/pool.d/www.conf', 'r', 'utf8'))
config['www']['ping.path'] = '/ping'
config['www']['pm.status_path'] = '/status'
config['www']['pm.max_requests'] = '500'
config['www']['pm.max_children'] = '100'
config['www']['pm.start_servers'] = '20'
config['www']['pm.min_spare_servers'] = '10'
config['www']['pm.max_spare_servers'] = '30'
config['www']['request_terminate_timeout'] = '300'
config['www']['pm'] = 'ondemand'
config['www']['listen'] = '127.0.0.1:9000'
with codecs.open('/etc/php5/fpm/pool.d/www.conf', encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'writting PHP5 configuration into /etc/php5/fpm/pool.d/www.conf')
config.write(configfile)
EEFileUtils.copyfile(self, '/etc/php5/fpm/pool.d/www.conf', '/etc/php5/fpm/pool.d/debug.conf')
EEFileUtils.searchreplace(self, '/etc/php5/fpm/pool.d/debug.conf', '[www]', '[debug]')
config = configparser.ConfigParser()
config.read('/etc/php5/fpm/pool.d/debug.conf')
config['debug']['listen'] = '127.0.0.1:9001'
config['debug']['rlimit_core'] = 'unlimited'
config['debug']['slowlog'] = '/var/log/php5/slow.log'
config['debug']['request_slowlog_timeout'] = '10s'
with open('/etc/php5/fpm/pool.d/debug.conf', encoding='utf-8', mode='w') as confifile:
Log.debug(self, 'writting PHP5 configuration into /etc/php5/fpm/pool.d/debug.conf')
config.write(confifile)
with open('/etc/php5/fpm/pool.d/debug.conf', encoding='utf-8', mode='a') as myfile:
myfile.write('php_admin_value[xdebug.profiler_output_dir] = /tmp/ \nphp_admin_value[xdebug.profiler_output_name] = cachegrind.out.%p-%H-%R \nphp_admin_flag[xdebug.profiler_enable_trigger] = on \nphp_admin_flag[xdebug.profiler_enable] = off\n')
EEFileUtils.searchreplace(self, '/etc/php5/mods-available/xdebug.ini', 'zend_extension', ';zend_extension')
if (not os.path.exists('{0}22222/htdocs/fpm/status/'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory {0}22222/htdocs/fpm/status/ '.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/fpm/status/'.format(EEVariables.ee_webroot))
open('{0}22222/htdocs/fpm/status/debug'.format(EEVariables.ee_webroot), encoding='utf-8', mode='a').close()
open('{0}22222/htdocs/fpm/status/php'.format(EEVariables.ee_webroot), encoding='utf-8', mode='a').close()
if (not os.path.exists('{0}22222/htdocs/php/'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory {0}22222/htdocs/php/ '.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/php'.format(EEVariables.ee_webroot))
with open('{0}22222/htdocs/php/info.php'.format(EEVariables.ee_webroot), encoding='utf-8', mode='w') as myfile:
myfile.write('<?php\nphpinfo();\n?>')
EEFileUtils.chown(self, '{0}22222'.format(EEVariables.ee_webroot), EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True)
EEGit.add(self, ['/etc/php5'], msg='Adding PHP into Git')
EEService.restart_service(self, 'php5-fpm')
if (((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) and set(EEVariables.ee_php5_6).issubset(set(apt_packages))):
if (not os.path.exists('/var/log/php/5.6/')):
Log.debug(self, 'Creating directory /var/log/php/5.6/')
os.makedirs('/var/log/php/5.6/')
config = configparser.ConfigParser()
Log.debug(self, 'configuring php file /etc/php/5.6/fpm/php.ini')
config.read('/etc/php/5.6/fpm/php.ini')
config['PHP']['expose_php'] = 'Off'
config['PHP']['post_max_size'] = '100M'
config['PHP']['upload_max_filesize'] = '100M'
config['PHP']['max_execution_time'] = '300'
config['PHP']['date.timezone'] = EEVariables.ee_timezone
with open('/etc/php/5.6/fpm/php.ini', encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'Writting php configuration into /etc/php/5.6/fpm/php.ini')
config.write(configfile)
'\n #Depreciated code. Mustache version Applied.\n\n config = configparser.ConfigParser()\n Log.debug(self, "configuring php file "\n "/etc/php/5.6/fpm/php-fpm.conf")\n config.read_file(codecs.open("/etc/php/5.6/fpm/php-fpm.conf",\n "r", "utf8"))\n config[\'global\'][\'error_log\'] = \'/var/log/php/5.6/fpm.log\'\n config.remove_option(\'global\', \'include\')\n config[\'global\'][\'log_level\'] = \'notice\'\n config[\'global\'][\'include\'] = \'/etc/php/5.6/fpm/pool.d/*.conf\'\n with codecs.open(\'/etc/php/5.6/fpm/php-fpm.conf\',\n encoding=\'utf-8\', mode=\'w\') as configfile:\n Log.debug(self, "writting php5 configuration into "\n "/etc/php/5.6/fpm/php-fpm.conf")\n config.write(configfile)\n '
data = dict(pid='/run/php/php5.6-fpm.pid', error_log='/var/log/php/5.6/fpm.log', include='/etc/php/5.6/fpm/pool.d/*.conf')
Log.debug(self, 'writting php5 configuration into /etc/php/5.6/fpm/php-fpm.conf')
ee_php_fpm = open('/etc/php/5.6/fpm/php-fpm.conf', encoding='utf-8', mode='w')
self.app.render(data, 'php-fpm.mustache', out=ee_php_fpm)
ee_php_fpm.close()
config = configparser.ConfigParser()
config.read_file(codecs.open('/etc/php/5.6/fpm/pool.d/www.conf', 'r', 'utf8'))
config['www']['ping.path'] = '/ping'
config['www']['pm.status_path'] = '/status'
config['www']['pm.max_requests'] = '500'
config['www']['pm.max_children'] = '100'
config['www']['pm.start_servers'] = '20'
config['www']['pm.min_spare_servers'] = '10'
config['www']['pm.max_spare_servers'] = '30'
config['www']['request_terminate_timeout'] = '300'
config['www']['pm'] = 'ondemand'
config['www']['listen'] = '127.0.0.1:9000'
with codecs.open('/etc/php/5.6/fpm/pool.d/www.conf', encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'writting PHP5 configuration into /etc/php/5.6/fpm/pool.d/www.conf')
config.write(configfile)
EEFileUtils.copyfile(self, '/etc/php/5.6/fpm/pool.d/www.conf', '/etc/php/5.6/fpm/pool.d/debug.conf')
EEFileUtils.searchreplace(self, '/etc/php/5.6/fpm/pool.d/debug.conf', '[www]', '[debug]')
config = configparser.ConfigParser()
config.read('/etc/php/5.6/fpm/pool.d/debug.conf')
config['debug']['listen'] = '127.0.0.1:9001'
config['debug']['rlimit_core'] = 'unlimited'
config['debug']['slowlog'] = '/var/log/php/5.6/slow.log'
config['debug']['request_slowlog_timeout'] = '10s'
with open('/etc/php/5.6/fpm/pool.d/debug.conf', encoding='utf-8', mode='w') as confifile:
Log.debug(self, 'writting PHP5 configuration into /etc/php/5.6/fpm/pool.d/debug.conf')
config.write(confifile)
with open('/etc/php/5.6/fpm/pool.d/debug.conf', encoding='utf-8', mode='a') as myfile:
myfile.write('php_admin_value[xdebug.profiler_output_dir] = /tmp/ \nphp_admin_value[xdebug.profiler_output_name] = cachegrind.out.%p-%H-%R \nphp_admin_flag[xdebug.profiler_enable_trigger] = on \nphp_admin_flag[xdebug.profiler_enable] = off\n')
if (not EEShellExec.cmd_exec(self, "grep -q ';zend_extension' /etc/php/5.6/mods-available/xdebug.ini")):
EEFileUtils.searchreplace(self, '/etc/php/5.6/mods-available/xdebug.ini', 'zend_extension', ';zend_extension')
if (not os.path.exists('{0}22222/htdocs/fpm/status/'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory {0}22222/htdocs/fpm/status/ '.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/fpm/status/'.format(EEVariables.ee_webroot))
open('{0}22222/htdocs/fpm/status/debug'.format(EEVariables.ee_webroot), encoding='utf-8', mode='a').close()
open('{0}22222/htdocs/fpm/status/php'.format(EEVariables.ee_webroot), encoding='utf-8', mode='a').close()
if (not os.path.exists('{0}22222/htdocs/php/'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory {0}22222/htdocs/php/ '.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/php'.format(EEVariables.ee_webroot))
with open('{0}22222/htdocs/php/info.php'.format(EEVariables.ee_webroot), encoding='utf-8', mode='w') as myfile:
myfile.write('<?php\nphpinfo();\n?>')
EEFileUtils.chown(self, '{0}22222'.format(EEVariables.ee_webroot), EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True)
EEGit.add(self, ['/etc/php'], msg='Adding PHP into Git')
EEService.restart_service(self, 'php5.6-fpm')
if ((EEVariables.ee_platform_codename == 'jessie') and set(EEVariables.ee_php7_0).issubset(set(apt_packages))):
if (not os.path.exists('/var/log/php/7.0/')):
Log.debug(self, 'Creating directory /var/log/php/7.0/')
os.makedirs('/var/log/php/7.0/')
config = configparser.ConfigParser()
Log.debug(self, 'configuring php file /etc/php/7.0/fpm/php.ini')
config.read('/etc/php/7.0/fpm/php.ini')
config['PHP']['expose_php'] = 'Off'
config['PHP']['post_max_size'] = '100M'
config['PHP']['upload_max_filesize'] = '100M'
config['PHP']['max_execution_time'] = '300'
config['PHP']['date.timezone'] = EEVariables.ee_timezone
with open('/etc/php/7.0/fpm/php.ini', encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'Writting php configuration into /etc/php/7.0/fpm/php.ini')
config.write(configfile)
data = dict(pid='/run/php/php7.0-fpm.pid', error_log='/var/log/php7.0-fpm.log', include='/etc/php/7.0/fpm/pool.d/*.conf')
Log.debug(self, 'writting php 7.0 configuration into /etc/php/7.0/fpm/php-fpm.conf')
ee_php_fpm = open('/etc/php/7.0/fpm/php-fpm.conf', encoding='utf-8', mode='w')
self.app.render(data, 'php-fpm.mustache', out=ee_php_fpm)
ee_php_fpm.close()
config = configparser.ConfigParser()
config.read_file(codecs.open('/etc/php/7.0/fpm/pool.d/www.conf', 'r', 'utf8'))
config['www']['ping.path'] = '/ping'
config['www']['pm.status_path'] = '/status'
config['www']['pm.max_requests'] = '500'
config['www']['pm.max_children'] = '100'
config['www']['pm.start_servers'] = '20'
config['www']['pm.min_spare_servers'] = '10'
config['www']['pm.max_spare_servers'] = '30'
config['www']['request_terminate_timeout'] = '300'
config['www']['pm'] = 'ondemand'
config['www']['listen'] = '127.0.0.1:9070'
with codecs.open('/etc/php/7.0/fpm/pool.d/www.conf', encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'writting PHP5 configuration into /etc/php/7.0/fpm/pool.d/www.conf')
config.write(configfile)
EEFileUtils.copyfile(self, '/etc/php/7.0/fpm/pool.d/www.conf', '/etc/php/7.0/fpm/pool.d/debug.conf')
EEFileUtils.searchreplace(self, '/etc/php/7.0/fpm/pool.d/debug.conf', '[www]', '[debug]')
config = configparser.ConfigParser()
config.read('/etc/php/7.0/fpm/pool.d/debug.conf')
config['debug']['listen'] = '127.0.0.1:9170'
config['debug']['rlimit_core'] = 'unlimited'
config['debug']['slowlog'] = '/var/log/php/7.0/slow.log'
config['debug']['request_slowlog_timeout'] = '10s'
with open('/etc/php/7.0/fpm/pool.d/debug.conf', encoding='utf-8', mode='w') as confifile:
Log.debug(self, 'writting PHP5 configuration into /etc/php/7.0/fpm/pool.d/debug.conf')
config.write(confifile)
with open('/etc/php/7.0/fpm/pool.d/debug.conf', encoding='utf-8', mode='a') as myfile:
myfile.write('php_admin_value[xdebug.profiler_output_dir] = /tmp/ \nphp_admin_value[xdebug.profiler_output_name] = cachegrind.out.%p-%H-%R \nphp_admin_flag[xdebug.profiler_enable_trigger] = on \nphp_admin_flag[xdebug.profiler_enable] = off\n')
if (not EEShellExec.cmd_exec(self, "grep -q ';zend_extension' /etc/php/7.0/mods-available/xdebug.ini")):
EEFileUtils.searchreplace(self, '/etc/php/7.0/mods-available/xdebug.ini', 'zend_extension', ';zend_extension')
if (not os.path.exists('{0}22222/htdocs/fpm/status/'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory {0}22222/htdocs/fpm/status/ '.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/fpm/status/'.format(EEVariables.ee_webroot))
open('{0}22222/htdocs/fpm/status/debug'.format(EEVariables.ee_webroot), encoding='utf-8', mode='a').close()
open('{0}22222/htdocs/fpm/status/php'.format(EEVariables.ee_webroot), encoding='utf-8', mode='a').close()
if (not os.path.exists('{0}22222/htdocs/php/'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory {0}22222/htdocs/php/ '.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/php'.format(EEVariables.ee_webroot))
with open('{0}22222/htdocs/php/info.php'.format(EEVariables.ee_webroot), encoding='utf-8', mode='w') as myfile:
myfile.write('<?php\nphpinfo();\n?>')
EEFileUtils.chown(self, '{0}22222'.format(EEVariables.ee_webroot), EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True)
EEGit.add(self, ['/etc/php'], msg='Adding PHP into Git')
EEService.restart_service(self, 'php7.0-fpm')
if (((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) and set(EEVariables.ee_php7_0).issubset(set(apt_packages))):
if (not os.path.exists('/var/log/php/7.0/')):
Log.debug(self, 'Creating directory /var/log/php/7.0/')
os.makedirs('/var/log/php/7.0/')
config = configparser.ConfigParser()
Log.debug(self, 'configuring php file /etc/php/7.0/fpm/php.ini')
config.read('/etc/php/7.0/fpm/php.ini')
config['PHP']['expose_php'] = 'Off'
config['PHP']['post_max_size'] = '100M'
config['PHP']['upload_max_filesize'] = '100M'
config['PHP']['max_execution_time'] = '300'
config['PHP']['date.timezone'] = EEVariables.ee_timezone
with open('/etc/php/7.0/fpm/php.ini', encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'Writting php configuration into /etc/php/7.0/fpm/php.ini')
config.write(configfile)
data = dict(pid='/run/php/php7.0-fpm.pid', error_log='/var/log/php/7.0/fpm.log', include='/etc/php/7.0/fpm/pool.d/*.conf')
Log.debug(self, 'writting php 7.0 configuration into /etc/php/7.0/fpm/php-fpm.conf')
ee_php_fpm = open('/etc/php/7.0/fpm/php-fpm.conf', encoding='utf-8', mode='w')
self.app.render(data, 'php-fpm.mustache', out=ee_php_fpm)
ee_php_fpm.close()
config = configparser.ConfigParser()
config.read_file(codecs.open('/etc/php/7.0/fpm/pool.d/www.conf', 'r', 'utf8'))
config['www']['ping.path'] = '/ping'
config['www']['pm.status_path'] = '/status'
config['www']['pm.max_requests'] = '500'
config['www']['pm.max_children'] = '100'
config['www']['pm.start_servers'] = '20'
config['www']['pm.min_spare_servers'] = '10'
config['www']['pm.max_spare_servers'] = '30'
config['www']['request_terminate_timeout'] = '300'
config['www']['pm'] = 'ondemand'
config['www']['listen'] = '127.0.0.1:9070'
with codecs.open('/etc/php/7.0/fpm/pool.d/www.conf', encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'writting PHP5 configuration into /etc/php/7.0/fpm/pool.d/www.conf')
config.write(configfile)
EEFileUtils.copyfile(self, '/etc/php/7.0/fpm/pool.d/www.conf', '/etc/php/7.0/fpm/pool.d/debug.conf')
EEFileUtils.searchreplace(self, '/etc/php/7.0/fpm/pool.d/debug.conf', '[www]', '[debug]')
config = configparser.ConfigParser()
config.read('/etc/php/7.0/fpm/pool.d/debug.conf')
config['debug']['listen'] = '127.0.0.1:9170'
config['debug']['rlimit_core'] = 'unlimited'
config['debug']['slowlog'] = '/var/log/php/7.0/slow.log'
config['debug']['request_slowlog_timeout'] = '10s'
with open('/etc/php/7.0/fpm/pool.d/debug.conf', encoding='utf-8', mode='w') as confifile:
Log.debug(self, 'writting PHP5 configuration into /etc/php/7.0/fpm/pool.d/debug.conf')
config.write(confifile)
with open('/etc/php/7.0/fpm/pool.d/debug.conf', encoding='utf-8', mode='a') as myfile:
myfile.write('php_admin_value[xdebug.profiler_output_dir] = /tmp/ \nphp_admin_value[xdebug.profiler_output_name] = cachegrind.out.%p-%H-%R \nphp_admin_flag[xdebug.profiler_enable_trigger] = on \nphp_admin_flag[xdebug.profiler_enable] = off\n')
if (not EEShellExec.cmd_exec(self, "grep -q ';zend_extension' /etc/php/7.0/mods-available/xdebug.ini")):
EEFileUtils.searchreplace(self, '/etc/php/7.0/mods-available/xdebug.ini', 'zend_extension', ';zend_extension')
if (not os.path.exists('{0}22222/htdocs/fpm/status/'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory {0}22222/htdocs/fpm/status/ '.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/fpm/status/'.format(EEVariables.ee_webroot))
open('{0}22222/htdocs/fpm/status/debug'.format(EEVariables.ee_webroot), encoding='utf-8', mode='a').close()
open('{0}22222/htdocs/fpm/status/php'.format(EEVariables.ee_webroot), encoding='utf-8', mode='a').close()
if (not os.path.exists('{0}22222/htdocs/php/'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory {0}22222/htdocs/php/ '.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/php'.format(EEVariables.ee_webroot))
with open('{0}22222/htdocs/php/info.php'.format(EEVariables.ee_webroot), encoding='utf-8', mode='w') as myfile:
myfile.write('<?php\nphpinfo();\n?>')
EEFileUtils.chown(self, '{0}22222'.format(EEVariables.ee_webroot), EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True)
EEGit.add(self, ['/etc/php'], msg='Adding PHP into Git')
EEService.restart_service(self, 'php7.0-fpm')
if set(EEVariables.ee_mysql).issubset(set(apt_packages)):
if (not os.path.isfile('/etc/mysql/my.cnf')):
config = '[mysqld]\nwait_timeout = 30\ninteractive_timeout=60\nperformance_schema = 0\nquery_cache_type = 1'
config_file = open('/etc/mysql/my.cnf', encoding='utf-8', mode='w')
config_file.write(config)
config_file.close()
else:
try:
EEShellExec.cmd_exec(self, 'sed -i "/#max_connections/a wait_timeout = 30 \\ninteractive_timeout = 60 \\nperformance_schema = 0\\nquery_cache_type = 1 " /etc/mysql/my.cnf')
except CommandExecutionError as e:
Log.error(self, 'Unable to update MySQL file')
EEFileUtils.chmod(self, '/usr/bin/mysqltuner', 509)
EEGit.add(self, ['/etc/mysql'], msg='Adding MySQL into Git')
EEService.reload_service(self, 'mysql')
if set(EEVariables.ee_mail).issubset(set(apt_packages)):
Log.debug(self, 'Adding user')
try:
EEShellExec.cmd_exec(self, "adduser --uid 5000 --home /var/vmail --disabled-password --gecos '' vmail")
except CommandExecutionError as e:
Log.error(self, 'Unable to add vmail user for mail server')
try:
EEShellExec.cmd_exec(self, 'openssl req -new -x509 -days 3650 -nodes -subj /commonName={hostname}/emailAddress={email} -out /etc/ssl/certs/dovecot.pem -keyout /etc/ssl/private/dovecot.pem'.format(hostname=EEVariables.ee_fqdn, email=EEVariables.ee_email))
except CommandExecutionError as e:
Log.error(self, 'Unable to generate PEM key for dovecot')
Log.debug(self, 'Setting Privileges to /etc/ssl/private/dovecot.pem file ')
EEFileUtils.chmod(self, '/etc/ssl/private/dovecot.pem', 384)
data = dict()
Log.debug(self, 'Writting configuration into file/etc/dovecot/conf.d/auth-sql.conf.ext ')
ee_dovecot = open('/etc/dovecot/conf.d/auth-sql.conf.ext', encoding='utf-8', mode='w')
self.app.render(data, 'auth-sql-conf.mustache', out=ee_dovecot)
ee_dovecot.close()
data = dict(email=EEVariables.ee_email)
Log.debug(self, 'Writting configuration into file/etc/dovecot/conf.d/99-ee.conf ')
ee_dovecot = open('/etc/dovecot/conf.d/99-ee.conf', encoding='utf-8', mode='w')
self.app.render(data, 'dovecot.mustache', out=ee_dovecot)
ee_dovecot.close()
try:
EEShellExec.cmd_exec(self, 'sed -i "s/\\!include auth-system.conf.ext/#\\!include auth-system.conf.ext/" /etc/dovecot/conf.d/10-auth.conf')
EEShellExec.cmd_exec(self, 'sed -i "s\'/etc/dovecot/dovecot.pem\'/etc/ssl/certs/dovecot.pem\'" /etc/dovecot/conf.d/10-ssl.conf')
EEShellExec.cmd_exec(self, 'sed -i "s\'/etc/dovecot/private/dovecot.pem\'/etc/ssl/private/dovecot.pem\'" /etc/dovecot/conf.d/10-ssl.conf')
EEShellExec.cmd_exec(self, "sed -i 's/#submission/submission/' /etc/postfix/master.cf")
EEShellExec.cmd_exec(self, "sed -i 's/#smtps/smtps/' /etc/postfix/master.cf")
EEShellExec.cmd_exec(self, 'postconf -e "smtpd_sasl_type = dovecot"')
EEShellExec.cmd_exec(self, 'postconf -e "smtpd_sasl_path = private/auth"')
EEShellExec.cmd_exec(self, 'postconf -e "smtpd_sasl_auth_enable = yes"')
EEShellExec.cmd_exec(self, 'postconf -e " smtpd_relay_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination"')
EEShellExec.cmd_exec(self, 'postconf -e "smtpd_tls_mandatory_protocols = !SSLv2,!SSLv3"')
EEShellExec.cmd_exec(self, 'postconf -e "smtp_tls_mandatory_protocols = !SSLv2,!SSLv3"')
EEShellExec.cmd_exec(self, 'postconf -e "smtpd_tls_protocols = !SSLv2,!SSLv3"')
EEShellExec.cmd_exec(self, 'postconf -e "smtp_tls_protocols = !SSLv2,!SSLv3"')
EEShellExec.cmd_exec(self, 'postconf -e "mydestination = localhost"')
EEShellExec.cmd_exec(self, 'postconf -e "virtual_transport = lmtp:unix:private/dovecot-lmtp"')
EEShellExec.cmd_exec(self, 'postconf -e "virtual_uid_maps = static:5000"')
EEShellExec.cmd_exec(self, 'postconf -e "virtual_gid_maps = static:5000"')
EEShellExec.cmd_exec(self, 'postconf -e " virtual_mailbox_domains = mysql:/etc/postfix/mysql/virtual_domains_maps.cf"')
EEShellExec.cmd_exec(self, 'postconf -e "virtual_mailbox_maps = mysql:/etc/postfix/mysql/virtual_mailbox_maps.cf"')
EEShellExec.cmd_exec(self, 'postconf -e "virtual_alias_maps = mysql:/etc/postfix/mysql/virtual_alias_maps.cf"')
EEShellExec.cmd_exec(self, 'openssl req -new -x509 -days 3650 -nodes -subj /commonName={hostname}/emailAddress={email} -out /etc/ssl/certs/postfix.pem -keyout /etc/ssl/private/postfix.pem'.format(hostname=EEVariables.ee_fqdn, email=EEVariables.ee_email))
EEShellExec.cmd_exec(self, 'chmod 0600 /etc/ssl/private/postfix.pem')
EEShellExec.cmd_exec(self, 'postconf -e "smtpd_tls_cert_file = /etc/ssl/certs/postfix.pem"')
EEShellExec.cmd_exec(self, 'postconf -e "smtpd_tls_key_file = /etc/ssl/private/postfix.pem"')
except CommandExecutionError as e:
Log.Error(self, 'Failed to update Dovecot configuration')
if (not os.path.exists('/var/lib/dovecot/sieve/')):
Log.debug(self, 'Creating directory /var/lib/dovecot/sieve/ ')
os.makedirs('/var/lib/dovecot/sieve/')
data = dict()
Log.debug(self, 'Writting configuration of EasyEngine into file /var/lib/dovecot/sieve/default.sieve')
ee_sieve = open('/var/lib/dovecot/sieve/default.sieve', encoding='utf-8', mode='w')
self.app.render(data, 'default-sieve.mustache', out=ee_sieve)
ee_sieve.close()
Log.debug(self, 'Setting Privileges to dovecot ')
EEFileUtils.chown(self, '/var/lib/dovecot', 'vmail', 'vmail', recursive=True)
try:
EEShellExec.cmd_exec(self, 'sievec /var/lib/dovecot//sieve/default.sieve')
except CommandExecutionError as e:
raise SiteError('Failed to compile default.sieve')
EEGit.add(self, ['/etc/postfix', '/etc/dovecot'], msg='Installed mail server')
EEService.restart_service(self, 'dovecot')
EEService.reload_service(self, 'postfix')
if set(EEVariables.ee_mailscanner).issubset(set(apt_packages)):
data = dict()
Log.debug(self, 'Configuring file /etc/amavis/conf.d/15-content_filter_mode')
ee_amavis = open('/etc/amavis/conf.d/15-content_filter_mode', encoding='utf-8', mode='w')
self.app.render(data, '15-content_filter_mode.mustache', out=ee_amavis)
ee_amavis.close()
if os.path.isfile('/etc/postfix/mysql/virtual_alias_maps.cf'):
vm_host = os.popen("grep hosts /etc/postfix/mysql/virtual_alias_maps.cf | awk '{ print $3 }' | tr -d '\\n'").read()
vm_pass = os.popen("grep password /etc/postfix/mysql/virtual_alias_maps.cf | awk '{ print $3 }' | tr -d '\\n'").read()
data = dict(host=vm_host, password=vm_pass)
vm_config = open('/etc/amavis/conf.d/50-user', encoding='utf-8', mode='w')
self.app.render(data, '50-user.mustache', out=vm_config)
vm_config.close()
try:
EEShellExec.cmd_exec(self, 'postconf -e "content_filter = smtp-amavis:[127.0.0.1]:10024"')
EEShellExec.cmd_exec(self, 'sed -i "s/1 pickup/1 pickup\\n -o content_filter=\\n -o receive_override_options=no_header_body_checks/" /etc/postfix/master.cf')
except CommandExecutionError as e:
raise SiteError('Failed to update Amavis-Postfix config')
amavis_master = 'smtp-amavis unix - - n - 2 smtp\n -o smtp_data_done_timeout=1200\n -o smtp_send_xforward_command=yes\n -o disable_dns_lookups=yes\n -o max_use=20\n127.0.0.1:10025 inet n - n - - smtpd\n -o content_filter=\n -o smtpd_delay_reject=no\n -o smtpd_client_restrictions=permit_mynetworks,reject\n -o smtpd_helo_restrictions=\n -o smtpd_sender_restrictions=\n -o smtpd_recipient_restrictions=permit_mynetworks,reject\n -o smtpd_data_restrictions=reject_unauth_pipelining\n -o smtpd_end_of_data_restrictions=\n -o smtpd_restriction_classes=\n -o mynetworks=127.0.0.0/8\n -o smtpd_error_sleep_time=0\n -o smtpd_soft_error_limit=1001\n -o smtpd_hard_error_limit=1000\n -o smtpd_client_connection_count_limit=0\n -o smtpd_client_connection_rate_limit=0\n -o local_header_rewrite_clients='
with open('/etc/postfix/master.cf', encoding='utf-8', mode='a') as am_config:
am_config.write(amavis_master)
try:
Log.debug(self, 'Adding new user clamav amavis')
EEShellExec.cmd_exec(self, 'adduser clamav amavis')
Log.debug(self, 'Adding new user amavis clamav')
EEShellExec.cmd_exec(self, 'adduser amavis clamav')
Log.debug(self, 'Setting Privileges to /var/lib/amavis/tmp')
EEFileUtils.chmod(self, '/var/lib/amavis/tmp', 493)
Log.debug(self, 'Updating database')
EEShellExec.cmd_exec(self, 'freshclam')
except CommandExecutionError as e:
raise SiteError(' Unable to update ClamAV-Amavis config')
EEGit.add(self, ['/etc/amavis'], msg='Adding Amavis into Git')
EEService.restart_service(self, 'dovecot')
EEService.reload_service(self, 'postfix')
EEService.restart_service(self, 'amavis')
if len(packages):
if any((('/usr/bin/wp' == x[1]) for x in packages)):
Log.debug(self, 'Setting Privileges to /usr/bin/wp file ')
EEFileUtils.chmod(self, '/usr/bin/wp', 509)
if any((('/tmp/pma.tar.gz' == x[1]) for x in packages)):
EEExtract.extract(self, '/tmp/pma.tar.gz', '/tmp/')
Log.debug(self, 'Extracting file /tmp/pma.tar.gz to location /tmp/')
if (not os.path.exists('{0}22222/htdocs/db'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating new directory {0}22222/htdocs/db'.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/db'.format(EEVariables.ee_webroot))
shutil.move('/tmp/phpmyadmin-STABLE/', '{0}22222/htdocs/db/pma/'.format(EEVariables.ee_webroot))
shutil.copyfile('{0}22222/htdocs/db/pma/config.sample.inc.php'.format(EEVariables.ee_webroot), '{0}22222/htdocs/db/pma/config.inc.php'.format(EEVariables.ee_webroot))
Log.debug(self, 'Setting Blowfish Secret Key FOR COOKIE AUTH to {0}22222/htdocs/db/pma/config.inc.php file '.format(EEVariables.ee_webroot))
blowfish_key = ''.join([random.choice((string.ascii_letters + string.digits)) for n in range(10)])
EEFileUtils.searchreplace(self, '{0}22222/htdocs/db/pma/config.inc.php'.format(EEVariables.ee_webroot), "$cfg['blowfish_secret'] = '';", "$cfg['blowfish_secret'] = '{0}';".format(blowfish_key))
Log.debug(self, 'Setting HOST Server For Mysql to {0}22222/htdocs/db/pma/config.inc.php file '.format(EEVariables.ee_webroot))
EEFileUtils.searchreplace(self, '{0}22222/htdocs/db/pma/config.inc.php'.format(EEVariables.ee_webroot), "$cfg['Servers'][$i]['host'] = 'localhost';", "$cfg['Servers'][$i]['host'] = '{0}';".format(EEVariables.ee_mysql_host))
Log.debug(self, 'Setting Privileges of webroot permission to {0}22222/htdocs/db/pma file '.format(EEVariables.ee_webroot))
EEFileUtils.chown(self, '{0}22222'.format(EEVariables.ee_webroot), EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True)
if any((('/tmp/memcache.tar.gz' == x[1]) for x in packages)):
Log.debug(self, 'Extracting memcache.tar.gz to location {0}22222/htdocs/cache/memcache '.format(EEVariables.ee_webroot))
EEExtract.extract(self, '/tmp/memcache.tar.gz', '{0}22222/htdocs/cache/memcache'.format(EEVariables.ee_webroot))
Log.debug(self, 'Setting Privileges to {0}22222/htdocs/cache/memcache file'.format(EEVariables.ee_webroot))
EEFileUtils.chown(self, '{0}22222'.format(EEVariables.ee_webroot), EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True)
if any((('/tmp/webgrind.tar.gz' == x[1]) for x in packages)):
Log.debug(self, 'Extracting file webgrind.tar.gz to location /tmp/ ')
EEExtract.extract(self, '/tmp/webgrind.tar.gz', '/tmp/')
if (not os.path.exists('{0}22222/htdocs/php'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directroy {0}22222/htdocs/php'.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/php'.format(EEVariables.ee_webroot))
shutil.move('/tmp/webgrind-master/', '{0}22222/htdocs/php/webgrind'.format(EEVariables.ee_webroot))
EEFileUtils.searchreplace(self, '{0}22222/htdocs/php/webgrind/config.php'.format(EEVariables.ee_webroot), '/usr/local/bin/dot', '/usr/bin/dot')
EEFileUtils.searchreplace(self, '{0}22222/htdocs/php/webgrind/config.php'.format(EEVariables.ee_webroot), 'Europe/Copenhagen', EEVariables.ee_timezone)
EEFileUtils.searchreplace(self, '{0}22222/htdocs/php/webgrind/config.php'.format(EEVariables.ee_webroot), '90', '100')
Log.debug(self, 'Setting Privileges of webroot permission to {0}22222/htdocs/php/webgrind/ file '.format(EEVariables.ee_webroot))
EEFileUtils.chown(self, '{0}22222'.format(EEVariables.ee_webroot), EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True)
if any((('/tmp/anemometer.tar.gz' == x[1]) for x in packages)):
Log.debug(self, 'Extracting file anemometer.tar.gz to location /tmp/ ')
EEExtract.extract(self, '/tmp/anemometer.tar.gz', '/tmp/')
if (not os.path.exists('{0}22222/htdocs/db/'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory')
os.makedirs('{0}22222/htdocs/db/'.format(EEVariables.ee_webroot))
shutil.move('/tmp/Anemometer-master', '{0}22222/htdocs/db/anemometer'.format(EEVariables.ee_webroot))
chars = ''.join(random.sample(string.ascii_letters, 8))
try:
EEShellExec.cmd_exec(self, 'mysql < {0}22222/htdocs/db/anemometer/install.sql'.format(EEVariables.ee_webroot))
except CommandExecutionError as e:
raise SiteError('Unable to import Anemometer database')
EEMysql.execute(self, "grant select on *.* to 'anemometer'@'{0}' IDENTIFIED BY '{1}'".format(self.app.config.get('mysql', 'grant-host'), chars))
Log.debug(self, 'grant all on slow-query-log.* to anemometer@root_user IDENTIFIED BY password ')
EEMysql.execute(self, "grant all on slow_query_log.* to'anemometer'@'{0}' IDENTIFIED BY '{1}'".format(self.app.config.get('mysql', 'grant-host'), chars), errormsg='cannot grant priviledges', log=False)
Log.debug(self, 'configration Anemometer')
data = dict(host=EEVariables.ee_mysql_host, port='3306', user='anemometer', password=chars)
ee_anemometer = open('{0}22222/htdocs/db/anemometer/conf/config.inc.php'.format(EEVariables.ee_webroot), encoding='utf-8', mode='w')
self.app.render(data, 'anemometer.mustache', out=ee_anemometer)
ee_anemometer.close()
if any((('/usr/bin/pt-query-advisor' == x[1]) for x in packages)):
EEFileUtils.chmod(self, '/usr/bin/pt-query-advisor', 509)
if any((('/tmp/vimbadmin.tar.gz' == x[1]) for x in packages)):
Log.debug(self, 'Extracting ViMbAdmin.tar.gz to location /tmp/')
EEExtract.extract(self, '/tmp/vimbadmin.tar.gz', '/tmp/')
if (not os.path.exists('{0}22222/htdocs/'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating directory {0}22222/htdocs/'.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/'.format(EEVariables.ee_webroot))
shutil.move('/tmp/ViMbAdmin-{0}/'.format(EEVariables.ee_vimbadmin), '{0}22222/htdocs/vimbadmin/'.format(EEVariables.ee_webroot))
Log.debug(self, 'Downloading composer https://getcomposer.org/installer | php ')
try:
EEShellExec.cmd_exec(self, 'cd {0}22222/htdocs/vimbadmin; curl -sS https://getcomposer.org/installer | php'.format(EEVariables.ee_webroot))
Log.debug(self, 'Installating of composer')
EEShellExec.cmd_exec(self, 'cd {0}22222/htdocs/vimbadmin && php composer.phar install --prefer-dist --no-dev && rm -f {1}22222/htdocs/vimbadmin/composer.phar'.format(EEVariables.ee_webroot, EEVariables.ee_webroot))
except CommandExecutionError as e:
raise SiteError('Failed to setup ViMbAdmin')
vm_passwd = ''.join(random.sample(string.ascii_letters, 8))
Log.debug(self, 'Creating vimbadmin database if not exist')
EEMysql.execute(self, 'create database if not exists vimbadmin')
Log.debug(self, " grant all privileges on `vimbadmin`.* to `vimbadmin`@`{0}` IDENTIFIED BY ' '".format(self.app.config.get('mysql', 'grant-host')))
EEMysql.execute(self, "grant all privileges on `vimbadmin`.* to `vimbadmin`@`{0}` IDENTIFIED BY '{1}'".format(self.app.config.get('mysql', 'grant-host'), vm_passwd), errormsg='Cannot grant user privileges', log=False)
vm_salt = ''.join(random.sample((string.ascii_letters + string.ascii_letters), 64))
data = dict(salt=vm_salt, host=EEVariables.ee_mysql_host, password=vm_passwd, php_user=EEVariables.ee_php_user)
Log.debug(self, 'Writting the ViMbAdmin configuration to file {0}22222/htdocs/vimbadmin/application/configs/application.ini'.format(EEVariables.ee_webroot))
ee_vmb = open('{0}22222/htdocs/vimbadmin/application/configs/application.ini'.format(EEVariables.ee_webroot), encoding='utf-8', mode='w')
self.app.render(data, 'vimbadmin.mustache', out=ee_vmb)
ee_vmb.close()
shutil.copyfile('{0}22222/htdocs/vimbadmin/public/.htaccess.dist'.format(EEVariables.ee_webroot), '{0}22222/htdocs/vimbadmin/public/.htaccess'.format(EEVariables.ee_webroot))
Log.debug(self, 'Executing command {0}22222/htdocs/vimbadmin/bin/doctrine2-cli.php orm:schema-tool:create'.format(EEVariables.ee_webroot))
try:
EEShellExec.cmd_exec(self, '{0}22222/htdocs/vimbadmin/bin/doctrine2-cli.php orm:schema-tool:create'.format(EEVariables.ee_webroot))
except CommandExecutionError as e:
raise SiteError('Unable to create ViMbAdmin schema')
EEFileUtils.chown(self, '{0}22222'.format(EEVariables.ee_webroot), EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True)
if (not os.path.exists('/etc/postfix/mysql/')):
Log.debug(self, 'Creating directory /etc/postfix/mysql/')
os.makedirs('/etc/postfix/mysql/')
if (EEVariables.ee_mysql_host is 'localhost'):
data = dict(password=vm_passwd, host='127.0.0.1')
else:
data = dict(password=vm_passwd, host=EEVariables.ee_mysql_host)
vm_config = open('/etc/postfix/mysql/virtual_alias_maps.cf', encoding='utf-8', mode='w')
self.app.render(data, 'virtual_alias_maps.mustache', out=vm_config)
vm_config.close()
Log.debug(self, 'Writting configuration to /etc/postfix/mysql/virtual_domains_maps.cf file')
vm_config = open('/etc/postfix/mysql/virtual_domains_maps.cf', encoding='utf-8', mode='w')
self.app.render(data, 'virtual_domains_maps.mustache', out=vm_config)
vm_config.close()
Log.debug(self, 'Writting configuration to /etc/postfix/mysql/virtual_mailbox_maps.cf file')
vm_config = open('/etc/postfix/mysql/virtual_mailbox_maps.cf', encoding='utf-8', mode='w')
self.app.render(data, 'virtual_mailbox_maps.mustache', out=vm_config)
vm_config.close()
Log.debug(self, 'Writting configration to /etc/dovecot/dovecot-sql.conf.ext file ')
vm_config = open('/etc/dovecot/dovecot-sql.conf.ext', encoding='utf-8', mode='w')
self.app.render(data, 'dovecot-sql-conf.mustache', out=vm_config)
vm_config.close()
if set(EEVariables.ee_mailscanner).issubset(set(apt_packages)):
vm_config = open('/etc/amavis/conf.d/50-user', encoding='utf-8', mode='w')
self.app.render(data, '50-user.mustache', out=vm_config)
vm_config.close()
EEService.restart_service(self, 'dovecot')
EEService.reload_service(self, 'nginx')
if ((EEVariables.ee_platform_distro == 'debian') or (EEVariables.ee_platform_codename == 'precise')):
EEService.reload_service(self, 'php5-fpm')
else:
EEService.reload_service(self, 'php5.6-fpm')
if EEAptGet.is_installed(self, 'php7.0-fpm'):
EEService.reload_service(self, 'php7.0-fpm')
self.msg = ((self.msg + ['Configure ViMbAdmin: DCTB https://{0}:22222/vimbadmin'.format(EEVariables.ee_fqdn)]) + ['Security Salt: {0}'.format(vm_salt)])
if any((('/tmp/roundcube.tar.gz' == x[1]) for x in packages)):
Log.debug(self, 'Extracting file /tmp/roundcube.tar.gz to location /tmp/ ')
EEExtract.extract(self, '/tmp/roundcube.tar.gz', '/tmp/')
if (not os.path.exists('{0}roundcubemail'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating new directory {0}roundcubemail/'.format(EEVariables.ee_webroot))
os.makedirs('{0}roundcubemail/'.format(EEVariables.ee_webroot))
shutil.move('/tmp/roundcubemail-{0}/'.format(EEVariables.ee_roundcube), '{0}roundcubemail/htdocs'.format(EEVariables.ee_webroot))
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
EEShellExec.cmd_exec(self, 'pear config-set php_dir /usr/share/php')
EEShellExec.cmd_exec(self, 'pear config-set doc_dir /lib/php/pear/docs')
EEShellExec.cmd_exec(self, 'pear config-set cfg_dir /lib/php/pear/cfg')
EEShellExec.cmd_exec(self, 'pear config-set data_dir /lib/php/pear/data')
EEShellExec.cmd_exec(self, 'pear config-set test_dir /lib/php/pear/tests')
EEShellExec.cmd_exec(self, 'pear config-set www_dir /lib/php/pear/www')
EEShellExec.cmd_exec(self, 'pear install Mail_Mime Net_SMTP Mail_mimeDecode Net_IDNA2-beta Auth_SASL Net_Sieve Crypt_GPG')
rc_passwd = ''.join(random.sample(string.ascii_letters, 8))
Log.debug(self, 'Creating Database roundcubemail')
EEMysql.execute(self, 'create database if not exists roundcubemail')
Log.debug(self, "grant all privileges on `roundcubemail`.* to `roundcube`@`{0}` IDENTIFIED BY ' '".format(self.app.config.get('mysql', 'grant-host')))
EEMysql.execute(self, "grant all privileges on `roundcubemail`.* to `roundcube`@`{0}` IDENTIFIED BY '{1}'".format(self.app.config.get('mysql', 'grant-host'), rc_passwd))
EEShellExec.cmd_exec(self, 'mysql roundcubemail < {0}roundcubemail/htdocs/SQL/mysql.initial.sql'.format(EEVariables.ee_webroot))
shutil.copyfile('{0}roundcubemail/htdocs/config/config.inc.php.sample'.format(EEVariables.ee_webroot), '{0}roundcubemail/htdocs/config/config.inc.php'.format(EEVariables.ee_webroot))
EEShellExec.cmd_exec(self, 'sed -i "s\'mysql://roundcube:pass@localhost/roundcubemail\'mysql://roundcube:{0}@{1}/roundcubemail\'" {2}roundcubemail/htdocs/config/config.inc.php'.format(rc_passwd, EEVariables.ee_mysql_host, EEVariables.ee_webroot))
EEShellExec.cmd_exec(self, ('bash -c "sed -i \\"s:\\$config\\[\'plugins\'\\] = array(:\\$config\\[\'plugins\'\\] = array(\\n \'sieverules\',:\\" {0}roundcubemail/htdocs/config'.format(EEVariables.ee_webroot) + '/config.inc.php"'))
EEShellExec.cmd_exec(self, ('echo "\\$config[\'sieverules_port\']=4190;" >> {0}roundcubemail'.format(EEVariables.ee_webroot) + '/htdocs/config/config.inc.php'))
data = dict(site_name='webmail', www_domain='webmail', static=False, basic=True, wp=False, w3tc=False, wpfc=False, wpsc=False, multisite=False, wpsubdir=False, webroot=EEVariables.ee_webroot, ee_db_name='', ee_db_user='', ee_db_pass='', ee_db_host='', rc=True)
Log.debug(self, 'Writting the nginx configuration for RoundCubemail')
ee_rc = open('/etc/nginx/sites-available/webmail', encoding='utf-8', mode='w')
self.app.render(data, 'virtualconf.mustache', out=ee_rc)
ee_rc.close()
EEFileUtils.create_symlink(self, ['/etc/nginx/sites-available/webmail', '/etc/nginx/sites-enabled/webmail'])
if (not os.path.exists('{0}roundcubemail/logs'.format(EEVariables.ee_webroot))):
os.makedirs('{0}roundcubemail/logs'.format(EEVariables.ee_webroot))
EEFileUtils.create_symlink(self, ['/var/log/nginx/webmail.access.log', '{0}roundcubemail/logs/access.log'.format(EEVariables.ee_webroot)])
EEFileUtils.create_symlink(self, ['/var/log/nginx/webmail.error.log', '{0}roundcubemail/logs/error.log'.format(EEVariables.ee_webroot)])
EEService.reload_service(self, 'nginx')
EEFileUtils.remove(self, ['{0}roundcubemail/htdocs/installer'.format(EEVariables.ee_webroot)])
EEFileUtils.chown(self, '{0}roundcubemail'.format(EEVariables.ee_webroot), EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True)
if any((('/tmp/pra.tar.gz' == x[1]) for x in packages)):
Log.debug(self, 'Extracting file /tmp/pra.tar.gz to loaction /tmp/')
EEExtract.extract(self, '/tmp/pra.tar.gz', '/tmp/')
if (not os.path.exists('{0}22222/htdocs/cache/redis'.format(EEVariables.ee_webroot))):
Log.debug(self, 'Creating new directory {0}22222/htdocs/cache/redis'.format(EEVariables.ee_webroot))
os.makedirs('{0}22222/htdocs/cache/redis'.format(EEVariables.ee_webroot))
shutil.move('/tmp/phpRedisAdmin-master/', '{0}22222/htdocs/cache/redis/phpRedisAdmin'.format(EEVariables.ee_webroot))
Log.debug(self, 'Extracting file /tmp/predis.tar.gz to loaction /tmp/')
EEExtract.extract(self, '/tmp/predis.tar.gz', '/tmp/')
shutil.move('/tmp/predis-1.0.1/', '{0}22222/htdocs/cache/redis/phpRedisAdmin/vendor'.format(EEVariables.ee_webroot))
Log.debug(self, 'Setting Privileges of webroot permission to {0}22222/htdocs/cache/ file '.format(EEVariables.ee_webroot))
EEFileUtils.chown(self, '{0}22222'.format(EEVariables.ee_webroot), EEVariables.ee_php_user, EEVariables.ee_php_user, recursive=True)
|
'Start installation of packages'
| @expose(help='Install packages')
def install(self, packages=[], apt_packages=[], disp_msg=True):
| if self.app.pargs.pagespeed:
Log.error(self, 'Pagespeed support has been dropped since EasyEngine v3.6.0', False)
Log.error(self, 'Please run command again without `--pagespeed`', False)
Log.error(self, 'For more details, read - https://easyengine.io/blog/disabling-pagespeed/')
self.msg = []
try:
if ((not self.app.pargs.web) and (not self.app.pargs.admin) and (not self.app.pargs.mail) and (not self.app.pargs.nginx) and (not self.app.pargs.php) and (not self.app.pargs.mysql) and (not self.app.pargs.postfix) and (not self.app.pargs.wpcli) and (not self.app.pargs.phpmyadmin) and (not self.app.pargs.hhvm) and (not self.app.pargs.pagespeed) and (not self.app.pargs.adminer) and (not self.app.pargs.utils) and (not self.app.pargs.mailscanner) and (not self.app.pargs.all) and (not self.app.pargs.redis) and (not self.app.pargs.phpredisadmin) and (not self.app.pargs.php7)):
self.app.pargs.web = True
self.app.pargs.admin = True
if self.app.pargs.all:
self.app.pargs.web = True
self.app.pargs.admin = True
self.app.pargs.mail = True
if self.app.pargs.web:
self.app.pargs.nginx = True
self.app.pargs.php = True
self.app.pargs.mysql = True
self.app.pargs.wpcli = True
self.app.pargs.postfix = True
if self.app.pargs.admin:
self.app.pargs.nginx = True
self.app.pargs.php = True
self.app.pargs.mysql = True
self.app.pargs.adminer = True
self.app.pargs.phpmyadmin = True
self.app.pargs.utils = True
if self.app.pargs.mail:
self.app.pargs.nginx = True
self.app.pargs.php = True
self.app.pargs.mysql = True
self.app.pargs.postfix = True
if (not EEAptGet.is_installed(self, 'dovecot-core')):
check_fqdn(self, os.popen("hostname -f | tr -d '\n'").read())
Log.debug(self, 'Setting apt_packages variable for mail')
apt_packages = (apt_packages + EEVariables.ee_mail)
packages = (packages + [['https://github.com/EasyEngine/ViMbAdmin/archive/{0}.tar.gz'.format(EEVariables.ee_vimbadmin), '/tmp/vimbadmin.tar.gz', 'ViMbAdmin'], ['https://github.com/roundcube/roundcubemail/releases/download/{0}/roundcubemail-{0}.tar.gz'.format(EEVariables.ee_roundcube), '/tmp/roundcube.tar.gz', 'Roundcube']])
if (EEVariables.ee_ram > 1024):
self.app.pargs.mailscanner = True
else:
Log.info(self, 'System RAM is less than 1GB\nMail scanner packages are not going to install automatically')
else:
Log.info(self, 'Mail server is already installed')
if self.app.pargs.redis:
if (not EEAptGet.is_installed(self, 'redis-server')):
apt_packages = (apt_packages + EEVariables.ee_redis)
self.app.pargs.php = True
else:
Log.info(self, 'Redis already installed')
if self.app.pargs.nginx:
Log.debug(self, 'Setting apt_packages variable for Nginx')
if (not EEAptGet.is_installed(self, 'nginx-custom')):
if (not (EEAptGet.is_installed(self, 'nginx-plus') or EEAptGet.is_installed(self, 'nginx'))):
apt_packages = (apt_packages + EEVariables.ee_nginx)
elif EEAptGet.is_installed(self, 'nginx-plus'):
Log.info(self, 'NGINX PLUS Detected ...')
apt = (['nginx-plus'] + EEVariables.ee_nginx)
self.post_pref(apt, packages)
elif EEAptGet.is_installed(self, 'nginx'):
Log.info(self, 'EasyEngine detected a previously installed Nginx package. It may or may not have required modules. \nIf you need help, please create an issue at https://github.com/EasyEngine/easyengine/issues/ \n')
apt = (['nginx'] + EEVariables.ee_nginx)
self.post_pref(apt, packages)
else:
Log.debug(self, 'Nginx Stable already installed')
if self.app.pargs.php:
Log.debug(self, 'Setting apt_packages variable for PHP')
if (not (EEAptGet.is_installed(self, 'php5-fpm') or EEAptGet.is_installed(self, 'php5.6-fpm'))):
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
apt_packages = ((apt_packages + EEVariables.ee_php5_6) + EEVariables.ee_php_extra)
else:
apt_packages = (apt_packages + EEVariables.ee_php)
else:
Log.debug(self, 'PHP already installed')
Log.info(self, 'PHP already installed')
if (self.app.pargs.php7 and (EEVariables.ee_platform_distro == 'debian')):
if (EEVariables.ee_platform_codename == 'jessie'):
Log.debug(self, 'Setting apt_packages variable for PHP 7.0')
if (not EEAptGet.is_installed(self, 'php7.0-fpm')):
apt_packages = (apt_packages + EEVariables.ee_php7_0)
if (not EEAptGet.is_installed(self, 'php5-fpm')):
apt_packages = (apt_packages + EEVariables.ee_php)
else:
Log.debug(self, 'PHP 7.0 already installed')
Log.info(self, 'PHP 7.0 already installed')
else:
Log.debug(self, 'PHP 7.0 Not Available for your Distribution')
Log.info(self, 'PHP 7.0 Not Available for your Distribution')
if (self.app.pargs.php7 and (not (EEVariables.ee_platform_distro == 'debian'))):
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
Log.debug(self, 'Setting apt_packages variable for PHP 7.0')
if (not EEAptGet.is_installed(self, 'php7.0-fpm')):
apt_packages = ((apt_packages + EEVariables.ee_php7_0) + EEVariables.ee_php_extra)
if (not EEAptGet.is_installed(self, 'php5.6-fpm')):
apt_packages = ((apt_packages + EEVariables.ee_php5_6) + EEVariables.ee_php_extra)
else:
Log.debug(self, 'PHP 7.0 already installed')
Log.info(self, 'PHP 7.0 already installed')
else:
Log.debug(self, 'PHP 7.0 Not Available for your Distribution')
Log.info(self, 'PHP 7.0 Not Available for your Distribution')
if self.app.pargs.hhvm:
Log.debug(self, 'Setting apt packages variable for HHVM')
if (platform.architecture()[0] is '32bit'):
Log.error(self, 'HHVM is not supported by 32bit system')
if (not EEAptGet.is_installed(self, 'hhvm')):
apt_packages = (apt_packages + EEVariables.ee_hhvm)
else:
Log.debug(self, 'HHVM already installed')
Log.info(self, 'HHVM already installed')
if self.app.pargs.mysql:
Log.debug(self, 'Setting apt_packages variable for MySQL')
if (not EEShellExec.cmd_exec(self, 'mysqladmin ping')):
apt_packages = (apt_packages + EEVariables.ee_mysql)
packages = (packages + [['https://raw.githubusercontent.com/major/MySQLTuner-perl/master/mysqltuner.pl', '/usr/bin/mysqltuner', 'MySQLTuner']])
else:
Log.debug(self, 'MySQL connection is already alive')
Log.info(self, 'MySQL connection is already alive')
if self.app.pargs.postfix:
Log.debug(self, 'Setting apt_packages variable for Postfix')
if (not EEAptGet.is_installed(self, 'postfix')):
apt_packages = (apt_packages + EEVariables.ee_postfix)
else:
Log.debug(self, 'Postfix is already installed')
Log.info(self, 'Postfix is already installed')
if self.app.pargs.wpcli:
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']])
else:
Log.debug(self, 'WP-CLI is already installed')
Log.info(self, 'WP-CLI is already installed')
if self.app.pargs.phpmyadmin:
Log.debug(self, 'Setting packages varible for phpMyAdmin ')
packages = (packages + [['https://github.com/phpmyadmin/phpmyadmin/archive/STABLE.tar.gz', '/tmp/pma.tar.gz', 'phpMyAdmin']])
if self.app.pargs.phpredisadmin:
Log.debug(self, 'Setting packages varible for phpRedisAdmin')
packages = (packages + [['https://github.com/ErikDubbelboer/phpRedisAdmin/archive/master.tar.gz', '/tmp/pra.tar.gz', 'phpRedisAdmin'], ['https://github.com/nrk/predis/archive/v1.0.1.tar.gz', '/tmp/predis.tar.gz', 'Predis']])
if self.app.pargs.adminer:
Log.debug(self, 'Setting packages variable for Adminer ')
packages = (packages + [['https://www.adminer.org/static/download/{0}/adminer-{0}.php'.format(EEVariables.ee_adminer), '{0}22222/htdocs/db/adminer/index.php'.format(EEVariables.ee_webroot), 'Adminer']])
if self.app.pargs.mailscanner:
if (not EEAptGet.is_installed(self, 'amavisd-new')):
if (EEAptGet.is_installed(self, 'dovecot-core') or self.app.pargs.mail):
apt_packages = (apt_packages + EEVariables.ee_mailscanner)
else:
Log.error(self, 'Failed to find installed Dovecot')
else:
Log.error(self, 'Mail scanner already installed')
if self.app.pargs.utils:
Log.debug(self, 'Setting packages variable for utils')
packages = (packages + [['https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/phpmemcacheadmin/phpMemcachedAdmin-1.2.2-r262.tar.gz', '/tmp/memcache.tar.gz', 'phpMemcachedAdmin'], ['https://raw.githubusercontent.com/rtCamp/eeadmin/master/cache/nginx/clean.php', '{0}22222/htdocs/cache/nginx/clean.php'.format(EEVariables.ee_webroot), 'clean.php'], ['https://raw.github.com/rlerdorf/opcache-status/master/opcache.php', '{0}22222/htdocs/cache/opcache/opcache.php'.format(EEVariables.ee_webroot), 'opcache.php'], ['https://raw.github.com/amnuts/opcache-gui/master/index.php', '{0}22222/htdocs/cache/opcache/opgui.php'.format(EEVariables.ee_webroot), 'Opgui'], ['https://gist.github.com/ck-on/4959032/raw/0b871b345fd6cfcd6d2be030c1f33d1ad6a475cb/ocp.php', '{0}22222/htdocs/cache/opcache/ocp.php'.format(EEVariables.ee_webroot), 'OCP.php'], ['https://github.com/jokkedk/webgrind/archive/master.tar.gz', '/tmp/webgrind.tar.gz', 'Webgrind'], ['http://bazaar.launchpad.net/~percona-toolkit-dev/percona-toolkit/2.1/download/head:/ptquerydigest-20110624220137-or26tn4expb9ul2a-16/pt-query-digest', '/usr/bin/pt-query-advisor', 'pt-query-advisor'], ['https://github.com/box/Anemometer/archive/master.tar.gz', '/tmp/anemometer.tar.gz', 'Anemometer']])
except Exception as e:
pass
if (len(apt_packages) or len(packages)):
Log.debug(self, 'Calling pre_pref')
self.pre_pref(apt_packages)
if len(apt_packages):
EESwap.add(self)
Log.info(self, 'Updating apt-cache, please wait...')
EEAptGet.update(self)
Log.info(self, 'Installing packages, please wait...')
EEAptGet.install(self, apt_packages)
if len(packages):
Log.debug(self, 'Downloading following: {0}'.format(packages))
EEDownload.download(self, packages)
Log.debug(self, 'Calling post_pref')
self.post_pref(apt_packages, packages)
if ('redis-server' in apt_packages):
if os.path.isfile('/etc/redis/redis.conf'):
if (EEVariables.ee_ram < 512):
Log.debug(self, 'Setting maxmemory variable to {0} in redis.conf'.format(int((((EEVariables.ee_ram * 1024) * 1024) * 0.1))))
EEShellExec.cmd_exec(self, "sed -i 's/# maxmemory <bytes>/maxmemory {0}/' /etc/redis/redis.conf".format(int((((EEVariables.ee_ram * 1024) * 1024) * 0.1))))
Log.debug(self, 'Setting maxmemory-policy variable to allkeys-lru in redis.conf')
EEShellExec.cmd_exec(self, "sed -i 's/# maxmemory-policy.*/maxmemory-policy allkeys-lru/' /etc/redis/redis.conf")
EEService.restart_service(self, 'redis-server')
else:
Log.debug(self, 'Setting maxmemory variable to {0} in redis.conf'.format(int((((EEVariables.ee_ram * 1024) * 1024) * 0.2))))
EEShellExec.cmd_exec(self, "sed -i 's/# maxmemory <bytes>/maxmemory {0}/' /etc/redis/redis.conf".format(int((((EEVariables.ee_ram * 1024) * 1024) * 0.2))))
Log.debug(self, 'Setting maxmemory-policy variable to allkeys-lru in redis.conf')
EEShellExec.cmd_exec(self, "sed -i 's/# maxmemory-policy.*/maxmemory-policy allkeys-lru/' /etc/redis/redis.conf")
EEService.restart_service(self, 'redis-server')
if disp_msg:
if len(self.msg):
for msg in self.msg:
Log.info(self, (Log.ENDC + msg))
Log.info(self, 'Successfully installed packages')
else:
return self.msg
|
'Start removal of packages'
| @expose(help='Remove packages')
def remove(self):
| apt_packages = []
packages = []
if self.app.pargs.pagespeed:
Log.error(self, 'Pagespeed support has been dropped since EasyEngine v3.6.0', False)
Log.error(self, 'Please run command again without `--pagespeed`', False)
Log.error(self, 'For more details, read - https://easyengine.io/blog/disabling-pagespeed/')
if ((not self.app.pargs.web) and (not self.app.pargs.admin) and (not self.app.pargs.mail) and (not self.app.pargs.nginx) and (not self.app.pargs.php) and (not self.app.pargs.php7) and (not self.app.pargs.mysql) and (not self.app.pargs.postfix) and (not self.app.pargs.wpcli) and (not self.app.pargs.phpmyadmin) and (not self.app.pargs.hhvm) and (not self.app.pargs.adminer) and (not self.app.pargs.utils) and (not self.app.pargs.mailscanner) and (not self.app.pargs.all) and (not self.app.pargs.pagespeed) and (not self.app.pargs.redis) and (not self.app.pargs.phpredisadmin)):
self.app.pargs.web = True
self.app.pargs.admin = True
if self.app.pargs.all:
self.app.pargs.web = True
self.app.pargs.admin = True
self.app.pargs.mail = True
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
self.app.pargs.php7 = True
if self.app.pargs.web:
self.app.pargs.nginx = True
self.app.pargs.php = True
self.app.pargs.mysql = True
self.app.pargs.wpcli = True
self.app.pargs.postfix = True
if self.app.pargs.admin:
self.app.pargs.adminer = True
self.app.pargs.phpmyadmin = True
self.app.pargs.utils = True
if self.app.pargs.mail:
Log.debug(self, 'Removing mail server packages')
apt_packages = (apt_packages + EEVariables.ee_mail)
apt_packages = (apt_packages + EEVariables.ee_mailscanner)
packages = (packages + ['{0}22222/htdocs/vimbadmin'.format(EEVariables.ee_webroot), '{0}roundcubemail'.format(EEVariables.ee_webroot)])
if EEShellExec.cmd_exec(self, 'mysqladmin ping'):
EEMysql.execute(self, 'drop database IF EXISTS vimbadmin')
EEMysql.execute(self, 'drop database IF EXISTS roundcubemail')
if self.app.pargs.mailscanner:
apt_packages = (apt_packages + EEVariables.ee_mailscanner)
if self.app.pargs.pagespeed:
Log.debug(self, 'Removing packages varible of Pagespeed')
packages = (packages + ['/etc/nginx/conf.d/pagespeed.conf'])
if self.app.pargs.nginx:
if EEAptGet.is_installed(self, 'nginx-custom'):
Log.debug(self, 'Removing apt_packages variable of Nginx')
apt_packages = (apt_packages + EEVariables.ee_nginx)
else:
Log.error(self, 'Cannot Remove! Nginx Stable version not found.')
if self.app.pargs.php:
Log.debug(self, 'Removing apt_packages variable of PHP')
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
apt_packages = (apt_packages + EEVariables.ee_php5_6)
if (not EEAptGet.is_installed(self, 'php7.0-fpm')):
apt_packages = (apt_packages + EEVariables.ee_php_extra)
else:
apt_packages = (apt_packages + EEVariables.ee_php)
if self.app.pargs.php7:
if (EEVariables.ee_platform_codename == 'jessie'):
Log.debug(self, 'Removing apt_packages variable of PHP 7.0')
apt_packages = (apt_packages + EEVariables.ee_php7_0)
if (not EEAptGet.is_installed(self, 'php5-fpm')):
apt_packages = (apt_packages + EEVariables.ee_php_extra)
else:
Log.info(self, 'PHP 7.0 not supported.')
if self.app.pargs.php7:
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
Log.debug(self, 'Removing apt_packages variable of PHP 7.0')
apt_packages = (apt_packages + EEVariables.ee_php7_0)
if (not EEAptGet.is_installed(self, 'php5.6-fpm')):
apt_packages = (apt_packages + EEVariables.ee_php_extra)
else:
Log.info(self, 'PHP 7.0 not supported.')
if self.app.pargs.hhvm:
if EEAptGet.is_installed(self, 'hhvm'):
Log.debug(self, 'Removing apt_packages variable of HHVM')
apt_packages = (apt_packages + EEVariables.ee_hhvm)
if self.app.pargs.redis:
Log.debug(self, 'Remove apt_packages variable of Redis')
apt_packages = (apt_packages + EEVariables.ee_redis)
if self.app.pargs.mysql:
Log.debug(self, 'Removing apt_packages variable of MySQL')
apt_packages = (apt_packages + EEVariables.ee_mysql)
packages = (packages + ['/usr/bin/mysqltuner'])
if self.app.pargs.postfix:
Log.debug(self, 'Removing apt_packages variable of Postfix')
apt_packages = (apt_packages + EEVariables.ee_postfix)
if self.app.pargs.wpcli:
Log.debug(self, 'Removing package variable of WPCLI ')
if os.path.isfile('/usr/bin/wp'):
packages = (packages + ['/usr/bin/wp'])
else:
Log.warn(self, 'WP-CLI is not installed with EasyEngine')
if self.app.pargs.phpmyadmin:
Log.debug(self, 'Removing package variable of phpMyAdmin ')
packages = (packages + ['{0}22222/htdocs/db/pma'.format(EEVariables.ee_webroot)])
if self.app.pargs.phpredisadmin:
Log.debug(self, 'Removing package variable of phpRedisAdmin ')
packages = (packages + ['{0}22222/htdocs/cache/redis/phpRedisAdmin'.format(EEVariables.ee_webroot)])
if self.app.pargs.adminer:
Log.debug(self, 'Removing package variable of Adminer ')
packages = (packages + ['{0}22222/htdocs/db/adminer'.format(EEVariables.ee_webroot)])
if self.app.pargs.utils:
Log.debug(self, 'Removing package variable of utils ')
packages = (packages + ['{0}22222/htdocs/php/webgrind/'.format(EEVariables.ee_webroot), '{0}22222/htdocs/cache/opcache'.format(EEVariables.ee_webroot), '{0}22222/htdocs/cache/nginx/clean.php'.format(EEVariables.ee_webroot), '{0}22222/htdocs/cache/memcache'.format(EEVariables.ee_webroot), '/usr/bin/pt-query-advisor', '{0}22222/htdocs/db/anemometer'.format(EEVariables.ee_webroot)])
if (len(packages) or len(apt_packages)):
ee_prompt = input('Are you sure you to want to remove from server.\nPackage configuration will remain on server after this operation.\nAny answer other than "yes" will be stop this operation : ')
if ((ee_prompt == 'YES') or (ee_prompt == 'yes')):
if set(['nginx-custom']).issubset(set(apt_packages)):
EEService.stop_service(self, 'nginx')
if len(packages):
EEFileUtils.remove(self, packages)
EEAptGet.auto_remove(self)
if len(apt_packages):
Log.debug(self, 'Removing apt_packages')
Log.info(self, 'Removing packages, please wait...')
EEAptGet.remove(self, apt_packages)
EEAptGet.auto_remove(self)
Log.info(self, 'Successfully removed packages')
if self.app.pargs.php7:
if EEAptGet.is_installed(self, 'php5.6-fpm'):
Log.info(self, 'PHP5.6-fpm found on system.')
Log.info(self, 'Verifying and installing missing packages,')
EEShellExec.cmd_exec(self, 'apt-get install -y php-memcached php-igbinary')
|
'Start purging of packages'
| @expose(help='Purge packages')
def purge(self):
| apt_packages = []
packages = []
if self.app.pargs.pagespeed:
Log.error(self, 'Pagespeed support has been dropped since EasyEngine v3.6.0', False)
Log.error(self, 'Please run command again without `--pagespeed`', False)
Log.error(self, 'For more details, read - https://easyengine.io/blog/disabling-pagespeed/')
if ((not self.app.pargs.web) and (not self.app.pargs.admin) and (not self.app.pargs.mail) and (not self.app.pargs.nginx) and (not self.app.pargs.php) and (not self.app.pargs.php7) and (not self.app.pargs.mysql) and (not self.app.pargs.postfix) and (not self.app.pargs.wpcli) and (not self.app.pargs.phpmyadmin) and (not self.app.pargs.hhvm) and (not self.app.pargs.adminer) and (not self.app.pargs.utils) and (not self.app.pargs.mailscanner) and (not self.app.pargs.all) and (not self.app.pargs.pagespeed) and (not self.app.pargs.redis) and (not self.app.pargs.phpredisadmin)):
self.app.pargs.web = True
self.app.pargs.admin = True
if self.app.pargs.all:
self.app.pargs.web = True
self.app.pargs.admin = True
self.app.pargs.mail = True
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
self.app.pargs.php7 = True
if self.app.pargs.web:
self.app.pargs.nginx = True
self.app.pargs.php = True
self.app.pargs.mysql = True
self.app.pargs.wpcli = True
self.app.pargs.postfix = True
if self.app.pargs.admin:
self.app.pargs.adminer = True
self.app.pargs.phpmyadmin = True
self.app.pargs.utils = True
if self.app.pargs.mail:
Log.debug(self, 'Removing mail server packages')
apt_packages = (apt_packages + EEVariables.ee_mail)
apt_packages = (apt_packages + EEVariables.ee_mailscanner)
packages = (packages + ['{0}22222/htdocs/vimbadmin'.format(EEVariables.ee_webroot), '{0}roundcubemail'.format(EEVariables.ee_webroot)])
if EEShellExec.cmd_exec(self, 'mysqladmin ping'):
EEMysql.execute(self, 'drop database IF EXISTS vimbadmin')
EEMysql.execute(self, 'drop database IF EXISTS roundcubemail')
if self.app.pargs.mailscanner:
apt_packages = (apt_packages + EEVariables.ee_mailscanner)
if self.app.pargs.pagespeed:
Log.debug(self, 'Purge packages varible of Pagespeed')
packages = (packages + ['/etc/nginx/conf.d/pagespeed.conf'])
if self.app.pargs.nginx:
if EEAptGet.is_installed(self, 'nginx-custom'):
Log.debug(self, 'Purge apt_packages variable of Nginx')
apt_packages = (apt_packages + EEVariables.ee_nginx)
else:
Log.error(self, 'Cannot Purge! Nginx Stable version not found.')
if self.app.pargs.php:
Log.debug(self, 'Purge apt_packages variable PHP')
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
apt_packages = (apt_packages + EEVariables.ee_php5_6)
if (not EEAptGet.is_installed(self, 'php7.0-fpm')):
apt_packages = (apt_packages + EEVariables.ee_php_extra)
else:
apt_packages = (apt_packages + EEVariables.ee_php)
if self.app.pargs.php7:
if (EEVariables.ee_platform_codename == 'jessie'):
Log.debug(self, 'Removing apt_packages variable of PHP 7.0')
apt_packages = (apt_packages + EEVariables.ee_php7_0)
if (not EEAptGet.is_installed(self, 'php5-fpm')):
apt_packages = (apt_packages + EEVariables.ee_php_extra)
else:
Log.info(self, 'PHP 7.0 not supported.')
if self.app.pargs.php7:
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
Log.debug(self, 'Removing apt_packages variable of PHP 7.0')
apt_packages = (apt_packages + EEVariables.ee_php7_0)
if (not EEAptGet.is_installed(self, 'php5.6-fpm')):
apt_packages = (apt_packages + EEVariables.ee_php_extra)
else:
Log.info(self, 'PHP 7.0 not supported.')
if self.app.pargs.hhvm:
if EEAptGet.is_installed(self, 'hhvm'):
Log.debug(self, 'Purge apt_packages varible of HHVM')
apt_packages = (apt_packages + EEVariables.ee_hhvm)
if self.app.pargs.redis:
Log.debug(self, 'Purge apt_packages variable of Redis')
apt_packages = (apt_packages + EEVariables.ee_redis)
if self.app.pargs.mysql:
Log.debug(self, 'Purge apt_packages variable MySQL')
apt_packages = (apt_packages + EEVariables.ee_mysql)
packages = (packages + ['/usr/bin/mysqltuner'])
if self.app.pargs.postfix:
Log.debug(self, 'Purge apt_packages variable PostFix')
apt_packages = (apt_packages + EEVariables.ee_postfix)
if self.app.pargs.wpcli:
Log.debug(self, 'Purge package variable WPCLI')
if os.path.isfile('/usr/bin/wp'):
packages = (packages + ['/usr/bin/wp'])
else:
Log.warn(self, 'WP-CLI is not installed with EasyEngine')
if self.app.pargs.phpmyadmin:
packages = (packages + ['{0}22222/htdocs/db/pma'.format(EEVariables.ee_webroot)])
Log.debug(self, 'Purge package variable phpMyAdmin')
if self.app.pargs.phpredisadmin:
Log.debug(self, 'Removing package variable of phpRedisAdmin ')
packages = (packages + ['{0}22222/htdocs/cache/redis/phpRedisAdmin'.format(EEVariables.ee_webroot)])
if self.app.pargs.adminer:
Log.debug(self, 'Purge package variable Adminer')
packages = (packages + ['{0}22222/htdocs/db/adminer'.format(EEVariables.ee_webroot)])
if self.app.pargs.utils:
Log.debug(self, 'Purge package variable utils')
packages = (packages + ['{0}22222/htdocs/php/webgrind/'.format(EEVariables.ee_webroot), '{0}22222/htdocs/cache/opcache'.format(EEVariables.ee_webroot), '{0}22222/htdocs/cache/nginx/clean.php'.format(EEVariables.ee_webroot), '{0}22222/htdocs/cache/memcache'.format(EEVariables.ee_webroot), '/usr/bin/pt-query-advisor', '{0}22222/htdocs/db/anemometer'.format(EEVariables.ee_webroot)])
if (len(packages) or len(apt_packages)):
ee_prompt = input('Are you sure you to want to purge from server along with their configuration packages,\nAny answer other than "yes" will be stop this operation :')
if ((ee_prompt == 'YES') or (ee_prompt == 'yes')):
if set(['nginx-custom']).issubset(set(apt_packages)):
EEService.stop_service(self, 'nginx')
if len(apt_packages):
Log.info(self, 'Purging packages, please wait...')
EEAptGet.remove(self, apt_packages, purge=True)
EEAptGet.auto_remove(self)
if len(packages):
EEFileUtils.remove(self, packages)
EEAptGet.auto_remove(self)
Log.info(self, 'Successfully purged packages')
if self.app.pargs.php7:
if EEAptGet.is_installed(self, 'php5.6-fpm'):
Log.info(self, 'PHP5.6-fpm found on system.')
Log.info(self, 'Verifying and installing missing packages,')
EEShellExec.cmd_exec(self, 'apt-get install -y php-memcached php-igbinary')
|
'1. reads database information from wp/ee-config.php
2. updates records into ee database accordingly.'
| @expose(hide=True)
def sync(self):
| Log.info(self, 'Synchronizing ee database, please wait...')
sites = getAllsites(self)
if (not sites):
pass
for site in sites:
if (site.site_type in ['mysql', 'wp', 'wpsubdir', 'wpsubdomain']):
ee_site_webroot = site.site_path
configfiles = glob.glob((ee_site_webroot + '/*-config.php'))
if (not configfiles):
Log.debug(self, 'Config files not found in {0}/ '.format(ee_site_webroot))
if (site.site_type != 'mysql'):
Log.debug(self, 'Searching wp-config.php in {0}/htdocs/ '.format(ee_site_webroot))
configfiles = glob.glob((ee_site_webroot + '/htdocs/wp-config.php'))
if configfiles:
if EEFileUtils.isexist(self, configfiles[0]):
ee_db_name = EEFileUtils.grep(self, configfiles[0], 'DB_NAME').split(',')[1].split(')')[0].strip().replace("'", '')
ee_db_user = EEFileUtils.grep(self, configfiles[0], 'DB_USER').split(',')[1].split(')')[0].strip().replace("'", '')
ee_db_pass = EEFileUtils.grep(self, configfiles[0], 'DB_PASSWORD').split(',')[1].split(')')[0].strip().replace("'", '')
ee_db_host = EEFileUtils.grep(self, configfiles[0], 'DB_HOST').split(',')[1].split(')')[0].strip().replace("'", '')
try:
if (not EEMysql.check_db_exists(self, ee_db_name)):
ee_db_name = 'deleted'
ee_db_user = 'deleted'
ee_db_pass = 'deleted'
except StatementExcecutionError as e:
Log.debug(self, str(e))
except Exception as e:
Log.debug(self, str(e))
if (site.db_name != ee_db_name):
Log.debug(self, 'Updating ee db record for {0}'.format(site.sitename))
updateSiteInfo(self, site.sitename, db_name=ee_db_name, db_user=ee_db_user, db_password=ee_db_pass, db_host=ee_db_host)
else:
Log.debug(self, 'Config files not found for {0} '.format(site.sitename))
|
'This function clears Redis cache'
| @expose(hide=True)
def clean_redis(self):
| 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')
|
'This function Clears memcache'
| @expose(hide=True)
def clean_memcache(self):
| try:
if EEAptGet.is_installed(self, 'memcached'):
EEService.restart_service(self, 'memcached')
Log.info(self, 'Cleaning MemCache')
else:
Log.info(self, 'Memcache not installed')
except Exception as e:
Log.debug(self, '{0}'.format(e))
Log.error(self, 'Unable to restart Memcached', False)
|
'This function clears Fastcgi cache'
| @expose(hide=True)
def clean_fastcgi(self):
| 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)
|
'This function clears opcache'
| @expose(hide=True)
def clean_opcache(self):
| try:
Log.info(self, 'Cleaning opcache')
wp = urllib.request.urlopen(' https://127.0.0.1:22222/cache/opcache/opgui.php?page=reset').read()
except Exception as e:
Log.debug(self, '{0}'.format(e))
Log.debug(self, 'Unable hit url, https://127.0.0.1:22222/cache/opcache/opgui.php?page=reset, please check you have admin tools installed')
Log.debug(self, 'please check you have admin tools installed, or install them with `ee stack install --admin`')
Log.error(self, 'Unable to clean opcache', False)
|
'Start/Stop Nginx debug'
| @expose(hide=True)
def debug_nginx(self):
| if ((self.app.pargs.nginx == 'on') and (not self.app.pargs.site_name)):
try:
debug_address = self.app.config.get('stack', 'ip-address').split()
except Exception as e:
debug_address = ['0.0.0.0/0']
if ((debug_address == ['127.0.0.1']) or (debug_address == [])):
debug_address = ['0.0.0.0/0']
for ip_addr in debug_address:
if (not (('debug_connection ' + ip_addr) in open('/etc/nginx/nginx.conf', encoding='utf-8').read())):
Log.info(self, ('Setting up Nginx debug connection for ' + ip_addr))
EEShellExec.cmd_exec(self, 'sed -i "/events {{/a\\ \\ \\ \\ $(echo debug_connection {ip}\\;)" /etc/nginx/nginx.conf'.format(ip=ip_addr))
self.trigger_nginx = True
if (not self.trigger_nginx):
Log.info(self, 'Nginx debug connection already enabled')
self.msg = (self.msg + ['/var/log/nginx/*.error.log'])
elif ((self.app.pargs.nginx == 'off') and (not self.app.pargs.site_name)):
if ('debug_connection ' in open('/etc/nginx/nginx.conf', encoding='utf-8').read()):
Log.info(self, 'Disabling Nginx debug connections')
EEShellExec.cmd_exec(self, 'sed -i "/debug_connection.*/d" /etc/nginx/nginx.conf')
self.trigger_nginx = True
else:
Log.info(self, 'Nginx debug connection already disabled')
elif ((self.app.pargs.nginx == 'on') and self.app.pargs.site_name):
config_path = '/etc/nginx/sites-available/{0}'.format(self.app.pargs.site_name)
if os.path.isfile(config_path):
if (not EEShellExec.cmd_exec(self, 'grep "error.log debug" {0}'.format(config_path))):
Log.info(self, 'Starting NGINX debug connection for {0}'.format(self.app.pargs.site_name))
EEShellExec.cmd_exec(self, 'sed -i "s/error.log;/error.log debug;/" {0}'.format(config_path))
self.trigger_nginx = True
else:
Log.info(self, 'Nginx debug for site already enabled')
self.msg = (self.msg + ['{0}{1}/logs/error.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 ((self.app.pargs.nginx == 'off') and self.app.pargs.site_name):
config_path = '/etc/nginx/sites-available/{0}'.format(self.app.pargs.site_name)
if os.path.isfile(config_path):
if EEShellExec.cmd_exec(self, 'grep "error.log debug" {0}'.format(config_path)):
Log.info(self, 'Stoping NGINX debug connection for {0}'.format(self.app.pargs.site_name))
EEShellExec.cmd_exec(self, 'sed -i "s/error.log debug;/error.log;/" {0}'.format(config_path))
self.trigger_nginx = True
else:
Log.info(self, 'Nginx debug for site already disabled')
else:
Log.info(self, '{0} domain not valid'.format(self.app.pargs.site_name))
|
'Start/Stop PHP debug'
| @expose(hide=True)
def debug_php(self):
| if ((self.app.pargs.php == 'on') and (not self.app.pargs.site_name)):
if (not EEShellExec.cmd_exec(self, 'sed -n "/upstream php{/,/}/p " /etc/nginx/conf.d/upstream.conf | grep 9001')):
Log.info(self, 'Enabling PHP debug')
nc = NginxConfig()
nc.loadf('/etc/nginx/conf.d/upstream.conf')
nc.set([('upstream', 'php'), 'server'], '127.0.0.1:9001')
if os.path.isfile('/etc/nginx/common/wpfc-hhvm.conf'):
nc.set([('upstream', 'hhvm'), 'server'], '127.0.0.1:9001')
nc.savef('/etc/nginx/conf.d/upstream.conf')
EEFileUtils.searchreplace(self, ('/etc/{0}/mods-available/'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')) + 'xdebug.ini'), ';zend_extension', 'zend_extension')
config = configparser.ConfigParser()
config.read('/etc/{0}/fpm/pool.d/debug.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')))
config['debug']['slowlog'] = '/var/log/{0}/slow.log'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5'))
config['debug']['request_slowlog_timeout'] = '10s'
with open('/etc/{0}/fpm/pool.d/debug.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')), encoding='utf-8', mode='w') as confifile:
Log.debug(self, 'Writting debug.conf configuration into /etc/{0}/fpm/pool.d/debug.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')))
config.write(confifile)
self.trigger_php = True
self.trigger_nginx = True
else:
Log.info(self, 'PHP debug is already enabled')
self.msg = (self.msg + ['/var/log/{0}/slow.log'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5'))])
elif ((self.app.pargs.php == 'off') and (not self.app.pargs.site_name)):
if EEShellExec.cmd_exec(self, ' sed -n "/upstream php {/,/}/p" /etc/nginx/conf.d/upstream.conf | grep 9001'):
Log.info(self, 'Disabling PHP debug')
nc = NginxConfig()
nc.loadf('/etc/nginx/conf.d/upstream.conf')
nc.set([('upstream', 'php'), 'server'], '127.0.0.1:9000')
if os.path.isfile('/etc/nginx/common/wpfc-hhvm.conf'):
nc.set([('upstream', 'hhvm'), 'server'], '127.0.0.1:8000')
nc.savef('/etc/nginx/conf.d/upstream.conf')
EEFileUtils.searchreplace(self, ('/etc/{0}/mods-available/'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')) + 'xdebug.ini'), 'zend_extension', ';zend_extension')
self.trigger_php = True
self.trigger_nginx = True
else:
Log.info(self, 'PHP debug is already disabled')
|
'Start/Stop PHP5-FPM debug'
| @expose(hide=True)
def debug_fpm(self):
| if ((self.app.pargs.fpm == 'on') and (not self.app.pargs.site_name)):
if (not EEShellExec.cmd_exec(self, 'grep "log_level = debug" /etc/{0}/fpm/php-fpm.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')))):
Log.info(self, 'Setting up PHP5-FPM log_level = debug')
config = configparser.ConfigParser()
config.read('/etc/{0}/fpm/php-fpm.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')))
config.remove_option('global', 'include')
config['global']['log_level'] = 'debug'
config['global']['include'] = '/etc/{0}/fpm/pool.d/*.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5'))
with open('/etc/{0}/fpm/php-fpm.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')), encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'Writting php5-FPM configuration into /etc/{0}/fpm/php-fpm.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')))
config.write(configfile)
self.trigger_php = True
else:
Log.info(self, 'PHP5-FPM log_level = debug already setup')
self.msg = (self.msg + ['/var/log/{0}/fpm.log'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5'))])
elif ((self.app.pargs.fpm == 'off') and (not self.app.pargs.site_name)):
if EEShellExec.cmd_exec(self, 'grep "log_level = debug" /etc/{0}/fpm/php-fpm.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5'))):
Log.info(self, 'Disabling PHP5-FPM log_level = debug')
config = configparser.ConfigParser()
config.read('/etc/{0}/fpm/php-fpm.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')))
config.remove_option('global', 'include')
config['global']['log_level'] = 'notice'
config['global']['include'] = '/etc/{0}/fpm/pool.d/*.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5'))
with open('/etc/{0}/fpm/php-fpm.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')), encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'writting php5 configuration into /etc/{0}/fpm/php-fpm.conf'.format(('php/5.6' if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) else 'php5')))
config.write(configfile)
self.trigger_php = True
else:
Log.info(self, 'PHP5-FPM log_level = debug already disabled')
|
'Start/Stop PHP debug'
| @expose(hide=True)
def debug_php7(self):
| if ((self.app.pargs.php7 == 'on') and (not self.app.pargs.site_name)):
if ((EEVariables.ee_platform_codename == 'wheezy') or (EEVariables.ee_platform_codename == 'precise')):
Log.error(self, 'PHP 7.0 not supported.')
if (not EEShellExec.cmd_exec(self, 'sed -n "/upstream php7{/,/}/p " /etc/nginx/conf.d/upstream.conf | grep 9170')):
Log.info(self, 'Enabling PHP 7.0 debug')
nc = NginxConfig()
nc.loadf('/etc/nginx/conf.d/upstream.conf')
nc.set([('upstream', 'php7'), 'server'], '127.0.0.1:9170')
if os.path.isfile('/etc/nginx/common/wpfc-hhvm.conf'):
nc.set([('upstream', 'hhvm'), 'server'], '127.0.0.1:9170')
nc.savef('/etc/nginx/conf.d/upstream.conf')
EEFileUtils.searchreplace(self, '/etc/php/7.0/mods-available/xdebug.ini', ';zend_extension', 'zend_extension')
config = configparser.ConfigParser()
config.read('/etc/php/7.0/fpm/pool.d/debug.conf')
config['debug']['slowlog'] = '/var/log/php/7.0/slow.log'
config['debug']['request_slowlog_timeout'] = '10s'
with open('/etc/php/7.0/fpm/pool.d/debug.conf', encoding='utf-8', mode='w') as confifile:
Log.debug(self, 'Writting debug.conf configuration into /etc/php/7.0/fpm/pool.d/debug.conf')
config.write(confifile)
self.trigger_php = True
self.trigger_nginx = True
else:
Log.info(self, 'PHP debug is already enabled')
self.msg = (self.msg + ['/var/log/php/7.0/slow.log'])
elif ((self.app.pargs.php7 == 'off') and (not self.app.pargs.site_name)):
if EEShellExec.cmd_exec(self, ' sed -n "/upstream php7 {/,/}/p" /etc/nginx/conf.d/upstream.conf | grep 9170'):
Log.info(self, 'Disabling PHP 7.0 debug')
nc = NginxConfig()
nc.loadf('/etc/nginx/conf.d/upstream.conf')
nc.set([('upstream', 'php7'), 'server'], '127.0.0.1:9070')
if os.path.isfile('/etc/nginx/common/wpfc-hhvm.conf'):
nc.set([('upstream', 'hhvm'), 'server'], '127.0.0.1:8000')
nc.savef('/etc/nginx/conf.d/upstream.conf')
EEFileUtils.searchreplace(self, '/etc/php/7.0/mods-available/xdebug.ini', 'zend_extension', ';zend_extension')
self.trigger_php = True
self.trigger_nginx = True
else:
Log.info(self, 'PHP 7.0 debug is already disabled')
|
'Start/Stop PHP5-FPM debug'
| @expose(hide=True)
def debug_fpm7(self):
| if ((self.app.pargs.fpm7 == 'on') and (not self.app.pargs.site_name)):
if (not EEShellExec.cmd_exec(self, 'grep "log_level = debug" /etc/php/7.0/fpm/php-fpm.conf')):
Log.info(self, 'Setting up PHP7.0-FPM log_level = debug')
config = configparser.ConfigParser()
config.read('/etc/php/7.0/fpm/php-fpm.conf')
config.remove_option('global', 'include')
config['global']['log_level'] = 'debug'
config['global']['include'] = '/etc/php/7.0/fpm/pool.d/*.conf'
with open('/etc/php/7.0/fpm/php-fpm.conf', encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'Writting php7.0-FPM configuration into /etc/php/7.0/fpm/php-fpm.conf')
config.write(configfile)
self.trigger_php = True
else:
Log.info(self, 'PHP7.0-FPM log_level = debug already setup')
self.msg = (self.msg + ['/var/log/php/7.0/fpm.log'])
elif ((self.app.pargs.fpm7 == 'off') and (not self.app.pargs.site_name)):
if EEShellExec.cmd_exec(self, 'grep "log_level = debug" /etc/php/7.0/fpm/php-fpm.conf'):
Log.info(self, 'Disabling PHP7.0-FPM log_level = debug')
config = configparser.ConfigParser()
config.read('/etc/php/7.0/fpm/php-fpm.conf')
config.remove_option('global', 'include')
config['global']['log_level'] = 'notice'
config['global']['include'] = '/etc/php/7.0/fpm/pool.d/*.conf'
with open('/etc/php/7.0/fpm/php-fpm.conf', encoding='utf-8', mode='w') as configfile:
Log.debug(self, 'writting php7.0 configuration into /etc/php/7.0/fpm/php-fpm.conf')
config.write(configfile)
self.trigger_php = True
else:
Log.info(self, 'PHP7.0-FPM log_level = debug already disabled')
|
'Start/Stop MySQL debug'
| @expose(hide=True)
def debug_mysql(self):
| if ((self.app.pargs.mysql == 'on') and (not self.app.pargs.site_name)):
if (not EEShellExec.cmd_exec(self, 'mysql -e "show variables like \'slow_query_log\';" | grep ON')):
Log.info(self, 'Setting up MySQL slow log')
EEMysql.execute(self, "set global slow_query_log = 'ON';")
EEMysql.execute(self, "set global slow_query_log_file = '/var/log/mysql/mysql-slow.log';")
EEMysql.execute(self, 'set global long_query_time = 2;')
EEMysql.execute(self, "set global log_queries_not_using_indexes = 'ON';")
else:
Log.info(self, 'MySQL slow log is already enabled')
self.msg = (self.msg + ['/var/log/mysql/mysql-slow.log'])
elif ((self.app.pargs.mysql == 'off') and (not self.app.pargs.site_name)):
if EEShellExec.cmd_exec(self, 'mysql -e "show variables like \'slow_query_log\';" | grep ON'):
Log.info(self, 'Disabling MySQL slow log')
EEMysql.execute(self, "set global slow_query_log = 'OFF';")
EEMysql.execute(self, "set global slow_query_log_file = '/var/log/mysql/mysql-slow.log';")
EEMysql.execute(self, 'set global long_query_time = 10;')
EEMysql.execute(self, "set global log_queries_not_using_indexes = 'OFF';")
EEShellExec.cmd_exec(self, "crontab -l | sed '/#EasyEngine start/,/#EasyEngine end/d' | crontab -")
else:
Log.info(self, 'MySQL slow log already disabled')
|
'Start/Stop WordPress debug'
| @expose(hide=True)
def debug_wp(self):
| if ((self.app.pargs.wp == 'on') 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 (not os.path.isfile(wp_config)):
wp_config = '{0}/{1}/htdocs/wp-config.php'.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);\\ndefine(\'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, 'Unable to find wp-config.php for site: {0}'.format(self.app.pargs.site_name))
elif ((self.app.pargs.wp == 'off') 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 (not os.path.isfile(wp_config)):
wp_config = '{0}/{1}/htdocs/wp-config.php'.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')
|
'Start/Stop Nginx rewrite rules debug'
| @expose(hide=True)
def debug_rewrite(self):
| if ((self.app.pargs.rewrite == 'on') and (not self.app.pargs.site_name)):
if (not EEShellExec.cmd_exec(self, 'grep "rewrite_log on;" /etc/nginx/nginx.conf')):
Log.info(self, 'Setting up Nginx rewrite logs')
EEShellExec.cmd_exec(self, "sed -i '/http {/a \\\\trewrite_log on;' /etc/nginx/nginx.conf")
self.trigger_nginx = True
else:
Log.info(self, 'Nginx rewrite logs already enabled')
if ('/var/log/nginx/*.error.log' not in self.msg):
self.msg = (self.msg + ['/var/log/nginx/*.error.log'])
elif ((self.app.pargs.rewrite == 'off') and (not self.app.pargs.site_name)):
if EEShellExec.cmd_exec(self, 'grep "rewrite_log on;" /etc/nginx/nginx.conf'):
Log.info(self, 'Disabling Nginx rewrite logs')
EEShellExec.cmd_exec(self, 'sed -i "/rewrite_log.*/d" /etc/nginx/nginx.conf')
self.trigger_nginx = True
else:
Log.info(self, 'Nginx rewrite logs already disabled')
elif ((self.app.pargs.rewrite == 'on') and self.app.pargs.site_name):
config_path = '/etc/nginx/sites-available/{0}'.format(self.app.pargs.site_name)
if (not EEShellExec.cmd_exec(self, 'grep "rewrite_log on;" {0}'.format(config_path))):
Log.info(self, 'Setting up Nginx rewrite logs for {0}'.format(self.app.pargs.site_name))
EEShellExec.cmd_exec(self, 'sed -i "/access_log/i \\\\\\trewrite_log on;" {0}'.format(config_path))
self.trigger_nginx = True
else:
Log.info(self, 'Nginx rewrite logs for {0} already setup'.format(self.app.pargs.site_name))
if ('{0}{1}/logs/error.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name) not in self.msg):
self.msg = (self.msg + ['{0}{1}/logs/error.log'.format(EEVariables.ee_webroot, self.app.pargs.site_name)])
elif ((self.app.pargs.rewrite == 'off') and self.app.pargs.site_name):
config_path = '/etc/nginx/sites-available/{0}'.format(self.app.pargs.site_name)
if EEShellExec.cmd_exec(self, 'grep "rewrite_log on;" {0}'.format(config_path)):
Log.info(self, 'Disabling Nginx rewrite logs for {0}'.format(self.app.pargs.site_name))
EEShellExec.cmd_exec(self, 'sed -i "/rewrite_log.*/d" {0}'.format(config_path))
self.trigger_nginx = True
else:
Log.info(self, 'Nginx rewrite logs for {0} already disabled'.format(self.app.pargs.site_name))
|
'Handle Ctrl+c hevent for -i option of debug'
| @expose(hide=True)
def signal_handler(self, signal, frame):
| self.start = False
if self.app.pargs.nginx:
self.app.pargs.nginx = 'off'
self.debug_nginx()
if self.app.pargs.php:
self.app.pargs.php = 'off'
self.debug_php()
if self.app.pargs.php7:
self.app.pargs.php7 = 'off'
self.debug_php7()
if self.app.pargs.fpm:
self.app.pargs.fpm = 'off'
self.debug_fpm()
if self.app.pargs.fpm7:
self.app.pargs.fpm7 = 'off'
self.debug_fpm7()
if self.app.pargs.mysql:
if (EEVariables.ee_mysql_host is 'localhost'):
self.app.pargs.mysql = 'off'
self.debug_mysql()
else:
Log.warn(self, 'Remote MySQL found, EasyEngine will not enable remote debug')
if self.app.pargs.wp:
self.app.pargs.wp = 'off'
self.debug_wp()
if self.app.pargs.rewrite:
self.app.pargs.rewrite = 'off'
self.debug_rewrite()
if self.trigger_nginx:
EEService.reload_service(self, 'nginx')
if self.trigger_php:
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
if EEAptGet.is_installed(self, 'php5.6-fpm'):
EEService.reload_service(self, 'php5.6-fpm')
if EEAptGet.is_installed(self, 'php7.0-fpm'):
EEService.reload_service(self, 'php7.0-fpm')
else:
EEService.reload_service(self, 'php5-fpm')
self.app.close(0)
|
'Default function of debug'
| @expose(hide=True)
def default(self):
| self.interactive = False
self.msg = []
self.trigger_nginx = False
self.trigger_php = False
if ((not self.app.pargs.nginx) and (not self.app.pargs.php) and (not self.app.pargs.php7) and (not self.app.pargs.fpm) and (not self.app.pargs.fpm7) and (not self.app.pargs.mysql) and (not self.app.pargs.wp) and (not self.app.pargs.rewrite) and (not self.app.pargs.all) and (not self.app.pargs.site_name) and (not self.app.pargs.import_slow_log) and (not self.app.pargs.interval)):
if (self.app.pargs.stop or self.app.pargs.start):
print '--start/stop option is deprecated since ee3.0.5'
self.app.args.print_help()
else:
self.app.args.print_help()
if self.app.pargs.import_slow_log:
self.import_slow_log()
if self.app.pargs.interval:
try:
cron_time = int(self.app.pargs.interval)
except Exception as e:
cron_time = 5
try:
if (not EEShellExec.cmd_exec(self, "crontab -l | grep 'ee debug --import-slow-log'")):
if (not (cron_time == 0)):
Log.info(self, 'setting up crontab entry, please wait...')
EEShellExec.cmd_exec(self, '/bin/bash -c "crontab -l 2> /dev/null | {{ cat; echo -e \\"#EasyEngine start MySQL slow log \\n*/{0} * * * * /usr/local/bin/ee debug --import-slow-log\\n#EasyEngine end MySQL slow log\\"; }} | crontab -"'.format(cron_time))
elif (not (cron_time == 0)):
Log.info(self, 'updating crontab entry, please wait...')
if (not EEShellExec.cmd_exec(self, '/bin/bash -c "crontab -l | sed \'/EasyEngine start MySQL slow log/!b;n;c\\*\\/{0} \\* \\* \\* \\* \\/usr\\/local\\/bin\\/ee debug --import\\-slow\\-log\' | crontab -"'.format(cron_time))):
Log.error(self, 'failed to update crontab entry')
else:
Log.info(self, 'removing crontab entry, please wait...')
if (not EEShellExec.cmd_exec(self, '/bin/bash -c "crontab -l | sed \'/EasyEngine start MySQL slow log/,+2d\'| crontab -"'.format(cron_time))):
Log.error(self, 'failed to remove crontab entry')
except CommandExecutionError as e:
Log.debug(self, str(e))
if (self.app.pargs.all == 'on'):
if self.app.pargs.site_name:
self.app.pargs.wp = 'on'
self.app.pargs.nginx = 'on'
self.app.pargs.php = 'on'
self.app.pargs.fpm = 'on'
if (((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) and EEAptGet.is_installed(self, 'php7.0-fpm')):
self.app.pargs.php7 = 'on'
self.app.pargs.fpm7 = 'on'
self.app.pargs.mysql = 'on'
self.app.pargs.rewrite = 'on'
if (self.app.pargs.all == 'off'):
if self.app.pargs.site_name:
self.app.pargs.wp = 'off'
self.app.pargs.nginx = 'off'
self.app.pargs.php = 'off'
self.app.pargs.fpm = 'off'
if (((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')) and EEAptGet.is_installed(self, 'php7.0-fpm')):
self.app.pargs.php7 = 'off'
self.app.pargs.fpm7 = 'off'
self.app.pargs.mysql = 'off'
self.app.pargs.rewrite = 'off'
if ((not self.app.pargs.nginx) and (not self.app.pargs.php) and (not self.app.pargs.php7) and (not self.app.pargs.fpm) and (not self.app.pargs.fpm7) and (not self.app.pargs.mysql) and (not self.app.pargs.wp) and (not self.app.pargs.rewrite) and self.app.pargs.site_name):
self.app.args.print_help()
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.php7:
self.debug_php7()
if self.app.pargs.fpm7:
self.debug_fpm7()
if self.app.pargs.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()
if self.app.pargs.interactive:
self.interactive = True
if self.trigger_nginx:
EEService.reload_service(self, 'nginx')
if self.trigger_php:
if ((EEVariables.ee_platform_codename == 'trusty') or (EEVariables.ee_platform_codename == 'xenial')):
if EEAptGet.is_installed(self, 'php5.6-fpm'):
EEService.restart_service(self, 'php5.6-fpm')
if EEAptGet.is_installed(self, 'php7.0-fpm'):
EEService.restart_service(self, 'php7.0-fpm')
else:
EEService.restart_service(self, 'php5-fpm')
if (EEVariables.ee_platform_codename == 'jessie'):
EEService.restart_service(self, 'php7.0-fpm')
if (len(self.msg) > 0):
if (not self.app.pargs.interactive):
disp_msg = ' '.join(self.msg)
Log.info(self, (('Use following command to check debug logs:\n' + Log.ENDC) + 'tail -f {0}'.format(disp_msg)))
else:
signal.signal(signal.SIGINT, self.signal_handler)
watch_list = []
for w_list in self.msg:
watch_list = (watch_list + glob.glob(w_list))
logwatch(self, watch_list)
|
'Default function for import slow log'
| @expose(hide=True)
def import_slow_log(self):
| if os.path.isdir('{0}22222/htdocs/db/anemometer'.format(EEVariables.ee_webroot)):
if os.path.isfile('/var/log/mysql/mysql-slow.log'):
Log.info(self, 'Importing MySQL slow log to Anemometer')
host = os.popen(('grep -e "\'host\'" {0}22222/htdocs/'.format(EEVariables.ee_webroot) + "db/anemometer/conf/config.inc.php | head -1 | cut -d\\' -f4 | tr -d '\n'")).read()
user = os.popen(('grep -e "\'user\'" {0}22222/htdocs/'.format(EEVariables.ee_webroot) + "db/anemometer/conf/config.inc.php | head -1 | cut -d\\' -f4 | tr -d '\n'")).read()
password = os.popen(('grep -e "\'password\'" {0}22222/'.format(EEVariables.ee_webroot) + "htdocs/db/anemometer/conf/config.inc.php | head -1 | cut -d\\' -f4 | tr -d '\n'")).read()
try:
EEShellExec.cmd_exec(self, 'pt-query-digest --user={0} --password={1} --review D=slow_query_log,t=global_query_review --history D=slow_query_log,t=global_query_review_history --no-report --limit=0% --filter=" \\$event->{{Bytes}} = length(\\$event->{{arg}}) and \\$event->{{hostname}}=\\"{2}\\"" /var/log/mysql/mysql-slow.log'.format(user, password, host))
except CommandExecutionError as e:
Log.debug(self, str(e))
Log.error(self, 'MySQL slow log import failed.')
else:
Log.error(self, 'MySQL slow log file not found, so not imported slow logs')
else:
Log.error(self, ((((('Anemometer is not installed.' + Log.ENDC) + '\nYou can install Anemometer with this command ') + Log.BOLD) + '\n `ee stack install --utils`') + Log.ENDC))
|
'Override setup actions (for every test).'
| def setUp(self):
| super(EETestCase, self).setUp()
|
'Override teardown actions (for every test).'
| def tearDown(self):
| super(EETestCase, self).tearDown()
|
'Method called to prepare the test fixture. This is called by the
unittest framework immediately before calling the test method; any exception
raised by this method will be considered an error rather than a test
failure. The default implementation does nothing.'
| def setUp(self):
| pass
|
'Method called immediately after the test method has been called and the
result recorded. This is called even if the test method raised an exception,
so the implementation in subclasses may need to be particularly careful
about checking internal state. Any exception raised by this method will be
considered an error rather than a test failure. This method will only be
called if the setUp() succeeds, regardless of the outcome of the test
method. The default implementation does nothing.'
| def tearDown(self):
| self.resetExtraLogItems()
|
'Override to force unittest framework to use test method names instead
of docstrings in the report.'
| def shortDescription(self):
| return None
|
'Print out what test we are running'
| def _printTestHeader(self):
| print '###############################################################'
print ('Running test: %s.%s...' % (self.__class__, self._testMethodName))
|
'Put the path to our datasets int the NTA_DATA_PATH variable which
will be used to set the environment for each of the workers
Parameters:
env: The current environment dict'
| def _setDataPath(self, env):
| assert (env is not None)
if ('NTA_DATA_PATH' in env):
newPath = ('%s%s%s' % (env['NTA_DATA_PATH'], os.pathsep, g_myEnv.testSrcDataDir))
else:
newPath = g_myEnv.testSrcDataDir
env['NTA_DATA_PATH'] = newPath
|
'Launch worker processes to execute the given command line
Parameters:
cmdLine: The command line for each worker
numWorkers: number of workers to launch
retval: list of workers'
| def _launchWorkers(self, cmdLine, numWorkers):
| workers = []
for i in range(numWorkers):
stdout = tempfile.TemporaryFile()
stderr = tempfile.TemporaryFile()
p = subprocess.Popen(cmdLine, bufsize=1, env=os.environ, shell=True, stdin=None, stdout=stdout, stderr=stderr)
workers.append(p)
return workers
|
'Return the job info for a job
Parameters:
cjDAO: client jobs database instance
workers: list of workers for this job
jobID: which job ID
retval: job info'
| def _getJobInfo(self, cjDAO, workers, jobID):
| jobInfo = cjDAO.jobInfo(jobID)
runningCount = 0
for worker in workers:
retCode = worker.poll()
if (retCode is None):
runningCount += 1
if (runningCount > 0):
status = ClientJobsDAO.STATUS_RUNNING
else:
status = ClientJobsDAO.STATUS_COMPLETED
jobInfo = jobInfo._replace(status=status)
if (status == ClientJobsDAO.STATUS_COMPLETED):
jobInfo = jobInfo._replace(completionReason=ClientJobsDAO.CMPL_REASON_SUCCESS)
return jobInfo
|
'This method generates a canned Hypersearch Job Params structure based
on some high level options
Parameters:
predictionCacheMaxRecords:
If specified, determine the maximum number of records in
the prediction cache.
dataPath: When expDirectory is not specified, this is the data file
to be used for the operation. If this value is not specified,
it will use the /extra/qa/hotgym/qa_hotgym.csv.'
| def _generateHSJobParams(self, expDirectory=None, hsImp='v2', maxModels=2, predictionCacheMaxRecords=None, dataPath=None, maxRecords=10):
| if (expDirectory is not None):
descriptionPyPath = os.path.join(expDirectory, 'description.py')
permutationsPyPath = os.path.join(expDirectory, 'permutations.py')
permutationsPyContents = open(permutationsPyPath, 'r').read()
descriptionPyContents = open(descriptionPyPath, 'r').read()
jobParams = {'persistentJobGUID': generatePersistentJobGUID(), 'permutationsPyContents': permutationsPyContents, 'descriptionPyContents': descriptionPyContents, 'maxModels': maxModels, 'hsVersion': hsImp}
if (predictionCacheMaxRecords is not None):
jobParams['predictionCacheMaxRecords'] = predictionCacheMaxRecords
else:
if (dataPath is None):
dataPath = resource_filename('nupic.data', os.path.join('extra', 'qa', 'hotgym', 'qa_hotgym.csv'))
streamDef = dict(version=1, info='TestHypersearch', streams=[dict(source=('file://%s' % dataPath), info=dataPath, columns=['*'], first_record=0, last_record=maxRecords)])
expDesc = {'predictionField': 'consumption', 'streamDef': streamDef, 'includedFields': [{'fieldName': 'gym', 'fieldType': 'string'}, {'fieldName': 'consumption', 'fieldType': 'float', 'minValue': 0, 'maxValue': 200}], 'iterationCount': maxRecords, 'resetPeriod': {'weeks': 0, 'days': 0, 'hours': 8, 'minutes': 0, 'seconds': 0, 'milliseconds': 0, 'microseconds': 0}}
jobParams = {'persistentJobGUID': generatePersistentJobGUID(), 'description': expDesc, 'maxModels': maxModels, 'hsVersion': hsImp}
if (predictionCacheMaxRecords is not None):
jobParams['predictionCacheMaxRecords'] = predictionCacheMaxRecords
return jobParams
|
'This runs permutations on the given experiment using just 1 worker
in the current process
Parameters:
jobParams: filled in job params for a hypersearch
loggingLevel: logging level to use in the Hypersearch worker
env: if not None, this is a dict of environment variables
that should be sent to each worker process. These can
aid in re-using the same description/permutations file
for different tests.
waitForCompletion: If True, wait for job to complete before returning
If False, then return resultsInfoForAllModels and
metricResults will be None
continueJobId: If not None, then this is the JobId of a job we want
to continue working on with another worker.
ignoreErrModels: If true, ignore erred models
retval: (jobId, jobInfo, resultsInfoForAllModels, metricResults)'
| def _runPermutationsLocal(self, jobParams, loggingLevel=logging.INFO, env=None, waitForCompletion=True, continueJobId=None, ignoreErrModels=False):
| print
print '=================================================================='
print 'Running Hypersearch job using 1 worker in current process'
print '=================================================================='
if (env is not None):
saveEnvState = copy.deepcopy(os.environ)
os.environ.update(env)
cjDAO = ClientJobsDAO.get()
if (continueJobId is None):
jobID = cjDAO.jobInsert(client='test', cmdLine='<started manually>', params=json.dumps(jobParams), alreadyRunning=True, minimumWorkers=1, maximumWorkers=1, jobType=cjDAO.JOB_TYPE_HS)
else:
jobID = continueJobId
args = ['ignoreThis', ('--jobID=%d' % jobID), ('--logLevel=%d' % loggingLevel)]
if (continueJobId is None):
args.append('--clearModels')
try:
hypersearch_worker.main(args)
except SystemExit:
pass
except:
raise
if (env is not None):
os.environ = saveEnvState
models = cjDAO.modelsGetUpdateCounters(jobID)
modelIDs = [model.modelId for model in models]
if (len(modelIDs) > 0):
results = cjDAO.modelsGetResultAndStatus(modelIDs)
else:
results = []
metricResults = []
for result in results:
if (result.results is not None):
metricResults.append(json.loads(result.results)[1].values()[0])
else:
metricResults.append(None)
if (not ignoreErrModels):
self.assertNotEqual(result.completionReason, cjDAO.CMPL_REASON_ERROR, ('Model did not complete successfully:\n%s' % result.completionMsg))
jobInfo = cjDAO.jobInfo(jobID)
return (jobID, jobInfo, results, metricResults)
|
'Given a prepared, filled in jobParams for a hypersearch, this starts
the job, waits for it to complete, and returns the results for all
models.
Parameters:
jobParams: filled in job params for a hypersearch
loggingLevel: logging level to use in the Hypersearch worker
maxNumWorkers: max # of worker processes to use
env: if not None, this is a dict of environment variables
that should be sent to each worker process. These can
aid in re-using the same description/permutations file
for different tests.
waitForCompletion: If True, wait for job to complete before returning
If False, then return resultsInfoForAllModels and
metricResults will be None
ignoreErrModels: If true, ignore erred models
retval: (jobID, jobInfo, resultsInfoForAllModels, metricResults)'
| def _runPermutationsCluster(self, jobParams, loggingLevel=logging.INFO, maxNumWorkers=4, env=None, waitForCompletion=True, ignoreErrModels=False, timeoutSec=DEFAULT_JOB_TIMEOUT_SEC):
| print
print '=================================================================='
print 'Running Hypersearch job on cluster'
print '=================================================================='
if ((env is not None) and (len(env) > 0)):
envItems = []
for (key, value) in env.iteritems():
if sys.platform.startswith('win'):
envItems.append(('set "%s=%s"' % (key, value)))
else:
envItems.append(('export %s=%s' % (key, value)))
if sys.platform.startswith('win'):
envStr = ('%s &' % ' & '.join(envItems))
else:
envStr = ('%s;' % ';'.join(envItems))
else:
envStr = ''
cmdLine = ('%s python -m nupic.swarming.hypersearch_worker --jobID={JOBID} --logLevel=%d' % (envStr, loggingLevel))
cjDAO = ClientJobsDAO.get()
jobID = cjDAO.jobInsert(client='test', cmdLine=cmdLine, params=json.dumps(jobParams), minimumWorkers=1, maximumWorkers=maxNumWorkers, jobType=cjDAO.JOB_TYPE_HS)
workerCmdLine = ('%s python -m nupic.swarming.hypersearch_worker --jobID=%d --logLevel=%d' % (envStr, jobID, loggingLevel))
workers = self._launchWorkers(cmdLine=workerCmdLine, numWorkers=maxNumWorkers)
print ('Successfully submitted new test job, jobID=%d' % jobID)
print ('Each of %d workers executing the command line: ' % maxNumWorkers), cmdLine
if (not waitForCompletion):
return (jobID, None, None)
if (timeoutSec is None):
timeout = DEFAULT_JOB_TIMEOUT_SEC
else:
timeout = timeoutSec
startTime = time.time()
lastUpdate = time.time()
lastCompleted = 0
lastCompletedWithError = 0
lastCompletedAsOrphan = 0
lastStarted = 0
lastJobStatus = 'NA'
lastJobResults = None
lastActiveSwarms = None
lastEngStatus = None
modelIDs = []
print ('\n%-15s %-15s %-15s %-15s %-15s' % ('jobStatus', 'modelsStarted', 'modelsCompleted', 'modelErrs', 'modelOrphans'))
print '-------------------------------------------------------------------'
while ((lastJobStatus != ClientJobsDAO.STATUS_COMPLETED) and ((time.time() - lastUpdate) < timeout)):
printUpdate = False
if (g_myEnv.options.verbosity == 0):
time.sleep(0.5)
jobInfo = self._getJobInfo(cjDAO, workers, jobID)
if (jobInfo.status != lastJobStatus):
if ((jobInfo.status == ClientJobsDAO.STATUS_RUNNING) and (lastJobStatus != ClientJobsDAO.STATUS_RUNNING)):
print ('# Swarm job now running. jobID=%s' % jobInfo.jobId)
lastJobStatus = jobInfo.status
printUpdate = True
if (g_myEnv.options.verbosity >= 1):
if (jobInfo.engWorkerState is not None):
activeSwarms = json.loads(jobInfo.engWorkerState)['activeSwarms']
if (activeSwarms != lastActiveSwarms):
print '>> Active swarms:\n ', '\n '.join(activeSwarms)
lastActiveSwarms = activeSwarms
print
if (jobInfo.results != lastJobResults):
print '>> New best:', jobInfo.results, '###'
lastJobResults = jobInfo.results
if (jobInfo.engStatus != lastEngStatus):
print ('>> Status: "%s"' % jobInfo.engStatus)
print
lastEngStatus = jobInfo.engStatus
modelCounters = cjDAO.modelsGetUpdateCounters(jobID)
if (len(modelCounters) != lastStarted):
modelIDs = [x.modelId for x in modelCounters]
lastStarted = len(modelCounters)
printUpdate = True
if (len(modelIDs) > 0):
completed = 0
completedWithError = 0
completedAsOrphan = 0
infos = cjDAO.modelsGetResultAndStatus(modelIDs)
for info in infos:
if (info.status == ClientJobsDAO.STATUS_COMPLETED):
completed += 1
if (info.completionReason == ClientJobsDAO.CMPL_REASON_ERROR):
completedWithError += 1
if (info.completionReason == ClientJobsDAO.CMPL_REASON_ORPHAN):
completedAsOrphan += 1
if ((completed != lastCompleted) or (completedWithError != lastCompletedWithError) or (completedAsOrphan != lastCompletedAsOrphan)):
lastCompleted = completed
lastCompletedWithError = completedWithError
lastCompletedAsOrphan = completedAsOrphan
printUpdate = True
if printUpdate:
lastUpdate = time.time()
if (g_myEnv.options.verbosity >= 1):
print '>>',
print ('%-15s %-15d %-15d %-15d %-15d' % (lastJobStatus, lastStarted, lastCompleted, lastCompletedWithError, lastCompletedAsOrphan))
print ('\n<< %-15s %-15d %-15d %-15d %-15d' % (lastJobStatus, lastStarted, lastCompleted, lastCompletedWithError, lastCompletedAsOrphan))
jobInfo = self._getJobInfo(cjDAO, workers, jobID)
if (not ignoreErrModels):
self.assertEqual(jobInfo.completionReason, ClientJobsDAO.CMPL_REASON_SUCCESS)
models = cjDAO.modelsGetUpdateCounters(jobID)
modelIDs = [model.modelId for model in models]
if (len(modelIDs) > 0):
results = cjDAO.modelsGetResultAndStatus(modelIDs)
else:
results = []
metricResults = []
for result in results:
if (result.results is not None):
metricResults.append(json.loads(result.results)[1].values()[0])
else:
metricResults.append(None)
if (not ignoreErrModels):
self.assertNotEqual(result.completionReason, cjDAO.CMPL_REASON_ERROR, ('Model did not complete successfully:\n%s' % result.completionMsg))
return (jobID, jobInfo, results, metricResults)
|
'This runs permutations on the given experiment using just 1 worker
Parameters:
expDirectory: directory containing the description.py and permutations.py
hsImp: which implementation of Hypersearch to use
maxModels: max # of models to generate
maxNumWorkers: max # of workers to use, N/A if onCluster is False
loggingLevel: logging level to use in the Hypersearch worker
onCluster: if True, run on the Hadoop cluster
env: if not None, this is a dict of environment variables
that should be sent to each worker process. These can
aid in re-using the same description/permutations file
for different tests.
waitForCompletion: If True, wait for job to complete before returning
If False, then return resultsInfoForAllModels and
metricResults will be None
continueJobId: If not None, then this is the JobId of a job we want
to continue working on with another worker.
ignoreErrModels: If true, ignore erred models
maxRecords: This value is passed to the function, _generateHSJobParams(),
to represent the maximum number of records to generate for
the operation.
dataPath: This value is passed to the function, _generateHSJobParams(),
which points to the data file for the operation.
predictionCacheMaxRecords:
If specified, determine the maximum number of records in
the prediction cache.
retval: (jobID, jobInfo, resultsInfoForAllModels, metricResults,
minErrScore)'
| def runPermutations(self, expDirectory, hsImp='v2', maxModels=2, maxNumWorkers=4, loggingLevel=logging.INFO, onCluster=False, env=None, waitForCompletion=True, continueJobId=None, dataPath=None, maxRecords=None, timeoutSec=None, ignoreErrModels=False, predictionCacheMaxRecords=None, **kwargs):
| if (env is None):
env = dict()
self._setDataPath(env)
jobParams = self._generateHSJobParams(expDirectory=expDirectory, hsImp=hsImp, maxModels=maxModels, maxRecords=maxRecords, dataPath=dataPath, predictionCacheMaxRecords=predictionCacheMaxRecords)
jobParams.update(kwargs)
if onCluster:
(jobID, jobInfo, resultInfos, metricResults) = self._runPermutationsCluster(jobParams=jobParams, loggingLevel=loggingLevel, maxNumWorkers=maxNumWorkers, env=env, waitForCompletion=waitForCompletion, ignoreErrModels=ignoreErrModels, timeoutSec=timeoutSec)
else:
(jobID, jobInfo, resultInfos, metricResults) = self._runPermutationsLocal(jobParams=jobParams, loggingLevel=loggingLevel, env=env, waitForCompletion=waitForCompletion, continueJobId=continueJobId, ignoreErrModels=ignoreErrModels)
if (not waitForCompletion):
return (jobID, jobInfo, resultInfos, metricResults, None)
print '\n------------------------------------------------------------------'
print ('Hadoop completion reason: %s' % jobInfo.completionReason)
print ('Worker completion reason: %s' % jobInfo.workerCompletionReason)
print ('Worker completion msg: %s' % jobInfo.workerCompletionMsg)
if (jobInfo.engWorkerState is not None):
print '\nEngine worker state:'
print '---------------------------------------------------------------'
pprint.pprint(json.loads(jobInfo.engWorkerState))
minErrScore = None
metricAmts = []
for result in metricResults:
if (result is None):
metricAmts.append(numpy.inf)
else:
metricAmts.append(result)
metricAmts = numpy.array(metricAmts)
if (len(metricAmts) > 0):
minErrScore = metricAmts.min()
minModelID = resultInfos[metricAmts.argmin()].modelId
cjDAO = ClientJobsDAO.get()
modelParams = cjDAO.modelsGetParams([minModelID])[0].params
print ('Model params for best model: \n%s' % pprint.pformat(json.loads(modelParams)))
print ('Best model result: %f' % minErrScore)
else:
print 'No models finished'
return (jobID, jobInfo, resultInfos, metricResults, minErrScore)
|
'Try running simple permutations'
| def testSimpleV2(self, onCluster=False, env=None, **kwargs):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
if (env is None):
env = dict()
env['NTA_TEST_numIterations'] = '99'
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, **kwargs)
self.assertEqual(minErrScore, 20)
self.assertLess(len(resultInfos), 350)
return
|
'Try running a simple permutations with delta encoder
Test which tests the delta encoder. Runs a swarm of the sawtooth dataset
With a functioning delta encoder this should give a perfect result
DEBUG: disabled temporarily because this test takes too long!!!'
| def testDeltaV2(self, onCluster=False, env=None, **kwargs):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'delta')
if (env is None):
env = dict()
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
env['NTA_TEST_exitAfterNModels'] = str(20)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, **kwargs)
self.assertLess(minErrScore, 0.002)
return
|
'Try running a simple permutations'
| def testSimpleV2NoSpeculation(self, onCluster=False, env=None, **kwargs):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
if (env is None):
env = dict()
env['NTA_TEST_numIterations'] = '99'
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, speculativeParticles=False, **kwargs)
self.assertEqual(minErrScore, 20)
self.assertGreater(len(resultInfos), 1)
self.assertLess(len(resultInfos), 350)
return
|
'Try running a simple permutations using an actual CLA model, not
a dummy'
| def testHTMPredictionModelV2(self, onCluster=False, env=None, maxModels=2, **kwargs):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'dummyV2')
if (env is None):
env = dict()
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=maxModels, **kwargs)
self.assertEqual(len(resultInfos), maxModels)
return
|
'Try running a simple permutations using an actual CLA model, not
a dummy'
| def testCLAMultistepModel(self, onCluster=False, env=None, maxModels=2, **kwargs):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simple_cla_multistep')
if (env is None):
env = dict()
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=maxModels, **kwargs)
self.assertEqual(len(resultInfos), maxModels)
return
|
'Try running a simple permutations using an actual CLA model, not
a dummy. This is a legacy CLA multi-step model that doesn\'t declare a
separate \'classifierOnly\' encoder for the predicted field.'
| def testLegacyCLAMultistepModel(self, onCluster=False, env=None, maxModels=2, **kwargs):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'legacy_cla_multistep')
if (env is None):
env = dict()
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=maxModels, **kwargs)
self.assertEqual(len(resultInfos), maxModels)
return
|
'Try running a simple permutations'
| def testFilterV2(self, onCluster=False):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
env = dict()
env['NTA_TEST_maxvalFilter'] = '225'
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = '6'
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None)
self.assertEqual(minErrScore, 45)
self.assertLess(len(resultInfos), 400)
return
|
'Try running a simple permutations where a worker comes in late,
after the some models have already been evaluated'
| def testLateWorker(self, onCluster=False):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
env = dict()
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
env['NTA_TEST_exitAfterNModels'] = '100'
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, maxModels=None, onCluster=onCluster, env=env, waitForCompletion=True)
self.assertEqual(len(resultInfos), 100)
env.pop('NTA_TEST_exitAfterNModels')
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, maxModels=None, onCluster=onCluster, env=env, waitForCompletion=True, continueJobId=jobID)
self.assertEqual(minErrScore, 20)
self.assertLess(len(resultInfos), 350)
return
|
'Run a worker on a model for a while, then have it exit before the
model finishes. Then, run another worker, which should detect the orphaned
model.'
| def testOrphanedModel(self, onCluster=False, modelRange=(0, 1)):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
env = dict()
env['NTA_TEST_numIterations'] = '2'
env['NTA_TEST_sysExitModelRange'] = ('%d,%d' % (modelRange[0], modelRange[1]))
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, maxModels=300, onCluster=onCluster, env=env, waitForCompletion=False)
(beg, end) = modelRange
self.assertEqual(len(resultInfos), end)
numRunning = 0
for res in resultInfos:
if (res.status == ClientJobsDAO.STATUS_RUNNING):
numRunning += 1
self.assertEqual(numRunning, 1)
env['NTA_CONF_PROP_nupic_hypersearch_modelOrphanIntervalSecs'] = '1'
time.sleep(2)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, maxModels=300, onCluster=onCluster, env=env, waitForCompletion=True, continueJobId=jobID)
self.assertEqual(minErrScore, 20)
self.assertLess(len(resultInfos), 350)
return
|
'Run a worker on a model for a while, then have it exit before a
model finishes in gen index 2. Then, run another worker, which should detect
the orphaned model.'
| def testOrphanedModelGen1(self):
| self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testOrphanedModel(modelRange=(10, 11))
|
'Run with 1 or more models generating errors'
| def testErredModel(self, onCluster=False, modelRange=(6, 7)):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
env = dict()
env['NTA_TEST_errModelRange'] = ('%d,%d' % (modelRange[0], modelRange[1]))
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, ignoreErrModels=True)
self.assertEqual(minErrScore, 20)
self.assertLess(len(resultInfos), 350)
return
|
'Run with 1 or more models generating jobFail exception'
| def testJobFailModel(self, onCluster=False, modelRange=(6, 7)):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
env = dict()
env['NTA_TEST_jobFailErr'] = 'True'
maxNumWorkers = 4
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, maxNumWorkers=maxNumWorkers, ignoreErrModels=True)
self.assertEqual(jobInfo.workerCompletionReason, ClientJobsDAO.CMPL_REASON_ERROR)
self.assertLess(len(resultInfos), (maxNumWorkers + 1))
return
|
'Run with too many models generating errors'
| def testTooManyErredModels(self, onCluster=False, modelRange=(5, 10)):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'simpleV2')
env = dict()
env['NTA_TEST_errModelRange'] = ('%d,%d' % (modelRange[0], modelRange[1]))
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, ignoreErrModels=True)
self.assertEqual(jobInfo.workerCompletionReason, ClientJobsDAO.CMPL_REASON_ERROR)
return
|
'Test minimum field contribution threshold for a field to be included in further sprints'
| def testFieldThreshold(self, onCluster=False, env=None, **kwargs):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'field_threshold_temporal')
if (env is None):
env = dict()
env['NTA_TEST_numIterations'] = '99'
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
env['NTA_CONF_PROP_nupic_hypersearch_max_field_branching'] = ('%d' % 0)
env['NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm'] = ('%d' % 2)
env['NTA_CONF_PROP_nupic_hypersearch_min_field_contribution'] = ('%f' % 100)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, dummyModel={'iterations': 200}, **kwargs)
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults['bestModel']])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = (prefix + ('.' + prefix).join(['attendance', 'visitor_winloss']))
self.assertEqual(params['particleState']['swarmId'], expectedSwarmId, ('Actual swarm id = %s\nExpcted swarm id = %s' % (params['particleState']['swarmId'], expectedSwarmId)))
self.assertEqual(bestModel.optimizedMetric, 75)
env['NTA_CONF_PROP_nupic_hypersearch_min_field_contribution'] = ('%f' % 20)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, dummyModel={'iterations': 200}, **kwargs)
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults['bestModel']])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = (prefix + ('.' + prefix).join(['attendance', 'home_winloss', 'visitor_winloss']))
self.assertEqual(params['particleState']['swarmId'], expectedSwarmId, ('Actual swarm id = %s\nExpcted swarm id = %s' % (params['particleState']['swarmId'], expectedSwarmId)))
assert (bestModel.optimizedMetric == 55), bestModel.optimizedMetric
env['NTA_CONF_PROP_nupic_hypersearch_min_field_contribution'] = ('%f' % 0.0)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, dummyModel={'iterations': 200}, **kwargs)
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults['bestModel']])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = (prefix + ('.' + prefix).join(['attendance', 'home_winloss', 'precip', 'timestamp_dayOfWeek', 'timestamp_timeOfDay', 'visitor_winloss']))
self.assertEqual(params['particleState']['swarmId'], expectedSwarmId, ('Actual swarm id = %s\nExpcted swarm id = %s' % (params['particleState']['swarmId'], expectedSwarmId)))
assert (bestModel.optimizedMetric == 25), bestModel.optimizedMetric
|
'Try running a spatial classification swarm'
| def testSpatialClassification(self, onCluster=False, env=None, **kwargs):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'spatial_classification')
if (env is None):
env = dict()
env['NTA_TEST_numIterations'] = '99'
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, **kwargs)
self.assertEqual(minErrScore, 20)
self.assertLess(len(resultInfos), 350)
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults['bestModel']])[0]
params = json.loads(bestModel.params)
actualFieldContributions = jobResults['fieldContributions']
print 'Actual field contributions:', pprint.pformat(actualFieldContributions)
expectedFieldContributions = {'address': ((100 * (90.0 - 30)) / 90.0), 'gym': ((100 * (90.0 - 40)) / 90.0), 'timestamp_dayOfWeek': ((100 * (90.0 - 80.0)) / 90.0), 'timestamp_timeOfDay': ((100 * (90.0 - 90.0)) / 90.0)}
for (key, value) in expectedFieldContributions.items():
self.assertEqual(actualFieldContributions[key], value, ("actual field contribution from field '%s' does not match the expected value of %f" % (key, value)))
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = (prefix + ('.' + prefix).join(['address', 'gym']))
self.assertEqual(params['particleState']['swarmId'], expectedSwarmId, ('Actual swarm id = %s\nExpcted swarm id = %s' % (params['particleState']['swarmId'], expectedSwarmId)))
return
|
'Run a swarm where \'inputPredictedField\' is set in the permutations
file. The dummy model for this swarm is designed to give the lowest
error when the predicted field is INCLUDED, so make sure we don\'t get
this low error'
| def testAlwaysInputPredictedField(self, onCluster=False, env=None, **kwargs):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'input_predicted_field')
if (env is None):
env = dict()
env['NTA_TEST_inputPredictedField'] = 'auto'
env['NTA_TEST_numIterations'] = '99'
env['NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm'] = ('%d' % 2)
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, **kwargs)
self.assertEqual(minErrScore, (-50))
self.assertLess(len(resultInfos), 350)
if (env is None):
env = dict()
env['NTA_TEST_inputPredictedField'] = 'yes'
env['NTA_TEST_numIterations'] = '99'
env['NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm'] = ('%d' % 2)
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, **kwargs)
self.assertEqual(minErrScore, (-40))
self.assertLess(len(resultInfos), 350)
return
|
'Test minimum field contribution threshold for a field to be included
in further sprints when doing a temporal search that does not require
the predicted field.'
| def testFieldThresholdNoPredField(self, onCluster=False, env=None, **kwargs):
| self._printTestHeader()
expDir = os.path.join(g_myEnv.testSrcExpDir, 'input_predicted_field')
if (env is None):
env = dict()
env['NTA_TEST_numIterations'] = '99'
env['NTA_TEST_inputPredictedField'] = 'auto'
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
env['NTA_CONF_PROP_nupic_hypersearch_max_field_branching'] = ('%d' % 0)
env['NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm'] = ('%d' % 2)
env['NTA_CONF_PROP_nupic_hypersearch_min_field_contribution'] = ('%f' % 0)
if True:
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, dummyModel={'iterations': 200}, **kwargs)
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults['bestModel']])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = (prefix + ('.' + prefix).join(['address', 'gym', 'timestamp_dayOfWeek', 'timestamp_timeOfDay']))
self.assertEqual(params['particleState']['swarmId'], expectedSwarmId, ('Actual swarm id = %s\nExpcted swarm id = %s' % (params['particleState']['swarmId'], expectedSwarmId)))
self.assertEqual(bestModel.optimizedMetric, (-50))
actualFieldContributions = jobResults['fieldContributions']
print 'Actual field contributions:', pprint.pformat(actualFieldContributions)
expectedFieldContributions = {'consumption': 0.0, 'address': ((100 * (60.0 - 40.0)) / 60.0), 'timestamp_timeOfDay': ((100 * (60.0 - 20.0)) / 60.0), 'timestamp_dayOfWeek': ((100 * (60.0 - 10.0)) / 60.0), 'gym': ((100 * (60.0 - 30.0)) / 60.0)}
for (key, value) in expectedFieldContributions.items():
self.assertEqual(actualFieldContributions[key], value, ("actual field contribution from field '%s' does not match the expected value of %f" % (key, value)))
if True:
env['NTA_CONF_PROP_nupic_hypersearch_min_field_contribution'] = ('%f' % 55)
env['NTA_CONF_PROP_nupic_hypersearch_max_field_branching'] = ('%d' % 5)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, dummyModel={'iterations': 200}, **kwargs)
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults['bestModel']])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = (prefix + ('.' + prefix).join(['timestamp_dayOfWeek', 'timestamp_timeOfDay']))
self.assertEqual(params['particleState']['swarmId'], expectedSwarmId, ('Actual swarm id = %s\nExpcted swarm id = %s' % (params['particleState']['swarmId'], expectedSwarmId)))
self.assertEqual(bestModel.optimizedMetric, (-20))
actualFieldContributions = jobResults['fieldContributions']
print 'Actual field contributions:', pprint.pformat(actualFieldContributions)
expectedFieldContributions = {'consumption': 0.0, 'address': ((100 * (60.0 - 40.0)) / 60.0), 'timestamp_timeOfDay': ((100 * (60.0 - 20.0)) / 60.0), 'timestamp_dayOfWeek': ((100 * (60.0 - 10.0)) / 60.0), 'gym': ((100 * (60.0 - 30.0)) / 60.0)}
for (key, value) in expectedFieldContributions.items():
self.assertEqual(actualFieldContributions[key], value, ("actual field contribution from field '%s' does not match the expected value of %f" % (key, value)))
if True:
env['NTA_CONF_PROP_nupic_hypersearch_min_field_contribution'] = ('%f' % 0)
env['NTA_CONF_PROP_nupic_hypersearch_max_field_branching'] = ('%d' % 3)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=None, dummyModel={'iterations': 200}, **kwargs)
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults['bestModel']])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = (prefix + ('.' + prefix).join(['gym', 'timestamp_dayOfWeek', 'timestamp_timeOfDay']))
self.assertEqual(params['particleState']['swarmId'], expectedSwarmId, ('Actual swarm id = %s\nExpcted swarm id = %s' % (params['particleState']['swarmId'], expectedSwarmId)))
self.assertEqual(bestModel.optimizedMetric, (-40))
if True:
env['NTA_CONF_PROP_nupic_hypersearch_swarmMaturityWindow'] = ('%d' % g_repeatableSwarmMaturityWindow)
env['NTA_CONF_PROP_nupic_hypersearch_max_field_branching'] = ('%d' % 0)
env['NTA_CONF_PROP_nupic_hypersearch_minParticlesPerSwarm'] = ('%d' % 5)
env['NTA_CONF_PROP_nupic_hypersearch_min_field_contribution'] = ('%f' % 0)
(jobID, jobInfo, resultInfos, metricResults, minErrScore) = self.runPermutations(expDir, hsImp='v2', loggingLevel=g_myEnv.options.logLevel, onCluster=onCluster, env=env, maxModels=10, dummyModel={'iterations': 200}, **kwargs)
cjDAO = ClientJobsDAO.get()
jobResultsStr = cjDAO.jobGetFields(jobID, ['results'])[0]
jobResults = json.loads(jobResultsStr)
bestModel = cjDAO.modelsInfo([jobResults['bestModel']])[0]
params = json.loads(bestModel.params)
prefix = 'modelParams|sensorParams|encoders|'
expectedSwarmId = (prefix + ('.' + prefix).join(['timestamp_dayOfWeek']))
self.assertEqual(params['particleState']['swarmId'], expectedSwarmId, ('Actual swarm id = %s\nExpcted swarm id = %s' % (params['particleState']['swarmId'], expectedSwarmId)))
self.assertEqual(bestModel.optimizedMetric, 10)
actualFieldContributions = jobResults['fieldContributions']
print 'Actual field contributions:', pprint.pformat(actualFieldContributions)
expectedFieldContributions = {'consumption': 0.0, 'address': ((100 * (60.0 - 40.0)) / 60.0), 'timestamp_timeOfDay': ((100 * (60.0 - 20.0)) / 60.0), 'timestamp_dayOfWeek': ((100 * (60.0 - 10.0)) / 60.0), 'gym': ((100 * (60.0 - 30.0)) / 60.0)}
|
'Try running a simple permutations'
| def testSimpleV2(self):
| self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testSimpleV2(onCluster=True)
|
'Try running a simple permutations'
| def testDeltaV2(self):
| self._printTestHeader()
inst = OneNodeTests(self._testMethodName)
return inst.testDeltaV2(onCluster=True)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.