Example #1
0
def home():
    '''
    home page function
    '''
    if 'logged_in' in session:
        return render_template('index.html', containers=lxc.ls(), dist=lwp.check_ubuntu(), templates=lwp.get_templates_list())
    return render_template('login.html')
Example #2
0
def home():
    '''
    home page function
    '''
    if 'logged_in' in session:

        listx = lxc.listx()
        containers_all = []

        for status in ['RUNNING', 'FROZEN', 'STOPPED']:
            containers_by_status = []

            for container in listx[status]:
                containers_by_status.append({
                    'name':
                    container,
                    'memusg':
                    lwp.memory_usage(container),
                    'settings':
                    lwp.get_container_settings(container)
                })
            containers_all.append({
                'status': status.lower(),
                'containers': containers_by_status
            })

        return render_template('index.html',
                               containers=lxc.ls(),
                               containers_all=containers_all,
                               dist=lwp.check_ubuntu(),
                               templates=lwp.get_templates_list())
    return render_template('login.html')
Example #3
0
def about():
    '''
    about page
    '''
    if 'logged_in' in session:
        return render_template('about.html', containers=lxc.ls(), version=lwp.check_version())
    return render_template('login.html')
Example #4
0
def home():
    '''
    home page function
    '''

    if 'logged_in' in session:
        listx = lxc.listx()
        containers_all = []

        for status in ['RUNNING', 'FROZEN', 'STOPPED']:
            containers_by_status = []

            for container in listx[status]:
                containers_by_status.append({
                    'name': container,
                    'memusg': lwp.memory_usage(container),
                    'settings': lwp.get_container_settings(container)
                })
            containers_all.append({
                'status': status.lower(),
                'containers': containers_by_status
            })

        return render_template('index.html', containers=lxc.ls(),
                               containers_all=containers_all,
                               dist=lwp.check_ubuntu(),
                               templates=lwp.get_templates_list())
    return render_template('login.html')
Example #5
0
def checkconfig():
    '''
    returns the display of lxc-checkconfig command
    '''
    if session['su'] != 'Yes':
        return abort(403)

    return render_template('checkconfig.html', containers=lxc.ls(), cfg=lxc.checkconfig())
Example #6
0
def about():
    '''
    about page
    '''
    if 'logged_in' in session:
        return render_template('about.html',
                               containers=lxc.ls(),
                               version=lwp.check_version())
    return render_template('login.html')
Example #7
0
def about():
    '''
    about page
    '''
    if 'logged_in' in session:
        return render_template('about.html',
                               containers=lxc.ls(),
                               version=lwp.check_version(url=config.get('version', 'url'), proxy=proxy))
    return render_template('login.html')
Example #8
0
def home():
    '''
    home page function
    '''
    if 'logged_in' in session:
        return render_template('index.html',
                               containers=lxc.ls(),
                               dist=lwp.check_ubuntu(),
                               templates=lwp.get_templates_list())
    return render_template('login.html')
Example #9
0
def home():
    '''
    home page function
    '''
    if 'logged_in' in session:
        return render_template('index.html',
                               containers=lxc.ls(),
                               dist=lwp.check_ubuntu(),
                               lvm=lwp.host_lvm_usage(vgname=config.get('overview', 'lvmvg')),
                               templates=lwp.get_templates_list())
    return render_template('login.html')
Example #10
0
def checkconfig():
    '''
    returns the display of lxc-checkconfig command
    '''
    if 'logged_in' in session:
        if session['su'] != 'Yes':
            return abort(403)

        return render_template('checkconfig.html', containers=lxc.ls(),
                               cfg=lxc.checkconfig())
    return render_template('login.html')
Example #11
0
def lxc_net():
    '''
    lxc-net (/etc/default/lxc) settings page and actions if form post request
    '''
    if session['su'] != 'Yes':
        return abort(403)

    if request.method == 'POST':
        if lxc.running() == []:
            cfg = lwp.get_net_settings()
            ip_regex = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'

            form = {}
            for key in ['bridge', 'address', 'netmask', 'network', 'range', 'max']:
                form[key] = request.form.get(key, None)
            form['use'] = request.form.get('use', None)


            if form['use'] != cfg['use']:
                lwp.push_net_value('USE_LXC_BRIDGE', 'true' if form['use'] else 'false')

            if form['bridge'] and form['bridge'] != cfg['bridge'] and re.match('^[a-zA-Z0-9_-]+$', form['bridge']):
                lwp.push_net_value('LXC_BRIDGE', form['bridge'])

            if form['address'] and form['address'] != cfg['address'] and re.match('^%s$' % ip_regex, form['address']):
                lwp.push_net_value('LXC_ADDR', form['address'])

            if form['netmask'] and form['netmask'] != cfg['netmask'] and re.match('^%s$' % ip_regex, form['netmask']):
                lwp.push_net_value('LXC_NETMASK', form['netmask'])

            if form['network'] and form['network'] != cfg['network'] and re.match('^%s(?:/\d{1,2}|)$' % ip_regex, form['network']):
                lwp.push_net_value('LXC_NETWORK', form['network'])

            if form['range'] and form['range'] != cfg['range'] and re.match('^%s,%s$' % (ip_regex, ip_regex), form['range']):
                lwp.push_net_value('LXC_DHCP_RANGE', form['range'])

            if form['max'] and form['max'] != cfg['max'] and re.match('^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', form['max']):
                lwp.push_net_value('LXC_DHCP_MAX', form['max'])


            if lwp.net_restart() == 0:
                flash(u'LXC Network settings applied successfully!', 'success')
            else:
                flash(u'Failed to restart LXC networking.', 'error')
        else:
            flash(u'Stop all containers before restart lxc-net.', 'warning')
    return render_template('lxc-net.html', containers=lxc.ls(), cfg=lwp.get_net_settings(), running=lxc.running())
Example #12
0
def home():
    '''
    home page function
    '''
    if 'logged_in' in session:
        if config.has_option('overview', 'lvmvg'):
            lvm = lwp.host_lvm_usage(vgname=config.get('overview', 'lvmvg'))
        else:
            lvm = lwp.host_lvm_usage()
        tmpppath = None
        if config.has_option('templates', 'precreated'):
            tmpppath = config.get('templates', 'precreated')
        return render_template('index.html',
                               containers=lxc.ls(),
                               dist=lwp.check_system_version(),
                               system_version=lwp.check_system_version(True),
                               lvm=lvm,
                               templates=lwp.get_templates_list(),
                               templatesPrecreated=lwp.get_templates_precreated_list(tmpppath))
    return render_template('login.html')
Example #13
0
def home():
    '''
    home page function
    '''
    listx = lxc.listx()
    containers_all = []

    for status in ['RUNNING', 'FROZEN', 'STOPPED']:
        containers_by_status = []

        for container in listx[status]:
            containers_by_status.append({
                'name': container,
                'memusg': lwp.memory_usage(container),
                'settings': lwp.get_container_settings(container),
                'ipv4': lxc.get_ipv4(container),
                'bucket': get_bucket_token(container)
            })
        containers_all.append({
            'status': status.lower(),
            'containers': containers_by_status
        })

    return render_template('index.html', containers=lxc.ls(), containers_all=containers_all, dist=lwp.check_ubuntu(), host=socket.gethostname(), templates=lwp.get_templates_list(), storage_repos=storage_repos, auth=AUTH)
Example #14
0
def edit(container=None):
    '''
    edit containers page and actions if form post request
    '''
    if 'logged_in' in session:
        host_memory = lwp.host_memory_usage()
        
        if request.method == 'POST':
            cfg = lwp.get_container_settings(container)
            ip_regex = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(/(3[0-2]|[12]?[0-9]))?'
            info = lxc.info(container)
            
            form = {}
            form['type'] = request.form['type']
            form['link'] = request.form['link']
            try:
                form['flags'] = request.form['flags']
            except KeyError:
                form['flags'] = 'down'
            form['hwaddr'] = request.form['hwaddress']
            form['rootfs'] = request.form['rootfs']
            form['utsname'] = request.form['hostname']
            form['ipv4'] = request.form['ipaddress']
            try:
                form['gateway'] = request.form['gatewayaddress']
            except KeyError:
                form['gateway'] = ''
            form['memlimit'] = request.form['memlimit']
            form['swlimit'] = request.form['swlimit']
            form['cpus'] = request.form['cpus']
            form['shares'] = request.form['cpushares']
            try:
                form['autostart'] = request.form['autostart']
            except KeyError:
                form['autostart'] = False

            if form['utsname'] != cfg['utsname'] and re.match('(?!^containers$)|^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$', form['utsname']):
                lwp.push_config_value('lxc.utsname', form['utsname'], container=container)
                flash(u'Hostname updated for %s!' % container, 'success')

            if form['flags'] != cfg['flags'] and re.match('^(up|down)$', form['flags']):
                lwp.push_config_value('lxc.network.flags', form['flags'], container=container)
                flash(u'Network flag updated for %s!' % container, 'success')

            if form['type'] != cfg['type'] and re.match('^\w+$', form['type']):
                lwp.push_config_value('lxc.network.type', form['type'], container=container)
                flash(u'Link type updated for %s!' % container, 'success')

            if form['link'] != cfg['link'] and re.match('^[a-zA-Z0-9_-]+$', form['link']):
                lwp.push_config_value('lxc.network.link', form['link'], container=container)
                flash(u'Link name updated for %s!' % container, 'success')

            if form['hwaddr'] != cfg['hwaddr'] and re.match('^([a-fA-F0-9]{2}[:|\-]?){6}$', form['hwaddr']):
                lwp.push_config_value('lxc.network.hwaddr', form['hwaddr'], container=container)
                flash(u'Hardware address updated for %s!' % container, 'success')

            if ( not form['ipv4'] and form['ipv4'] != cfg['ipv4'] ) or ( form['ipv4'] != cfg['ipv4'] and re.match('^%s$' % ip_regex, form['ipv4']) ):
                lwp.push_config_value('lxc.network.ipv4', form['ipv4'], container=container)
                flash(u'IP address updated for %s!' % container, 'success')
            
            if ( not form['gateway'] and form['gateway'] != cfg['gateway'] ) or ( form['gateway'] != cfg['gateway'] and re.match('^%s$' % ip_regex, form['gateway']) ):
                if IPAddress(form['gateway']) in IPNetwork(form['ipv4']):
                    lwp.push_config_value('lxc.network.ipv4.gateway', form['gateway'], container=container)
                    flash(u'Gateway address updated for %s!' % container, 'success')
                else:
                    flash(u'Gateway address not in same network of ip address','error')


            if form['memlimit'] != cfg['memlimit'] and form['memlimit'].isdigit() and int(form['memlimit']) <= int(host_memory['total']):
                if int(form['memlimit']) == int(host_memory['total']):
                    form['memlimit'] = ''

                if form['memlimit'] != cfg['memlimit']:
                    lwp.push_config_value('lxc.cgroup.memory.limit_in_bytes', form['memlimit'], container=container)
                    if info["state"].lower() != 'stopped':
                        lxc.cgroup(container, 'lxc.cgroup.memory.limit_in_bytes', form['memlimit'])
                    flash(u'Memory limit updated for %s!' % container, 'success')

            if form['swlimit'] != cfg['swlimit'] and form['swlimit'].isdigit() and int(form['swlimit']) <= int(host_memory['total'] * 2):
                if int(form['swlimit']) == int(host_memory['total'] * 2):
                    form['swlimit'] = ''

                if form['swlimit'].isdigit(): form['swlimit'] = int(form['swlimit'])
                if form['memlimit'].isdigit(): form['memlimit'] = int(form['memlimit'])

                if ( form['memlimit'] == '' and form['swlimit'] != '' ) or ( form['memlimit'] > form['swlimit'] and form['swlimit'] != '' ):
                    flash(u'Can\'t assign swap memory lower than the memory limit', 'warning')

                elif form['swlimit'] != cfg['swlimit'] and form['memlimit'] <= form['swlimit']:
                    lwp.push_config_value('lxc.cgroup.memory.memsw.limit_in_bytes', form['swlimit'], container=container)
                    if info["state"].lower() != 'stopped':
                        lxc.cgroup(container, 'lxc.cgroup.memory.memsw.limit_in_bytes', form['swlimit'])
                    flash(u'Swap limit updated for %s!' % container, 'success')

            if ( not form['cpus'] and form['cpus'] != cfg['cpus'] ) or ( form['cpus'] != cfg['cpus'] and re.match('^[0-9,-]+$', form['cpus']) ):
                lwp.push_config_value('lxc.cgroup.cpuset.cpus', form['cpus'], container=container)
                if info["state"].lower() != 'stopped':
                        lxc.cgroup(container, 'lxc.cgroup.cpuset.cpus', form['cpus'])
                flash(u'CPUs updated for %s!' % container, 'success')

            if ( not form['shares'] and form['shares'] != cfg['shares'] ) or ( form['shares'] != cfg['shares'] and re.match('^[0-9]+$', form['shares']) ):
                lwp.push_config_value('lxc.cgroup.cpu.shares', form['shares'], container=container)
                if info["state"].lower() != 'stopped':
                        lxc.cgroup(container, 'lxc.cgroup.cpu.shares', form['shares'])
                flash(u'CPU shares updated for %s!' % container, 'success')

            if form['rootfs'] != cfg['rootfs'] and re.match('^[a-zA-Z0-9_/\-]+', form['rootfs']):
                lwp.push_config_value('lxc.rootfs', form['rootfs'], container=container)
                flash(u'Rootfs updated!' % container, 'success')

            auto = lwp.ls_auto()
            if form['autostart'] == 'True' and not ('%s.conf' % container) in auto:
                try:
                    os.symlink('/var/lib/lxc/%s/config' % container, '/etc/lxc/auto/%s.conf' % container)
                    flash(u'Autostart enabled for %s' % container, 'success')
                except OSError:
                    flash(u'Unable to create symlink \'/etc/lxc/auto/%s.conf\'' % container, 'error')
            elif not form['autostart'] and ('%s.conf' % container) in auto:
                try:
                    os.remove('/etc/lxc/auto/%s.conf' % container)
                    flash(u'Autostart disabled for %s' % container, 'success')
                except OSError:
                    flash(u'Unable to remove symlink', 'error')


        info = lxc.info(container)
        status = info['state']
        pid = info['pid']

        infos = {'status': status, 'pid': pid, 'memusg': lwp.memory_usage(container)}
        return render_template('edit.html', containers=lxc.ls(), container=container, infos=infos, settings=lwp.get_container_settings(container), host_memory=host_memory)
    return render_template('login.html')
Example #15
0
def lxc_net():
    '''
    lxc-net (/etc/default/lxc) settings page and actions if form post request
    '''
    if 'logged_in' in session:
        if session['su'] != 'Yes':
            return abort(403)
        try:
            cfg = lwp.get_net_settings()
        except lwp.LxcConfigFileNotComplete:
            cfg = []

        if request.method == 'POST': #By default the request method is GET

            if lxc.running() == []:
                ip_regex = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'

                form = {}
                try: form['use'] = request.form['use']
                except KeyError: form['use'] = 'false'

                try: form['bridge'] = request.form['bridge']
                except KeyError: form['bridge'] = None

                try: form['address'] = request.form['address']
                except KeyError: form['address'] = None

                try: form['netmask'] = request.form['netmask']
                except KeyError: form['netmask'] = None

                try: form['network'] = request.form['network']
                except KeyError: form['network'] = None

                try: form['range'] = request.form['range']
                except KeyError: form['range'] = None

                try: form['max'] = request.form['max']
                except KeyError: form['max'] = None


                if form['use'] == 'true' and form['use'] != cfg['use']:
                    lwp.push_net_value('USE_LXC_BRIDGE', 'true')

                elif form['use'] == 'false' and form['use'] != cfg['use']:
                    lwp.push_net_value('USE_LXC_BRIDGE', 'false')

                if form['bridge'] and form['bridge'] != cfg['bridge'] and re.match('^[a-zA-Z0-9_-]+$', form['bridge']):
                    lwp.push_net_value('LXC_BRIDGE', form['bridge'])

                if form['address'] and form['address'] != cfg['address'] and re.match('^%s$' % ip_regex, form['address']):
                    lwp.push_net_value('LXC_ADDR', form['address'])

                if form['netmask'] and form['netmask'] != cfg['netmask'] and re.match('^%s$' % ip_regex, form['netmask']):
                    lwp.push_net_value('LXC_NETMASK', form['netmask'])

                if form['network'] and form['network'] != cfg['network'] and re.match('^%s(?:/\d{1,2}|)$' % ip_regex, form['network']):
                    lwp.push_net_value('LXC_NETWORK', form['network'])

                if form['range'] and form['range'] != cfg['range'] and re.match('^%s,%s$' % (ip_regex, ip_regex), form['range']):
                    lwp.push_net_value('LXC_DHCP_RANGE', form['range'])

                if form['max'] and form['max'] != cfg['max'] and re.match('^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', form['max']):
                    lwp.push_net_value('LXC_DHCP_MAX', form['max'])


                if lwp.net_restart() == 0:
                    flash(u'LXC Network settings applied successfully!', 'success')
                else:
                    flash(u'Failed to restart LXC networking.', 'error')
            else:
                flash(u'Stop all containers before restart lxc-net.', 'warning')
        if cfg == []:
            flash(u'This is not a Ubuntu distro ! Check if all config params are set in /etc/default/lxc','warning')
            return redirect(url_for('home'))
        return render_template('lxc-net.html', containers=lxc.ls(), cfg=cfg, running=lxc.running())
    return render_template('login.html')
Example #16
0
def lwp_users():
    '''
    returns users and get posts request : can edit or add user in page.
    this funtction uses sqlite3
    '''
    if 'logged_in' in session:
        if session['su'] != 'Yes':
            return abort(403)

        try:
            trash = request.args.get('trash')
        except KeyError:
            trash = 0

        su_users = query_db("SELECT COUNT(id) as num FROM users WHERE su='Yes'", [], one=True)

        if request.args.get('token') == session.get('token') and int(trash) == 1 and request.args.get('userid') and request.args.get('username'):
            nb_users = query_db("SELECT COUNT(id) as num FROM users", [], one=True)

            if nb_users['num'] > 1:
                if su_users['num'] <= 1:
                    su_user = query_db("SELECT username FROM users WHERE su='Yes'", [], one=True)

                    if su_user['username'] == request.args.get('username'):
                        flash(u'Can\'t delete the last admin user : %s' % request.args.get('username'), 'error')
                        return redirect(url_for('lwp_users'))

                g.db.execute("DELETE FROM users WHERE id=? AND username=?", [request.args.get('userid'), request.args.get('username')])
                g.db.commit()
                flash(u'Deleted %s' % request.args.get('username'), 'success')
                return redirect(url_for('lwp_users'))

            flash(u'Can\'t delete the last user!', 'error')
            return redirect(url_for('lwp_users'))

        if request.method == 'POST':
            users = query_db('SELECT id, name, username, su FROM users ORDER BY id ASC')

            if request.form['newUser'] == 'True':
                if not request.form['username'] in [user['username'] for user in users]:
                    if re.match('^\w+$', request.form['username']) and request.form['password1']:
                        if request.form['password1'] == request.form['password2']:
                            if request.form['name']:
                                if re.match('[a-z A-Z0-9]{3,32}', request.form['name']):
                                    g.db.execute("INSERT INTO users (name, username, password) VALUES (?, ?, ?)", [request.form['name'], request.form['username'], hash_passwd(request.form['password1'])])
                                    g.db.commit()
                                else: flash(u'Invalid name!', 'error')
                            else:
                                g.db.execute("INSERT INTO users (username, password) VALUES (?, ?)", [request.form['username'], hash_passwd(request.form['password1'])])
                                g.db.commit()

                            flash(u'Created %s' % request.form['username'], 'success')
                        else: flash(u'No password match', 'error')
                    else: flash(u'Invalid username or password!', 'error')
                else: flash(u'Username already exist!', 'error')

            elif request.form['newUser'] == 'False':
                if request.form['password1'] == request.form['password2']:
                    if re.match('[a-z A-Z0-9]{3,32}', request.form['name']):
                        if su_users['num'] <= 1:
                            su = 'Yes'
                        else:
                            try:
                                su = request.form['su']
                            except KeyError:
                                su = 'No'

                        if not request.form['name']:
                            g.db.execute("UPDATE users SET name='', su=? WHERE username=?", [su, request.form['username']])
                            g.db.commit()
                        elif request.form['name'] and not request.form['password1'] and not request.form['password2']:
                            g.db.execute("UPDATE users SET name=?, su=? WHERE username=?", [request.form['name'], su, request.form['username']])
                            g.db.commit()
                        elif request.form['name'] and request.form['password1'] and request.form['password2']:
                            g.db.execute("UPDATE users SET name=?, password=?, su=? WHERE username=?", [request.form['name'], hash_passwd(request.form['password1']), su, request.form['username']])
                            g.db.commit()
                        elif request.form['password1'] and request.form['password2']:
                            g.db.execute("UPDATE users SET password=?, su=? WHERE username=?", [hash_passwd(request.form['password1']), su, request.form['username']])
                            g.db.commit()

                        flash(u'Updated', 'success')
                    else:
                        flash(u'Invalid name!', 'error')
                else:
                    flash(u'No password match', 'error')
            else:
                flash(u'Unknown error!', 'error')

        users = query_db("SELECT id, name, username, su FROM users ORDER BY id ASC")
        nb_users = query_db("SELECT COUNT(id) as num FROM users", [], one=True)
        su_users = query_db("SELECT COUNT(id) as num FROM users WHERE su='Yes'", [], one=True)

        return render_template('users.html', containers=lxc.ls(), users=users, nb_users=nb_users, su_users=su_users)
    return render_template('login.html')
Example #17
0
def edit(container=None):
    '''
    edit containers page and actions if form post request
    '''
    if 'logged_in' in session:
        host_memory = lwp.host_memory_usage()
        
        info = lxc.info(container)

        if request.method == 'POST':
            cfg = lwp.get_container_settings(container)
            ip_regex = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(/(3[0-2]|[12]?[0-9]))?'

            form = {}
            form['type'] = request.form['type']
            form['link'] = request.form['link']
            try:
                form['flags'] = request.form['flags']
            except KeyError:
                form['flags'] = 'down'
            form['hwaddr'] = request.form['hwaddress']
            form['rootfs'] = request.form['rootfs']
            form['utsname'] = request.form['hostname']
            form['ipv4'] = request.form['ipaddress']
            form['memlimit'] = request.form['memlimit']
            form['swlimit'] = request.form['swlimit']
            form['cpus'] = request.form['cpus']
            form['shares'] = request.form['cpushares']
            try:
                form['autostart'] = request.form['autostart']
            except KeyError:
                form['autostart'] = False


            form['priority'] = request.form['priority']
            if form['priority'].isdigit():
                form['priority'] = int(form['priority'])
            else:
                form['priority'] = ''


            if form['utsname'] != cfg['utsname'] and re.match('(?!^containers$)|^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$', form['utsname']):
                lwp.push_config_value('lxc.utsname', form['utsname'], container=container)
                flash(u'Hostname updated for %s!' % container, 'success')

            if form['flags'] != cfg['flags'] and re.match('^(up|down)$', form['flags']):
                lwp.push_config_value('lxc.network.flags', form['flags'], container=container)
                flash(u'Network flag updated for %s!' % container, 'success')

            if form['type'] != cfg['type'] and re.match('^\w+$', form['type']):
                lwp.push_config_value('lxc.network.type', form['type'], container=container)
                flash(u'Link type updated for %s!' % container, 'success')

            if form['link'] != cfg['link'] and re.match('^[\w\d]+$', form['link']):
                lwp.push_config_value('lxc.network.link', form['link'], container=container)
                flash(u'Link name updated for %s!' % container, 'success')

            if form['hwaddr'] != cfg['hwaddr'] and re.match('^([a-fA-F0-9]{2}[:|\-]?){6}$', form['hwaddr']):
                lwp.push_config_value('lxc.network.hwaddr', form['hwaddr'], container=container)
                flash(u'Hardware address updated for %s!' % container, 'success')

            if ( not form['ipv4'] and form['ipv4'] != cfg['ipv4'] ) or ( form['ipv4'] != cfg['ipv4'] and re.match('^%s$' % ip_regex, form['ipv4']) ):
                lwp.push_config_value('lxc.network.ipv4', form['ipv4'], container=container)
                flash(u'IP address updated for %s!' % container, 'success')

            if form['memlimit'] != cfg['memlimit'] and form['memlimit'].isdigit() and int(form['memlimit']) <= int(host_memory['total']):
                if int(form['memlimit']) == int(host_memory['total']):
                    form['memlimit'] = ''

                if form['memlimit'] != cfg['memlimit']:
                    lwp.push_config_value('lxc.cgroup.memory.limit_in_bytes', form['memlimit'], container=container)
                    if info["state"].lower() != "stopped":
                        lxc.cgroup(container, 'lxc.cgroup.memory.limit_in_bytes', int(form['memlimit'])*1024*1024)
                    flash(u'Memory limit updated for %s!' % container, 'success')

            if form['swlimit'] != cfg['swlimit'] and form['swlimit'].isdigit() and int(form['swlimit']) <= int(host_memory['total'] * 2):
                if int(form['swlimit']) == int(host_memory['total'] * 2):
                    form['swlimit'] = ''

                if form['swlimit'].isdigit(): form['swlimit'] = int(form['swlimit'])
                if form['memlimit'].isdigit(): form['memlimit'] = int(form['memlimit'])

                if ( form['memlimit'] == '' and form['swlimit'] != '' ) or ( form['memlimit'] > form['swlimit'] and form['swlimit'] != '' ):
                    flash(u'Can\'t assign swap memory lower than the memory limit', 'warning')

                elif form['swlimit'] != cfg['swlimit'] and form['memlimit'] <= form['swlimit']:
                    lwp.push_config_value('lxc.cgroup.memory.memsw.limit_in_bytes', form['swlimit'], container=container)
                    if info["state"].lower() != "stopped":
                        lxc.cgroup(container, 'lxc.cgroup.memory.memsw.limit_in_bytes', int(form['swlimit'])*1024*1024)
                    flash(u'Swap limit updated for %s!' % container, 'success')

            if ( not form['cpus'] and form['cpus'] != cfg['cpus'] ) or ( form['cpus'] != cfg['cpus'] and re.match('^[0-9,-]+$', form['cpus']) ):
                lwp.push_config_value('lxc.cgroup.cpuset.cpus', form['cpus'], container=container)
                if info["state"].lower() != "stopped":
                    lxc.cgroup(container, 'lxc.cgroup.cpuset.cpus', form['cpus'])
                flash(u'CPUs updated for %s!' % container, 'success')

            if ( not form['shares'] and form['shares'] != cfg['shares'] ) or ( form['shares'] != cfg['shares'] and re.match('^[0-9]+$', form['shares']) ):
                lwp.push_config_value('lxc.cgroup.cpu.shares', form['shares'], container=container)
                if info["state"].lower() != "stopped":
                    lxc.cgroup(container, 'lxc.cgroup.cpu.shares', form['shares'])
                flash(u'CPU shares updated for %s!' % container, 'success')

            if form['rootfs'] != cfg['rootfs'] and re.match('^[a-zA-Z0-9_/\-]+', form['rootfs']):
                lwp.push_config_value('lxc.rootfs', form['rootfs'], container=container)
                flash(u'Rootfs updated!' % container, 'success')

            auto = lwp.ls_auto()
            if form['autostart'] == 'True' and (not container in auto or auto[container] != form['priority']):
                try:
                    if container in auto and auto[container]:
                        old_conf = '/etc/lxc/auto/%06d-%s.conf' % (auto[container], container,)
                        if os.path.exists(old_conf):
                            os.remove(old_conf)
                            flash(u'Autostart for %s: old priority dropped' % container, 'success')
                    else:
                        old_conf = '/etc/lxc/auto/%s.conf' % (container,)
                        if os.path.exists(old_conf):
                            os.remove(old_conf)
                            flash(u'Autostart for %s: default priority dropped' % container, 'success')

                    if form['priority']:
                        new_conf = '/etc/lxc/auto/%06d-%s.conf' % (form['priority'], container, )
                        flash(u'Autostart for %s: set new priority' % container, 'success')
                    else:
                        new_conf = '/etc/lxc/auto/%s.conf' % (container,)

                    os.symlink('/var/lib/lxc/%s/config' % container, new_conf)
                    flash(u'Autostart enabled for %s' % container, 'success')
                except OSError:
                    flash(u'Unable to create symlink \'/etc/lxc/auto/%s.conf\'' % container, 'error')
            elif not form['autostart'] and container in auto:
                try:
                    if auto[container]:
                        old_conf = '/etc/lxc/auto/%06d-%s.conf' % (auto[container], container, )
                    else:
                        old_conf = '/etc/lxc/auto/%s.conf' % (container, )
                    os.remove(old_conf)
                    flash(u'Autostart disabled for %s' % container, 'success')
                except OSError:
                    flash(u'Unable to remove symlink', 'error')


        info = lxc.info(container)
        status = info['state']
        pid = info['pid']

        infos = {
            'status': status,
            'pid': pid,
            'memusg': lwp.memory_usage(container),
            'cpu': lwp.container_cpu_percent(container),
            'max_memusg': lwp.max_memory_usage(container),
            'diskusg': lwp.get_filesystem_usage(container)
        }

        settings = lwp.get_container_settings(container)
        settings["ipv4_hint"] = 'Undefined'
        if settings["ipv4_real"]:
            settings["ipv4_hint"] = settings["ipv4"]
            settings["ipv4"] = ''

        # Align value to slider step
        host_memory["total"] -= host_memory["total"] % 2

        return render_template('edit.html',
                               containers=lxc.ls(),
                               container=container,
                               infos=infos,
                               settings=settings,
                               host_memory=host_memory)
    return render_template('login.html')
Example #18
0
def lwp_users():
    '''
    returns users and get posts request : can edit or add user in page.
    this funtction uses sqlite3
    '''
    if 'logged_in' in session:
        if session['su'] != 'Yes':
            return abort(403)

        try:
            trash = request.args.get('trash')
        except KeyError:
            trash = 0

        su_users = query_db(
            "SELECT COUNT(id) as num FROM users WHERE su='Yes'", [], one=True)

        if request.args.get('token') == session.get('token') and int(
                trash) == 1 and request.args.get(
                    'userid') and request.args.get('username'):
            nb_users = query_db("SELECT COUNT(id) as num FROM users", [],
                                one=True)

            if nb_users['num'] > 1:
                if su_users['num'] <= 1:
                    su_user = query_db(
                        "SELECT username FROM users WHERE su='Yes'", [],
                        one=True)

                    if su_user['username'] == request.args.get('username'):
                        flash(
                            u'Can\'t delete the last admin user : %s' %
                            request.args.get('username'), 'error')
                        return redirect(url_for('lwp_users'))

                g.db.execute(
                    "DELETE FROM users WHERE id=? AND username=?",
                    [request.args.get('userid'),
                     request.args.get('username')])
                g.db.commit()
                flash(u'Deleted %s' % request.args.get('username'), 'success')
                return redirect(url_for('lwp_users'))

            flash(u'Can\'t delete the last user!', 'error')
            return redirect(url_for('lwp_users'))

        if request.method == 'POST':
            users = query_db(
                'SELECT id, name, username, su FROM users ORDER BY id ASC')

            if request.form['newUser'] == 'True':
                if not request.form['username'] in [
                        user['username'] for user in users
                ]:
                    if re.match('^\w+$', request.form['username']
                                ) and request.form['password1']:
                        if request.form['password1'] == request.form[
                                'password2']:
                            if request.form['name']:
                                if re.match('[a-z A-Z0-9]{3,32}',
                                            request.form['name']):
                                    g.db.execute(
                                        "INSERT INTO users (name, username, password) VALUES (?, ?, ?)",
                                        [
                                            request.form['name'],
                                            request.form['username'],
                                            hash_passwd(
                                                request.form['password1'])
                                        ])
                                    g.db.commit()
                                else:
                                    flash(u'Invalid name!', 'error')
                            else:
                                g.db.execute(
                                    "INSERT INTO users (username, password) VALUES (?, ?)",
                                    [
                                        request.form['username'],
                                        hash_passwd(request.form['password1'])
                                    ])
                                g.db.commit()

                            flash(u'Created %s' % request.form['username'],
                                  'success')
                        else:
                            flash(u'No password match', 'error')
                    else:
                        flash(u'Invalid username or password!', 'error')
                else:
                    flash(u'Username already exist!', 'error')

            elif request.form['newUser'] == 'False':
                if request.form['password1'] == request.form['password2']:
                    if re.match('[a-z A-Z0-9]{3,32}', request.form['name']):
                        if su_users['num'] <= 1:
                            su = 'Yes'
                        else:
                            try:
                                su = request.form['su']
                            except KeyError:
                                su = 'No'

                        if not request.form['name']:
                            g.db.execute(
                                "UPDATE users SET name='', su=? WHERE username=?",
                                [su, request.form['username']])
                            g.db.commit()
                        elif request.form['name'] and not request.form[
                                'password1'] and not request.form['password2']:
                            g.db.execute(
                                "UPDATE users SET name=?, su=? WHERE username=?",
                                [
                                    request.form['name'], su,
                                    request.form['username']
                                ])
                            g.db.commit()
                        elif request.form['name'] and request.form[
                                'password1'] and request.form['password2']:
                            g.db.execute(
                                "UPDATE users SET name=?, password=?, su=? WHERE username=?",
                                [
                                    request.form['name'],
                                    hash_passwd(request.form['password1']), su,
                                    request.form['username']
                                ])
                            g.db.commit()
                        elif request.form['password1'] and request.form[
                                'password2']:
                            g.db.execute(
                                "UPDATE users SET password=?, su=? WHERE username=?",
                                [
                                    hash_passwd(request.form['password1']), su,
                                    request.form['username']
                                ])
                            g.db.commit()

                        flash(u'Updated', 'success')
                    else:
                        flash(u'Invalid name!', 'error')
                else:
                    flash(u'No password match', 'error')
            else:
                flash(u'Unknown error!', 'error')

        users = query_db(
            "SELECT id, name, username, su FROM users ORDER BY id ASC")
        nb_users = query_db("SELECT COUNT(id) as num FROM users", [], one=True)
        su_users = query_db(
            "SELECT COUNT(id) as num FROM users WHERE su='Yes'", [], one=True)

        return render_template('users.html',
                               containers=lxc.ls(),
                               users=users,
                               nb_users=nb_users,
                               su_users=su_users)
    return render_template('login.html')
Example #19
0
def lxc_net():
    '''
    lxc-net (/etc/default/lxc) settings page and actions if form post request
    '''
    if 'logged_in' in session:
        if session['su'] != 'Yes':
            return abort(403)

        if request.method == 'POST':
            if lxc.running() == []:
                cfg = lwp.get_net_settings()
                ip_regex = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'

                form = {}
                try:
                    form['use'] = request.form['use']
                except KeyError:
                    form['use'] = 'false'

                try:
                    form['bridge'] = request.form['bridge']
                except KeyError:
                    form['bridge'] = None

                try:
                    form['address'] = request.form['address']
                except KeyError:
                    form['address'] = None

                try:
                    form['netmask'] = request.form['netmask']
                except KeyError:
                    form['netmask'] = None

                try:
                    form['network'] = request.form['network']
                except KeyError:
                    form['network'] = None

                try:
                    form['range'] = request.form['range']
                except KeyError:
                    form['range'] = None

                try:
                    form['max'] = request.form['max']
                except KeyError:
                    form['max'] = None

                if form['use'] == 'true' and form['use'] != cfg['use']:
                    lwp.push_net_value('USE_LXC_BRIDGE', 'true')

                elif form['use'] == 'false' and form['use'] != cfg['use']:
                    lwp.push_net_value('USE_LXC_BRIDGE', 'false')

                if form['bridge'] and form[
                        'bridge'] != cfg['bridge'] and re.match(
                            '^[a-zA-Z0-9_-]+$', form['bridge']):
                    lwp.push_net_value('LXC_BRIDGE', form['bridge'])

                if form['address'] and form[
                        'address'] != cfg['address'] and re.match(
                            '^%s$' % ip_regex, form['address']):
                    lwp.push_net_value('LXC_ADDR', form['address'])

                if form['netmask'] and form[
                        'netmask'] != cfg['netmask'] and re.match(
                            '^%s$' % ip_regex, form['netmask']):
                    lwp.push_net_value('LXC_NETMASK', form['netmask'])

                if form['network'] and form[
                        'network'] != cfg['network'] and re.match(
                            '^%s(?:/\d{1,2}|)$' % ip_regex, form['network']):
                    lwp.push_net_value('LXC_NETWORK', form['network'])

                if form['range'] and form['range'] != cfg['range'] and re.match(
                        '^%s,%s$' % (ip_regex, ip_regex), form['range']):
                    lwp.push_net_value('LXC_DHCP_RANGE', form['range'])

                if form['max'] and form['max'] != cfg['max'] and re.match(
                        '^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$',
                        form['max']):
                    lwp.push_net_value('LXC_DHCP_MAX', form['max'])

                if lwp.net_restart() == 0:
                    flash(u'LXC Network settings applied successfully!',
                          'success')
                else:
                    flash(u'Failed to restart LXC networking.', 'error')
            else:
                flash(u'Stop all containers before restart lxc-net.',
                      'warning')
        return render_template('lxc-net.html',
                               containers=lxc.ls(),
                               cfg=lwp.get_net_settings(),
                               running=lxc.running())
    return render_template('login.html')
Example #20
0
def edit(container=None):
    '''
    edit containers page and actions if form post request
    '''
    if 'logged_in' in session:
        host_memory = lwp.host_memory_usage()

        if request.method == 'POST':
            cfg = lwp.get_container_settings(container)
            ip_regex = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(/(3[0-2]|[12]?[0-9]))?'
            info = lxc.info(container)

            form = {}
            form['type'] = request.form['type']
            form['link'] = request.form['link']
            try:
                form['flags'] = request.form['flags']
            except KeyError:
                form['flags'] = 'down'
            form['hwaddr'] = request.form['hwaddress']
            form['rootfs'] = request.form['rootfs']
            form['utsname'] = request.form['hostname']
            form['ipv4'] = request.form['ipaddress']
            form['memlimit'] = request.form['memlimit']
            form['swlimit'] = request.form['swlimit']
            form['cpus'] = request.form['cpus']
            form['shares'] = request.form['cpushares']
            try:
                form['autostart'] = request.form['autostart']
            except KeyError:
                form['autostart'] = False

            if form['utsname'] != cfg['utsname'] and re.match(
                    '(?!^containers$)|^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$',
                    form['utsname']):
                lwp.push_config_value('lxc.utsname',
                                      form['utsname'],
                                      container=container)
                flash(u'Hostname updated for %s!' % container, 'success')

            if form['flags'] != cfg['flags'] and re.match(
                    '^(up|down)$', form['flags']):
                lwp.push_config_value('lxc.network.flags',
                                      form['flags'],
                                      container=container)
                flash(u'Network flag updated for %s!' % container, 'success')

            if form['type'] != cfg['type'] and re.match('^\w+$', form['type']):
                lwp.push_config_value('lxc.network.type',
                                      form['type'],
                                      container=container)
                flash(u'Link type updated for %s!' % container, 'success')

            if form['link'] != cfg['link'] and re.match(
                    '^[a-zA-Z0-9_-]+$', form['link']):
                lwp.push_config_value('lxc.network.link',
                                      form['link'],
                                      container=container)
                flash(u'Link name updated for %s!' % container, 'success')

            if form['hwaddr'] != cfg['hwaddr'] and re.match(
                    '^([a-fA-F0-9]{2}[:|\-]?){6}$', form['hwaddr']):
                lwp.push_config_value('lxc.network.hwaddr',
                                      form['hwaddr'],
                                      container=container)
                flash(u'Hardware address updated for %s!' % container,
                      'success')

            if (not form['ipv4'] and form['ipv4'] != cfg['ipv4']) or (
                    form['ipv4'] != cfg['ipv4']
                    and re.match('^%s$' % ip_regex, form['ipv4'])):
                lwp.push_config_value('lxc.network.ipv4',
                                      form['ipv4'],
                                      container=container)
                flash(u'IP address updated for %s!' % container, 'success')

            if form['memlimit'] != cfg['memlimit'] and form[
                    'memlimit'].isdigit() and int(form['memlimit']) <= int(
                        host_memory['total']):
                if int(form['memlimit']) == int(host_memory['total']):
                    form['memlimit'] = ''

                if form['memlimit'] != cfg['memlimit']:
                    lwp.push_config_value('lxc.cgroup.memory.limit_in_bytes',
                                          form['memlimit'],
                                          container=container)
                    if info["state"].lower() != 'stopped':
                        lxc.cgroup(container,
                                   'lxc.cgroup.memory.limit_in_bytes',
                                   form['memlimit'])
                    flash(u'Memory limit updated for %s!' % container,
                          'success')

            if form['swlimit'] != cfg['swlimit'] and form['swlimit'].isdigit(
            ) and int(form['swlimit']) <= int(host_memory['total'] * 2):
                if int(form['swlimit']) == int(host_memory['total'] * 2):
                    form['swlimit'] = ''

                if form['swlimit'].isdigit():
                    form['swlimit'] = int(form['swlimit'])
                if form['memlimit'].isdigit():
                    form['memlimit'] = int(form['memlimit'])

                if (form['memlimit'] == '' and form['swlimit'] != '') or (
                        form['memlimit'] > form['swlimit']
                        and form['swlimit'] != ''):
                    flash(
                        u'Can\'t assign swap memory lower than the memory limit',
                        'warning')

                elif form['swlimit'] != cfg['swlimit'] and form[
                        'memlimit'] <= form['swlimit']:
                    lwp.push_config_value(
                        'lxc.cgroup.memory.memsw.limit_in_bytes',
                        form['swlimit'],
                        container=container)
                    if info["state"].lower() != 'stopped':
                        lxc.cgroup(container,
                                   'lxc.cgroup.memory.memsw.limit_in_bytes',
                                   form['swlimit'])
                    flash(u'Swap limit updated for %s!' % container, 'success')

            if (not form['cpus'] and form['cpus'] != cfg['cpus']) or (
                    form['cpus'] != cfg['cpus']
                    and re.match('^[0-9,-]+$', form['cpus'])):
                lwp.push_config_value('lxc.cgroup.cpuset.cpus',
                                      form['cpus'],
                                      container=container)
                if info["state"].lower() != 'stopped':
                    lxc.cgroup(container, 'lxc.cgroup.cpuset.cpus',
                               form['cpus'])
                flash(u'CPUs updated for %s!' % container, 'success')

            if (not form['shares'] and form['shares'] != cfg['shares']) or (
                    form['shares'] != cfg['shares']
                    and re.match('^[0-9]+$', form['shares'])):
                lwp.push_config_value('lxc.cgroup.cpu.shares',
                                      form['shares'],
                                      container=container)
                if info["state"].lower() != 'stopped':
                    lxc.cgroup(container, 'lxc.cgroup.cpu.shares',
                               form['shares'])
                flash(u'CPU shares updated for %s!' % container, 'success')

            if form['rootfs'] != cfg['rootfs'] and re.match(
                    '^[a-zA-Z0-9_/\-]+', form['rootfs']):
                lwp.push_config_value('lxc.rootfs',
                                      form['rootfs'],
                                      container=container)
                flash(u'Rootfs updated!' % container, 'success')

            auto = lwp.ls_auto()
            if form['autostart'] == 'True' and not ('%s.conf' %
                                                    container) in auto:
                try:
                    os.symlink(
                        '/var/lib/docker/containers/%s/config' % container,
                        '/etc/lxc/auto/%s.conf' % container)
                    flash(u'Autostart enabled for %s' % container, 'success')
                except OSError:
                    flash(
                        u'Unable to create symlink \'/etc/lxc/auto/%s.conf\'' %
                        container, 'error')
            elif not form['autostart'] and ('%s.conf' % container) in auto:
                try:
                    os.remove('/etc/lxc/auto/%s.conf' % container)
                    flash(u'Autostart disabled for %s' % container, 'success')
                except OSError:
                    flash(u'Unable to remove symlink', 'error')

        info = lxc.info(container)
        status = info['state']
        pid = info['pid']

        infos = {
            'status': status,
            'pid': pid,
            'memusg': lwp.memory_usage(container)
        }
        return render_template('edit.html',
                               containers=lxc.ls(),
                               container=container,
                               infos=infos,
                               settings=lwp.get_container_settings(container),
                               host_memory=host_memory)
    return render_template('login.html')
Example #21
0
def edit(container=None):
    '''
    edit containers page and actions if form post request
    '''
    host_memory = lwp.host_memory_usage()
    cfg = lwp.get_container_settings(container)
    # read config also from databases
    cfg['bucket'] = get_bucket_token(container)

    if request.method == 'POST':
        ip_regex = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(/(3[0-2]|[12]?[0-9]))?'
        info = lxc.info(container)

        form = {}
        form['type'] = request.form['type']
        form['link'] = request.form['link']
        try:
            form['flags'] = request.form['flags']
        except KeyError:
            form['flags'] = 'down'
        form['hwaddr'] = request.form['hwaddress']
        form['rootfs'] = request.form['rootfs']
        form['utsname'] = request.form['hostname']
        form['ipv4'] = request.form['ipaddress']
        form['memlimit'] = request.form['memlimit']
        form['swlimit'] = request.form['swlimit']
        form['cpus'] = request.form['cpus']
        form['shares'] = request.form['cpushares']
        form['bucket'] = request.form['bucket']
        try:
            form['autostart'] = request.form['autostart']
        except KeyError:
            form['autostart'] = False

        if form['utsname'] != cfg['utsname'] and re.match('(?!^containers$)|^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$', form['utsname']):
            lwp.push_config_value('lxc.utsname', form['utsname'], container=container)
            flash(u'Hostname updated for %s!' % container, 'success')

        if form['flags'] != cfg['flags'] and re.match('^(up|down)$', form['flags']):
            lwp.push_config_value('lxc.network.flags', form['flags'], container=container)
            flash(u'Network flag updated for %s!' % container, 'success')

        if form['type'] != cfg['type'] and re.match('^\w+$', form['type']):
            lwp.push_config_value('lxc.network.type', form['type'], container=container)
            flash(u'Link type updated for %s!' % container, 'success')

        if form['link'] != cfg['link'] and re.match('^[a-zA-Z0-9_-]+$', form['link']):
            lwp.push_config_value('lxc.network.link', form['link'], container=container)
            flash(u'Link name updated for %s!' % container, 'success')

        if form['hwaddr'] != cfg['hwaddr'] and re.match('^([a-fA-F0-9]{2}[:|\-]?){6}$', form['hwaddr']):
            lwp.push_config_value('lxc.network.hwaddr', form['hwaddr'], container=container)
            flash(u'Hardware address updated for %s!' % container, 'success')

        if (not form['ipv4'] and form['ipv4'] != cfg['ipv4']) or (form['ipv4'] != cfg['ipv4'] and re.match('^%s$' % ip_regex, form['ipv4'])):
            lwp.push_config_value('lxc.network.ipv4', form['ipv4'], container=container)
            flash(u'IP address updated for %s!' % container, 'success')

        if form['memlimit'] != cfg['memlimit'] and form['memlimit'].isdigit() and int(form['memlimit']) <= int(host_memory['total']):
            if int(form['memlimit']) == int(host_memory['total']):
                form['memlimit'] = ''

            if form['memlimit'] != cfg['memlimit']:
                lwp.push_config_value('lxc.cgroup.memory.limit_in_bytes', form['memlimit'], container=container)
                if info["state"].lower() != 'stopped':
                    lxc.cgroup(container, 'lxc.cgroup.memory.limit_in_bytes', form['memlimit'])
                flash(u'Memory limit updated for %s!' % container, 'success')

        if form['swlimit'] != cfg['swlimit'] and form['swlimit'].isdigit() and int(form['swlimit']) <= int(host_memory['total'] * 2):
            if int(form['swlimit']) == int(host_memory['total'] * 2):
                form['swlimit'] = ''

            if form['swlimit'].isdigit():
                form['swlimit'] = int(form['swlimit'])

            if form['memlimit'].isdigit():
                form['memlimit'] = int(form['memlimit'])

            if (form['memlimit'] == '' and form['swlimit'] != '') or (form['memlimit'] > form['swlimit'] and form['swlimit'] != ''):
                flash(u'Can\'t assign swap memory lower than the memory limit', 'warning')

            elif form['swlimit'] != cfg['swlimit'] and form['memlimit'] <= form['swlimit']:
                lwp.push_config_value('lxc.cgroup.memory.memsw.limit_in_bytes', form['swlimit'], container=container)
                if info["state"].lower() != 'stopped':
                    lxc.cgroup(container, 'lxc.cgroup.memory.memsw.limit_in_bytes', form['swlimit'])
                flash(u'Swap limit updated for %s!' % container, 'success')

        if (not form['cpus'] and form['cpus'] != cfg['cpus']) or (form['cpus'] != cfg['cpus'] and re.match('^[0-9,-]+$', form['cpus'])):
            lwp.push_config_value('lxc.cgroup.cpuset.cpus', form['cpus'], container=container)
            if info["state"].lower() != 'stopped':
                    lxc.cgroup(container, 'lxc.cgroup.cpuset.cpus', form['cpus'])
            flash(u'CPUs updated for %s!' % container, 'success')

        if (not form['shares'] and form['shares'] != cfg['shares']) or (form['shares'] != cfg['shares'] and re.match('^[0-9]+$', form['shares'])):
            lwp.push_config_value('lxc.cgroup.cpu.shares', form['shares'], container=container)
            if info["state"].lower() != 'stopped':
                    lxc.cgroup(container, 'lxc.cgroup.cpu.shares', form['shares'])
            flash(u'CPU shares updated for %s!' % container, 'success')

        if form['rootfs'] != cfg['rootfs'] and re.match('^[a-zA-Z0-9_/\-]+', form['rootfs']):
            lwp.push_config_value('lxc.rootfs', form['rootfs'], container=container)
            flash(u'Rootfs updated!' % container, 'success')

        if bool(form['autostart']) != bool(cfg['auto']):
            lwp.push_config_value('lxc.start.auto', 1 if form['autostart'] else 0, container=container)
            flash(u'Autostart saved for %s' % container, 'success')

        if form['bucket'] != cfg['bucket']:
            g.db.execute("INSERT INTO machine(machine_name, bucket_token) VALUES (?, ?)", [container, form['bucket']])
            g.db.commit()
            flash(u'Bucket config for %s saved!' % container, 'success')

    info = lxc.info(container)
    status = info['state']
    pid = info['pid']

    infos = {'status': status, 'pid': pid, 'memusg': lwp.memory_usage(container)}
    return render_template('edit.html', containers=lxc.ls(), container=container, infos=infos, settings=cfg, host_memory=host_memory, storage_repos=storage_repos)
Example #22
0
def about():
    '''
    about page
    '''
    return render_template('about.html', containers=lxc.ls(), version=lwp.check_version())