Example #1
0
 def clean_fastcgi(self):
     """This function clears Fastcgi cache"""
     if (os.path.isdir("/var/run/nginx-cache")):
         Log.info(self, "Cleaning NGINX FastCGI cache")
         EEShellExec.cmd_exec(self, "rm -rf /var/run/nginx-cache/*")
     else:
         Log.error(self, "Unable to clean FastCGI cache", False)
Example #2
0
 def secure_port(self):
     """This function Secures port"""
     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 spdy;/\" "
                              "/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;/\" "
                              "/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))
Example #3
0
 def clean_pagespeed(self):
     """This function clears Pagespeed cache"""
     if(os.path.isdir("/var/ngx_pagespeed_cache")):
         Log.info(self, "Cleaning PageSpeed cache")
         EEShellExec.cmd_exec(self, "rm -rf /var/ngx_pagespeed_cache/*")
     else:
         Log.error(self, "Unable to clean Pagespeed cache")
Example #4
0
 def clean_redis(self):
     """This function clears Redis cache"""
     if (EEAptGet.is_installed(self, "redis-server")):
         Log.info(self, "Cleaning Redis cache")
         EEShellExec.cmd_exec(self, "redis-cli flushall")
     else:
         Log.info(self, "Redis is not installed")
Example #5
0
 def clean_pagespeed(self):
     """This function clears Pagespeed cache"""
     if (os.path.isdir("/var/ngx_pagespeed_cache")):
         Log.info(self, "Cleaning PageSpeed cache")
         EEShellExec.cmd_exec(self, "rm -rf /var/ngx_pagespeed_cache/*")
     else:
         Log.error(self, "Unable to clean Pagespeed cache")
Example #6
0
 def clean_redis(self):
     """This function clears Redis cache"""
     if(EEAptGet.is_installed(self, "redis-server")):
         Log.info(self, "Cleaning Redis cache")
         EEShellExec.cmd_exec(self, "redis-cli flushall")
     else:
         Log.info(self, "Redis is not installed")
Example #7
0
    def secure_port(self):
        """This function Secures port"""
        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 spdy;/\" "
                "/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;/\" "
                "/etc/nginx/sites-available/22222".format(
                    port=self.app.pargs.user_input))
        EEGit.add(self, ["/etc/nginx"],
                  msg="Adding changed secure port into Git")

        Log.info(
            self, "Successfully port changed {port}".format(
                port=self.app.pargs.user_input))
Example #8
0
 def clean_fastcgi(self):
     """This function clears Fastcgi cache"""
     if(os.path.isdir("/var/run/nginx-cache")):
         Log.info(self, "Cleaning NGINX FastCGI cache")
         EEShellExec.cmd_exec(self, "rm -rf /var/run/nginx-cache/*")
     else:
         Log.error(self, "Unable to clean FastCGI cache", False)
Example #9
0
 def secure_auth(self):
     """This function Secures authentication"""
     passwd = ''.join([
         random.choice(string.ascii_letters + string.digits)
         for n in range(6)
     ])
     if not self.app.pargs.user_input:
         username = input("Provide HTTP authentication user "
                          "name [{0}] :".format(EEVariables.ee_user))
         self.app.pargs.user_input = username
         if username == "":
             self.app.pargs.user_input = EEVariables.ee_user
     if not self.app.pargs.user_pass:
         password = getpass.getpass("Provide HTTP authentication "
                                    "password [{0}] :".format(passwd))
         self.app.pargs.user_pass = password
         if password == "":
             self.app.pargs.user_pass = passwd
     Log.debug(
         self, "printf username:"******"$(openssl passwd -crypt "
         "password 2> /dev/null)\n\""
         "> /etc/nginx/htpasswd-ee 2>/dev/null")
     EEShellExec.cmd_exec(self,
                          "printf \"{username}:"
                          "$(openssl passwd -crypt "
                          "{password} 2> /dev/null)\n\""
                          "> /etc/nginx/htpasswd-ee 2>/dev/null".format(
                              username=self.app.pargs.user_input,
                              password=self.app.pargs.user_pass),
                          log=False)
     EEGit.add(self, ["/etc/nginx"],
               msg="Adding changed secure auth into Git")
Example #10
0
 def secure_auth(self):
     """This function Secures authentication"""
     passwd = ''.join([random.choice
                      (string.ascii_letters + string.digits)
                      for n in range(6)])
     if not self.app.pargs.user_input:
         username = input("Provide HTTP authentication user "
                          "name [{0}] :".format(EEVariables.ee_user))
         self.app.pargs.user_input = username
         if username == "":
             self.app.pargs.user_input = EEVariables.ee_user
     if not self.app.pargs.user_pass:
         password = getpass.getpass("Provide HTTP authentication "
                                    "password [{0}] :".format(passwd))
         self.app.pargs.user_pass = password
         if password == "":
             self.app.pargs.user_pass = passwd
     Log.debug(self, "printf username:"******"$(openssl passwd -crypt "
               "password 2> /dev/null)\n\""
               "> /etc/nginx/htpasswd-ee 2>/dev/null")
     EEShellExec.cmd_exec(self, "printf \"{username}:"
                          "$(openssl passwd -crypt "
                          "{password} 2> /dev/null)\n\""
                          "> /etc/nginx/htpasswd-ee 2>/dev/null"
                          .format(username=self.app.pargs.user_input,
                                  password=self.app.pargs.user_pass),
                          log=False)
     EEGit.add(self, ["/etc/nginx"],
               msg="Adding changed secure auth into Git")
Example #11
0
    def remove(self, ppa=None, repo_url=None):
        """
        This function used to remove ppa's
        If ppa is provided adds repo file to
            /etc/apt/sources.list.d/
        command.
        """
        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")
Example #12
0
def sitebackup(self, data):
    ee_site_webroot = data['webroot']
    backup_path = ee_site_webroot + '/backup/{0}'.format(EEVariables.ee_date)
    if not EEFileUtils.isexist(self, backup_path):
        EEFileUtils.mkdir(self, backup_path)
    Log.info(self, "Backup location : {0}".format(backup_path))
    EEFileUtils.copyfile(
        self, '/etc/nginx/sites-available/{0}'.format(data['site_name']),
        backup_path)

    if data['currsitetype'] in ['html', 'php', 'mysql']:
        Log.info(self, "Backing up Webroot \t\t", end='')
        EEFileUtils.mvfile(self, ee_site_webroot + '/htdocs', backup_path)
        Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]")

    configfiles = glob.glob(ee_site_webroot + '/*-config.php')

    if configfiles and EEFileUtils.isexist(self, configfiles[0]):
        ee_db_name = (EEFileUtils.grep(
            self, configfiles[0],
            'DB_NAME').split(',')[1].split(')')[0].strip().replace('\'', ''))
        Log.info(self, 'Backing up database \t\t', end='')
        EEShellExec.cmd_exec(self,
                             "mysqldump {0} > {1}/{0}.sql".format(
                                 ee_db_name, backup_path),
                             errormsg="\nFailed: Backup Database")
        Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]")
        # move wp-config.php/ee-config.php to backup
        if data['currsitetype'] in ['mysql']:
            EEFileUtils.mvfile(self, configfiles[0], backup_path)
        else:
            EEFileUtils.copyfile(self, configfiles[0], backup_path)
Example #13
0
def site_package_check(self, stype):
    apt_packages = []
    packages = []
    stack = EEStackController()
    stack.app = self.app
    if stype in ['html', 'php', 'mysql', 'wp', 'wpsubdir', 'wpsubdomain']:
        Log.debug(self, "Setting apt_packages variable for Nginx")
        if not EEAptGet.is_installed(self, 'nginx-common'):
            apt_packages = apt_packages + EEVariables.ee_nginx

    if stype in ['php', 'mysql', 'wp', 'wpsubdir', 'wpsubdomain']:
        Log.debug(self, "Setting apt_packages variable for PHP")
        if not EEAptGet.is_installed(self, 'php5-fpm'):
            apt_packages = apt_packages + EEVariables.ee_php

    if stype in ['mysql', 'wp', 'wpsubdir', 'wpsubdomain']:
        Log.debug(self, "Setting apt_packages variable for MySQL")
        if not EEShellExec.cmd_exec(self, "mysqladmin ping"):
            apt_packages = apt_packages + EEVariables.ee_mysql

    if stype in ['php', 'mysql', 'wp', 'wpsubdir', 'wpsubdomain']:
        Log.debug(self, "Setting apt_packages variable for Postfix")
        if not EEAptGet.is_installed(self, 'postfix'):
            apt_packages = apt_packages + EEVariables.ee_postfix

    if stype in ['wp', 'wpsubdir', 'wpsubdomain']:
        Log.debug(self, "Setting packages variable for WP-CLI")
        if not EEShellExec.cmd_exec(self, "which wp"):
            packages = packages + [["https://github.com/wp-cli/wp-cli/"
                                    "releases/download/v{0}/"
                                    "wp-cli-{0}.phar"
                                    .format(EEVariables.ee_wp_cli),
                                    "/usr/bin/wp", "WP-CLI"]]
    return(stack.install(apt_packages=apt_packages, packages=packages,
                         disp_msg=False))
Example #14
0
def sitebackup(self, data):
    ee_site_webroot = data['webroot']
    backup_path = ee_site_webroot + '/backup/{0}'.format(EEVariables.ee_date)
    if not EEFileUtils.isexist(self, backup_path):
        EEFileUtils.mkdir(self, backup_path)
    Log.info(self, "Backup location : {0}".format(backup_path))
    EEFileUtils.copyfile(self, '/etc/nginx/sites-available/{0}'
                         .format(data['site_name']), backup_path)

    if data['currsitetype'] in ['html', 'php', 'mysql']:
        Log.info(self, "Backing up Webroot \t\t", end='')
        EEFileUtils.mvfile(self, ee_site_webroot + '/htdocs', backup_path)
        Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]")

    configfiles = glob.glob(ee_site_webroot + '/*-config.php')

    if configfiles and EEFileUtils.isexist(self, configfiles[0]):
        ee_db_name = (EEFileUtils.grep(self, configfiles[0],
                      'DB_NAME').split(',')[1]
                      .split(')')[0].strip().replace('\'', ''))
        Log.info(self, 'Backing up database \t\t', end='')
        EEShellExec.cmd_exec(self, "mysqldump {0} > {1}/{0}.sql"
                             .format(ee_db_name, backup_path),
                             errormsg="\nFailed: Backup Database")
        Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]")
        # move wp-config.php/ee-config.php to backup
        if data['currsitetype'] in ['mysql']:
            EEFileUtils.mvfile(self, configfiles[0], backup_path)
        else:
            EEFileUtils.copyfile(self, configfiles[0], backup_path)
Example #15
0
    def getExpirationDays(self, domain, returnonerror=False):
        # check if exist
        if not os.path.isfile(
                '/etc/letsencrypt/live/{0}/cert.pem'.format(domain)):
            Log.error(
                self,
                'File Not Found : /etc/letsencrypt/live/{0}/cert.pem'.format(
                    domain), False)
            if returnonerror:
                return -1
            Log.error(
                self, "Check logs for reason "
                "`tail /var/log/ee/ee.log` & Try Again!!!")

        current_date = EEShellExec.cmd_exec_stdout(self, "date -d \"now\" +%s")
        expiration_date = EEShellExec.cmd_exec_stdout(
            self,
            "date -d \"`openssl x509 -in /etc/letsencrypt/live/{0}/cert.pem"
            " -text -noout|grep \"Not After\"|cut -c 25-`\" +%s".format(
                domain))

        days_left = int((int(expiration_date) - int(current_date)) / 86400)
        if (days_left > 0):
            return days_left
        else:
            # return "Certificate Already Expired ! Please Renew soon."
            return -1
Example #16
0
 def secure_port(self):
     """This function Secures port"""
     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,http2=("http2" if
                                                        EEAptGet.is_installed(self,'nginx-mainline') else "spdy")))
     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,http2=("http2" if
                                                        EEAptGet.is_installed(self,'nginx-mainline') else "spdy")))
     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))
Example #17
0
def uninstallwp_plugin(self, plugin_name, data):
    ee_site_webroot = data['webroot']
    Log.debug(self, "Uninstalling plugin {0}".format(plugin_name))
    EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot))
    EEShellExec.cmd_exec(self, "php /usr/bin/wp plugin --allow-root uninstall "
                         "{0}".format(plugin_name),
                         errormsg="Unable to UnInstall plugin {0}"
                         .format(plugin_name))
Example #18
0
    def migrate_mariadb(self):
        # Backup all database
        EEMysql.backupAll(self)

        # Add MariaDB repo
        Log.info(self, "Adding repository for MariaDB, please wait ...")

        mysql_pref = ("Package: *\nPin: origin mirror.aarnet.edu.au"
                      "\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))
        EERepo.add_key(self, '0xcbcb082a1bb943db',
                       keyserver="keyserver.ubuntu.com")

        config = configparser.ConfigParser()
        config.read(os.path.expanduser("~")+'/.my.cnf')
        try:
            chars = config['client']['password']
        except Exception as e:
            Log.error(self, "Error: process exited with error %s"
                            % e)

        Log.debug(self, "Pre-seeding MariaDB")
        Log.debug(self, "echo \"mariadb-server-10.0 "
                        "mysql-server/root_password "
                        "password \" | "
                        "debconf-set-selections")
        EEShellExec.cmd_exec(self, "echo \"mariadb-server-10.0 "
                                   "mysql-server/root_password "
                                   "password {chars}\" | "
                                   "debconf-set-selections"
                                   .format(chars=chars),
                                   log=False)
        Log.debug(self, "echo \"mariadb-server-10.0 "
                        "mysql-server/root_password_again "
                        "password \" | "
                        "debconf-set-selections")
        EEShellExec.cmd_exec(self, "echo \"mariadb-server-10.0 "
                                   "mysql-server/root_password_again "
                                   "password {chars}\" | "
                                   "debconf-set-selections"
                                   .format(chars=chars),
                                   log=False)

        # Install MariaDB
        apt_packages = EEVariables.ee_mysql + ["php5-mysql"]
        Log.info(self, "Updating apt-cache, please wait ...")
        EEAptGet.update(self)
        Log.info(self, "Installing MariaDB, please wait ...")
        EEAptGet.remove(self, ["mysql-common", "libmysqlclient18"])
        EEAptGet.auto_remove(self)
        EEAptGet.install(self, apt_packages)
Example #19
0
 def clean_pagespeed(self):
     """This function clears Pagespeed cache"""
     if(os.path.isdir("/var/ngx_pagespeed_cache")):
         Log.info(self, "Cleaning PageSpeed cache")
         EEShellExec.cmd_exec(self, "rm -rf /var/ngx_pagespeed_cache/*")
     else:
         Log.debug(self, "/var/ngx_pagespeed_cache does not exist," 
                         " so cache not cleared")
         Log.error(self, "Unable to clean pagespeed cache", False)
Example #20
0
def setupwordpressnetwork(self, data):
    ee_site_webroot = data['webroot']
    EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot))
    Log.info(self, "Setting up WordPress Network \t", end='')
    EEShellExec.cmd_exec(self, 'wp --allow-root core multisite-convert'
                         ' --title=\'{0}\' {subdomains}'
                         .format(data['www_domain'], subdomains='--subdomains'
                                 if not data['wpsubdir'] else ''))
    Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]")
Example #21
0
def uninstallwp_plugin(self, plugin_name, data):
    ee_site_webroot = data['webroot']
    Log.debug(self, "Uninstalling plugin {0}".format(plugin_name))
    EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot))
    EEShellExec.cmd_exec(
        self,
        "php /usr/bin/wp plugin --allow-root uninstall "
        "{0}".format(plugin_name),
        errormsg="Unable to UnInstall plugin {0}".format(plugin_name))
    def upgrade_php56(self):
        if EEVariables.ee_platform_distro == "ubuntu":
            if os.path.isfile("/etc/apt/sources.list.d/ondrej-php5-5_6-{0}."
                              "list".format(EEVariables.ee_platform_codename)):
                Log.error(self, "Unable to find PHP 5.5")
        else:
            if not (os.path.isfile(EEVariables.ee_repo_file_path)
                    and EEFileUtils.grep(self, EEVariables.ee_repo_file_path,
                                         "php55")):
                Log.error(self, "Unable to find PHP 5.5")

        Log.info(
            self, "During PHP update process non nginx-cached"
            " parts of your site may remain down.")

        # Check prompt
        if (not self.app.pargs.no_prompt):
            start_upgrade = input("Do you want to continue:[y/N]")
            if start_upgrade != "Y" and start_upgrade != "y":
                Log.error(self, "Not starting PHP package update")

        if EEVariables.ee_platform_distro == "ubuntu":
            EERepo.remove(self, ppa="ppa:ondrej/php5")
            EERepo.add(self, ppa=EEVariables.ee_php_repo)
        else:
            EEAptGet.remove(self, ["php5-xdebug"])
            EEFileUtils.searchreplace(self, EEVariables.ee_repo_file_path,
                                      "php55", "php56")

        Log.info(self, "Updating apt-cache, please wait...")
        EEAptGet.update(self)
        Log.info(self, "Installing packages, please wait ...")
        if (EEVariables.ee_platform_codename == 'trusty'
                or EEVariables.ee_platform_codename == 'xenial'
                or EEVariables.ee_platform_codename == 'bionic'):
            EEAptGet.install(self,
                             EEVariables.ee_php5_6 + EEVariables.ee_php_extra)
        else:
            EEAptGet.install(self, EEVariables.ee_php)

        if EEVariables.ee_platform_distro == "debian":
            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"
            ])

        Log.info(self, "Successfully upgraded from PHP 5.5 to PHP 5.6")
Example #23
0
 def remove_cron(self,cmd):
     if EEShellExec.cmd_exec(self, "crontab -l | grep -q \'{0}\'".format(cmd)):
         if not EEShellExec.cmd_exec(self, "/bin/bash -c "
                                                 "\"crontab "
                                                 "-l | sed '/{0}/d'"
                                                 "| crontab -\""
                                                 .format(cmd)):
             Log.error(self, "Failed to remove crontab entry",False)
     else:
         Log.debug(self, "Cron not found")
Example #24
0
 def remove_cron(self,cmd):
     if EEShellExec.cmd_exec(self, "crontab -l | grep -q \'{0}\'".format(cmd)):
         if not EEShellExec.cmd_exec(self, "/bin/bash -c "
                                                 "\"crontab "
                                                 "-l | sed '/{0}/d'"
                                                 "| crontab -\""
                                                 .format(cmd)):
             Log.error(self, "Failed to remove crontab entry",False)
     else:
         Log.debug(self, "Cron not found")
Example #25
0
def setupwordpressnetwork(self, data):
    ee_site_webroot = data['webroot']
    EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot))
    Log.info(self, "Setting up WordPress Network \t", end='')
    EEShellExec.cmd_exec(
        self, 'wp --allow-root core multisite-convert'
        ' --title={0} {subdomains}'.format(
            data['www_domain'],
            subdomains='--subdomains' if not data['wpsubdir'] else ''))
    Log.info(self, "[" + Log.ENDC + "Done" + Log.OKBLUE + "]")
Example #26
0
 def clean_pagespeed(self):
     """This function clears Pagespeed cache"""
     if (os.path.isdir("/var/ngx_pagespeed_cache")):
         Log.info(self, "Cleaning PageSpeed cache")
         EEShellExec.cmd_exec(self, "rm -rf /var/ngx_pagespeed_cache/*")
     else:
         Log.debug(
             self, "/var/ngx_pagespeed_cache does not exist,"
             " so cache not cleared")
         Log.error(self, "Unable to clean pagespeed cache", False)
Example #27
0
 def remove(self, ppa=None):
     """
     This function used to remove ppa's
     If ppa is provided adds repo file to
         /etc/apt/sources.list.d/
     command.
     """
     EEShellExec.cmd_exec(self, "add-apt-repository -y "
                          "--remove '{ppa_name}'"
                          .format(ppa_name=repo_url))
Example #28
0
 def remove(self, ppa=None):
     """
     This function used to remove ppa's
     If ppa is provided adds repo file to
         /etc/apt/sources.list.d/
     command.
     """
     EEShellExec.cmd_exec(
         self, "add-apt-repository -y "
         "--remove '{ppa_name}'".format(ppa_name=repo_url))
Example #29
0
    def setcron_daily(self,cmd,comment='Cron set by EasyEngine',user='******',min=0,hour=12):
        if not EEShellExec.cmd_exec(self, "crontab -l | grep -q \'{0}\'".format(cmd)):

            EEShellExec.cmd_exec(self, "/bin/bash -c \"crontab -l "
                                             "2> /dev/null | {{ cat; echo -e"
                                             " \\\""
                                             "\\n0 12 * * * "
                                             "{0}".format(cmd) +
                                             " # {0}".format(comment)+
                                             "\\\"; } | crontab -\"")
            Log.debug(self, "Cron set")
Example #30
0
    def setcron_weekly(self,cmd,comment='Cron set by EasyEngine',user='******',min=0,hour=12):
        if not EEShellExec.cmd_exec(self, "crontab -l | grep -q \'{0}\'".format(cmd)):

            EEShellExec.cmd_exec(self, "/bin/bash -c \"crontab -l "
                                             "2> /dev/null | {{ cat; echo -e"
                                             " \\\""
                                             "\\n0 0 * * 0 "
                                             "{0}".format(cmd) +
                                             " # {0}".format(comment)+
                                             "\\\"; } | crontab -\"")
            Log.debug(self, "Cron set")
Example #31
0
    def debug_php(self):
        """Start/Stop PHP debug"""
        # PHP global debug start
        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")
                data = dict(php="9001", debug="9001", hhvm="9001")
                Log.debug(self, 'Writting the Nginx debug configration 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()
                # Enable xdebug
                EEFileUtils.searchreplace(self, "/etc/php5/mods-available/"
                                          "xdebug.ini",
                                          ";zend_extension",
                                          "zend_extension")

                self.trigger_php = True
                self.trigger_nginx = True
            else:
                Log.info(self, "PHP debug is already enabled")

            self.msg = self.msg + ['/var/log/php5/slow.log']

        # PHP global debug stop
        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")
                data = dict(php="9000", debug="9001", hhvm="8000")
                Log.debug(self, 'Writting the Nginx debug configration 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()
                # Disable xdebug
                EEFileUtils.searchreplace(self, "/etc/php5/mods-available/"
                                          "xdebug.ini",
                                          "zend_extension",
                                          ";zend_extension")

                self.trigger_php = True
                self.trigger_nginx = True
            else:
                Log.info(self, "PHP debug is already disabled")
Example #32
0
 def add_key(self, keyids, keyserver=None):
     """
     This function adds imports repository keys from keyserver.
     default keyserver is hkp://keys.gnupg.net
     user can provide other keyserver with keyserver="hkp://xyz"
     """
     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 - ")
Example #33
0
    def upgrade_php56(self):
        if EEVariables.ee_platform_distro == "ubuntu":
            if os.path.isfile("/etc/apt/sources.list.d/ondrej-php5-5_6-{0}."
                              "list".format(EEVariables.ee_platform_codename)):
                Log.error(self, "Unable to find PHP 5.5")
        else:
            if not(os.path.isfile(EEVariables.ee_repo_file_path) and
                   EEFileUtils.grep(self, EEVariables.ee_repo_file_path,
                                    "php55")):
                Log.error(self, "Unable to find PHP 5.5")

        Log.info(self, "During PHP update process non nginx-cached"
                 " parts of your site may remain down.")

        # Check prompt
        if (not self.app.pargs.no_prompt):
            start_upgrade = input("Do you want to continue:[y/N]")
            if start_upgrade != "Y" and start_upgrade != "y":
                Log.error(self, "Not starting PHP package update")

        if EEVariables.ee_platform_distro == "ubuntu":
            EERepo.remove(self, ppa="ppa:ondrej/php5")
            EERepo.add(self, ppa=EEVariables.ee_php_repo)
        else:
            EEAptGet.remove(self, ["php5-xdebug"])
            EEFileUtils.searchreplace(self, EEVariables.ee_repo_file_path,
                                      "php55", "php56")

        Log.info(self, "Updating apt-cache, please wait...")
        EEAptGet.update(self)
        Log.info(self, "Installing packages, please wait ...")
        if (EEVariables.ee_platform_codename == 'trusty' or EEVariables.ee_platform_codename == 'xenial'):
            EEAptGet.install(self, EEVariables.ee_php5_6 + EEVariables.ee_php_extra)
        else:
            EEAptGet.install(self, EEVariables.ee_php)

        if EEVariables.ee_platform_distro == "debian":
            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"])

        Log.info(self, "Successfully upgraded from PHP 5.5 to PHP 5.6")
Example #34
0
def installwp_plugin(self, plugin_name, data):
    ee_site_webroot = data['webroot']
    Log.info(self, "Installing plugin {0}".format(plugin_name))
    EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot))
    EEShellExec.cmd_exec(self, "php /usr/bin/wp plugin --allow-root install "
                         "{0}".format(plugin_name),
                         errormsg="Unable to Install plugin {0}"
                         .format(plugin_name))

    EEShellExec.cmd_exec(self, "php /usr/bin/wp plugin --allow-root activate "
                         "{0} {na}"
                         .format(plugin_name,
                                 na='--network' if data['multisite'] else ''),
                         errormsg="Unable to Activate plugin {0}"
                         .format(plugin_name))
    def default(self):
        if ((not self.app.pargs.mariadb)):
            self.app.args.print_help()
        if self.app.pargs.mariadb:
            if EEVariables.ee_mysql_host is not "localhost":
                Log.error(
                    self, "Remote MySQL found, EasyEngine will not "
                    "install MariaDB")

            if EEShellExec.cmd_exec(self, "mysqladmin ping") and (
                    not EEAptGet.is_installed(self, 'mariadb-server')):

                Log.info(
                    self, "If your database size is big, "
                    "migration may take some time.")
                Log.info(
                    self, "During migration non nginx-cached parts of "
                    "your site may remain down")
                start_migrate = input("Type \"mariadb\" to continue:")
                if start_migrate != "mariadb":
                    Log.error(self, "Not starting migration")
                self.migrate_mariadb()
            else:
                Log.error(
                    self, "Your current MySQL is not alive or "
                    "you allready installed MariaDB")
Example #36
0
    def default(self):
        """default function for info"""
        if (not self.app.pargs.nginx and not self.app.pargs.php
           and not self.app.pargs.mysql):
            self.app.pargs.nginx = True
            self.app.pargs.php = True
            self.app.pargs.mysql = True

        if self.app.pargs.nginx:
            if EEAptGet.is_installed(self, 'nginx-common'):
                self.info_nginx()
            else:
                Log.error(self, "Nginx is not installed")

        if self.app.pargs.php:
            if EEAptGet.is_installed(self, 'php5-fpm'):
                self.info_php()
            else:
                Log.error(self, "PHP5 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")
Example #37
0
def installwp_plugin(self, plugin_name, data):
    ee_site_webroot = data['webroot']
    Log.debug(self, "Installing plugin {0}".format(plugin_name))
    EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot))
    EEShellExec.cmd_exec(
        self,
        "php /usr/bin/wp plugin --allow-root install "
        "{0}".format(plugin_name),
        errormsg="Unable to Install plugin {0}".format(plugin_name))

    EEShellExec.cmd_exec(
        self,
        "php /usr/bin/wp plugin --allow-root activate "
        "{0} {na}".format(plugin_name,
                          na='--network' if data['multisite'] else ''),
        errormsg="Unable to Activate plugin {0}".format(plugin_name))
Example #38
0
    def default(self):
        """default function for info"""
        if (not self.app.pargs.nginx and not self.app.pargs.php
                and not self.app.pargs.mysql):
            self.app.pargs.nginx = True
            self.app.pargs.php = True
            self.app.pargs.mysql = True

        if self.app.pargs.nginx:
            if EEAptGet.is_installed(self, 'nginx-common'):
                self.info_nginx()
            else:
                Log.error(self, "Nginx is not installed")

        if self.app.pargs.php:
            if EEAptGet.is_installed(self, 'php5-fpm'):
                self.info_php()
            else:
                Log.error(self, "PHP5 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")
Example #39
0
    def default(self):
        """Default function for import slow log"""
        if os.path.isdir("{0}22222/htdocs/db/anemometer".format(
                EEVariables.ee_webroot)):
            if os.path.isfile("/var/log/mysql/mysql-slow.log"):
                # Get Anemometer user name and password
                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()

                # Import slow log Anemometer using pt-query-digest
                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))
            else:
                Log.error(self, "Unable to find MySQL slow log file")
        else:
            Log.error(self, "Anemometer is not installed")
Example #40
0
    def debug_fpm(self):
        """Start/Stop PHP5-FPM debug"""
        # PHP5-FPM start global debug
        if self.start:
            if not EEShellExec.cmd_exec(self, "grep \"log_level = debug\" "
                                              "/etc/php5/fpm/php-fpm.conf"):
                Log.info(self, "Setting up PHP5-FPM log_level = debug")
                config = configparser.ConfigParser()
                config.read('/etc/php5/fpm/php-fpm.conf')
                config.remove_option('global', 'include')
                config['global']['log_level'] = 'debug'
                config['global']['include'] = '/etc/php5/fpm/pool.d/*.conf'
                with open('/etc/php5/fpm/php-fpm.conf',
                          encoding='utf-8', mode='w') as configfile:
                    Log.debug(self, "Writting php5-FPM configuration into "
                              "/etc/php5/fpm/php-fpm.conf")
                    config.write(configfile)
                self.trigger_php = True
            else:
                Log.info(self, "PHP5-FPM log_level = debug already setup")

            self.msg = self.msg + ['/var/log/php5/fpm.log']

        # PHP5-FPM stop global debug
        else:
            if EEShellExec.cmd_exec(self, "grep \"log_level = debug\" "
                                          "/etc/php5/fpm/php-fpm.conf"):
                Log.info(self, "Disabling PHP5-FPM log_level = debug")
                config = configparser.ConfigParser()
                config.read('/etc/php5/fpm/php-fpm.conf')
                config.remove_option('global', 'include')
                config['global']['log_level'] = 'notice'
                config['global']['include'] = '/etc/php5/fpm/pool.d/*.conf'
                with open('/etc/php5/fpm/php-fpm.conf',
                          encoding='utf-8', mode='w') as configfile:
                    Log.debug(self, "writting php5 configuration into "
                              "/etc/php5/fpm/php-fpm.conf")
                    config.write(configfile)

                self.trigger_php = True
            else:
                Log.info(self, "PHP5-FPM log_level = debug  already disabled")
Example #41
0
    def debug_fpm(self):
        """Start/Stop PHP5-FPM debug"""
        # PHP5-FPM start global debug
        if (self.app.pargs.php == 'on'and not self.app.pargs.site_name):
            if not EEShellExec.cmd_exec(self, "grep \"log_level = debug\" "
                                              "/etc/php5/fpm/php-fpm.conf"):
                Log.info(self, "Setting up PHP5-FPM log_level = debug")
                config = configparser.ConfigParser()
                config.read('/etc/php5/fpm/php-fpm.conf')
                config.remove_option('global', 'include')
                config['global']['log_level'] = 'debug'
                config['global']['include'] = '/etc/php5/fpm/pool.d/*.conf'
                with open('/etc/php5/fpm/php-fpm.conf',
                          encoding='utf-8', mode='w') as configfile:
                    Log.debug(self, "Writting php5-FPM configuration into "
                              "/etc/php5/fpm/php-fpm.conf")
                    config.write(configfile)
                self.trigger_php = True
            else:
                Log.info(self, "PHP5-FPM log_level = debug already setup")

            self.msg = self.msg + ['/var/log/php5/fpm.log']

        # PHP5-FPM stop global debug
        elif (self.app.pargs.php == 'on' and not self.app.pargs.site_name):
            if EEShellExec.cmd_exec(self, "grep \"log_level = debug\" "
                                          "/etc/php5/fpm/php-fpm.conf"):
                Log.info(self, "Disabling PHP5-FPM log_level = debug")
                config = configparser.ConfigParser()
                config.read('/etc/php5/fpm/php-fpm.conf')
                config.remove_option('global', 'include')
                config['global']['log_level'] = 'notice'
                config['global']['include'] = '/etc/php5/fpm/pool.d/*.conf'
                with open('/etc/php5/fpm/php-fpm.conf',
                          encoding='utf-8', mode='w') as configfile:
                    Log.debug(self, "writting php5 configuration into "
                              "/etc/php5/fpm/php-fpm.conf")
                    config.write(configfile)

                self.trigger_php = True
            else:
                Log.info(self, "PHP5-FPM log_level = debug  already disabled")
Example #42
0
    def add(self, repo_url=None, ppa=None):
        """
        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.
        """

        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:
            if EEVariables.ee_platform_distro == 'squeeze':
                print("Cannot add repo for {distro}"
                      .format(distro=EEVariables.ee_platform_distro))
            else:
                EEShellExec.cmd_exec(self, "add-apt-repository -y "
                                           "'{ppa_name}'"
                                     .format(ppa_name=ppa))
Example #43
0
    def add(self, repo_url=None, ppa=None):
        """
        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.
        """

        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:
            if EEVariables.ee_platform_distro == 'squeeze':
                print("Cannot add repo for {distro}".format(
                    distro=EEVariables.ee_platform_distro))
            else:
                EEShellExec.cmd_exec(
                    self, "add-apt-repository -y "
                    "'{ppa_name}'".format(ppa_name=ppa))
Example #44
0
    def default(self):
        """Default function for import slow log"""
        if os.path.isdir("{0}22222/htdocs/db/anemometer"
                         .format(EEVariables.ee_webroot)):
            if os.path.isfile("/var/log/mysql/mysql-slow.log"):
                # Get Anemometer user name and password
                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()

                # Import slow log Anemometer using pt-query-digest
                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))
            else:
                Log.error(self, "Unable to find MySQL slow log file")
        else:
            Log.error(self, "Anemometer is not installed")
Example #45
0
   def getExpirationDays(self,domain):
        # check if exist
        if not os.path.isfile('/etc/letsencrypt/live/{0}/cert.pem'
                      .format(domain)):
            Log.error(self,'File Not Found : /etc/letsencrypt/live/{0}/cert.pem'
                      .format(domain),False)
            Log.error(self, "Check logs for reason "
                      "`tail /var/log/ee/ee.log` & Try Again!!!")


        current_date = EEShellExec.cmd_exec_stdout(self, "date -d \"now\" +%s")
        expiration_date =  EEShellExec.cmd_exec_stdout(self, "date -d \"`openssl x509 -in /etc/letsencrypt/live/{0}/cert.pem"
                                           " -text -noout|grep \"Not After\"|cut -c 25-`\" +%s".format(domain))

        days_left = int((int(expiration_date) - int(current_date))/ 86400)
        if (days_left > 0):
            return days_left
        else:
            # return "Certificate Already Expired ! Please Renew soon."
            return -1
Example #46
0
   def getExpirationDate(self,domain):
        # check if exist
        if not os.path.isfile('/etc/letsencrypt/live/{0}/cert.pem'
                      .format(domain)):
            Log.error(self,'File Not Found : /etc/letsencrypt/live/{0}/cert.pem'
                      .format(domain),False)
            Log.error(self, "Check logs for reason "
                      "`tail /var/log/ee/ee.log` & Try Again!!!")

        expiration_date =  EEShellExec.cmd_exec_stdout(self, "date -d \"`openssl x509 -in /etc/letsencrypt/live/{0}/cert.pem"
                                           " -text -noout|grep \"Not After\"|cut -c 25-`\" ".format(domain))
        return expiration_date
Example #47
0
   def getExpirationDate(self,domain):
        # check if exist
        if not os.path.isfile('/etc/letsencrypt/live/{0}/cert.pem'
                      .format(domain)):
            Log.error(self,'File Not Found : /etc/letsencrypt/live/{0}/cert.pem'
                      .format(domain),False)
            Log.error(self, "Check logs for reason "
                      "`tail /var/log/ee/ee.log` & Try Again!!!")

        expiration_date =  EEShellExec.cmd_exec_stdout(self, "date -d \"`openssl x509 -in /etc/letsencrypt/live/{0}/cert.pem"
                                           " -text -noout|grep \"Not After\"|cut -c 25-`\" ".format(domain))
        return expiration_date
Example #48
0
    def add(self):
        """Swap addition with EasyEngine"""
        if EEVariables.ee_ram < 512:
            if EEVariables.ee_swap < 1000:
                Log.info(self, "Adding SWAP")

                # Install dphys-swapfile
                EEAptGet.update(self)
                EEAptGet.install(self, ["dphys-swapfile"])
                # Stop service
                EEShellExec.cmd_exec(self, "service dphys-swapfile stop")
                # Remove Default swap created
                EEShellExec.cmd_exec(self, "/sbin/dphys-swapfile uninstall")

                # Modify Swap configuration
                if os.path.isfile("/etc/dphys-swapfile"):
                    EEFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                              "#CONF_SWAPFILE=/var/swap",
                                              "CONF_SWAPFILE=/ee-swapfile")
                    EEFileUtils.searchreplace(self,  "/etc/dphys-swapfile",
                                              "#CONF_MAXSWAP=2048",
                                              "CONF_MAXSWAP=1024")
                    EEFileUtils.searchreplace(self,  "/etc/dphys-swapfile",
                                              "#CONF_SWAPSIZE=",
                                              "CONF_SWAPSIZE=1024")
                else:
                    with open("/etc/dphys-swapfile", 'w') as conffile:
                        conffile.write("CONF_SWAPFILE=/ee-swapfile\n"
                                       "CONF_SWAPSIZE=1024\n"
                                       "CONF_MAXSWAP=1024\n")
                # Create swap file
                EEShellExec.cmd_exec(self, "service dphys-swapfile start")
Example #49
0
    def add(self):
        """Swap addition with EasyEngine"""
        if EEVariables.ee_ram < 512:
            if EEVariables.ee_swap < 1000:
                Log.info(self, "Adding SWAP file, please wait...")

                # Install dphys-swapfile
                EEAptGet.update(self)
                EEAptGet.install(self, ["dphys-swapfile"])
                # Stop service
                EEShellExec.cmd_exec(self, "service dphys-swapfile stop")
                # Remove Default swap created
                EEShellExec.cmd_exec(self, "/sbin/dphys-swapfile uninstall")

                # Modify Swap configuration
                if os.path.isfile("/etc/dphys-swapfile"):
                    EEFileUtils.searchreplace(self, "/etc/dphys-swapfile",
                                              "#CONF_SWAPFILE=/var/swap",
                                              "CONF_SWAPFILE=/ee-swapfile")
                    EEFileUtils.searchreplace(self,  "/etc/dphys-swapfile",
                                              "#CONF_MAXSWAP=2048",
                                              "CONF_MAXSWAP=1024")
                    EEFileUtils.searchreplace(self,  "/etc/dphys-swapfile",
                                              "#CONF_SWAPSIZE=",
                                              "CONF_SWAPSIZE=1024")
                else:
                    with open("/etc/dphys-swapfile", 'w') as conffile:
                        conffile.write("CONF_SWAPFILE=/ee-swapfile\n"
                                       "CONF_SWAPSIZE=1024\n"
                                       "CONF_MAXSWAP=1024\n")
                # Create swap file
                EEShellExec.cmd_exec(self, "service dphys-swapfile start")
Example #50
0
    def debug_php(self):
        """Start/Stop PHP debug"""
        # PHP global debug start
        if self.start:
            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")
                data = dict(php="9001", debug="9001")
                Log.info(self, 'Writting the Nginx debug configration 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()
                self.trigger_php = True
                self.trigger_nginx = True
            else:
                Log.info(self, "PHP debug is already enabled")

            self.msg = self.msg + ['/var/log/php5/slow.log']

        # PHP global debug stop
        else:
            if EEShellExec.cmd_exec(self, "sed -n \"/upstream php {/,/}/p\" "
                                          "/etc/nginx/conf.d/upstream.conf "
                                          "| grep 9001"):
                Log.info(self, "Disabling PHP debug")
                data = dict(php="9000", debug="9001")
                Log.debug(self, 'Writting the Nginx debug configration 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()
                self.trigger_php = True
                self.trigger_nginx = True
            else:
                Log.info(self, "PHP debug is already disabled")
Example #51
0
    def secure_ip(self):
        """This function Secures IP"""
        # TODO:remaining with ee.conf updation in file
        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")
Example #52
0
    def secure_ip(self):
        """This function Secures IP"""
        # TODO:remaining with ee.conf updation in file
        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")
Example #53
0
def site_package_check(self, stype):
    apt_packages = []
    packages = []
    stack = EEStackController()
    stack.app = self.app
    if stype in ['html', 'php', 'mysql', 'wp', 'wpsubdir', 'wpsubdomain']:
        Log.debug(self, "Setting apt_packages variable for Nginx")
        if not EEAptGet.is_installed(self, 'nginx-common'):
            apt_packages = apt_packages + EEVariables.ee_nginx

    if stype in ['php', 'mysql', 'wp', 'wpsubdir', 'wpsubdomain']:
        Log.debug(self, "Setting apt_packages variable for PHP")
        if not EEAptGet.is_installed(self, 'php5-fpm'):
            apt_packages = apt_packages + EEVariables.ee_php

    if stype in ['mysql', 'wp', 'wpsubdir', 'wpsubdomain']:
        Log.debug(self, "Setting apt_packages variable for MySQL")
        if not EEShellExec.cmd_exec(self, "mysqladmin ping"):
            apt_packages = apt_packages + EEVariables.ee_mysql

    if stype in ['php', 'mysql', 'wp', 'wpsubdir', 'wpsubdomain']:
        Log.debug(self, "Setting apt_packages variable for Postfix")
        if not EEAptGet.is_installed(self, 'postfix'):
            apt_packages = apt_packages + EEVariables.ee_postfix

    if stype in ['wp', 'wpsubdir', 'wpsubdomain']:
        Log.debug(self, "Setting packages variable for WP-CLI")
        if not EEShellExec.cmd_exec(self, "which wp"):
            packages = packages + [[
                "https://github.com/wp-cli/wp-cli/"
                "releases/download/v{0}/"
                "wp-cli-{0}.phar".format(EEVariables.ee_wp_cli), "/usr/bin/wp",
                "WP-CLI"
            ]]
    return (stack.install(apt_packages=apt_packages,
                          packages=packages,
                          disp_msg=False))
Example #54
0
def updatewpuserpassword(self, ee_domain, ee_site_webroot):

    ee_wp_user = ''
    ee_wp_pass = ''
    EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot))

    # Check if ee_domain is wordpress install
    is_wp = EEShellExec.cmd_exec(
        self, "wp --allow-root core"
        " version",
        errormsg="{0} : Unable to check if wp install".format(ee_domain))

    # Exit if ee_domain is not wordpress install
    if not is_wp:
        Log.error(self,
                  "{0} does not seem to be a WordPress site".format(ee_domain))

    try:
        ee_wp_user = input("Provide WordPress user name [admin]: ")
    except Exception as e:
        Log.debug(self, "{0}".format(e))
        Log.error(self, "\nCould not update password")

    if ee_wp_user == "?":
        Log.info(self, "Fetching WordPress user list")
        EEShellExec.cmd_exec(self, "wp --allow-root user list "
                             "--fields=user_login | grep -v user_login",
                             errormsg="Unable to Fetch users list")

    if not ee_wp_user:
        ee_wp_user = '******'

    is_user_exist = EEShellExec.cmd_exec(
        self, "wp --allow-root user list "
        "--fields=user_login | grep {0}$ ".format(ee_wp_user))

    if is_user_exist:
        try:
            ee_wp_pass = getpass.getpass(prompt="Provide password for "
                                         "{0} user: "******"{0}".format(e))
            Log.error(self, "Could not update password")

        if len(ee_wp_pass) > 8:
            EEShellExec.cmd_exec(
                self, "wp --allow-root user update {0}"
                "  --user_pass={1}".format(ee_wp_user, ee_wp_pass))
            Log.info(self, "Password updated successfully")
        else:
            Log.error(
                self, "Password Unchanged. Hint : Your password must be "
                "8 characters long")
    else:
        Log.error(
            self, "Invalid WordPress user {0} for {1}.".format(
                ee_wp_user, ee_domain))
Example #55
0
    def debug_php(self):
        """Start/Stop PHP debug"""
        # PHP global debug start
        if self.start:
            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")
                data = dict(php="9001", debug="9001")
                Log.info(self, "Writting the Nginx debug configration 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()
                self.trigger_php = True
                self.trigger_nginx = True
            else:
                Log.info(self, "PHP debug is already enabled")

            self.msg = self.msg + ["/var/log/php5/slow.log"]

        # PHP global debug stop
        else:
            if EEShellExec.cmd_exec(
                self, ' sed -n "/upstream php {/,/}/p" ' "/etc/nginx/conf.d/upstream.conf " "| grep 9001"
            ):
                Log.info(self, "Disabling PHP debug")
                data = dict(php="9000", debug="9001")
                Log.debug(self, "Writting the Nginx debug configration 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()
                self.trigger_php = True
                self.trigger_nginx = True
            else:
                Log.info(self, "PHP debug is already disabled")
Example #56
0
def updatewpuserpassword(self, ee_domain, ee_site_webroot):

    ee_wp_user = ''
    ee_wp_pass = ''
    EEFileUtils.chdir(self, '{0}/htdocs/'.format(ee_site_webroot))

    # Check if ee_domain is wordpress install
    is_wp = EEShellExec.cmd_exec(self, "wp --allow-root core"
                                 " version",
                                 errormsg="{0} : Unable to check if wp install"
                                 .format(ee_domain))

    # Exit if ee_domain is not wordpress install
    if not is_wp:
        Log.error(self, "{0} does not seem to be a WordPress site"
                  .format(ee_domain))

    try:
        ee_wp_user = input("Provide WordPress user name [admin]: ")
    except Exception as e:
        Log.debug(self, "{0}".format(e))
        Log.error(self, "\nCould not update password")

    if ee_wp_user == "?":
        Log.info(self, "Fetching WordPress user list")
        EEShellExec.cmd_exec(self, "wp --allow-root user list "
                             "--fields=user_login | grep -v user_login",
                             errormsg="Unable to Fetch users list")

    if not ee_wp_user:
        ee_wp_user = '******'

    is_user_exist = EEShellExec.cmd_exec(self, "wp --allow-root user list "
                                         "--fields=user_login | grep {0}$ "
                                         .format(ee_wp_user))

    if is_user_exist:
        try:
            ee_wp_pass = getpass.getpass(prompt="Provide password for "
                                         "{0} user: "******"{0}".format(e))
            Log.error(self, "Could not update password")

        if len(ee_wp_pass) > 8:
            EEShellExec.cmd_exec(self, "wp --allow-root user update {0}"
                                 "  --user_pass={1}"
                                 .format(ee_wp_user, ee_wp_pass))
            Log.info(self, "Password updated successfully")
        else:
            Log.error(self, "Password Unchanged. Hint : Your password must be "
                      "8 characters long")
    else:
        Log.error(self, "Invalid WordPress user {0} for {1}."
                  .format(ee_wp_user, ee_domain))
Example #57
0
    def debug_fpm(self):
        """Start/Stop PHP5-FPM debug"""
        # PHP5-FPM start global debug
        if self.start:
            if not EEShellExec.cmd_exec(self, 'grep "log_level = debug" ' "/etc/php5/fpm/php-fpm.conf"):
                Log.info(self, "Setting up PHP5-FPM log_level = debug")
                config = configparser.ConfigParser()
                config.read("/etc/php5/fpm/php-fpm.conf")
                config.remove_option("global", "include")
                config["global"]["log_level"] = "debug"
                config["global"]["include"] = "/etc/php5/fpm/pool.d/*.conf"
                with open("/etc/php5/fpm/php-fpm.conf", encoding="utf-8", mode="w") as configfile:
                    Log.debug(self, "Writting php5-FPM configuration into " "/etc/php5/fpm/php-fpm.conf")
                    config.write(configfile)
                self.trigger_php = True
            else:
                Log.info(self, "PHP5-FPM log_level = debug already setup")

            self.msg = self.msg + ["/var/log/php5/fpm.log"]

        # PHP5-FPM stop global debug
        else:
            if EEShellExec.cmd_exec(self, 'grep "log_level = debug" ' "/etc/php5/fpm/php-fpm.conf"):
                Log.info(self, "Disabling PHP5-FPM log_level = debug")
                config = configparser.ConfigParser()
                config.read("/etc/php5/fpm/php-fpm.conf")
                config.remove_option("global", "include")
                config["global"]["log_level"] = "notice"
                config["global"]["include"] = "/etc/php5/fpm/pool.d/*.conf"
                with open("/etc/php5/fpm/php-fpm.conf", encoding="utf-8", mode="w") as configfile:
                    Log.debug(self, "writting php5 configuration into " "/etc/php5/fpm/php-fpm.conf")
                    config.write(configfile)

                self.trigger_php = True
            else:
                Log.info(self, "PHP5-FPM log_level = debug  already disabled")
Example #58
0
    def debug_mysql(self):
        """Start/Stop MySQL debug"""
        # MySQL start global debug
        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\';")
                if self.app.pargs.interval:
                    try:
                        cron_time = int(self.app.pargs.interval)
                    except Exception as e:
                        cron_time = 5

                    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 "
                                         "import-slow-log\\n"
                                         "#EasyEngine end MySQL slow log"
                                         "\\\"; }} | crontab -\""
                                         .format(cron_time))
            else:
                Log.info(self, "MySQL slow log is already enabled")

            self.msg = self.msg + ['/var/log/mysql/mysql-slow.log']

        # MySQL stop global debug
        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_index"
                                "es = \'OFF\';")
                EEShellExec.cmd_exec(self, "crontab -l | sed \'/#EasyEngine "
                                     "start/,/#EasyEngine end/d\' | crontab -")
            else:
                Log.info(self, "MySQL slow log already disabled")