def home(): """ home page function """ listx = lxc.listx() containers_all = [] for status in ('RUNNING', 'FROZEN', 'STOPPED'): containers_by_status = [] for container in listx[status]: container_info = { 'name': container, 'settings': lwp.get_container_settings(container, status), 'memusg': 0, 'bucket': get_bucket_token(container) } containers_by_status.append(container_info) containers_all.append({ 'status': status.lower(), 'containers': containers_by_status }) return render_template('index.html', containers=lxc.ls(), containers_all=containers_all, dist=lwp.name_distro(), host=socket.gethostname(), templates=lwp.get_templates_list(), storage_repos=storage_repos, auth=AUTH)
def home(): """ home page function """ listx = lxc.listx() containers_all = [] for status in ('RUNNING', 'FROZEN', 'STOPPED'): containers_by_status = [] for container in listx[status]: container_info = { 'name': container, 'settings': lwp.get_container_settings(container, status), 'memusg': 0, 'bucket': get_bucket_token(container) } containers_by_status.append(container_info) 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)
def home(): """ home page function """ listx = lxc.listx() containers_all = [] for status in ("RUNNING", "FROZEN", "STOPPED"): containers_by_status = [] for container in listx[status]: container_info = { "name": container, "settings": lwp.get_container_settings(container, status), "memusg": 0, "bucket": get_bucket_token(container), } containers_by_status.append(container_info) containers_all.append({"status": status.lower(), "containers": containers_by_status}) clonable_containers = listx["STOPPED"] return render_template( "index.html", containers=lxc.ls(), containers_all=containers_all, dist=lwp.name_distro(), host=socket.gethostname(), templates=lwp.get_templates_list(), storage_repos=storage_repos, auth=AUTH, clonable_containers=clonable_containers, )
def home(self): listx = lxc.listx() # return all containers sorted by status # memory usage is excluded in this as it slows down the homepage # quite a bit, they are retrieved later using AJAX. all_containers = [] for status in ('RUNNING', 'FROZEN', 'STOPPED'): all_containers.append({ 'status': status.lower(), 'containers': [{ 'name': container, 'memory_usage': 0, # I prefer to cache this one day 'settings': get_container_settings(container), 'bucket': get_bucket_token(container) } for container in listx[status]] }) return { 'all_containers': all_containers, 'dist': check_ubuntu(), 'host': socket.gethostname(), 'templates': get_templates_list(), 'storage_repos': self.settings['storage_repos'], 'auth': self.settings['auth.backend'] }
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) if request.method == 'POST': form = request.form.copy() if form['bucket'] != get_bucket_token(container): 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') # convert boolean in correct value for lxc, if checkbox is inset value is not submitted inside POST form['flags'] = 'up' if 'flags' in form else 'down' form['start_auto'] = '1' if 'start_auto' in form else '0' # if memlimits/memswlimit is at max values unset form values if int(form['memlimit']) == host_memory['total']: form['memlimit'] = '' if int(form['swlimit']) == host_memory['total'] * 2: form['swlimit'] = '' for option in form.keys(): # if the key is supported AND is different if option in cfg.keys() and form[option] != cfg[option]: # validate value with regex if re.match(cgroup_ext[option][1], form[option]): lwp.push_config_value(cgroup_ext[option][0], form[option], container=container) flash(cgroup_ext[option][2], 'success') else: flash( 'Cannot validate value for option {}. Unsaved!'.format( option), 'error') # we should re-read container configuration now to be coherent with the newly saved values cfg = lwp.get_container_settings(container) info = lxc.info(container) infos = { 'status': info['state'], 'pid': info['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)
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) if request.method == "POST": form = request.form.copy() if form["bucket"] != get_bucket_token(container): 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") # convert boolean in correct value for lxc, if checkbox is inset value is not submitted inside POST form["flags"] = "up" if "flags" in form else "down" form["start_auto"] = "1" if "start_auto" in form else "0" # if memlimits/memswlimit is at max values unset form values if int(form["memlimit"]) == host_memory["total"]: form["memlimit"] = "" if int(form["swlimit"]) == host_memory["total"] * 2: form["swlimit"] = "" for option in form.keys(): # if the key is supported AND is different if option in cfg.keys() and form[option] != cfg[option]: # validate value with regex if re.match(cgroup_ext[option][1], form[option]): lwp.push_config_value(cgroup_ext[option][0], form[option], container=container) flash(cgroup_ext[option][2], "success") else: flash("Cannot validate value for option {}. Unsaved!".format(option), "error") # we should re-read container configuration now to be coherent with the newly saved values cfg = lwp.get_container_settings(container) info = lxc.info(container) infos = {"status": info["state"], "pid": info["pid"], "memusg": lwp.memory_usage(container)} # prepare a regex dict from cgroups_ext definition regex = {} for k, v in cgroup_ext.items(): regex[k] = v[1] return render_template( "edit.html", containers=lxc.ls(), container=container, infos=infos, settings=cfg, host_memory=host_memory, storage_repos=storage_repos, regex=regex, clonable_containers=lxc.listx()["STOPPED"], )
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) if request.method == 'POST': form = request.form.copy() if form['bucket'] != get_bucket_token(container): 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') # convert boolean in correct value for lxc, if checkbox is inset value is not submitted inside POST form['flags'] = 'up' if 'flags' in form else 'down' form['start_auto'] = '1' if 'start_auto' in form else '0' # if memlimits/memswlimit is at max values unset form values if int(form['memlimit']) == host_memory['total']: form['memlimit'] = '' if int(form['swlimit']) == host_memory['total'] * 2: form['swlimit'] = '' for option in form.keys(): # if the key is supported AND is different if option in cfg.keys() and form[option] != cfg[option]: # validate value with regex if re.match(cgroup_ext[option][1], form[option]): lwp.push_config_value(cgroup_ext[option][0], form[option], container=container) flash(cgroup_ext[option][2], 'success') else: flash('Cannot validate value for option {}. Unsaved!'.format(option), 'error') # we should re-read container configuration now to be coherent with the newly saved values cfg = lwp.get_container_settings(container) info = lxc.info(container) infos = {'status': info['state'], 'pid': info['pid'], 'memusg': lwp.memory_usage(container)} # prepare a regex dict from cgroups_ext definition regex = {} for k, v in cgroup_ext.items(): regex[k] = v[1] return render_template('edit.html', containers=lxc.ls(), container=container, infos=infos, settings=cfg, host_memory=host_memory, storage_repos=storage_repos, regex=regex, clonable_containers=lxc.listx()['STOPPED'])
def backup_container(): """ Verify the form to backup a container """ if request.method == 'POST': container = request.form['orig'] sr_type = request.form['dest'] if 'push' in request.form: push = request.form['push'] else: push = False sr_path = None for sr in storage_repos: if sr_type in sr: sr_path = sr[1] break backup_failed = True try: backup_file = lxc.backup(container=container, sr_type=sr_type, destination=sr_path) bucket_token = get_bucket_token(container) if push and bucket_token and USE_BUCKET: os.system('curl http://{}:{}/{} -F file=@{}'.format( BUCKET_HOST, BUCKET_PORT, bucket_token, backup_file)) backup_failed = False except lxc.ContainerDoesntExists: flash(u'The Container %s does not exist !' % container, 'error') except lxc.DirectoryDoesntExists: flash(u'Local backup directory "%s" does not exist !' % sr_path, 'error') except lxc.NFSDirectoryNotMounted: flash(u'NFS repository "%s" not mounted !' % sr_path, 'error') except subprocess.CalledProcessError: flash(u'Error during transfert !', 'error') except: flash(u'Error during transfert !', 'error') if backup_failed is not True: flash(u'Container %s backed up successfully' % container, 'success') else: flash(u'Failed to backup %s container' % container, 'error') return redirect(url_for('main.home'))
def get_container_settings(name): """ returns a dict of all utils settings for a container """ filename = '{}/{}/config'.format(lxc.lxcdir(), name) if not file_exist(filename): return False config = ConfigParser.SafeConfigParser() config.readfp(FakeSection(open(filename))) # start with bucket token, as this is not from the config file cfg = {'bucket': get_bucket_token(name)} # for each key in CGROUP_EXT add value to cfg dict and initialize values for options in CGROUP_EXT.keys(): if config.has_option('DEFAULT', CGROUP_EXT[options][0]): cfg[options] = config.get('DEFAULT', CGROUP_EXT[options][0]) else: # add the key in dictionary anyway to match form if options == 'loglevel': cfg[options] = '5' # default loglevel is 5 (error) else: cfg[options] = '' # default for all other missing fields # if ipv4 is unset try to determine it if cfg['ipv4'] == '': cmd = ['lxc-ls --fancy --fancy-format name,ipv4|grep \'%s\' |egrep -o \'[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\'' % name] try: cfg['ipv4'] = subprocess.check_output(cmd, shell=True) except subprocess.CalledProcessError: cfg['ipv4'] = '' # parse memlimits to ints cfg['memlimit'] = re.sub(r'[a-zA-Z]', '', cfg['memlimit']) cfg['swlimit'] = re.sub(r'[a-zA-Z]', '', cfg['swlimit']) # the form requires these to be actual ints if cfg['memlimit'] != '': cfg['memlimit'] = int(cfg['memlimit']) if cfg['swlimit'] != '': cfg['swlimit'] = int(cfg['swlimit']) # convert internal lxc values to boolean cfg['start_auto'] = True if cfg['start_auto'] is '1' else False cfg['flags'] = True if cfg['flags'] == 'up' else False return cfg
def backup_container(): """ Verify the form to backup a container """ if request.method == "POST": container = request.form["orig"] sr_type = request.form["dest"] if "push" in request.form: push = request.form["push"] else: push = False sr_path = None for sr in storage_repos: if sr_type in sr: sr_path = sr[1] break backup_failed = True try: backup_file = lxc.backup(container=container, sr_type=sr_type, destination=sr_path) bucket_token = get_bucket_token(container) if push and bucket_token and USE_BUCKET: os.system( "curl http://{}:{}/{} -F file=@{}".format(BUCKET_HOST, BUCKET_PORT, bucket_token, backup_file) ) backup_failed = False except lxc.ContainerDoesntExists: flash(u"The Container %s does not exist !" % container, "error") except lxc.DirectoryDoesntExists: flash(u'Local backup directory "%s" does not exist !' % sr_path, "error") except lxc.NFSDirectoryNotMounted: flash(u'NFS repository "%s" not mounted !' % sr_path, "error") except subprocess.CalledProcessError: flash(u"Error during transfert !", "error") except: flash(u"Error during transfert !", "error") if backup_failed is not True: flash(u"Container %s backed up successfully" % container, "success") else: flash(u"Failed to backup %s container" % container, "error") return redirect(url_for("main.home"))
def backup_container(): """ Verify the form to backup a container """ if request.method == 'POST': container = request.form['orig'] sr_type = request.form['dest'] if 'push' in request.form: push = request.form['push'] else: push = False sr_path = None for sr in storage_repos: if sr_type in sr: sr_path = sr[1] break backup_failed = True try: backup_file = lxc.backup(container=container, sr_type=sr_type, destination=sr_path) bucket_token = get_bucket_token(container) if push and bucket_token and USE_BUCKET: os.system('curl http://{}:{}/{} -F file=@{}'.format(BUCKET_HOST, BUCKET_PORT, bucket_token, backup_file)) backup_failed = False except lxc.ContainerDoesntExists: flash(u'The Container %s does not exist !' % container, 'error') except lxc.DirectoryDoesntExists: flash(u'Local backup directory "%s" does not exist !' % sr_path, 'error') except lxc.NFSDirectoryNotMounted: flash(u'NFS repository "%s" not mounted !' % sr_path, 'error') except subprocess.CalledProcessError: flash(u'Error during transfert !', 'error') except: flash(u'Error during transfert !', 'error') if backup_failed is not True: flash(u'Container %s backed up successfully' % container, 'success') else: flash(u'Failed to backup %s container' % container, 'error') return redirect(url_for('main.home'))
def backup_container(self): """ Verify the form to backup a container. """ if self.request.method == 'POST': container = self.request.POST['orig'] sr_type = self.request.POST['dest'] push = self.request.POST['push'] sr_path = None for sr in self.settings['storage_repos']: if sr_type in sr: sr_path = sr[1] break out = None try: backup_file = lxc.backup(container=container, sr_type=sr_type, destination=sr_path) bucket_token = get_bucket_token(container) if push and bucket_token and self.settings['buckets.enabled']: os.system('curl http://{}:{}/{} -F file=@{}'.format(self.settings['buckets.host'], self.settings['buckets.port'], bucket_token, backup_file)) except lxc.ContainerDoesNotExist: self.session.flash('The Container {} does not exist'.format(container), queue='error') except lxc.DirectoryDoesNotExist: self.session.flash('Local backup directory "{}" does not exist'.format(sr_path), queue='error') except lxc.NFSDirectoryNotMounted: self.session.flash('NFS repository "{}" not mounted'.format(sr_path), queue='error') except subprocess.CalledProcessError: self.session.flash('Error during transfer', queue='error') except: # TODO: do we really need this unchecked exception? self.session.flash('Error during transfer', queue='error') if out == 0: self.session.flash('Container {} backed up successfully'.format(container), queue='success') elif out != 0: self.session.flash('Failed to backup {} container'.format(container), queue='error') return HTTPFound(location=self.request.route_path('home'))