Example #1
0
def home():
    '''
    home page function
    '''
    if 'logged_in' in session:
        containers = lxc.list_containers(as_object=True)
        listx = {'RUNNING': [], 'FROZEN': [], 'STOPPED': []}
        for container in containers:
            listx[container.state].append(container)
        containers_all = []

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

            for container in listx[status]:
                ips = list()
                if status == 'RUNNING':
                    ips = container.get_ips()
                containers_by_status.append({
                    'name': container.name,
                    'ips': ips,
                    '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.list_containers(),
                               containers_all=containers_all,
                               dist=lwp.check_ubuntu(),
                               templates=lwp.get_templates_list())
    return render_template('login.html')
Example #2
0
def server_main(CONTAINER_NAME, TEMPLATE, SERVER_TYPE, INTF, SRC_PORT, DST_PORT, DEBUG, NEW) :
	if NEW == False:
		assert lxc.list_containers().count(BASE_CONTAINER), "The " + BASE_CONTAINER + " doesn't exist" 
		print(BASE_CONTAINER + ' is present')		

	container = lxc_wrapper.lxc_main(CONTAINER_NAME, BASE_CONTAINER, TEMPLATE, NEW, DEBUG)
	time.sleep(5)
	ip_addr = container.get_ips()[0]
	
	if SERVER_TYPE == 'http' :
		if NEW:
			copy_file(container, 'http_server.py', '.')
		http_cmd = "./http_server.py --src_port="+DST_PORT
		lxc_wrapper.lxc_attach_process(container, http_cmd)
		add_iptable(INTF, SRC_PORT, ip_addr, DST_PORT)
		http_server = server_class(container, 'http', SRC_PORT, DST_PORT)

	if SERVER_TYPE == 'ftp':
		if NEW:
			copy_file(container, 'ftp_server.py', '.')
		ftp_cmd = "./ftp_server.py --src_port=" + DST_PORT
		lxc_wrapper.lxc_attach_process(container, ftp_cmd)
		add_iptable(INTF, SRC_PORT, ip_addr, DST_PORT)
		ftp_server = server_class(container, 'ftp', SRC_PORT, DST_PORT)
	
	if SERVER_TYPE == 'https':
		if NEW:
			copy_file(container, 'https_server.py', '.')
			copy_file(container, 'privcert.pem', '.')
		https_cmd = "./https_server.py " + DST_PORT
		lxc_wrapper.lxc_attach_process(container, https_cmd)
		add_iptable(INTF, SRC_PORT, ip_addr, DST_PORT)
		https_server = server_class(container, 'https', SRC_PORT, DST_PORT)
Example #3
0
def listdomains():
    con = mdb.connect(options['DB_HOST'], options['DB_USERNAME'], options['DB_PASSWORD'], options['DB']);
    cur = con.cursor()

    entries={'container':[],'domains':[]}
    cur.execute('SELECT domain,www,`ssl`,container,crtfile FROM domains')
    rows = cur.fetchall()

    for row in rows:
        try:
            ip=socket.gethostbyname(row[0])
        except:
            ip="not hosted"
        c={'domain':row[0],
           'www':row[1],
           'ssl':row[2],
           'container':row[3],
           'crtfile':row[4],
           'ip':ip
        }
        entries['domains'].append(c)

    con.close()

    for container in lxc.list_containers(as_object=True):
        if (container.name != "_template"):
            entries['container'].append(container.name)

    return render_template('list_domains.tmpl',entries=entries)
Example #4
0
def ip_from_name(CONTAINER_NAME):
	assert lxc.list_containers().count(CONTAINER_NAME), "The container " + CONTAINER_NAME + " doesn't exist"
	container = lxc.Container(CONTAINER_NAME)
	if (container.running):
		return container.get_ips()[0]
	else:
		return None
Example #5
0
def get_containers():
    containers = []
    cnames = lxc.list_containers()
    for cname in cnames:
        current_container = LXCContainer.pick(cname)
        containers.append(current_container.get_jsonable())
    return containers    
Example #6
0
File: lxci.py Project: epeli/lxci
def list_archived_containers():
    containers = []
    for name in lxc.list_containers(config_path=config.ARCHIVE_CONFIG_PATH):
        container = RuntimeContainer(lxc.Container(name, config_path=config.ARCHIVE_CONFIG_PATH))
        if container.is_archived():
            containers.append(name)
    return containers
Example #7
0
def container_status_check():
    containers = lxc.list_containers(as_object=True)
    for container in containers:
        if container.name != "default":
            status = "running" if container.running else "not running"
            print("Container: {0} is {1} | ip addresses: {2}" \
                  .format(container.name, status, container.get_ips()))
def main():
    module = AnsibleModule(
        argument_spec=dict(name=dict(
            required=True,
            type='str',
        ), ),
        supports_check_mode=False,
    )

    try:
        import lxc
    except ImportError:
        module.fail_json(
            changed=False,
            msg='Error importing lxc, is python-lxc installed?',
        )

    container_name = module.params.get('name')

    result = {}
    result['name'] = container_name

    if container_name in lxc.list_containers():
        result['exists'] = True
    else:
        result['exists'] = False

    result['changed'] = True
    module.exit_json(**result)
Example #9
0
def container_status_check():
    containers = lxc.list_containers(as_object=True)
    for container in containers:
        if container.name != "default":
            status = "running" if container.running else "not running"
            print("Container: {0} is {1} | ip addresses: {2}" \
                  .format(container.name, status, container.get_ips()))
Example #10
0
def init_containers():
    containers = lxc.list_containers()

    smr_containers = [
        SMRContainer(con) for con in containers if re.match(rxp, con)
    ]
    return smr_containers
Example #11
0
def listusers():
    con = mdb.connect(options['DB_HOST'], options['DB_USERNAME'], options['DB_PASSWORD'], options['DB']);
    cur = con.cursor()


    cur.execute('SELECT userid,passwd,container FROM ftpuser')
    rows = cur.fetchall()

    entries={'user':[],'container':[]}

    for row in rows:
        c={'user':row[0],
           'password':row[1],
           'container':row[2],
        }
        entries['user'].append(c)

    con.close()

    for container in lxc.list_containers(as_object=True):
        if (container.name != "_template"):
            entries['container'].append(container.name)


    return render_template('list_users.tmpl',entries=entries)
def main():
    module = AnsibleModule(
            argument_spec = dict(
                name = dict(
                    required = True,
                    type = 'str',
                    ),
                path = dict(
                    required = True,
                    type = 'str',
                    ),
            ),
    )

    try:
        import lxc

    except ImportError:
        module.fail_json(
                changed = False,
                msg = 'Error importing lxc, is python-lxc installed?',
                )

    container_name = module.params.get('name')
    file_path = module.params.get('path')

    result = {}
    result['name'] = container_name
    result['path'] = file_path

    if container_name in lxc.list_containers():

        container = lxc.Container(container_name)

        file_exists = container.attach_wait(
                read_file_in_container,
                (file_path, module),
                env_policy = lxc.LXC_ATTACH_CLEAR_ENV,
                )

    else:
        module.fail_json(
                available_container = lxc.list_containers(),
                msg = 'Target container does not exists',
                name = container_name,
                path = file_path,
                )
Example #13
0
def list_containers():
    try:
        list_all_containers = []
        for container in lxc.list_containers(as_object=True):
            list_all_containers.append(container.name)
        return list_all_containers
    except Exception as exception:
        return exception
def check_containers_ware_generated(container_list):
    all_container_list = lxc.list_containers()

    for container_name in container_list:
        if container_name in all_container_list:
            print(container_name + ' was generated.')
        else:
            print(container_name + ' was not generated.')
def main():
    module = AnsibleModule(argument_spec=dict(
        name=dict(
            required=True,
            type='str',
        ),
        path=dict(
            required=True,
            type='str',
        ),
    ), )

    try:
        import lxc

    except ImportError:
        module.fail_json(
            changed=False,
            msg='Error importing lxc, is python-lxc installed?',
        )

    container_name = module.params.get('name')
    file_path = module.params.get('path')

    result = {}
    result['name'] = container_name
    result['path'] = file_path

    if container_name in lxc.list_containers():

        container = lxc.Container(container_name)

        file_exists = container.attach_wait(
            read_file_in_container,
            (file_path, module),
            env_policy=lxc.LXC_ATTACH_CLEAR_ENV,
        )

    else:
        module.fail_json(
            available_container=lxc.list_containers(),
            msg='Target container does not exists',
            name=container_name,
            path=file_path,
        )
Example #16
0
def about():
    '''
    about page
    '''

    if 'logged_in' in session:
        return render_template('about.html', containers=lxc.list_containers(),
                               version=lwp.check_version())
    return render_template('login.html')
Example #17
0
 def rm_all_batch_containers(self):
     for con in lxc.list_containers():
         keys = con.split('-')
         if len(keys) < 2 or keys[1] != 'batch':
             continue
         if self.stop_and_rm_containers(con):
             logger.info("delete container %s success" % con)
         else:
             logger.error("delete container %s failed" % con)
def get_available_name_from_base(name_base):
    name = 'lap-{}'.format(name_base)
    containers = lxc.list_containers()
    if name in containers:
        i = 2
        while '{name}-{i}'.format(name=name, i=i) in containers:
            i += 1
        name = '{name}-{i}'.format(name=name, i=i)
    return name
Example #19
0
 def rm_all_batch_containers(self):
     for con in lxc.list_containers():
         keys = con.split('-')
         if len(keys) < 2 or keys[1] != 'batch':
             continue
         if self.stop_and_rm_containers(con):
             logger.info("delete container %s success" % con)
         else:
             logger.error("delete container %s failed" % con)
Example #20
0
 def list(self):
     try:
         a=[]
         for _container in lxc.list_containers():
             c=self.container(_container,details=False)
             a.append(c)
         return a
     except Exception as e:
         return {"status":"error","extstatus":str(e)}
Example #21
0
def get_container_list():
    retval = {}
    retval['containers'] = []
    for name in lxc.list_containers():
        c = get_container_object(name)
        retval['containers'].append({
               "name": name,
               "state": c.state,
               "init_pid": c.init_pid})
    return retval
Example #22
0
def simulate_churn(cycle_num, recovery_time):
    print("Starting network churn simulation")
    containers = lxc.list_containers(as_object=True)
    for _ in range(cycle_num):
        for container in containers:
            if container.name != "default":
                print("ipop on {} rebooting...".format(container.name))
                ipop_command(container.name, "ipop-kill")
                time.sleep(2)
                ipop_command(container.name, "ipop-run")
                time.sleep(recovery_time)
Example #23
0
File: lxci.py Project: epeli/lxci
def clear_archive():
    """
    Destroy all stopped containers in archive
    """
    containers = lxc.list_containers(config_path=config.ARCHIVE_CONFIG_PATH)

    with timer_print("Destroying {} archived containers".format(len(containers))):
        for name in  containers:
            container = lxc.Container(name, config_path=config.ARCHIVE_CONFIG_PATH)
            if container.state == "STOPPED" and RuntimeContainer(container).is_archived():
                assert_ret(container.destroy())
Example #24
0
def show_container():
    classmap = {'RUNNING': 'text-success',
                'STOPPED': 'text-error',
               }
    names = lxc.list_containers()
    machines = list()
    for name in names:
        machine = lxc.Container(name)
        machine.klass = classmap.get(machine.state, 'text-warning')
        machines.append(machine)
    return render_template('overview.html', machines=sorted(machines, key=machinesorter))
def container_check(thresh):
    containers = lxc.list_containers()
    for container in containers:
        c = lxc.Container(container)
        with Chroot('/proc/%s/root' % int(c.init_pid)):
            for partition in psutil.disk_partitions():
                percent_used = disk_usage(part=partition)
                if percent_used >= thresh:
                    return False
    else:
        return True
Example #26
0
def simulate_churn(cycle_num, recovery_time):
    print("Starting network churn simulation")
    containers = lxc.list_containers(as_object=True)
    for _ in range(cycle_num):
        for container in containers:
            if container.name != "default":
                print("ipop on {} rebooting...".format(container.name))
                ipop_command(container.name, "ipop-kill")
                time.sleep(2)
                ipop_command(container.name, "ipop-run")
                time.sleep(recovery_time)
Example #27
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.list_containers(),
                               cfg=lxclite.checkconfig())
    return render_template('login.html')
Example #28
0
def getContainers():
    result = []
    for container_name in lxc.list_containers():
        result.append(getContainer(container_name))
    finalresult = {
        "class": "ch.epfl.mybackup.beans.Server",
        "hostname": HOSTNAME,
        "hostIP": socket.gethostbyname(socket.gethostname()),
        "containers": result
    }
    return finalresult
Example #29
0
    def get(self):
        containers = []

        for c in lxc.list_containers():
            if c in current_user.containers:
                containers.append(lwp.ct_infos(c))

        sorted_dict = sorted(containers, key=lambda k: k['sorted_dict'])
        for ct_dict in sorted_dict:
            del ct_dict['sorted_dict']

        return {'containers': sorted_dict} # Sorted like the frontend
Example #30
0
def _list_containers(config_path, return_object=False, tag_filter=None):
    containers = []
    for name in lxc.list_containers(config_path=config_path):
        container = RuntimeContainer(lxc.Container(name, config_path=config_path))
        if tag_filter and tag_filter not in container.get_tags():
            continue
        if container.is_lxci_container():
            if return_object:
                containers.append(container)
            else:
                containers.append(name)
    return containers
def check(args):

    if on_lxc_container:
        containers = lxc.list_containers()
        neutron_agent_containers = []
        for container in containers:
            if 'neutron_agents' in container:
                metric_bool('agents_found',
                            True, m_name='maas_neutron')
                neutron_agent_containers.append(container)

        if len(neutron_agent_containers) == 0:
            metric_bool('agents_found', False, m_name='maas_neutron')
            status_err('no running neutron agents containers found',
                       m_name='maas_neutron')
            return

        for neutron_agent_container in neutron_agent_containers:
            # Get the neutron_agent_container's init PID.
            try:
                c = lxc.Container(neutron_agent_container)
                # If the container wasn't found, exit now.
                if c.init_pid == -1:
                    metric_bool('container_success',
                                False,
                                m_name='maas_neutron_agent_container')
                    status_err(
                        'Could not find PID for container {}'.format(
                            neutron_agent_container
                        ),
                        m_name='maas_neutron_agent_container'
                    )
            except (Exception, SystemError) as e:
                metric_bool('container_success', False,
                            m_name='maas_neutron_agent_container')
                status_err(
                    'Container lookup failed on "{}". ERROR: "{}"'
                    .format(
                        neutron_agent_container,
                        e
                    ),
                    m_name='maas_neutron_agent_container'
                )
            else:
                metric_bool('container_success', True,
                            m_name='maas_neutron_agent_container')

            # c is the lxc container instance of this
            # neutron_agent_container
            check_process_statuses(neutron_agent_container, c)
    else:
        ovs_agent_host = socket.gethostname()
        check_process_statuses(ovs_agent_host)
Example #32
0
    def _container_exists(name):
        """Check if a container exists.

        :param name: Name of the container.
        :type: ``str``
        :returns: True or False if the container is found.
        :rtype: ``bol``
        """
        if [i for i in lxc.list_containers() if i == name]:
            return True
        else:
            return False
Example #33
0
    def _container_exists(name):
        """Check if a container exists.

        :param name: Name of the container.
        :type: ``str``
        :returns: True or False if the container is found.
        :rtype: ``bol``
        """
        if [i for i in lxc.list_containers() if i == name]:
            return True
        else:
            return False
Example #34
0
def pingall_test(packet_count):
    test_results = []
    containers = lxc.list_containers(as_object=True)
    for current_container in containers:
        name = current_container.name
        if name not in ["default"]:
            for other_container in containers:
                other_name = other_container.name
                if other_name not in ["default", name]:
                    test_results.append(ping_and_parse(current_container,
                                                       name, other_name,
                                                       packet_count))
    return test_results
Example #35
0
def pingall_test(packet_count):
    test_results = []
    containers = lxc.list_containers(as_object=True)
    for current_container in containers:
        name = current_container.name
        if name not in ["default"]:
            for other_container in containers:
                other_name = other_container.name
                if other_name not in ["default", name]:
                    test_results.append(
                        ping_and_parse(current_container, name, other_name,
                                       packet_count))
    return test_results
Example #36
0
def refresh_memory_containers(name=None):
    if 'logged_in' in session:
        if name == 'containers':
            containers_running = lxc.list_containers(active=True, defined=False, as_object=True)
            containers = []
            for container in containers_running:
                name = container.name.replace(' (auto)', '')
                containers.append({'name': name,
                                   'memusg': lwp.memory_usage(container)})
            return jsonify(data=containers)
        elif name == 'host':
            return jsonify(lwp.host_memory_usage())
        return jsonify({'memusg': lwp.memory_usage(lxc.Container(name))})
def main():
    module = AnsibleModule(
            argument_spec = dict(
                name = dict(
                    required= True,
                    type = 'str',
                    ),
                other_arg = dict(
                    # provide a default if
                    # not required
                    default = 'spam',
                    required = False,
                    # always add the type
                    # to let ansible check
                    # your module call
                    type = 'str',
                    ),
            ),
            # can you predict if there will
            # be any changes?
            supports_check_mode=True
    )
    
    try:
        import lxc
    except ImportError:
        module.fail_json(
                changed = False,
                # A task can also fail
                # and stop the playbook
                # execution
                #failure = True,
                msg = 'Error importing lxc, is python-lxc installed?',
                )

    container_name = module.params.get('name')
    other_arg = module.params.get('other_arg')

    result = {}
    result['name'] = container_name
    result['other_arg'] = other_arg

    if container_name in lxc.list_containers():
        result['exists'] = True
        # do other things in here
    else:
        result['exists'] = False
        module.exit_json(**result)

    result['changed'] = True
    module.exit_json(**result)
Example #38
0
def __lxc_clone (container):
	# Check if base container is installed
	pr_debug("<debug> Check if " + BASE_CONTAINER + " is present")
	assert lxc.list_containers().count(BASE_CONTAINER), "The container " + BASE_CONTAINER + " doesn't exist"
	# Clone base container with new name
	NAME = container.name
	base_container = lxc.Container(BASE_CONTAINER)
	container = base_container.clone(NAME) 
	assert container, 'Cloning was unsuccessful for ' + BASE_CONTAINER
	pr_debug("<debug> Container was successfully cloned from the base container.")
	# Check config details and health
	health_check_stopped(container.name, container)
	# Return container object 
	return container
Example #39
0
def list():
    try:
        container_list = {"containers": []}
        containers = lxc.list_containers()
        for c in containers:
            container_list["containers"].append(str(c))
        response = Response(response=json.dumps(container_list),
                            status=200,
                            mimetype='application/json')
    except Exception as e:
        response = Response(response=json.dumps({"error": "{}".format(e)}),
                            status=500,
                            mimetype='application/json')
    return response
def container_check(thresh):
    containers = lxc.list_containers()
    for container in containers:
        c = lxc.Container(container)
        if c.init_pid == -1:
            return True

        with Chroot('/proc/%s/root' % int(c.init_pid)):
            for partition in psutil.disk_partitions():
                percent_used = disk_usage(part=partition)
                if percent_used >= thresh:
                    return False
    else:
        return True
Example #41
0
  def _get_list_containers(self):
    """
    :return: list
    """
    lst_cnt = list()
    cnt = lxc.list_containers(True, True, True, False)
    d = {}
    for ins in cnt:
      d['name'] = ins.name
      d['state'] = ins.state
      d['size'] = self._get_fs_size(ins.name)
      d['release'] = ins.config_file_name
      lst_cnt.append(d)

    return lst_cnt
Example #42
0
    def get(self):
        """
        Get containers list
        """
        containers = []

        for c in lxc.list_containers():
            container = Container.query.filter_by(name=c).first()
            if container.id in current_identity.containers or current_identity.admin:
                infos = lwp.ct_infos(c)
                container_json = container.__jsonapi__()
                container_json['attributes'] = infos
                containers.append(container_json)

        return {'data': containers}
Example #43
0
def _next_ip():
    ips = []

    for container in lxc.list_containers(as_object=True):
        # get the ip as set in the config
        ip = container.get_config_item('lxc.net.0.ipv4.address')

        if ip:
            ips.append(IPv4Address(ip.split('/')[0]))

    if not ips:
        # return a default first address
        return IPv4Address('10.0.3.2')

    # returns the ip address just after the max current address
    return max(ips) + 1
Example #44
0
    def get(self):
        """
        Get containers list
        """
        current_identity = import_user()
        containers = []

        for c in lxc.list_containers():
            container = Container.query.filter_by(name=c).first()
            if container.id in current_identity.containers or current_identity.admin:
                infos = lwp.ct_infos(c)
                container_json = container.__jsonapi__()
                container_json['attributes'] = infos
                containers.append(container_json)

        return {'data': containers}
Example #45
0
def build_dict():
    """Returns a dictionary keyed to the defined LXC groups. All
    containers, including the ones not in any group, are included in the
    "all" group."""
    # Enumerate all containers, and list the groups they are in. Also,
    # implicitly add every container to the 'all' group.
    containers = dict([(c,
                        ['all'] +
                        (lxc.Container(c).get_config_item('lxc.group') or []))
                       for c in lxc.list_containers()])

    # Extract the groups, flatten the list, and remove duplicates
    groups = set(sum([g for g in containers.values()], []))

    # Create a dictionary for each group (including the 'all' group
    return dict([(g, {'hosts': [k for k, v in containers.items() if g in v],
                      'vars': {'ansible_connection':'lxc'}}) for g in groups])
Example #46
0
def build_dict():
    """Returns a dictionary keyed to the defined LXC groups. All
    containers, including the ones not in any group, are included in the
    "all" group."""
    # Enumerate all containers, and list the groups they are in. Also,
    # implicitly add every container to the 'all' group.
    containers = dict([(c,
                        ['all'] +
                        (lxc.Container(c).get_config_item('lxc.group') or []))
                       for c in lxc.list_containers()])

    # Extract the groups, flatten the list, and remove duplicates
    groups = set(sum([g for g in containers.values()], []))

    # Create a dictionary for each group (including the 'all' group
    return dict([(g, {'hosts': [k for k, v in containers.items() if g in v],
                      'vars': {'ansible_connection': 'lxc'}}) for g in groups])
Example #47
0
def populate_containers_table():
    current_containers_list = lxc.list_containers()
    database_containers_list = [str(i.name) for i in Container.query.all()]

    # Removing old containers from database
    for ct in database_containers_list:
        if not ct in current_containers_list:
            container = Container.query.filter_by(name=ct).first()
            db.session.delete(container)

    # Adding new containers to database
    for ct in current_containers_list:
        if not ct in database_containers_list:
            container = Container(name=ct)
            db.session.add(container)

    db.session.commit()
Example #48
0
def hydrate_system():
    """
    Checks for unmanaged hosts and containers in db.
    """
    #~ print("hydrating...")
    hosts = Hosts.select()
    admin = Users.get(Users.username == 'admin')
    containers_in_db = Containers.select()
    containers_in_host = lxc.list_containers()
    print(len(containers_in_db), len(containers_in_host))
    if len(containers_in_host) > len(containers_in_db):
        for cih in containers_in_host:
            #~ print(cih)
            search = Containers.select().where(Containers.name == cih)
            if len(search) == 0:
                container = Containers.create(name=cih, host=host, admin=admin)

    return jsonify({})
Example #49
0
def clean(k=None):
    shutdown(k)
    ct = readconf.read_conf()
    if k == None:
        for k in ct.svcs():
            c = lxc.Container(k)
            c.shutdown(timeout=0)
            c.destroy()
        for k in lxc.list_containers():
            c = lxc.Container(k)
            c.shutdown(timeout=0)
            c.destroy()
        c = lxc.Container(BASE)
        c.shutdown(timeout=0)
        c.destroy()
    else:
        c = lxc.Container(k)
        c.destroy()
Example #50
0
def list_containers():
    res = dict()
    hostvars = {}
    containers = lxc.list_containers(active=True, defined=False)
    for container_name in containers:
        group = get_group_name_from_container(container_name)
        if group not in res:
            res[group] = {}
            res[group]['hosts'] = []
        if isinstance(res[group], dict):
            res[group]['hosts'].append(container_name)
        container = lxc.Container(name=container_name)
        if container.get_interfaces():
            ips = container.get_ips()
            if len(ips):
                hostvars[container_name] = \
                    dict(ansible_host=ips[ANSIBLE_SSH_HOST_INDEX])
    res["_meta"] = {"hostvars": hostvars}
    res['all'] = list(containers)
    return res
Example #51
0
def lxc_cgroup_set_cpuset(cpus):
    for container in lxc.list_containers(as_object=True):
        if container.running:
            print("lxc_cgroup_set_cpus(): Setting CPUs for " + container.name +
                  " to " + cpus)

            exception_occured = False

            try:
                f = io.open(cpuset_mount + "lxc/" + container.name +
                            "/cpuset.cpus",
                            'w',
                            encoding="ascii")
            except IOError as e:
                exception_occured = True
                print("I/O error occured")
                #print("I/O error(" + e.errno + "): " + e.strerror)

            # No point in doing the following if an I/O occured in the prior try/catch
            if exception_occured != True:
                f.write(cpus)
                f.close
 def handle_get_containers_method(self):
     return lxc.list_containers()
Example #53
0
def container_list(status=False):
    if status:
        return {x.name: x.state for x in lxc.list_containers(as_object=True)}
    else:
        return lxc.list_containers()
def main():

    module = AnsibleModule(argument_spec=dict(
        backing_store=dict(
            default='lvm',
            choices=[
                'dir',
                'lvm',
                'loop',
                'btrsf',
                'overlayfs',
                'zfs',
            ],
            type='str',
        ),
        config=dict(
            required=False,
            default='/etc/lxc/default.conf',
        ),
        container_command=dict(
            required=False,
            type='str',
            default='',
        ),
        fs_size=dict(
            required=False,
            default='5G',
            type='str',
        ),
        fs_type=dict(
            required=False,
            default='ext4',
            type='str',
        ),
        lv_name=dict(type='str', ),
        name=dict(
            required=True,
            type='str',
        ),
        state=dict(
            default='started',
            choices=['started', 'stopped', 'restarted', 'absent', 'frozen'],
            type='str',
        ),
        template=dict(
            required=False,
            default='debian',
            type='str',
        ),
        template_options=dict(
            required=False,
            default='--release jessie --packages=ssh,python',
            type='str',
        ),
        vg_name=dict(
            required=False,
            default='newsysvg',
            type='str',
        ),
    ))

    try:
        import lxc
    except ImportError:
        module.fail_json(changed=False,
                         msg='liblxc is required for this module to work')

    lilik_container = LilikContainer(module)

    result = {}
    result['name'] = lilik_container.name
    result['state'] = lilik_container.state

    if lilik_container.state == 'absent':

        # destroy the container
        if lilik_container.destoy():
            module.exit_json(changed=True)

        # TODO: remove redundant test
        # test wether the container is absent or not
        if lilik_container.name in lxc.list_containers():
            module.fail_json(changed=False)

        # the container has been removed
        else:
            module.exit_json(changed=True)
        # end TODO: remove redundant test

    elif lilik_container.state in [
            'started', 'stopped', 'restarted', 'frozen'
    ]:

        # the container exists, just set the state as required
        if lilik_container.name in lxc.list_containers():

            container_actions_from_state = {
                'started': lilik_container.start,
                'stopped': lilik_container.stop,
                'restarted': lilik_container.restart,
                'frozen': lilik_container.freeze,
            }

            # selected action
            action = container_actions.get(container.state)

            if action():
                module.exit_json(changed=True)
            else:
                module.exit_json(changed=False)

        # the container does not exists, create it
        else:
            try:
                new_container = lilik_container.create_container()
                module.exit_json(changed=True)
            except Exception as e:
                module.fail_json(
                    changed=False,
                    msg='An excption was raised while creating the container',
                    exception_message=str(e),
                )
def check(args):
    neutron = get_openstack_client('network')

    try:
        # Gather neutron agent states
        if args.host:
            agents = [i for i in neutron.agents(host=args.host)]
        elif args.fqdn:
            agents = [i for i in neutron.agents(host=args.fqdn)]
        else:
            agents = [i for i in neutron.agents()]

    # An API status metric is not gathered so catch any exception
    except Exception as e:
        metric_bool('client_success', False, m_name='maas_neutron')
        metric('%s_status' % "neutron-openvswitch-agent",
               'string',
               '%s cannot reach API' % "neutron-openvswitch-agent",
               m_name='maas_neutron')
        status_err_no_exit(str(e), m_name='maas_neutron')
        return
    else:
        metric_bool('client_success', True, m_name='maas_neutron')

    try:
        ovs_agent = next(a for a in agents if 'openvswitch' in a['binary'])
    except StopIteration:
        status_err("No host(s) found in the agents list",
                   m_name='maas_neutron')
    else:
        # Return all the things
        status_ok(m_name='maas_neutron')

        agent_is_up = "Yes"
        if ovs_agent['is_admin_state_up'] and not ovs_agent['is_alive']:
            agent_is_up = "No"

        if args.host:
            name = '%s_status' % ovs_agent['binary']
        elif args.fqdn:
            name = '%s_status' % ovs_agent['binary']
        else:
            name = '%s_%s_on_host_%s' % (ovs_agent['binary'], ovs_agent['id'],
                                         ovs_agent['host'])

        metric(name, 'string', agent_is_up, m_name='maas_neutron')

    if on_lxc_container:
        all_containers = lxc.list_containers()
        neutron_containers_list = []
        neutron_agent_containers_list = []

        # NOTE(npawelek): The neutron container architecture was
        # refactored in recent versions removing all neutron containers
        # with the exception of one, or even using baremetal directly.
        # Since logic is looking for the presence of LXC, we do not need
        # to account for baremetal here.
        for container in all_containers:
            if 'neutron_agents' in container:
                neutron_agent_containers_list.append(container)

            if 'neutron' in container:
                neutron_containers_list.append(container)

        if len(neutron_containers_list) == 1 and \
                'neutron_server' in neutron_containers_list[0]:
            valid_containers = neutron_containers_list
        elif len(neutron_agent_containers_list) > 0:
            valid_containers = neutron_agent_containers_list
        else:
            valid_containers = 0

        if len(valid_containers) == 0:
            status_err('no neutron agent or server containers found',
                       m_name='maas_neutron')
            return

        for container in valid_containers:
            # Get the neutron_agent_container's init PID.
            try:
                c = lxc.Container(container)
                # If the container wasn't found, exit now.
                if c.init_pid == -1:
                    metric_bool('container_success',
                                False,
                                m_name='maas_neutron')
                    status_err('Could not find PID for container {}'.format(
                        container),
                               m_name='maas_neutron')
            except (Exception, SystemError) as e:
                metric_bool('container_success', False, m_name='maas_neutron')
                status_err(
                    'Container lookup failed on "{}". ERROR: "{}"'.format(
                        container, e),
                    m_name='maas_neutron')
            else:
                metric_bool('container_success', True, m_name='maas_neutron')

                # c is the lxc container instance of this
                # neutron_agent_container
                check_process_statuses(container, c)
    else:
        ovs_agent_host = socket.gethostname()
        check_process_statuses(ovs_agent_host)
Example #56
0
def list():
    container_list = lxc.list_containers()

    return "List of containers: {0}\n".format(container_list)
Example #57
0
    tar = tarfile.open(backup_path + ".tar.gz", "w:gz")
    tar.add(backup_path, arcname=backup_path)
    tar.close()
    print("DONE create archive")


def remove_container_directory(backup_directory, name):
    destroy_directory = backup_directory + name
    shutil.rmtree(destroy_directory)


work_directory = "/var/lib/lxc/"
#backup_directory = "/srv/photo_backup/"
backup_directory = "/srv/"

array_container = lxc.list_containers()
for i in array_container:
    print(work_directory + i)
    print(lxc.Container(i).state)
    if lxc.Container(i).state != 'STOPPED':
        lxc.Container(i).freeze()
        print(i + " " + lxc.Container(i).state)
        print("COPY")
        copy_container(work_directory, i)
        print("...................")
        lxc.Container(i).unfreeze()
        print("UNFREEZING")
        print(i + " " + lxc.Container(i).state)
    else:
        print("COPY STOPPED CONTAINER")
        copy_container(work_directory, i)
Example #58
0
            arch = dpkg.stdout.read().strip()
except:
    pass

## Create a rootfs
print("Creating rootfs using 'download', arch=%s" % arch)
container.create("download", 0, {
    "dist": "ubuntu",
    "release": "xenial",
    "arch": arch
})

assert (container.defined)
assert (container.name == CONTAINER_NAME ==
        container.get_config_item("lxc.utsname"))
assert (container.name in lxc.list_containers())

## Test the config
print("Testing the configuration")
capdrop = container.get_config_item("lxc.cap.drop")
container.clear_config_item("lxc.cap.drop")
container.set_config_item("lxc.cap.drop", capdrop[:-1])
container.append_config_item("lxc.cap.drop", capdrop[-1])
container.save_config()

# A few basic checks of the current state
assert (isinstance(capdrop, list))
assert (capdrop == container.get_config_item("lxc.cap.drop"))

## Test the networking
print("Testing the networking")