Exemple #1
0
    def post_install(self, name, path, vars, dbinfo={}):
        # Write a basic index file showing that we are here
        if vars.getvalue('php', '0') == '1':
            php = True
            path = os.path.join(path, 'htdocs')
            os.mkdir(path)
            c = nginx.loadf(os.path.join('/etc/nginx/sites-available', name))
            for x in c.servers:
                if x.filter('Key', 'root'):
                    x.filter('Key', 'root')[0].value = path
            nginx.dumpf(c, os.path.join('/etc/nginx/sites-available', name))
        else:
            php = False

        if php:
            phpctl = apis.langassist(self.app).get_interface('PHP')
            phpctl.enable_mod('xcache')
        if php and dbinfo and dbinfo['engine'] == 'MariaDB':
            phpctl.enable_mod('mysql')

        f = open(
            os.path.join(path, 'index.' + ('php' if php is True else 'html')),
            'w')
        f.write('<html>\n'
                '<body>\n'
                '<h1>Genesis - Custom Site</h1>\n'
                '<p>Your site is online and available at ' + path + '</p>\n'
                '<p>Feel free to paste your site files here</p>\n'
                '</body>\n'
                '</html>\n')
        f.close()

        # Give access to httpd
        shell('chown -R http:http ' + path)
Exemple #2
0
def reconfigure(cfg):
    if not os.path.exists(RCFG_FILE):
        return

    rcfg = ConfigParser()
    rcfg.read(RCFG_FILE)

    if rcfg.has_option('genesis', 'credentials'):
        u,p = rcfg.get('genesis', 'credentials').split(':')
        cfg.remove_option('users', 'admin')
        if not p.startswith('{SHA}'):
            p = hashpw(p)
        cfg.set('users', u, p)

    if rcfg.has_option('genesis', 'plugins'):
        for x in rcfg.get('genesis', 'plugins').split():
            shell('genesis-pkg get ' + x)

    if rcfg.has_option('genesis', 'ssl'):
        c,k = rcfg.get('genesis', 'ssl').split()
        cfg.set('ssl', '1')
        cfg.set('cert_key', k)
        cfg.set('cert_file', c)

    if rcfg.has_option('genesis', 'port'):
        cfg.set('genesis', 'bind_port', rcfg.get('genesis', 'port'))

    if rcfg.has_option('genesis', 'host'):
        cfg.set('genesis', 'bind_host', rcfg.get('genesis', 'host'))

    cfg.set('genesis', 'firstrun', 'no')
    cfg.save()
    os.unlink(RCFG_FILE)
Exemple #3
0
    def post_install(self, name, path, vars, dbinfo={}):
        phpctl = apis.langassist(self.app).get_interface('PHP')

        # Create Lychee automatic configuration file
        f = open(os.path.join(path, 'data', 'config.php'), 'w')
        f.write(
            '<?php\n'
            '   if(!defined(\'LYCHEE\')) exit(\'Error: Direct access is allowed!\');\n'
            '   $dbHost = \'localhost\';\n'
            '   $dbUser = \'' + dbinfo['user'] + '\';\n'
            '   $dbPassword = \'' + dbinfo['passwd'] + '\';\n'
            '   $dbName = \'' + dbinfo['name'] + '\';\n'
            '   $dbTablePrefix = \'\';\n'
            '?>\n'
        )
        f.close()

        # Make sure that the correct PHP settings are enabled
        phpctl.enable_mod('mysql', 'mysqli', 'gd', 'zip', 'exif', 'json', 'mbstring')

        # Rename lychee index.html to index.php to make it work with our default nginx config
        os.rename(os.path.join(path, "index.html"), os.path.join(path, "index.php"))

        # Finally, make sure that permissions are set so that Lychee
        # can make adjustments and save plugins when need be.
        shell('chown -R http:http %s' % path)

        return "Lychee has been installed. Login with a blank username and password the first time to set your credentials."
Exemple #4
0
	def post_install(self, name, path, vars):
		# Make sure the webapps config points to the _site directory and generate it.
		shell('sed -i "s/.*root .*/   root %s\;/" /etc/nginx/sites-available/%s' % (re.escape(path+'/_site'), name))
		shell('jekyll build --source '+path+' --destination '+path+'/_site')

		# Return an explicatory message.
		return 'Jekyll has been setup, with a sample site at '+path+'. Modify these files as you like. To learn how to use Jekyll, visit http://jekyllrb.com/docs/usage. After making changes, click the Configure button next to the site, then "Regenerate Site" to bring your changes live.'
Exemple #5
0
 def add_django_site(self, name, path, user, group):
     shell('cd %s; django-admin.py startproject %s' % (path, name))
     gconf = '#! /bin/bash\n\n'
     gconf += 'NAME="%s"\n' % name
     gconf += 'SOCKFILE=%s\n' % os.path.join(path, 'gunicorn.sock')
     gconf += 'USER=%s\n' % user
     gconf += 'GROUP=%s\n' % group
     gconf += 'NUM_WORKERS=3\n'
     gconf += 'DJANGODIR=%s\n' % path
     gconf += 'DJANGO_SETTINGS_MODULE=%s.settings\n' % name
     gconf += 'DJANGO_WSGI_MODULE=%s.wsgi\n\n' % name
     gconf += 'export PYTHONPATH=$DJANGODIR:$PYTHONPATH\n\n'
     gconf += 'echo "Starting $NAME as `whoami`"\n\n'
     gconf += 'exec gunicorn ${DJANGO_WSGI_MODULE}:application \ \n'
     gconf += '--name $NAME --workers $NUM_WORKERS \ \n'
     gconf += '--user=$USER --group=$GROUP \ \n'
     gconf += '--log-level=debug --bind=unix:$SOCKFILE\n'
     open(os.path.join(path, 'gunicorn'), 'w').write(gconf)
     st = os.stat(os.path.join(path, 'gunicorn'))
     os.chmod(os.path.join(path, 'gunicorn'), st.st_mode | 0111)
     s = filter(lambda x: x.id == 'supervisor',
                self.app.grab_plugins(apis.orders.IListener))
     if s:
         s[0].order('new', name, 'program', [
             ('directory', path), ('user', user),
             ('command', os.path.join(path, 'gunicorn')),
             ('stdout_logfile', os.path.join(path,
                                             '%s_logfile.log' % name)),
             ('stderr_logfile', os.path.join(path, '%s_logfile.log' % name))
         ])
Exemple #6
0
def reconfigure(cfg):
    if not os.path.exists(RCFG_FILE):
        return

    rcfg = ConfigParser()
    rcfg.read(RCFG_FILE)

    if rcfg.has_option('genesis', 'credentials'):
        u, p = rcfg.get('genesis', 'credentials').split(':')
        cfg.remove_option('users', 'admin')
        if not p.startswith('{SHA}'):
            p = hashpw(p)
        cfg.set('users', u, p)

    if rcfg.has_option('genesis', 'plugins'):
        for x in rcfg.get('genesis', 'plugins').split():
            shell('genesis-pkg get ' + x)

    if rcfg.has_option('genesis', 'ssl'):
        c, k = rcfg.get('genesis', 'ssl').split()
        cfg.set('ssl', '1')
        cfg.set('cert_key', k)
        cfg.set('cert_file', c)

    if rcfg.has_option('genesis', 'port'):
        cfg.set('genesis', 'bind_port', rcfg.get('genesis', 'port'))

    if rcfg.has_option('genesis', 'host'):
        cfg.set('genesis', 'bind_host', rcfg.get('genesis', 'host'))

    cfg.set('genesis', 'firstrun', 'no')
    cfg.save()
    os.unlink(RCFG_FILE)
Exemple #7
0
    def get_expected_result(self, st):
        r = {}

        cmd = 'pacman -Sp --noconfirm --print-format \'%n %v\' '
        a = False
        for x in st.pending:
            if st.pending[x] == 'install':
                cmd += x + ' '
                a = True

        if a:
            r.update(self._parse_pm_p(
                utils.shell(cmd).splitlines(), 'install'))

        cmd = 'pacman -Rpc --noconfirm --print-format \'%n %v\' '
        a = False
        for x in st.pending:
            if st.pending[x] != 'install':
                cmd += x + ' '
                a = True

        if a:
            r.update(self._parse_pm_p(utils.shell(cmd).splitlines(), 'remove'))

        return r
Exemple #8
0
    def initialize(self):
        tb = iptc.Table(iptc.Table.FILTER)
        c = iptc.Chain(tb, 'INPUT')
        c.flush()

        # Accept loopback
        r = iptc.Rule()
        r.in_interface = 'lo'
        t = iptc.Target(r, 'ACCEPT')
        r.target = t
        c.append_rule(r)

        # Accept designated apps
        r = iptc.Rule()
        t = iptc.Target(r, 'genesis-apps')
        r.target = t
        c.append_rule(r)

        # Allow ICMP (ping)
        shell('iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT')

        # Accept established/related connections
        # Unfortunately this has to be done clasically
        shell('iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT')

        # Reject all else by default
        r = iptc.Rule()
        t = iptc.Target(r, 'DROP')
        r.target = t
        c.append_rule(r)

        self.save()
Exemple #9
0
    def post_install(self, name, path, vars):
        # Create a database if the user wants one
        if vars.getvalue("ws-dbsel", "None") != "None":
            dbtype = vars.getvalue("ws-dbsel", "")
            dbname = vars.getvalue("ws-dbname", "")
            passwd = vars.getvalue("ws-dbpass", "")
            dbase = apis.databases(self.app).get_interface(dbtype)
            dbase.add(dbname)
            dbase.usermod(dbname, "add", passwd)
            dbase.chperm(dbname, dbname, "grant")

            # Write a basic index file showing that we are here
        if vars.getvalue("php", "0") == "1":
            php = True
        else:
            php = False
        f = open(os.path.join(path, "index." + ("php" if php is True else "html")), "w")
        f.write(
            "<html>\n"
            "<body>\n"
            "<h1>Genesis - Custom Site</h1>\n"
            "<p>Your site is online and available at " + path + "</p>\n"
            "<p>Feel free to paste your site files here</p>\n"
            "</body>\n"
            "</html>\n"
        )
        f.close()

        # Give access to httpd
        shell("chown -R http:http " + path)
Exemple #10
0
    def post_install(self, name, path, vars, dbinfo={}):
        # Write a basic index file showing that we are here
        if vars.getvalue('php', '0') == '1':
            php = True
            path = os.path.join(path, 'htdocs')
            os.mkdir(path)
            c = nginx.loadf(os.path.join('/etc/nginx/sites-available', name))
            for x in c.servers:
                if x.filter('Key', 'root'):
                    x.filter('Key', 'root')[0].value = path
            nginx.dumpf(c, os.path.join('/etc/nginx/sites-available', name))
        else:
            php = False
            
        if php:
            phpctl = apis.langassist(self.app).get_interface('PHP')
            phpctl.enable_mod('xcache')
        if php and dbinfo and dbinfo['engine'] == 'MariaDB':
            phpctl.enable_mod('mysql')

        f = open(os.path.join(path, 'index.'+('php' if php is True else 'html')), 'w')
        f.write(
            '<html>\n'
            '<body>\n'
            '<h1>Genesis - Custom Site</h1>\n'
            '<p>Your site is online and available at '+path+'</p>\n'
            '<p>Feel free to paste your site files here</p>\n'
            '</body>\n'
            '</html>\n'
            )
        f.close()

        # Give access to httpd
        shell('chown -R http:http '+path)
Exemple #11
0
 def add_django_site(self, name, path, user, group):
     shell('cd %s; django-admin.py startproject %s' % (path,name))
     gconf = '#! /bin/bash\n\n'
     gconf += 'NAME="%s"\n' % name
     gconf += 'SOCKFILE=%s\n' % os.path.join(path, 'gunicorn.sock')
     gconf += 'USER=%s\n' % user
     gconf += 'GROUP=%s\n' % group
     gconf += 'NUM_WORKERS=3\n'
     gconf += 'DJANGODIR=%s\n' % path
     gconf += 'DJANGO_SETTINGS_MODULE=%s.settings\n' % name
     gconf += 'DJANGO_WSGI_MODULE=%s.wsgi\n\n' % name
     gconf += 'export PYTHONPATH=$DJANGODIR:$PYTHONPATH\n\n'
     gconf += 'echo "Starting $NAME as `whoami`"\n\n'
     gconf += 'exec gunicorn ${DJANGO_WSGI_MODULE}:application \ \n'
     gconf += '--name $NAME --workers $NUM_WORKERS \ \n'
     gconf += '--user=$USER --group=$GROUP \ \n'
     gconf += '--log-level=debug --bind=unix:$SOCKFILE\n'
     open(os.path.join(path, 'gunicorn'), 'w').write(gconf)
     st = os.stat(os.path.join(path, 'gunicorn'))
     os.chmod(os.path.join(path, 'gunicorn'), st.st_mode | 0111)
     s = filter(lambda x: x.id == 'supervisor',
         self.app.grab_plugins(apis.orders.IListener))
     if s:
         s[0].order('new', name, 'program', 
             [('directory', path), ('user', user), 
             ('command', os.path.join(path, 'gunicorn')),
             ('stdout_logfile', os.path.join(path, '%s_logfile.log'%name)),
             ('stderr_logfile', os.path.join(path, '%s_logfile.log'%name))])
Exemple #12
0
    def backup(self, provider):
        try:
            os.makedirs(os.path.join(self.dir, provider.id))
        except:
            pass
        dir = tempfile.mkdtemp()
        
        try:
            for f in provider.list_files():
                for x in glob.glob(f):
                    xdir = os.path.join(dir, os.path.split(x)[0][1:])
                    shell('mkdir -p \'%s\'' % xdir)
                    shell('cp -r \'%s\' \'%s\'' % (x, xdir))

            metafile = open(dir + '/genesis-backup', 'w')
            metafile.write(provider.id)
            metafile.close()

            if shell_status('cd %s; tar czf backup.tar.gz *'%dir) != 0:
                raise Exception()
            
            name = 0
            try:
                name = int(os.listdir(self.dir+'/'+provider.id)[0].split('.')[0])
            except:
                pass
            
            while os.path.exists('%s/%s/%i.tar.gz'%(self.dir,provider.id,name)):
                name += 1
            
            shutil.move('%s/backup.tar.gz'%dir, '%s/%s/%s.tar.gz'%(self.dir,provider.id,name))
        except:
            raise
        finally:
            shutil.rmtree(dir)
Exemple #13
0
 def add_django_site(self, name, path, user, group):
     shell("cd %s; django-admin.py startproject %s" % (path, name))
     gconf = "#! /bin/bash\n\n"
     gconf += 'NAME="%s"\n' % name
     gconf += "SOCKFILE=%s\n" % os.path.join(path, "gunicorn.sock")
     gconf += "USER=%s\n" % user
     gconf += "GROUP=%s\n" % group
     gconf += "NUM_WORKERS=3\n"
     gconf += "DJANGODIR=%s\n" % path
     gconf += "DJANGO_SETTINGS_MODULE=%s.settings\n" % name
     gconf += "DJANGO_WSGI_MODULE=%s.wsgi\n\n" % name
     gconf += "export PYTHONPATH=$DJANGODIR:$PYTHONPATH\n\n"
     gconf += 'echo "Starting $NAME as `whoami`"\n\n'
     gconf += "exec gunicorn ${DJANGO_WSGI_MODULE}:application \ \n"
     gconf += "--name $NAME --workers $NUM_WORKERS \ \n"
     gconf += "--user=$USER --group=$GROUP \ \n"
     gconf += "--log-level=debug --bind=unix:$SOCKFILE\n"
     open(os.path.join(path, "gunicorn"), "w").write(gconf)
     st = os.stat(os.path.join(path, "gunicorn"))
     os.chmod(os.path.join(path, "gunicorn"), st.st_mode | 0111)
     s = self.app.get_backend(apis.services.IServiceManager)
     s.edit(
         name,
         {
             "stype": "program",
             "directory": path,
             "user": user,
             "command": os.path.join(path, "gunicorn"),
             "stdout_logfile": os.path.join(path, "%s_logfile.log" % name),
             "stderr_logfile": os.path.join(path, "%s_logfile.log" % name),
         },
     )
     s.enable(name, "supervisor")
Exemple #14
0
 def get_temp(self):
     if detect_architecture()[1] == 'Raspberry Pi':
         return '%3.1f°C'%(float(shell('cat /sys/class/thermal/thermal_zone0/temp').split('\n')[0])/1000)
     else:
         if os.path.exists('/sys/class/hwmon/hwmon1/temp1_input'):
             return '%3.1f°C'%(float(shell('cat /sys/class/hwmon/hwmon1/temp1_input'))/1000)
     return ''
Exemple #15
0
 def get_temp(self):
     if self.app.board == 'Raspberry Pi':
         return '%3.1f°C'%(float(shell('cat /sys/class/thermal/thermal_zone0/temp').split('\n')[0])/1000)
     else:
         if os.path.exists('/sys/class/hwmon/hwmon1/temp1_input'):
             return '%3.1f°C'%(float(shell('cat /sys/class/hwmon/hwmon1/temp1_input'))/1000)
     return ''
Exemple #16
0
 def on_submit(self, event, params, vars=None):
     if params[0] == 'frmGeneral':
         if vars.getvalue('action', '') == 'OK':
             if self.app.gconfig.get('genesis', 'bind_host', '') != vars.getvalue('bind_host', ''):
                 self._changed = True
             if self.app.gconfig.get('genesis', 'bind_port', '') != vars.getvalue('bind_port', ''):
                 self._changed = True
             self.app.gconfig.set('genesis', 'bind_host', vars.getvalue('bind_host', ''))
             self.app.gconfig.set('genesis', 'bind_port', vars.getvalue('bind_port', '8000'))
             self.app.gconfig.set('genesis', 'dformat', vars.getvalue('dformat', '%d %b %Y'))
             self.app.gconfig.set('genesis', 'tformat', vars.getvalue('tformat', '%H:%M'))
             self.app.gconfig.set('genesis', 'timedalert', vars.getvalue('timedalert', ''))
             self.app.gconfig.set('genesis', 'auth_enabled', vars.getvalue('httpauth', '0'))
             self.app.gconfig.set('genesis', 'nofx', vars.getvalue('nofx', '0'))
             self.app.gconfig.set('genesis', 'updcheck', vars.getvalue('updcheck', '1'))
             self.app.gconfig.set('genesis', 'purge', vars.getvalue('purge', '0'))
             self.app.gconfig.save()
             self.put_message('success', 'Settings saved.')
     if params[0] == 'dlgEditModuleConfig':
         if vars.getvalue('action','') == 'OK':
             cfg = self.app.get_config_by_classname(self._config)
             cfg.apply_vars(vars)
             cfg.save()
         self._config = None
     if params[0] == 'dlgUpdate':
         if vars.getvalue('action', '') == 'OK':
             shell('pacman -S --noconfirm genesis')
             self.put_message('info', 'Update complete. Please reboot your system.')
         self._update = None
Exemple #17
0
 def nginx_edit(self, origname, name, stype, path, addr, port, ssl, php=False):
     # TODO update this to use nginxparser
     if path.endswith("_site"):
         path = re.sub("/", "\/", os.path.join("/srv/http/webapps/", name, "_site"))
     else:
         path = re.sub("/", "\/", os.path.join("/srv/http/webapps/", name))
     shell(
         'sed -i "s/.*GENESIS.*/# GENESIS %s %s/" /etc/nginx/sites-available/%s'
         % (stype, (("https:\/\/" if ssl else "http:\/\/") + addr + ":" + port), origname)
     )
     shell(
         'sed -i "s/.*listen .*/\tlisten %s\;/" /etc/nginx/sites-available/%s'
         % ((port + " ssl" if ssl else port), origname)
     )
     shell('sed -i "s/.*server_name .*/\tserver_name %s\;/" /etc/nginx/sites-available/%s' % (addr, origname))
     shell('sed -i "s/.*root .*/\troot %s\;/" /etc/nginx/sites-available/%s' % (path, origname))
     shell(
         'sed -i "s/.*index index.*/\tindex index.%s\;/" /etc/nginx/sites-available/%s'
         % ("php" if php else "html", origname)
     )
     if name != origname:
         if os.path.exists(os.path.join("/srv/http/webapps", name)):
             shutil.rmtree(os.path.join("/srv/http/webapps", name))
         shutil.move(os.path.join("/srv/http/webapps", origname), os.path.join("/srv/http/webapps", name))
         shutil.move(
             os.path.join("/etc/nginx/sites-available", origname), os.path.join("/etc/nginx/sites-available", name)
         )
         self.nginx_disable(origname, reload=False)
         self.nginx_enable(name)
     self.nginx_reload()
Exemple #18
0
 def add_django_site(self, name, path, user, group):
     shell('cd %s; django-admin.py startproject %s' % (path, name))
     gconf = '#! /bin/bash\n\n'
     gconf += 'NAME="%s"\n' % name
     gconf += 'SOCKFILE=%s\n' % os.path.join(path, 'gunicorn.sock')
     gconf += 'USER=%s\n' % user
     gconf += 'GROUP=%s\n' % group
     gconf += 'NUM_WORKERS=3\n'
     gconf += 'DJANGODIR=%s\n' % path
     gconf += 'DJANGO_SETTINGS_MODULE=%s.settings\n' % name
     gconf += 'DJANGO_WSGI_MODULE=%s.wsgi\n\n' % name
     gconf += 'export PYTHONPATH=$DJANGODIR:$PYTHONPATH\n\n'
     gconf += 'echo "Starting $NAME as `whoami`"\n\n'
     gconf += 'exec gunicorn ${DJANGO_WSGI_MODULE}:application \ \n'
     gconf += '--name $NAME --workers $NUM_WORKERS \ \n'
     gconf += '--user=$USER --group=$GROUP \ \n'
     gconf += '--log-level=debug --bind=unix:$SOCKFILE\n'
     open(os.path.join(path, 'gunicorn'), 'w').write(gconf)
     st = os.stat(os.path.join(path, 'gunicorn'))
     os.chmod(os.path.join(path, 'gunicorn'), st.st_mode | 0111)
     s = self.app.get_backend(apis.services.IServiceManager)
     s.edit(
         name, {
             'stype': 'program',
             'directory': path,
             'user': user,
             'command': os.path.join(path, 'gunicorn'),
             'stdout_logfile': os.path.join(path, '%s_logfile.log' % name),
             'stderr_logfile': os.path.join(path, '%s_logfile.log' % name)
         })
     s.enable(name, 'supervisor')
Exemple #19
0
 def update(self, path, pkg, ver):
     # General update procedure
     nodectl = apis.langassist(self.app).get_interface('NodeJS')
     s = self.app.get_backend(apis.services.IServiceManager)
     out = shell('unzip -o -d %s %s' % (path, pkg), stderr=True)
     shell('chown -R ghost '+path)
     nodectl.install_from_package(path, 'production', {'sqlite': '/usr/bin', 'python': '/usr/bin/python2'})
     s.restart('ghost', 'supervisor')
Exemple #20
0
 def regenerate_site(self, site):
     s = shell_cs(
         "jekyll build --source " + site.path.rstrip("_site") + " --destination " + os.path.join(site.path),
         stderr=True,
     )
     if s[0] != 0:
         raise Exception("Jekyll failed to build: %s" % str(s[1]))
     shell("chmod 755 $(find %s -type d)" % site.path.rstrip("_site"))
     shell("chmod 644 $(find %s -type f)" % site.path.rstrip("_site"))
Exemple #21
0
 def set_autostart(self, active):
     if active:
         open(self.path, 'w').write(self.apply_shell)
         shell('chmod 755 ' + self.path)
     else:
         try:
             os.unlink(self.path)
         except:
             pass
Exemple #22
0
 def set_autostart(self, active):
     if active:
         open(self.path, 'w').write(self.apply_shell)
         shell('chmod 755 ' + self.path)
     else:
         try:
             os.unlink(self.path)
         except:
             pass
Exemple #23
0
	def post_install(self, name, path, vars):
		# Make sure the webapps config points to the _site directory and generate it.
		c = nginx.loadf(os.path.join('/etc/nginx/sites-available', name))
		c.servers[0].filter('Key', 'root')[0].value = os.path.join(path, '_site')
		nginx.dumpf(c, os.path.join('/etc/nginx/sites-available', name))
		shell('jekyll build --source '+path+' --destination '+os.path.join(path, '_site'))

		# Return an explicatory message.
		return 'Jekyll has been setup, with a sample site at '+path+'. Modify these files as you like. To learn how to use Jekyll, visit http://jekyllrb.com/docs/usage. After making changes, click the Configure button next to the site, then "Regenerate Site" to bring your changes live.'
Exemple #24
0
    def get_ip(self, iface):
        try:
            return shell('ifconfig %s | grep \'inet addr\''%iface.name).split()[1].split(':')[1]
        except: pass

        try:
            return shell('ifconfig %s | grep \'inet\''%iface.name).split()[1]
        except: pass
        
        return '0.0.0.0'
Exemple #25
0
 def get_rx(self, iface):
     try:
         return int(shell('ifconfig %s | grep \'RX bytes\''%iface.name).split()[1].split(':')[1])
     except: pass
     
     try:
         return int(shell('ifconfig %s | grep -E \'RX .+ bytes\''%iface.name).split()[4])
     except: pass
     
     return 0
Exemple #26
0
    def post_install(self, name, path, vars):
        # Make sure the webapps config points to the _site directory and generate it.
        shell(
            'sed -i "s/.*root .*/   root %s\;/" /etc/nginx/sites-available/%s'
            % (re.escape(path + '/_site'), name))
        shell('jekyll build --source ' + path + ' --destination ' + path +
              '/_site')

        # Return an explicatory message.
        return 'Jekyll has been setup, with a sample site at ' + path + '. Modify these files as you like. To learn how to use Jekyll, visit http://jekyllrb.com/docs/usage. After making changes, click the Configure button next to the site, then "Regenerate Site" to bring your changes live.'
Exemple #27
0
    def post_install(self, name, path, vars):
        # Get the database object, and determine proper values
        dbase = apis.databases(self.app).get_interface('MariaDB')
        if vars.getvalue('wp-dbname', '') == '':
            dbname = name
        else:
            dbname = vars.getvalue('wp-dbname')
        secret_key = hashlib.sha1(str(random.random())).hexdigest()
        if vars.getvalue('wp-dbpasswd', '') == '':
            passwd = secret_key[0:8]
        else:
            passwd = vars.getvalue('wp-dbpasswd')

        # Request a database and user to interact with it
        dbase.add(dbname)
        dbase.usermod(dbname, 'add', passwd)
        dbase.chperm(dbname, dbname, 'grant')

        # Write a standard WordPress config file
        f = open(os.path.join(path, 'wp-config.php'), 'w')
        f.write('<?php\n'
                'define(\'DB_NAME\', \'' + dbname + '\');\n'
                'define(\'DB_USER\', \'' + dbname + '\');\n'
                'define(\'DB_PASSWORD\', \'' + passwd + '\');\n'
                'define(\'DB_HOST\', \'localhost\');\n'
                'define(\'DB_CHARSET\', \'utf8\');\n'
                'define(\'SECRET_KEY\', \'' + secret_key + '\');\n'
                '\n'
                'define(\'WP_CACHE\', true);\n'
                '\n'
                '/*\n'
                'define(\'AUTH_KEY\', \'' + secret_key + '\');\n'
                'define(\'SECURE_AUTH_KEY\', \'' + secret_key + '\');\n'
                'define(\'LOGGED_IN_KEY\', \'' + secret_key + '\');\n'
                'define(\'NONCE_KEY\', \'' + secret_key + '\');\n'
                '*/'
                '\n'
                '$table_prefix = \'wp_\';\n'
                '\n'
                '/** Absolute path to the WordPress directory. */\n'
                'if ( !defined(\'ABSPATH\') )\n'
                '	define(\'ABSPATH\', dirname(__FILE__) . \'/\');\n'
                '\n'
                '/** Sets up WordPress vars and included files. */\n'
                'require_once(ABSPATH . \'wp-settings.php\');\n')
        f.close()

        # Make sure that the correct PHP settings are enabled
        shell(
            'sed -i s/;extension=mysql.so/extension=mysql.so/g /etc/php/php.ini'
        )

        # Finally, make sure that permissions are set so that Wordpress
        # can make adjustments and save plugins when need be.
        shell('chown -R http:http ' + path)
Exemple #28
0
	def post_install(self, name, path, vars):
		# Get the database object, and determine proper values
		dbase = apis.databases(self.app).get_interface('MariaDB')
		if vars.getvalue('wp-dbname', '') == '':
			dbname = name
		else:
			dbname = vars.getvalue('wp-dbname')
		secret_key = hashlib.sha1(str(random.random())).hexdigest()
		if vars.getvalue('wp-dbpasswd', '') == '':
			passwd = secret_key[0:8]
		else:
			passwd = vars.getvalue('wp-dbpasswd')

		# Request a database and user to interact with it
		dbase.add(dbname)
		dbase.usermod(dbname, 'add', passwd)
		dbase.chperm(dbname, dbname, 'grant')

		# Write a standard WordPress config file
		f = open(os.path.join(path, 'wp-config.php'), 'w')
		f.write('<?php\n'
				'define(\'DB_NAME\', \''+dbname+'\');\n'
				'define(\'DB_USER\', \''+dbname+'\');\n'
				'define(\'DB_PASSWORD\', \''+passwd+'\');\n'
				'define(\'DB_HOST\', \'localhost\');\n'
				'define(\'DB_CHARSET\', \'utf8\');\n'
				'define(\'SECRET_KEY\', \''+secret_key+'\');\n'
				'\n'
				'define(\'WP_CACHE\', true);\n'
				'\n'
				'/*\n'
				'define(\'AUTH_KEY\', \''+secret_key+'\');\n'
				'define(\'SECURE_AUTH_KEY\', \''+secret_key+'\');\n'
				'define(\'LOGGED_IN_KEY\', \''+secret_key+'\');\n'
				'define(\'NONCE_KEY\', \''+secret_key+'\');\n'
				'*/'
				'\n'
				'$table_prefix = \'wp_\';\n'
				'\n'
				'/** Absolute path to the WordPress directory. */\n'
				'if ( !defined(\'ABSPATH\') )\n'
				'	define(\'ABSPATH\', dirname(__FILE__) . \'/\');\n'
				'\n'
				'/** Sets up WordPress vars and included files. */\n'
				'require_once(ABSPATH . \'wp-settings.php\');\n'
			)
		f.close()

		# Make sure that the correct PHP settings are enabled
		shell('sed -i s/;extension=mysql.so/extension=mysql.so/g /etc/php/php.ini')

		# Finally, make sure that permissions are set so that Wordpress
		# can make adjustments and save plugins when need be.
		shell('chown -R http:http '+path)
Exemple #29
0
 def handle_btns(self, event, params, vars=None):
     if params[0] == 'aborttask':
         for p in self.app.grab_plugins(IProgressBoxProvider):
             if p.plugin_id == params[1] and p.has_progress():
                 p.abort()
     if params[0] == 'gen_reload':
         self.app.restart()
     if params[0] == 'gen_shutdown':
         shell('shutdown -P now')
     if params[0] == 'gen_reboot':
         shell('reboot')
Exemple #30
0
 def handle_btns(self, event, params, vars=None):
     if params[0] == 'aborttask':
         for p in self.app.grab_plugins(IProgressBoxProvider):
             if p.plugin_id == params[1] and p.has_progress():
                 p.abort()
     if params[0] == 'gen_reload':
         self.app.restart()
     if params[0] == 'gen_shutdown':
         shell('shutdown -P now')
     if params[0] == 'gen_reboot':
         shell('reboot')
Exemple #31
0
    def get_backups(self):
        dir = tempfile.mkdtemp()
        temparch = os.path.join(dir, 'backup-all.tar.gz')
        shell('tar czf ' + temparch + ' -C /var/backups/ genesis')
        size = os.path.getsize(temparch)

        f = open(temparch, 'rb')
        arch = f.read()
        f.close()
        shell('rm -r ' + dir)
        return (size, arch)
Exemple #32
0
    def post_install(self, name, path, vars):
        # Make sure the webapps config points to the _site directory and generate it.
        c = nginx.loadf(os.path.join('/etc/nginx/sites-available', name))
        c.servers[0].filter('Key',
                            'root')[0].value = os.path.join(path, '_site')
        nginx.dumpf(c, os.path.join('/etc/nginx/sites-available', name))
        shell('jekyll build --source ' + path + ' --destination ' +
              os.path.join(path, '_site'))

        # Return an explicatory message.
        return 'Jekyll has been setup, with a sample site at ' + path + '. Modify these files as you like. To learn how to use Jekyll, visit http://jekyllrb.com/docs/usage. After making changes, click the Configure button next to the site, then "Regenerate Site" to bring your changes live.'
Exemple #33
0
 def install_composer(self):
     cwd = os.getcwd()
     os.environ['COMPOSER_HOME'] = '/root'
     self.enable_mod('phar')
     self.open_basedir('add', '/root')
     s = shell_cs('cd /root; curl -sS https://getcomposer.org/installer | php', stderr=True)
     if s[0] != 0:
         raise Exception('Composer download/config failed. Error: %s'%str(s[1]))
     os.rename('/root/composer.phar', '/usr/local/bin/composer')
     os.chmod('/usr/local/bin/composer', 755)
     self.open_basedir('add', '/usr/local/bin')
     shell('cd %s'%cwd)
Exemple #34
0
    def post_install(self, name, path, vars):
        # Write a basic index file showing that we are here
        if vars.getvalue('php', '0') == '1':
            php = True
            path = os.path.join(path, 'htdocs')
            os.mkdir(path)
            c = nginx.loadf(os.path.join('/etc/nginx/sites-available', name))
            for x in c.servers:
                if x.filter('Key', 'root'):
                    x.filter('Key', 'root')[0].value = path
            nginx.dumpf(c, os.path.join('/etc/nginx/sites-available', name))
        else:
            php = False

        # Create a database if the user wants one
        if php:
            phpctl = apis.langassist(self.app).get_interface('PHP')
        if vars.getvalue('ws-dbsel', 'None') != 'None':
            dbtype = vars.getvalue('ws-dbsel', '')
            dbname = vars.getvalue('ws-dbname', '')
            passwd = vars.getvalue('ws-dbpass', '')
            dbase = apis.databases(self.app).get_interface(dbtype)
            if hasattr(dbase, 'connect'):
                conn = apis.databases(self.app).get_dbconn(dbtype)
                dbase.add(dbname, conn)
                dbase.usermod(dbname, 'add', passwd, conn)
                dbase.chperm(dbname, dbname, 'grant', conn)
            else:
                dbase.add(dbname)
                dbase.usermod(dbname, 'add', passwd)
                dbase.chperm(dbname, dbname, 'grant')
            if php:
                phpctl.enable_mod('mysql')

        f = open(
            os.path.join(path, 'index.' + ('php' if php is True else 'html')),
            'w')
        f.write('<html>\n'
                '<body>\n'
                '<h1>Genesis - Custom Site</h1>\n'
                '<p>Your site is online and available at ' + path + '</p>\n'
                '<p>Feel free to paste your site files here</p>\n'
                '</body>\n'
                '</html>\n')
        f.close()

        # Give access to httpd
        shell('chown -R http:http ' + path)

        # Enable xcache if PHP is set
        if php:
            phpctl.enable_mod('xcache')
Exemple #35
0
    def post_install(self, name, path, vars):
        # Write a basic index file showing that we are here
        if vars.getvalue('php', '0') == '1':
            php = True
            path = os.path.join(path, 'htdocs')
            os.mkdir(path)
            c = nginx.loadf(os.path.join('/etc/nginx/sites-available', name))
            for x in c.servers:
                if x.filter('Key', 'root'):
                    x.filter('Key', 'root')[0].value = path
            nginx.dumpf(c, os.path.join('/etc/nginx/sites-available', name))
        else:
            php = False
            
        # Create a database if the user wants one
        if php:
            phpctl = apis.langassist(self.app).get_interface('PHP')
        if vars.getvalue('ws-dbsel', 'None') != 'None':
            dbtype = vars.getvalue('ws-dbsel', '')
            dbname = vars.getvalue('ws-dbname', '')
            passwd = vars.getvalue('ws-dbpass', '')
            dbase = apis.databases(self.app).get_interface(dbtype)
            if hasattr(dbase, 'connect'):
                conn = apis.databases(self.app).get_dbconn(dbtype)
                dbase.add(dbname, conn)
                dbase.usermod(dbname, 'add', passwd, conn)
                dbase.chperm(dbname, dbname, 'grant', conn)
            else:
                dbase.add(dbname)
                dbase.usermod(dbname, 'add', passwd)
                dbase.chperm(dbname, dbname, 'grant')
            if php:
                phpctl.enable_mod('mysql')

        f = open(os.path.join(path, 'index.'+('php' if php is True else 'html')), 'w')
        f.write(
            '<html>\n'
            '<body>\n'
            '<h1>Genesis - Custom Site</h1>\n'
            '<p>Your site is online and available at '+path+'</p>\n'
            '<p>Feel free to paste your site files here</p>\n'
            '</body>\n'
            '</html>\n'
            )
        f.close()

        # Give access to httpd
        shell('chown -R http:http '+path)

        # Enable xcache if PHP is set
        if php:
            phpctl.enable_mod('xcache')
Exemple #36
0
 def get_info(self, pkg):
     i = apis.pkgman.PackageInfo()
     ss = utils.shell('apt-cache policy ' + pkg).split('\n')
     i.installed = ss[1].split(':')[1].strip()
     i.available = ss[2].split(':')[1].strip()
     ss = utils.shell('apt-cache show ' + pkg).split('\n')
     while len(ss) > 0 and not ss[0].startswith('Desc'):
         ss = ss[1:]
     i.description = ss[0].split(':')[1]
     ss = ss[1:]
     while len(ss) > 0 and ss[0].startswith(' '):
         i.description += '\n' + ss[0][1:]
         ss = ss[1:]
     return i
Exemple #37
0
    def remove(self, id):
        """
        Uninstalls given plugin

        :param  id:     Plugin id
        :type   id:     str
        """

        try:
            self.purge = self.config.get('genesis', 'purge')
        except:
            self.purge = '1'

        dir = self.config.get('genesis', 'plugins')
        shell('rm -r %s/%s' % (dir, id))

        if id in PluginLoader.list_plugins():
            try:
                pdata = PluginLoader.list_plugins()[id].deps
                for thing in pdata:
                    if 'app' in thing[0]:
                        shell('systemctl stop ' + thing[2])
                        shell('systemctl disable ' + thing[2])
                        shell('pacman -%s --noconfirm ' %('Rn' if self.purge is '1' else 'R') + thing[1])
            except KeyError:
                pass
            PluginLoader.unload(id)

        self.update_installed()
        self.update_available()
Exemple #38
0
 def on_click(self, event, params, vars=None):
     if params[0] == 'updaction':
         if self._updstat[0] == False:
             UpdateCheck.get().check_updates(refresh=True)
         else:
             self._update = True
     if params[0] == 'editconfig':
         self._config = params[1]
     if params[0] == 'restart':
         self.app.restart()
     if params[0] == 'shutdown':
         shell('shutdown -P now')
     if params[0] == 'reboot':
         shell('reboot')
Exemple #39
0
 def get_info(self, pkg):
     i = apis.pkgman.PackageInfo()
     ss = utils.shell('apt-cache policy '+pkg).split('\n')
     i.installed = ss[1].split(':')[1].strip()
     i.available = ss[2].split(':')[1].strip()
     ss = utils.shell('apt-cache show '+pkg).split('\n')
     while len(ss)>0 and not ss[0].startswith('Desc'):
         ss = ss[1:]
     i.description = ss[0].split(':')[1]
     ss = ss[1:]
     while len(ss)>0 and ss[0].startswith(' '):
         i.description += '\n' + ss[0][1:]
         ss = ss[1:]
     return i
Exemple #40
0
	def post_install(self, name, path, vars, dbinfo={}):
		phpctl = apis.langassist(self.app).get_interface('PHP')
		secret_key = hashlib.sha1(str(random.random())).hexdigest()

		# Use the WordPress key generators as first option
		# If connection fails, use the secret_key as fallback
		try:
			keysection = urllib.urlopen('https://api.wordpress.org/secret-key/1.1/salt/').read()
		except:
			keysection = ''
		if not 'define(\'AUTH_KEY' in keysection:
			keysection = (
				'define(\'AUTH_KEY\', \''+secret_key+'\');\n'
				'define(\'SECURE_AUTH_KEY\', \''+secret_key+'\');\n'
				'define(\'LOGGED_IN_KEY\', \''+secret_key+'\');\n'
				'define(\'NONCE_KEY\', \''+secret_key+'\');\n'
				)

		# Write a standard WordPress config file
		f = open(os.path.join(path, 'wp-config.php'), 'w')
		f.write('<?php\n'
				'define(\'DB_NAME\', \''+dbinfo['name']+'\');\n'
				'define(\'DB_USER\', \''+dbinfo['user']+'\');\n'
				'define(\'DB_PASSWORD\', \''+dbinfo['passwd']+'\');\n'
				'define(\'DB_HOST\', \'localhost\');\n'
				'define(\'DB_CHARSET\', \'utf8\');\n'
				'define(\'SECRET_KEY\', \''+secret_key+'\');\n'
				'\n'
				'define(\'WP_CACHE\', true);\n'
				'define(\'FORCE_SSL_ADMIN\', false);\n'
				'\n'
				+keysection+
				'\n'
				'$table_prefix = \'wp_\';\n'
				'\n'
				'/** Absolute path to the WordPress directory. */\n'
				'if ( !defined(\'ABSPATH\') )\n'
				'	define(\'ABSPATH\', dirname(__FILE__) . \'/\');\n'
				'\n'
				'/** Sets up WordPress vars and included files. */\n'
				'require_once(ABSPATH . \'wp-settings.php\');\n'
			)
		f.close()

		# Make sure that the correct PHP settings are enabled
		phpctl.enable_mod('mysql', 'xcache')

		# Finally, make sure that permissions are set so that Wordpress
		# can make adjustments and save plugins when need be.
		shell('chown -R http:http '+path)
Exemple #41
0
    def upload(self, file):
        dir = '/var/backups/genesis/'

        # Get the backup then read its metadata
        tempdir = mkdtemp()
        temparch = path.join(tempdir, 'backup.tar.gz')
        open(temparch, 'wb').write(file)

        shell('tar xzf ' + temparch + ' -C ' + tempdir)
        bfile = open(path.join(tempdir, 'genesis-backup'), 'r')
        name = bfile.readline()
        bfile.close()

        # Make sure the appropriate plugin is installed
        if not path.exists(dir + name):
            shell('rm -r ' + tempdir)
            raise Exception()

        # Name the file and do some work
        priors = listdir(dir + name)
        thinglist = []
        for thing in priors:
            thing = thing.split('.')
            thinglist.append(thing[0])
        newver = int(max(thinglist)) + 1

        shell('cp %s %s' % (temparch, dir + name + '/' + str(newver) + '.tar.gz'))
        shell('rm -r ' + tempdir)
Exemple #42
0
    def upload(self, file):
        dir = '/var/backups/genesis/'

        # Get the backup then read its metadata
        tempdir = mkdtemp()
        temparch = path.join(tempdir, 'backup.tar.gz')
        open(temparch, 'wb').write(file)

        shell('tar xzf ' + temparch + ' -C ' + tempdir)
        bfile = open(path.join(tempdir, 'genesis-backup'), 'r')
        name = bfile.readline()
        bfile.close()

        # Make sure the appropriate plugin is installed
        if not path.exists(dir + name):
            shell('rm -r ' + tempdir)
            raise Exception()

        # Name the file and do some work
        priors = listdir(dir + name)
        thinglist = []
        for thing in priors:
            thing = thing.split('.')
            thinglist.append(thing[0])
        newver = int(max(thinglist)) + 1

        shell('cp %s %s' %
              (temparch, dir + name + '/' + str(newver) + '.tar.gz'))
        shell('rm -r ' + tempdir)
Exemple #43
0
    def remove(self, id):
        """
        Uninstalls given plugin

        :param  id:     Plugin id
        :type   id:     str
        """
        dir = self.config.get('genesis', 'plugins')
        shell('rm -r %s/%s' % (dir, id))

        if id in PluginLoader.list_plugins():
            PluginLoader.unload(id)

        self.update_installed()
        self.update_available()
Exemple #44
0
    def post_install(self, name, path, vars, dbinfo={}):
        phpctl = apis.langassist(self.app).get_interface('PHP')
        secret_key = hashlib.sha1(str(random.random())).hexdigest()

        # Use the WordPress key generators as first option
        # If connection fails, use the secret_key as fallback
        try:
            keysection = urllib.urlopen(
                'https://api.wordpress.org/secret-key/1.1/salt/').read()
        except:
            keysection = ''
        if not 'define(\'AUTH_KEY' in keysection:
            keysection = ('define(\'AUTH_KEY\', \'' + secret_key + '\');\n'
                          'define(\'SECURE_AUTH_KEY\', \'' + secret_key +
                          '\');\n'
                          'define(\'LOGGED_IN_KEY\', \'' + secret_key +
                          '\');\n'
                          'define(\'NONCE_KEY\', \'' + secret_key + '\');\n')

        # Write a standard WordPress config file
        f = open(os.path.join(path, 'wp-config.php'), 'w')
        f.write('<?php\n'
                'define(\'DB_NAME\', \'' + dbinfo['name'] + '\');\n'
                'define(\'DB_USER\', \'' + dbinfo['user'] + '\');\n'
                'define(\'DB_PASSWORD\', \'' + dbinfo['passwd'] + '\');\n'
                'define(\'DB_HOST\', \'localhost\');\n'
                'define(\'DB_CHARSET\', \'utf8\');\n'
                'define(\'SECRET_KEY\', \'' + secret_key + '\');\n'
                '\n'
                'define(\'WP_CACHE\', true);\n'
                'define(\'FORCE_SSL_ADMIN\', false);\n'
                '\n' + keysection + '\n'
                '$table_prefix = \'wp_\';\n'
                '\n'
                '/** Absolute path to the WordPress directory. */\n'
                'if ( !defined(\'ABSPATH\') )\n'
                '	define(\'ABSPATH\', dirname(__FILE__) . \'/\');\n'
                '\n'
                '/** Sets up WordPress vars and included files. */\n'
                'require_once(ABSPATH . \'wp-settings.php\');\n')
        f.close()

        # Make sure that the correct PHP settings are enabled
        phpctl.enable_mod('mysql', 'xcache')

        # Finally, make sure that permissions are set so that Wordpress
        # can make adjustments and save plugins when need be.
        shell('chown -R http:http ' + path)
Exemple #45
0
    def post_install(self, name, path, vars):
        port = vars.getvalue('ghost-port', '2368')
        hostname = vars.getvalue('ghost-host', '127.0.0.1')
        url = vars.getvalue('ghost-url', 'my-ghost-blog.com')

        replacements = [
            ('2368', port),
            ('127.0.0.1', hostname),
            ('my-ghost-blog.com', url)
        ]

        # Get Mail settings
        mail_settings = {
            'transport' : vars.getvalue('ghost-transport', ''),
            'service' : vars.getvalue('ghost-service', ''),
            'mail_user' : vars.getvalue('ghost-mail-user', ''),
            'mail_pass' : vars.getvalue('ghost-mail-pass', ''),
            'from_address' : vars.getvalue('ghost-from-address', '')
        }

        # Create/Edit the Ghost config file
        f = open(os.path.join(path, 'config.example.js'), 'r').read()
        with open(os.path.join(path, 'config.js'), 'w') as config_file:
            for r in replacements:
                f = f.replace(r[0], r[1])
            if len(set(mail_settings.values())) != 1 and\
               mail_settings['transport'] != '':
                # If the mail settings exist, add them
                f = f.replace(
                    "mail: {},",\
                    'mail: {\n'
                    "\tfromaddress: '" + mail_settings['from_address'] + "',\n"
                    "\ttransport: '" + mail_settings['transport'] + "',\n"
                    "\t\toptions: {\n"
                    "\t\t\tservice: '" + mail_settings['service'] + "',\n"
                    "\t\t\tauth: {\n"
                    "\t\t\t\tuser: '******'mail_user'] + "',\n"
                    "\t\t\t\tpass: '******'mail_pass'] + "'\n"
                    "\t\t\t}\n"
                    "\t\t}\n"
                    "},\n"
                )
            config_file.write(f)
            config_file.close()

        # Finally, make sure that permissions are set so that Ghost
        # can make adjustments and save plugins when need be.
        shell('chown -R http:http ' + path)
Exemple #46
0
 def get_ip(self, iface):
     s = shell('ip addr list %s | grep \'inet\''%iface)
     try:
         s = s.split()[1]
     except:
         s = '0.0.0.0'
     return s    
Exemple #47
0
    def refresh(self, st):
        p = utils.shell('pkg_version|grep \'<\'').split('\n')
        a = self._get_all()
        st.upgradeable = {}

        for x in p:
            try:
                s = x.split()[0]
                st.upgradeable[s] = a[s]
            except:
                pass

        st.pending = {}
        try:
            ss = open('/tmp/genesis-ports-pending.list',
                      'r').read().splitlines()
            for s in ss:
                s = s.split()
                try:
                    st.pending[s[1]] = s[0]
                except:
                    pass
        except:
            pass

        st.full = a
Exemple #48
0
 def is_installed(self, name):
     s = shell('pip%s freeze' %
               '2' if self.app.platform in ['arkos', 'arch'] else '')
     for x in s.split('\n'):
         if name in x.split('==')[0]:
             return True
     return False
Exemple #49
0
    def add_project(self, name, crypto=False):
        self.setup()
        if crypto:
            name = name + '-crypto'
        s = shell_cs('git init --quiet --bare "%s"' %
                     os.path.join('/home/sparkleshare', name))
        if s[0] != 0:
            self.app.log.error(
                'Creation of Git repository failed. Error:\n%s' % s[1])
            raise Exception(
                'Creation of Git repository failed. See the logs for details')
        shell('git config --file %s receive.denyNonFastForwards true' %
              os.path.join('/home/sparkleshare', name, 'config'))

        # Add list of files that Git should not compress
        extensions = [
            'jpg', 'jpeg', 'png', 'tiff', 'gif', 'flac', 'mp3', 'ogg', 'oga',
            'avi', 'mov', 'mpg', 'mpeg', 'mkv', 'ogv', 'ogx', 'webm', 'zip',
            'gz', 'bz', 'bz2', 'rpm', 'deb', 'tgz', 'rar', 'ace', '7z', 'pak',
            'iso', 'dmg'
        ]
        if os.path.exists(
                os.path.join('/home/sparkleshare', name, 'info/attributes')):
            f = open(
                os.path.join('/home/sparkleshare', name, 'info/attributes'),
                'r').read()
        else:
            f = ''
        for x in extensions:
            f += '*.%s -delta\n' % x
            f += '*.%s -delta\n' % x.upper()
        open(os.path.join('/home/sparkleshare', name, 'info/attributes'),
             'w').write(f)

        uid = pwd.getpwnam('sparkleshare').pw_uid
        gid = grp.getgrnam('sparkleshare').gr_gid
        for r, d, f in os.walk(os.path.join('/home/sparkleshare', name)):
            for x in d:
                os.chown(os.path.join(r, x), uid, gid)
                os.chmod(os.path.join(r, x), 0770)
            for x in f:
                os.chown(os.path.join(r, x), uid, gid)
                os.chmod(os.path.join(r, x), 0770)

        return ('ssh://sparkleshare@%s' %
                self.app.get_backend(IHostnameManager).gethostname().lower(),
                os.path.join('/home/sparkleshare', name))
Exemple #50
0
 def get_ram(self):
     s = shell('free -b | grep Mem').split()[1:]
     t = int(s[0])
     u = int(s[1])
     b = int(s[4])
     c = int(s[5])
     u -= c + b
     return (u, t)
Exemple #51
0
    def get_backups(self, req, start_response):
        dir = mkdtemp()
        temparch = path.join(dir, 'backup-all.tar.gz')
        shell('tar czf ' + temparch + ' -C /var/backups/ genesis')
        size = path.getsize(temparch)

        f = open(temparch, 'rb')
        arch = f.read()
        f.close()
        shell('rm -r ' + dir)

        start_response('200 OK', [
            ('Content-type', 'application/gzip'),
            ('Content-length', str(size)),
            ('Content-Disposition', 'attachment; filename=backup-all.tar.gz')
        ])
        return arch
Exemple #52
0
 def get_rx(self, iface):
     s = shell('ip -s link ls %s' % iface.name)
     s = s.split('\n')[3]
     try:
         s = s.split()[0]
     except:
         s = '0'
     return int(s)
Exemple #53
0
    def post_install(self, name, path, vars):
        port = vars.getvalue('ghost-port', '2368')
        hostname = vars.getvalue('ghost-host', '127.0.0.1')
        url = vars.getvalue('ghost-url', 'my-ghost-blog.com')

        replacements = [('2368', port), ('127.0.0.1', hostname),
                        ('my-ghost-blog.com', url)]

        # Get Mail settings
        mail_settings = {
            'transport': vars.getvalue('ghost-transport', ''),
            'service': vars.getvalue('ghost-service', ''),
            'mail_user': vars.getvalue('ghost-mail-user', ''),
            'mail_pass': vars.getvalue('ghost-mail-pass', ''),
            'from_address': vars.getvalue('ghost-from-address', '')
        }

        # Create/Edit the Ghost config file
        f = open(os.path.join(path, 'config.example.js'), 'r').read()
        with open(os.path.join(path, 'config.js'), 'w') as config_file:
            for r in replacements:
                f = f.replace(r[0], r[1])
            if len(set(mail_settings.values())) != 1 and\
               mail_settings['transport'] != '':
                # If the mail settings exist, add them
                f = f.replace(
                    "mail: {},",\
                    'mail: {\n'
                    "\tfromaddress: '" + mail_settings['from_address'] + "',\n"
                    "\ttransport: '" + mail_settings['transport'] + "',\n"
                    "\t\toptions: {\n"
                    "\t\t\tservice: '" + mail_settings['service'] + "',\n"
                    "\t\t\tauth: {\n"
                    "\t\t\t\tuser: '******'mail_user'] + "',\n"
                    "\t\t\t\tpass: '******'mail_pass'] + "'\n"
                    "\t\t\t}\n"
                    "\t\t}\n"
                    "},\n"
                )
            config_file.write(f)
            config_file.close()

        # Finally, make sure that permissions are set so that Ghost
        # can make adjustments and save plugins when need be.
        shell('chown -R http:http ' + path)
Exemple #54
0
    def remove(self, id, cat=''):
        """
        Uninstalls given plugin

        :param  id:     Plugin id
        :type   id:     str
        """

        try:
            self.purge = self.config.get('genesis', 'purge')
        except:
            self.purge = '1'

        exclude = ['openssl', 'openssh', 'nginx', 'python2']

        if cat:
            cat.put_statusmsg('Removing plugin...')
        dir = self.config.get('genesis', 'plugins')
        shell('rm -r %s/%s' % (dir, id))

        if id in PluginLoader.list_plugins():
            depends = []
            try:
                pdata = PluginLoader.list_plugins()
                thisplugin = pdata[id].deps
                for thing in thisplugin:
                    if 'app' in thing[0]:
                        depends.append((thing, 0))
                for plugin in pdata:
                    for item in enumerate(depends):
                        if item[1][0] in pdata[plugin].deps:
                            depends[item[0]] = (depends[item[0]][0],
                                                depends[item[0]][1] + 1)
                for thing in depends:
                    if thing[1] <= 1 and not thing[0][1] in exclude:
                        if cat:
                            cat.put_statusmsg('Removing dependency %s...' %
                                              thing[0][1])
                        shell('systemctl stop ' + thing[0][2])
                        shell('systemctl disable ' + thing[0][2])
                        shell('pacman -%s --noconfirm ' %
                              ('Rn' if self.purge is '1' else 'R') +
                              thing[0][1])
            except KeyError:
                pass
            PluginLoader.unload(id)

        self.update_installed()
        self.update_available()
        if cat:
            cat.put_message(
                'info',
                'Plugin removed. Refresh page for changes to take effect.')
Exemple #55
0
 def get_info(self, pkg):
     i = apis.pkgman.PackageInfo()
     ss = utils.shell('pacman -Qi ' + pkg).split('\n')
     i.installed = ''
     i.available = ss[1].split(':')[1]
     while len(ss) > 0 and not ss[0].startswith('Desc'):
         ss = ss[1:]
     ss[0] = ss[0].split(':')[1]
     i.description = '\n'.join(ss)
     return i