repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
percolate/ec2-security-groups-dumper | ec2_security_groups_dumper/main.py | Firewall.rules | def rules(self):
"""
Returns a sorted list of firewall rules.
Returns:
list
"""
list_of_rules = []
for main_row in self.dict_rules:
if 'rules' in main_row:
for rule_row in main_row['rules']:
if 'grants' in rule_row:
for grant_row in rule_row['grants']:
if 'group_id' in grant_row:
# Set a var to not go over 80 chars
group_id = grant_row['group_id']
# Some VPC grants don't specify a name
if 'name' in grant_row:
row_name = grant_row['name']
else:
row_name = None
fr = FirewallRule(
main_row['id'],
main_row['name'],
main_row['description'],
rules_direction=rule_row['direction'],
rules_ip_protocol=rule_row['ip_protocol'],
rules_from_port=rule_row['from_port'],
rules_to_port=rule_row['to_port'],
rules_grants_group_id=group_id,
rules_grants_name=row_name,
rules_description=grant_row['description'])
list_of_rules.append(fr)
elif 'cidr_ip' in grant_row:
fr = FirewallRule(
main_row['id'],
main_row['name'],
main_row['description'],
rules_direction=rule_row['direction'],
rules_ip_protocol=rule_row['ip_protocol'],
rules_from_port=rule_row['from_port'],
rules_to_port=rule_row['to_port'],
rules_grants_cidr_ip=grant_row['cidr_ip'],
rules_description=grant_row['description'])
list_of_rules.append(fr)
else:
raise ValueError("Unsupported grant:",
grant_row)
else:
fr = FirewallRule(
main_row['id'],
main_row['name'],
main_row['description'],
rules_direction=rule_row['direction'],
rules_ip_protocol=rule_row['ip_protocol'],
rules_from_port=rule_row['from_port'],
rules_to_port=rule_row['to_port'])
list_of_rules.append(fr)
else:
fr = FirewallRule(main_row['id'],
main_row['name'],
main_row['description'])
list_of_rules.append(fr)
# Sort the data in order to get a consistent output
sorted_list = sorted(list_of_rules,
key=lambda fr: (str(fr.id),
str(fr.name),
str(fr.description),
str(fr.rules_direction),
str(fr.rules_ip_protocol),
str(fr.rules_from_port),
str(fr.rules_to_port),
str(fr.rules_grants_group_id),
str(fr.rules_grants_name),
str(fr.rules_grants_cidr_ip)))
return sorted_list | python | def rules(self):
"""
Returns a sorted list of firewall rules.
Returns:
list
"""
list_of_rules = []
for main_row in self.dict_rules:
if 'rules' in main_row:
for rule_row in main_row['rules']:
if 'grants' in rule_row:
for grant_row in rule_row['grants']:
if 'group_id' in grant_row:
# Set a var to not go over 80 chars
group_id = grant_row['group_id']
# Some VPC grants don't specify a name
if 'name' in grant_row:
row_name = grant_row['name']
else:
row_name = None
fr = FirewallRule(
main_row['id'],
main_row['name'],
main_row['description'],
rules_direction=rule_row['direction'],
rules_ip_protocol=rule_row['ip_protocol'],
rules_from_port=rule_row['from_port'],
rules_to_port=rule_row['to_port'],
rules_grants_group_id=group_id,
rules_grants_name=row_name,
rules_description=grant_row['description'])
list_of_rules.append(fr)
elif 'cidr_ip' in grant_row:
fr = FirewallRule(
main_row['id'],
main_row['name'],
main_row['description'],
rules_direction=rule_row['direction'],
rules_ip_protocol=rule_row['ip_protocol'],
rules_from_port=rule_row['from_port'],
rules_to_port=rule_row['to_port'],
rules_grants_cidr_ip=grant_row['cidr_ip'],
rules_description=grant_row['description'])
list_of_rules.append(fr)
else:
raise ValueError("Unsupported grant:",
grant_row)
else:
fr = FirewallRule(
main_row['id'],
main_row['name'],
main_row['description'],
rules_direction=rule_row['direction'],
rules_ip_protocol=rule_row['ip_protocol'],
rules_from_port=rule_row['from_port'],
rules_to_port=rule_row['to_port'])
list_of_rules.append(fr)
else:
fr = FirewallRule(main_row['id'],
main_row['name'],
main_row['description'])
list_of_rules.append(fr)
# Sort the data in order to get a consistent output
sorted_list = sorted(list_of_rules,
key=lambda fr: (str(fr.id),
str(fr.name),
str(fr.description),
str(fr.rules_direction),
str(fr.rules_ip_protocol),
str(fr.rules_from_port),
str(fr.rules_to_port),
str(fr.rules_grants_group_id),
str(fr.rules_grants_name),
str(fr.rules_grants_cidr_ip)))
return sorted_list | [
"def",
"rules",
"(",
"self",
")",
":",
"list_of_rules",
"=",
"[",
"]",
"for",
"main_row",
"in",
"self",
".",
"dict_rules",
":",
"if",
"'rules'",
"in",
"main_row",
":",
"for",
"rule_row",
"in",
"main_row",
"[",
"'rules'",
"]",
":",
"if",
"'grants'",
"in... | Returns a sorted list of firewall rules.
Returns:
list | [
"Returns",
"a",
"sorted",
"list",
"of",
"firewall",
"rules",
"."
] | f2a40d1b3802211c85767fe74281617e4dbae543 | https://github.com/percolate/ec2-security-groups-dumper/blob/f2a40d1b3802211c85767fe74281617e4dbae543/ec2_security_groups_dumper/main.py#L148-L229 | train | 31,600 |
percolate/ec2-security-groups-dumper | ec2_security_groups_dumper/main.py | Firewall.csv | def csv(self):
"""
Returns the security rules as a CSV.
CSV format:
- id
- name
- description
- rules_direction
- rules_ip_protocol
- rules_from_port
- rules_to_port
- rules_grants_group_id
- rules_grants_name
- rules_grants_cidr_ip
- rules_description
Returns:
str
"""
# Generate a csv file in memory with all the data in
output = StringIO.StringIO()
fieldnames = ['id',
'name',
'description',
'rules_direction',
'rules_ip_protocol',
'rules_from_port',
'rules_to_port',
'rules_grants_group_id',
'rules_grants_name',
'rules_grants_cidr_ip',
'rules_description']
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
for fr in self.rules:
writer.writerow(fr.as_dict())
# Get the CSV in a string
csv_content = output.getvalue()
# Removing some useless newline at the end
stripped_csv_content = csv_content.strip()
return stripped_csv_content | python | def csv(self):
"""
Returns the security rules as a CSV.
CSV format:
- id
- name
- description
- rules_direction
- rules_ip_protocol
- rules_from_port
- rules_to_port
- rules_grants_group_id
- rules_grants_name
- rules_grants_cidr_ip
- rules_description
Returns:
str
"""
# Generate a csv file in memory with all the data in
output = StringIO.StringIO()
fieldnames = ['id',
'name',
'description',
'rules_direction',
'rules_ip_protocol',
'rules_from_port',
'rules_to_port',
'rules_grants_group_id',
'rules_grants_name',
'rules_grants_cidr_ip',
'rules_description']
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
for fr in self.rules:
writer.writerow(fr.as_dict())
# Get the CSV in a string
csv_content = output.getvalue()
# Removing some useless newline at the end
stripped_csv_content = csv_content.strip()
return stripped_csv_content | [
"def",
"csv",
"(",
"self",
")",
":",
"# Generate a csv file in memory with all the data in",
"output",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"fieldnames",
"=",
"[",
"'id'",
",",
"'name'",
",",
"'description'",
",",
"'rules_direction'",
",",
"'rules_ip_protocol... | Returns the security rules as a CSV.
CSV format:
- id
- name
- description
- rules_direction
- rules_ip_protocol
- rules_from_port
- rules_to_port
- rules_grants_group_id
- rules_grants_name
- rules_grants_cidr_ip
- rules_description
Returns:
str | [
"Returns",
"the",
"security",
"rules",
"as",
"a",
"CSV",
"."
] | f2a40d1b3802211c85767fe74281617e4dbae543 | https://github.com/percolate/ec2-security-groups-dumper/blob/f2a40d1b3802211c85767fe74281617e4dbae543/ec2_security_groups_dumper/main.py#L232-L276 | train | 31,601 |
percolate/ec2-security-groups-dumper | ec2_security_groups_dumper/main.py | Firewall._get_rules_from_aws | def _get_rules_from_aws(self):
"""
Load the EC2 security rules off AWS into a list of dict.
Returns:
list
"""
list_of_rules = list()
if self.profile:
boto3.setup_default_session(profile_name=self.profile)
if self.region:
ec2 = boto3.client('ec2', region_name=self.region)
else:
ec2 = boto3.client('ec2')
security_groups = ec2.describe_security_groups(Filters=self.filters)
for group in security_groups['SecurityGroups']:
group_dict = dict()
group_dict['id'] = group['GroupId']
group_dict['name'] = group['GroupName']
group_dict['description'] = group.get('Description', None)
if (group.get('IpPermissions', None) or
group.get('IpPermissionsEgress', None)):
group_dict['rules'] = list()
for rule in group.get('IpPermissions', None):
rule_dict = self._build_rule(rule)
rule_dict['direction'] = "INGRESS"
group_dict['rules'].append(rule_dict)
for rule in group.get('IpPermissionsEgress', None):
rule_dict = self._build_rule(rule)
rule_dict['direction'] = "EGRESS"
group_dict['rules'].append(rule_dict)
list_of_rules.append(group_dict)
return list_of_rules | python | def _get_rules_from_aws(self):
"""
Load the EC2 security rules off AWS into a list of dict.
Returns:
list
"""
list_of_rules = list()
if self.profile:
boto3.setup_default_session(profile_name=self.profile)
if self.region:
ec2 = boto3.client('ec2', region_name=self.region)
else:
ec2 = boto3.client('ec2')
security_groups = ec2.describe_security_groups(Filters=self.filters)
for group in security_groups['SecurityGroups']:
group_dict = dict()
group_dict['id'] = group['GroupId']
group_dict['name'] = group['GroupName']
group_dict['description'] = group.get('Description', None)
if (group.get('IpPermissions', None) or
group.get('IpPermissionsEgress', None)):
group_dict['rules'] = list()
for rule in group.get('IpPermissions', None):
rule_dict = self._build_rule(rule)
rule_dict['direction'] = "INGRESS"
group_dict['rules'].append(rule_dict)
for rule in group.get('IpPermissionsEgress', None):
rule_dict = self._build_rule(rule)
rule_dict['direction'] = "EGRESS"
group_dict['rules'].append(rule_dict)
list_of_rules.append(group_dict)
return list_of_rules | [
"def",
"_get_rules_from_aws",
"(",
"self",
")",
":",
"list_of_rules",
"=",
"list",
"(",
")",
"if",
"self",
".",
"profile",
":",
"boto3",
".",
"setup_default_session",
"(",
"profile_name",
"=",
"self",
".",
"profile",
")",
"if",
"self",
".",
"region",
":",
... | Load the EC2 security rules off AWS into a list of dict.
Returns:
list | [
"Load",
"the",
"EC2",
"security",
"rules",
"off",
"AWS",
"into",
"a",
"list",
"of",
"dict",
"."
] | f2a40d1b3802211c85767fe74281617e4dbae543 | https://github.com/percolate/ec2-security-groups-dumper/blob/f2a40d1b3802211c85767fe74281617e4dbae543/ec2_security_groups_dumper/main.py#L278-L321 | train | 31,602 |
lago-project/lago | lago/sdk_utils.py | getattr_sdk | def getattr_sdk(attr, name):
"""
Filter SDK attributes
Args:
attr(attribute): Attribute as returned by :func:`getattr`.
name(str): Attribute name.
Returns:
`attr` if passed.
"""
if inspect.isroutine(attr):
if hasattr(attr, '_sdkmeta'):
return attr
raise AttributeError(name) | python | def getattr_sdk(attr, name):
"""
Filter SDK attributes
Args:
attr(attribute): Attribute as returned by :func:`getattr`.
name(str): Attribute name.
Returns:
`attr` if passed.
"""
if inspect.isroutine(attr):
if hasattr(attr, '_sdkmeta'):
return attr
raise AttributeError(name) | [
"def",
"getattr_sdk",
"(",
"attr",
",",
"name",
")",
":",
"if",
"inspect",
".",
"isroutine",
"(",
"attr",
")",
":",
"if",
"hasattr",
"(",
"attr",
",",
"'_sdkmeta'",
")",
":",
"return",
"attr",
"raise",
"AttributeError",
"(",
"name",
")"
] | Filter SDK attributes
Args:
attr(attribute): Attribute as returned by :func:`getattr`.
name(str): Attribute name.
Returns:
`attr` if passed. | [
"Filter",
"SDK",
"attributes"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/sdk_utils.py#L59-L73 | train | 31,603 |
lago-project/lago | lago/sdk_utils.py | setup_sdk_logging | def setup_sdk_logging(logfile=None, loglevel=logging.INFO):
"""
Setup a NullHandler to the root logger. If ``logfile`` is passed,
additionally add a FileHandler in ``loglevel`` level.
Args:
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
None
"""
logging.root.setLevel(logging.DEBUG)
logging.root.addHandler(logging.NullHandler())
if logfile:
fh = logging.FileHandler(logfile)
fh.setLevel(loglevel)
fh.setFormatter(get_default_log_formatter())
logging.root.addHandler(fh) | python | def setup_sdk_logging(logfile=None, loglevel=logging.INFO):
"""
Setup a NullHandler to the root logger. If ``logfile`` is passed,
additionally add a FileHandler in ``loglevel`` level.
Args:
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
None
"""
logging.root.setLevel(logging.DEBUG)
logging.root.addHandler(logging.NullHandler())
if logfile:
fh = logging.FileHandler(logfile)
fh.setLevel(loglevel)
fh.setFormatter(get_default_log_formatter())
logging.root.addHandler(fh) | [
"def",
"setup_sdk_logging",
"(",
"logfile",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"INFO",
")",
":",
"logging",
".",
"root",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"logging",
".",
"root",
".",
"addHandler",
"(",
"logging",
".",
... | Setup a NullHandler to the root logger. If ``logfile`` is passed,
additionally add a FileHandler in ``loglevel`` level.
Args:
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
None | [
"Setup",
"a",
"NullHandler",
"to",
"the",
"root",
"logger",
".",
"If",
"logfile",
"is",
"passed",
"additionally",
"add",
"a",
"FileHandler",
"in",
"loglevel",
"level",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/sdk_utils.py#L76-L95 | train | 31,604 |
lago-project/lago | lago/ssh.py | get_ssh_client | def get_ssh_client(
ip_addr,
ssh_key=None,
host_name=None,
ssh_tries=None,
propagate_fail=True,
username='root',
password='123456',
):
"""
Get a connected SSH client
Args:
ip_addr(str): IP address of the endpoint
ssh_key(str or list of str): Path to a file which
contains the private key
hotname(str): The hostname of the endpoint
ssh_tries(int): The number of attempts to connect to the endpoint
propagate_fail(bool): If set to true, this event will be in the log
and fail the outer stage. Otherwise, it will be discarded.
username(str): The username to authenticate with
password(str): Used for password authentication
or for private key decryption
Raises:
:exc:`~LagoSSHTimeoutException`: If the client failed to connect after
"ssh_tries"
"""
host_name = host_name or ip_addr
with LogTask(
'Get ssh client for %s' % host_name,
level='debug',
propagate_fail=propagate_fail,
):
ssh_timeout = int(config.get('ssh_timeout'))
if ssh_tries is None:
ssh_tries = int(config.get('ssh_tries', 10))
start_time = time.time()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy(), )
while ssh_tries > 0:
try:
client.connect(
ip_addr,
username=username,
password=password,
key_filename=ssh_key,
timeout=ssh_timeout,
)
break
except (socket.error, socket.timeout) as err:
LOGGER.debug(
'Socket error connecting to %s: %s',
host_name,
err,
)
except paramiko.ssh_exception.SSHException as err:
LOGGER.debug(
'SSH error connecting to %s: %s',
host_name,
err,
)
except EOFError as err:
LOGGER.debug('EOFError connecting to %s: %s', host_name, err)
ssh_tries -= 1
LOGGER.debug(
'Still got %d tries for %s',
ssh_tries,
host_name,
)
time.sleep(1)
else:
end_time = time.time()
raise LagoSSHTimeoutException(
'Timed out (in %d s) trying to ssh to %s' %
(end_time - start_time, host_name)
)
return client | python | def get_ssh_client(
ip_addr,
ssh_key=None,
host_name=None,
ssh_tries=None,
propagate_fail=True,
username='root',
password='123456',
):
"""
Get a connected SSH client
Args:
ip_addr(str): IP address of the endpoint
ssh_key(str or list of str): Path to a file which
contains the private key
hotname(str): The hostname of the endpoint
ssh_tries(int): The number of attempts to connect to the endpoint
propagate_fail(bool): If set to true, this event will be in the log
and fail the outer stage. Otherwise, it will be discarded.
username(str): The username to authenticate with
password(str): Used for password authentication
or for private key decryption
Raises:
:exc:`~LagoSSHTimeoutException`: If the client failed to connect after
"ssh_tries"
"""
host_name = host_name or ip_addr
with LogTask(
'Get ssh client for %s' % host_name,
level='debug',
propagate_fail=propagate_fail,
):
ssh_timeout = int(config.get('ssh_timeout'))
if ssh_tries is None:
ssh_tries = int(config.get('ssh_tries', 10))
start_time = time.time()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy(), )
while ssh_tries > 0:
try:
client.connect(
ip_addr,
username=username,
password=password,
key_filename=ssh_key,
timeout=ssh_timeout,
)
break
except (socket.error, socket.timeout) as err:
LOGGER.debug(
'Socket error connecting to %s: %s',
host_name,
err,
)
except paramiko.ssh_exception.SSHException as err:
LOGGER.debug(
'SSH error connecting to %s: %s',
host_name,
err,
)
except EOFError as err:
LOGGER.debug('EOFError connecting to %s: %s', host_name, err)
ssh_tries -= 1
LOGGER.debug(
'Still got %d tries for %s',
ssh_tries,
host_name,
)
time.sleep(1)
else:
end_time = time.time()
raise LagoSSHTimeoutException(
'Timed out (in %d s) trying to ssh to %s' %
(end_time - start_time, host_name)
)
return client | [
"def",
"get_ssh_client",
"(",
"ip_addr",
",",
"ssh_key",
"=",
"None",
",",
"host_name",
"=",
"None",
",",
"ssh_tries",
"=",
"None",
",",
"propagate_fail",
"=",
"True",
",",
"username",
"=",
"'root'",
",",
"password",
"=",
"'123456'",
",",
")",
":",
"host... | Get a connected SSH client
Args:
ip_addr(str): IP address of the endpoint
ssh_key(str or list of str): Path to a file which
contains the private key
hotname(str): The hostname of the endpoint
ssh_tries(int): The number of attempts to connect to the endpoint
propagate_fail(bool): If set to true, this event will be in the log
and fail the outer stage. Otherwise, it will be discarded.
username(str): The username to authenticate with
password(str): Used for password authentication
or for private key decryption
Raises:
:exc:`~LagoSSHTimeoutException`: If the client failed to connect after
"ssh_tries" | [
"Get",
"a",
"connected",
"SSH",
"client"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/ssh.py#L312-L391 | train | 31,605 |
lago-project/lago | lago/sysprep.py | sysprep | def sysprep(disk, distro, loader=None, backend='direct', **kwargs):
"""
Run virt-sysprep on the ``disk``, commands are built from the distro
specific template and arguments passed in ``kwargs``. If no template is
available it will default to ``sysprep-base.j2``.
Args:
disk(str): path to disk
distro(str): distro to render template for
loader(jinja2.BaseLoader): Jinja2 template loader, if not passed,
will search Lago's package.
backend(str): libguestfs backend to use
**kwargs(dict): environment variables for Jinja2 template
Returns:
None
Raises:
RuntimeError: On virt-sysprep none 0 exit code.
"""
if loader is None:
loader = PackageLoader('lago', 'templates')
sysprep_file = _render_template(distro, loader=loader, **kwargs)
cmd = ['virt-sysprep', '-a', disk]
cmd.extend(['--commands-from-file', sysprep_file])
env = os.environ.copy()
if 'LIBGUESTFS_BACKEND' not in env:
env['LIBGUESTFS_BACKEND'] = backend
ret = utils.run_command(cmd, env=env)
if ret:
raise RuntimeError(
'Failed to bootstrap %s\ncommand:%s\nstdout:%s\nstderr:%s' % (
disk,
' '.join('"%s"' % elem for elem in cmd),
ret.out,
ret.err,
)
) | python | def sysprep(disk, distro, loader=None, backend='direct', **kwargs):
"""
Run virt-sysprep on the ``disk``, commands are built from the distro
specific template and arguments passed in ``kwargs``. If no template is
available it will default to ``sysprep-base.j2``.
Args:
disk(str): path to disk
distro(str): distro to render template for
loader(jinja2.BaseLoader): Jinja2 template loader, if not passed,
will search Lago's package.
backend(str): libguestfs backend to use
**kwargs(dict): environment variables for Jinja2 template
Returns:
None
Raises:
RuntimeError: On virt-sysprep none 0 exit code.
"""
if loader is None:
loader = PackageLoader('lago', 'templates')
sysprep_file = _render_template(distro, loader=loader, **kwargs)
cmd = ['virt-sysprep', '-a', disk]
cmd.extend(['--commands-from-file', sysprep_file])
env = os.environ.copy()
if 'LIBGUESTFS_BACKEND' not in env:
env['LIBGUESTFS_BACKEND'] = backend
ret = utils.run_command(cmd, env=env)
if ret:
raise RuntimeError(
'Failed to bootstrap %s\ncommand:%s\nstdout:%s\nstderr:%s' % (
disk,
' '.join('"%s"' % elem for elem in cmd),
ret.out,
ret.err,
)
) | [
"def",
"sysprep",
"(",
"disk",
",",
"distro",
",",
"loader",
"=",
"None",
",",
"backend",
"=",
"'direct'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"loader",
"is",
"None",
":",
"loader",
"=",
"PackageLoader",
"(",
"'lago'",
",",
"'templates'",
")",
"... | Run virt-sysprep on the ``disk``, commands are built from the distro
specific template and arguments passed in ``kwargs``. If no template is
available it will default to ``sysprep-base.j2``.
Args:
disk(str): path to disk
distro(str): distro to render template for
loader(jinja2.BaseLoader): Jinja2 template loader, if not passed,
will search Lago's package.
backend(str): libguestfs backend to use
**kwargs(dict): environment variables for Jinja2 template
Returns:
None
Raises:
RuntimeError: On virt-sysprep none 0 exit code. | [
"Run",
"virt",
"-",
"sysprep",
"on",
"the",
"disk",
"commands",
"are",
"built",
"from",
"the",
"distro",
"specific",
"template",
"and",
"arguments",
"passed",
"in",
"kwargs",
".",
"If",
"no",
"template",
"is",
"available",
"it",
"will",
"default",
"to",
"s... | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/sysprep.py#L69-L110 | train | 31,606 |
lago-project/lago | lago/providers/libvirt/utils.py | get_domain_template | def get_domain_template(distro, libvirt_ver, **kwargs):
"""
Get a rendered Jinja2 domain template
Args:
distro(str): domain distro
libvirt_ver(int): libvirt version
kwargs(dict): args for template render
Returns:
str: rendered template
"""
env = Environment(
loader=PackageLoader('lago', 'providers/libvirt/templates'),
trim_blocks=True,
lstrip_blocks=True,
)
template_name = 'dom_template-{0}.xml.j2'.format(distro)
try:
template = env.get_template(template_name)
except TemplateNotFound:
LOGGER.debug('could not find template %s using default', template_name)
template = env.get_template('dom_template-base.xml.j2')
return template.render(libvirt_ver=libvirt_ver, **kwargs) | python | def get_domain_template(distro, libvirt_ver, **kwargs):
"""
Get a rendered Jinja2 domain template
Args:
distro(str): domain distro
libvirt_ver(int): libvirt version
kwargs(dict): args for template render
Returns:
str: rendered template
"""
env = Environment(
loader=PackageLoader('lago', 'providers/libvirt/templates'),
trim_blocks=True,
lstrip_blocks=True,
)
template_name = 'dom_template-{0}.xml.j2'.format(distro)
try:
template = env.get_template(template_name)
except TemplateNotFound:
LOGGER.debug('could not find template %s using default', template_name)
template = env.get_template('dom_template-base.xml.j2')
return template.render(libvirt_ver=libvirt_ver, **kwargs) | [
"def",
"get_domain_template",
"(",
"distro",
",",
"libvirt_ver",
",",
"*",
"*",
"kwargs",
")",
":",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"PackageLoader",
"(",
"'lago'",
",",
"'providers/libvirt/templates'",
")",
",",
"trim_blocks",
"=",
"True",
",",
... | Get a rendered Jinja2 domain template
Args:
distro(str): domain distro
libvirt_ver(int): libvirt version
kwargs(dict): args for template render
Returns:
str: rendered template | [
"Get",
"a",
"rendered",
"Jinja2",
"domain",
"template"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/utils.py#L118-L142 | train | 31,607 |
lago-project/lago | lago/providers/libvirt/utils.py | dict_to_xml | def dict_to_xml(spec, full_document=False):
"""
Convert dict to XML
Args:
spec(dict): dict to convert
full_document(bool): whether to add XML headers
Returns:
lxml.etree.Element: XML tree
"""
middle = xmltodict.unparse(spec, full_document=full_document, pretty=True)
return lxml.etree.fromstring(middle) | python | def dict_to_xml(spec, full_document=False):
"""
Convert dict to XML
Args:
spec(dict): dict to convert
full_document(bool): whether to add XML headers
Returns:
lxml.etree.Element: XML tree
"""
middle = xmltodict.unparse(spec, full_document=full_document, pretty=True)
return lxml.etree.fromstring(middle) | [
"def",
"dict_to_xml",
"(",
"spec",
",",
"full_document",
"=",
"False",
")",
":",
"middle",
"=",
"xmltodict",
".",
"unparse",
"(",
"spec",
",",
"full_document",
"=",
"full_document",
",",
"pretty",
"=",
"True",
")",
"return",
"lxml",
".",
"etree",
".",
"f... | Convert dict to XML
Args:
spec(dict): dict to convert
full_document(bool): whether to add XML headers
Returns:
lxml.etree.Element: XML tree | [
"Convert",
"dict",
"to",
"XML"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/utils.py#L145-L158 | train | 31,608 |
lago-project/lago | lago/guestfs_tools.py | guestfs_conn_ro | def guestfs_conn_ro(disk):
"""
Open a GuestFS handle and add `disk` in read only mode.
Args:
disk(disk path): Path to the disk.
Yields:
guestfs.GuestFS: Open GuestFS handle
Raises:
:exc:`GuestFSError`: On any guestfs operation failure
"""
disk_path = os.path.expandvars(disk)
conn = guestfs.GuestFS(python_return_dict=True)
conn.add_drive_ro(disk_path)
conn.set_backend(os.environ.get('LIBGUESTFS_BACKEND', 'direct'))
try:
conn.launch()
except RuntimeError as err:
LOGGER.debug(err)
raise GuestFSError(
'failed starting guestfs in readonly mode for disk: {0}'.
format(disk)
)
try:
yield conn
finally:
conn.shutdown()
conn.close() | python | def guestfs_conn_ro(disk):
"""
Open a GuestFS handle and add `disk` in read only mode.
Args:
disk(disk path): Path to the disk.
Yields:
guestfs.GuestFS: Open GuestFS handle
Raises:
:exc:`GuestFSError`: On any guestfs operation failure
"""
disk_path = os.path.expandvars(disk)
conn = guestfs.GuestFS(python_return_dict=True)
conn.add_drive_ro(disk_path)
conn.set_backend(os.environ.get('LIBGUESTFS_BACKEND', 'direct'))
try:
conn.launch()
except RuntimeError as err:
LOGGER.debug(err)
raise GuestFSError(
'failed starting guestfs in readonly mode for disk: {0}'.
format(disk)
)
try:
yield conn
finally:
conn.shutdown()
conn.close() | [
"def",
"guestfs_conn_ro",
"(",
"disk",
")",
":",
"disk_path",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"disk",
")",
"conn",
"=",
"guestfs",
".",
"GuestFS",
"(",
"python_return_dict",
"=",
"True",
")",
"conn",
".",
"add_drive_ro",
"(",
"disk_path",
... | Open a GuestFS handle and add `disk` in read only mode.
Args:
disk(disk path): Path to the disk.
Yields:
guestfs.GuestFS: Open GuestFS handle
Raises:
:exc:`GuestFSError`: On any guestfs operation failure | [
"Open",
"a",
"GuestFS",
"handle",
"and",
"add",
"disk",
"in",
"read",
"only",
"mode",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/guestfs_tools.py#L37-L67 | train | 31,609 |
lago-project/lago | lago/guestfs_tools.py | guestfs_conn_mount_ro | def guestfs_conn_mount_ro(disk_path, disk_root, retries=5, wait=1):
"""
Open a GuestFS handle with `disk_path` and try mounting the root
filesystem. `disk_root` is a hint where it should be looked and will
only be used if GuestFS will not be able to deduce it independently.
Note that mounting a live guest, can lead to filesystem inconsistencies,
causing the mount operation to fail. As we use readonly mode, this is
safe, but the operation itself can still fail. Therefore, this method
will watch for mount failures and retry 5 times before throwing
an exception.
Args:
disk_path(str): Path to the disk.
disk_root(str): Hint what is the root device with the OS filesystem.
retries(int): Number of retries for :func:`~guestfs.GuestFS.mount_ro`
operation. Note that on each retry a new GuestFS handle will
be used.
wait(int): Time to wait between retries.
Yields:
guestfs.GuestFS: An open GuestFS handle.
Raises:
:exc:`GuestFSError`: On any guestfs operation error, including
exceeding retries for the :func:`~guestfs.GuestFS.mount_ro`
operation.
"""
for attempt in range(retries):
with guestfs_conn_ro(disk_path) as conn:
rootfs = find_rootfs(conn, disk_root)
try:
conn.mount_ro(rootfs, '/')
except RuntimeError as err:
LOGGER.debug(err)
if attempt < retries - 1:
LOGGER.debug(
(
'failed mounting %s:%s using guestfs, '
'attempt %s/%s'
), disk_path, rootfs, attempt + 1, retries
)
time.sleep(wait)
continue
else:
raise GuestFSError(
'failed mounting {0}:{1} using guestfs'.format(
disk_path, rootfs
)
)
yield conn
try:
conn.umount(rootfs)
except RuntimeError as err:
LOGGER.debug(err)
raise GuestFSError(
('failed unmounting {0}:{1} using'
'guestfs').format(disk_path, rootfs)
)
break | python | def guestfs_conn_mount_ro(disk_path, disk_root, retries=5, wait=1):
"""
Open a GuestFS handle with `disk_path` and try mounting the root
filesystem. `disk_root` is a hint where it should be looked and will
only be used if GuestFS will not be able to deduce it independently.
Note that mounting a live guest, can lead to filesystem inconsistencies,
causing the mount operation to fail. As we use readonly mode, this is
safe, but the operation itself can still fail. Therefore, this method
will watch for mount failures and retry 5 times before throwing
an exception.
Args:
disk_path(str): Path to the disk.
disk_root(str): Hint what is the root device with the OS filesystem.
retries(int): Number of retries for :func:`~guestfs.GuestFS.mount_ro`
operation. Note that on each retry a new GuestFS handle will
be used.
wait(int): Time to wait between retries.
Yields:
guestfs.GuestFS: An open GuestFS handle.
Raises:
:exc:`GuestFSError`: On any guestfs operation error, including
exceeding retries for the :func:`~guestfs.GuestFS.mount_ro`
operation.
"""
for attempt in range(retries):
with guestfs_conn_ro(disk_path) as conn:
rootfs = find_rootfs(conn, disk_root)
try:
conn.mount_ro(rootfs, '/')
except RuntimeError as err:
LOGGER.debug(err)
if attempt < retries - 1:
LOGGER.debug(
(
'failed mounting %s:%s using guestfs, '
'attempt %s/%s'
), disk_path, rootfs, attempt + 1, retries
)
time.sleep(wait)
continue
else:
raise GuestFSError(
'failed mounting {0}:{1} using guestfs'.format(
disk_path, rootfs
)
)
yield conn
try:
conn.umount(rootfs)
except RuntimeError as err:
LOGGER.debug(err)
raise GuestFSError(
('failed unmounting {0}:{1} using'
'guestfs').format(disk_path, rootfs)
)
break | [
"def",
"guestfs_conn_mount_ro",
"(",
"disk_path",
",",
"disk_root",
",",
"retries",
"=",
"5",
",",
"wait",
"=",
"1",
")",
":",
"for",
"attempt",
"in",
"range",
"(",
"retries",
")",
":",
"with",
"guestfs_conn_ro",
"(",
"disk_path",
")",
"as",
"conn",
":",... | Open a GuestFS handle with `disk_path` and try mounting the root
filesystem. `disk_root` is a hint where it should be looked and will
only be used if GuestFS will not be able to deduce it independently.
Note that mounting a live guest, can lead to filesystem inconsistencies,
causing the mount operation to fail. As we use readonly mode, this is
safe, but the operation itself can still fail. Therefore, this method
will watch for mount failures and retry 5 times before throwing
an exception.
Args:
disk_path(str): Path to the disk.
disk_root(str): Hint what is the root device with the OS filesystem.
retries(int): Number of retries for :func:`~guestfs.GuestFS.mount_ro`
operation. Note that on each retry a new GuestFS handle will
be used.
wait(int): Time to wait between retries.
Yields:
guestfs.GuestFS: An open GuestFS handle.
Raises:
:exc:`GuestFSError`: On any guestfs operation error, including
exceeding retries for the :func:`~guestfs.GuestFS.mount_ro`
operation. | [
"Open",
"a",
"GuestFS",
"handle",
"with",
"disk_path",
"and",
"try",
"mounting",
"the",
"root",
"filesystem",
".",
"disk_root",
"is",
"a",
"hint",
"where",
"it",
"should",
"be",
"looked",
"and",
"will",
"only",
"be",
"used",
"if",
"GuestFS",
"will",
"not",... | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/guestfs_tools.py#L71-L133 | train | 31,610 |
lago-project/lago | lago/guestfs_tools.py | find_rootfs | def find_rootfs(conn, disk_root):
"""
Find the image's device root filesystem, and return its path.
1. Use :func:`guestfs.GuestFS.inspect_os` method. If it returns more than
one root filesystem or None, try:
2. Find an exact match of `disk_root` from
:func:`guestfs.GuestFS.list_filesystems`, if none is found, try:
3. Return the device that has the substring `disk_root` contained in it,
from the output of :func:`guestfs.GuestFS.list_filesystems`.
Args:
conn(guestfs.GuestFS): Open GuestFS handle.
disk_root(str): Root device to search for. Note that by default, if
guestfs can deduce the filesystem, it will not be used.
Returns:
str: root device path
Raises:
:exc:`GuestFSError` if no root filesystem was found
"""
rootfs = conn.inspect_os()
if not rootfs or len(rootfs) > 1:
filesystems = conn.list_filesystems()
if disk_root in filesystems:
rootfs = [disk_root]
else:
rootfs = [fs for fs in filesystems.keys() if disk_root in fs]
if not rootfs:
raise GuestFSError(
'no root fs {0} could be found from list {1}'.format(
disk_root, str(filesystems)
)
)
return sorted(rootfs)[0] | python | def find_rootfs(conn, disk_root):
"""
Find the image's device root filesystem, and return its path.
1. Use :func:`guestfs.GuestFS.inspect_os` method. If it returns more than
one root filesystem or None, try:
2. Find an exact match of `disk_root` from
:func:`guestfs.GuestFS.list_filesystems`, if none is found, try:
3. Return the device that has the substring `disk_root` contained in it,
from the output of :func:`guestfs.GuestFS.list_filesystems`.
Args:
conn(guestfs.GuestFS): Open GuestFS handle.
disk_root(str): Root device to search for. Note that by default, if
guestfs can deduce the filesystem, it will not be used.
Returns:
str: root device path
Raises:
:exc:`GuestFSError` if no root filesystem was found
"""
rootfs = conn.inspect_os()
if not rootfs or len(rootfs) > 1:
filesystems = conn.list_filesystems()
if disk_root in filesystems:
rootfs = [disk_root]
else:
rootfs = [fs for fs in filesystems.keys() if disk_root in fs]
if not rootfs:
raise GuestFSError(
'no root fs {0} could be found from list {1}'.format(
disk_root, str(filesystems)
)
)
return sorted(rootfs)[0] | [
"def",
"find_rootfs",
"(",
"conn",
",",
"disk_root",
")",
":",
"rootfs",
"=",
"conn",
".",
"inspect_os",
"(",
")",
"if",
"not",
"rootfs",
"or",
"len",
"(",
"rootfs",
")",
">",
"1",
":",
"filesystems",
"=",
"conn",
".",
"list_filesystems",
"(",
")",
"... | Find the image's device root filesystem, and return its path.
1. Use :func:`guestfs.GuestFS.inspect_os` method. If it returns more than
one root filesystem or None, try:
2. Find an exact match of `disk_root` from
:func:`guestfs.GuestFS.list_filesystems`, if none is found, try:
3. Return the device that has the substring `disk_root` contained in it,
from the output of :func:`guestfs.GuestFS.list_filesystems`.
Args:
conn(guestfs.GuestFS): Open GuestFS handle.
disk_root(str): Root device to search for. Note that by default, if
guestfs can deduce the filesystem, it will not be used.
Returns:
str: root device path
Raises:
:exc:`GuestFSError` if no root filesystem was found | [
"Find",
"the",
"image",
"s",
"device",
"root",
"filesystem",
"and",
"return",
"its",
"path",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/guestfs_tools.py#L136-L171 | train | 31,611 |
lago-project/lago | lago/guestfs_tools.py | extract_paths | def extract_paths(disk_path, disk_root, paths, ignore_nopath):
"""
Extract paths from a disk using guestfs
Args:
disk_path(str): path to the disk
disk_root(str): root partition
paths(list of tuples): files to extract in
`[(src1, dst1), (src2, dst2)...]` format, if ``srcN`` is a
directory in the guest, and ``dstN`` does not exist on the host,
it will be created. If ``srcN`` is a file on the guest, it will be
copied exactly to ``dstN``
ignore_nopath(bool): If set to True, ignore paths in the guest that
do not exit
Returns:
None
Raises:
:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing
path was found on the guest, and `ignore_nopath` is False.
:exc:`~lago.plugins.vm.ExtractPathError`: on all other failures.
"""
with guestfs_conn_mount_ro(disk_path, disk_root) as conn:
for (guest_path, host_path) in paths:
msg = ('Extracting guestfs://{0} to {1}').format(
guest_path, host_path
)
LOGGER.debug(msg)
try:
_copy_path(conn, guest_path, host_path)
except ExtractPathNoPathError as err:
if ignore_nopath:
LOGGER.debug('%s - ignoring', err)
else:
raise | python | def extract_paths(disk_path, disk_root, paths, ignore_nopath):
"""
Extract paths from a disk using guestfs
Args:
disk_path(str): path to the disk
disk_root(str): root partition
paths(list of tuples): files to extract in
`[(src1, dst1), (src2, dst2)...]` format, if ``srcN`` is a
directory in the guest, and ``dstN`` does not exist on the host,
it will be created. If ``srcN`` is a file on the guest, it will be
copied exactly to ``dstN``
ignore_nopath(bool): If set to True, ignore paths in the guest that
do not exit
Returns:
None
Raises:
:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing
path was found on the guest, and `ignore_nopath` is False.
:exc:`~lago.plugins.vm.ExtractPathError`: on all other failures.
"""
with guestfs_conn_mount_ro(disk_path, disk_root) as conn:
for (guest_path, host_path) in paths:
msg = ('Extracting guestfs://{0} to {1}').format(
guest_path, host_path
)
LOGGER.debug(msg)
try:
_copy_path(conn, guest_path, host_path)
except ExtractPathNoPathError as err:
if ignore_nopath:
LOGGER.debug('%s - ignoring', err)
else:
raise | [
"def",
"extract_paths",
"(",
"disk_path",
",",
"disk_root",
",",
"paths",
",",
"ignore_nopath",
")",
":",
"with",
"guestfs_conn_mount_ro",
"(",
"disk_path",
",",
"disk_root",
")",
"as",
"conn",
":",
"for",
"(",
"guest_path",
",",
"host_path",
")",
"in",
"pat... | Extract paths from a disk using guestfs
Args:
disk_path(str): path to the disk
disk_root(str): root partition
paths(list of tuples): files to extract in
`[(src1, dst1), (src2, dst2)...]` format, if ``srcN`` is a
directory in the guest, and ``dstN`` does not exist on the host,
it will be created. If ``srcN`` is a file on the guest, it will be
copied exactly to ``dstN``
ignore_nopath(bool): If set to True, ignore paths in the guest that
do not exit
Returns:
None
Raises:
:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing
path was found on the guest, and `ignore_nopath` is False.
:exc:`~lago.plugins.vm.ExtractPathError`: on all other failures. | [
"Extract",
"paths",
"from",
"a",
"disk",
"using",
"guestfs"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/guestfs_tools.py#L174-L211 | train | 31,612 |
lago-project/lago | lago/plugins/cli.py | cli_plugin_add_argument | def cli_plugin_add_argument(*args, **kwargs):
"""
Decorator generator that adds an argument to the cli plugin based on the
decorated function
Args:
*args: Any args to be passed to
:func:`argparse.ArgumentParser.add_argument`
*kwargs: Any keyword args to be passed to
:func:`argparse.ArgumentParser.add_argument`
Returns:
function: Decorator that builds or extends the cliplugin for the
decorated function, adding the given argument definition
Examples:
>>> @cli_plugin_add_argument('-m', '--mogambo', action='store_true')
... def test(**kwargs):
... print 'test'
...
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test._parser_args
[(('-m', '--mogambo'), {'action': 'store_true'})]
>>> @cli_plugin_add_argument('-m', '--mogambo', action='store_true')
... @cli_plugin_add_argument('-b', '--bogabmo', action='store_false')
... @cli_plugin
... def test(**kwargs):
... print 'test'
...
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test._parser_args # doctest: +NORMALIZE_WHITESPACE
[(('-b', '--bogabmo'), {'action': 'store_false'}),
(('-m', '--mogambo'), {'action': 'store_true'})]
"""
def decorator(func):
if not isinstance(func, CLIPluginFuncWrapper):
func = CLIPluginFuncWrapper(do_run=func)
func.add_argument(*args, **kwargs)
return func
return decorator | python | def cli_plugin_add_argument(*args, **kwargs):
"""
Decorator generator that adds an argument to the cli plugin based on the
decorated function
Args:
*args: Any args to be passed to
:func:`argparse.ArgumentParser.add_argument`
*kwargs: Any keyword args to be passed to
:func:`argparse.ArgumentParser.add_argument`
Returns:
function: Decorator that builds or extends the cliplugin for the
decorated function, adding the given argument definition
Examples:
>>> @cli_plugin_add_argument('-m', '--mogambo', action='store_true')
... def test(**kwargs):
... print 'test'
...
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test._parser_args
[(('-m', '--mogambo'), {'action': 'store_true'})]
>>> @cli_plugin_add_argument('-m', '--mogambo', action='store_true')
... @cli_plugin_add_argument('-b', '--bogabmo', action='store_false')
... @cli_plugin
... def test(**kwargs):
... print 'test'
...
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test._parser_args # doctest: +NORMALIZE_WHITESPACE
[(('-b', '--bogabmo'), {'action': 'store_false'}),
(('-m', '--mogambo'), {'action': 'store_true'})]
"""
def decorator(func):
if not isinstance(func, CLIPluginFuncWrapper):
func = CLIPluginFuncWrapper(do_run=func)
func.add_argument(*args, **kwargs)
return func
return decorator | [
"def",
"cli_plugin_add_argument",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"if",
"not",
"isinstance",
"(",
"func",
",",
"CLIPluginFuncWrapper",
")",
":",
"func",
"=",
"CLIPluginFuncWrapper",
"(",
"do_r... | Decorator generator that adds an argument to the cli plugin based on the
decorated function
Args:
*args: Any args to be passed to
:func:`argparse.ArgumentParser.add_argument`
*kwargs: Any keyword args to be passed to
:func:`argparse.ArgumentParser.add_argument`
Returns:
function: Decorator that builds or extends the cliplugin for the
decorated function, adding the given argument definition
Examples:
>>> @cli_plugin_add_argument('-m', '--mogambo', action='store_true')
... def test(**kwargs):
... print 'test'
...
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test._parser_args
[(('-m', '--mogambo'), {'action': 'store_true'})]
>>> @cli_plugin_add_argument('-m', '--mogambo', action='store_true')
... @cli_plugin_add_argument('-b', '--bogabmo', action='store_false')
... @cli_plugin
... def test(**kwargs):
... print 'test'
...
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test._parser_args # doctest: +NORMALIZE_WHITESPACE
[(('-b', '--bogabmo'), {'action': 'store_false'}),
(('-m', '--mogambo'), {'action': 'store_true'})] | [
"Decorator",
"generator",
"that",
"adds",
"an",
"argument",
"to",
"the",
"cli",
"plugin",
"based",
"on",
"the",
"decorated",
"function"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/plugins/cli.py#L193-L240 | train | 31,613 |
lago-project/lago | lago/plugins/cli.py | cli_plugin_add_help | def cli_plugin_add_help(help):
"""
Decorator generator that adds the cli help to the cli plugin based on the
decorated function
Args:
help (str): help string for the cli plugin
Returns:
function: Decorator that builds or extends the cliplugin for the
decorated function, setting the given help
Examples:
>>> @cli_plugin_add_help('my help string')
... def test(**kwargs):
... print 'test'
...
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test.help
my help string
>>> @cli_plugin_add_help('my help string')
... @cli_plugin()
... def test(**kwargs):
... print 'test'
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test.help
my help string
"""
def decorator(func):
if not isinstance(func, CLIPluginFuncWrapper):
func = CLIPluginFuncWrapper(do_run=func)
func.set_help(help)
return func
return decorator | python | def cli_plugin_add_help(help):
"""
Decorator generator that adds the cli help to the cli plugin based on the
decorated function
Args:
help (str): help string for the cli plugin
Returns:
function: Decorator that builds or extends the cliplugin for the
decorated function, setting the given help
Examples:
>>> @cli_plugin_add_help('my help string')
... def test(**kwargs):
... print 'test'
...
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test.help
my help string
>>> @cli_plugin_add_help('my help string')
... @cli_plugin()
... def test(**kwargs):
... print 'test'
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test.help
my help string
"""
def decorator(func):
if not isinstance(func, CLIPluginFuncWrapper):
func = CLIPluginFuncWrapper(do_run=func)
func.set_help(help)
return func
return decorator | [
"def",
"cli_plugin_add_help",
"(",
"help",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"if",
"not",
"isinstance",
"(",
"func",
",",
"CLIPluginFuncWrapper",
")",
":",
"func",
"=",
"CLIPluginFuncWrapper",
"(",
"do_run",
"=",
"func",
")",
"func",
"."... | Decorator generator that adds the cli help to the cli plugin based on the
decorated function
Args:
help (str): help string for the cli plugin
Returns:
function: Decorator that builds or extends the cliplugin for the
decorated function, setting the given help
Examples:
>>> @cli_plugin_add_help('my help string')
... def test(**kwargs):
... print 'test'
...
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test.help
my help string
>>> @cli_plugin_add_help('my help string')
... @cli_plugin()
... def test(**kwargs):
... print 'test'
>>> print test.__class__
<class 'cli.CLIPluginFuncWrapper'>
>>> print test.help
my help string | [
"Decorator",
"generator",
"that",
"adds",
"the",
"cli",
"help",
"to",
"the",
"cli",
"plugin",
"based",
"on",
"the",
"decorated",
"function"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/plugins/cli.py#L243-L282 | train | 31,614 |
lago-project/lago | lago/providers/libvirt/vm.py | LocalLibvirtVMProvider._get_domain | def _get_domain(self):
"""
Return the object representation of this provider VM.
Returns:
libvirt.virDomain: Libvirt domain object
Raises:
:exc:`~lago.plugins.vm.LagoFailedToGetVMStateError:
If the VM exist, but the query returned an error.
"""
try:
return self.libvirt_con.lookupByName(self._libvirt_name())
except libvirt.libvirtError as e:
raise vm_plugin.LagoVMDoesNotExistError(str(e)) | python | def _get_domain(self):
"""
Return the object representation of this provider VM.
Returns:
libvirt.virDomain: Libvirt domain object
Raises:
:exc:`~lago.plugins.vm.LagoFailedToGetVMStateError:
If the VM exist, but the query returned an error.
"""
try:
return self.libvirt_con.lookupByName(self._libvirt_name())
except libvirt.libvirtError as e:
raise vm_plugin.LagoVMDoesNotExistError(str(e)) | [
"def",
"_get_domain",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"libvirt_con",
".",
"lookupByName",
"(",
"self",
".",
"_libvirt_name",
"(",
")",
")",
"except",
"libvirt",
".",
"libvirtError",
"as",
"e",
":",
"raise",
"vm_plugin",
".",
"La... | Return the object representation of this provider VM.
Returns:
libvirt.virDomain: Libvirt domain object
Raises:
:exc:`~lago.plugins.vm.LagoFailedToGetVMStateError:
If the VM exist, but the query returned an error. | [
"Return",
"the",
"object",
"representation",
"of",
"this",
"provider",
"VM",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/vm.py#L278-L292 | train | 31,615 |
lago-project/lago | lago/providers/libvirt/vm.py | LocalLibvirtVMProvider.raw_state | def raw_state(self):
"""
Return the state of the domain in Libvirt's terms
Retruns:
tuple of ints: The state and its reason
Raises:
:exc:`~lago.plugins.vm.LagoVMDoesNotExistError`:
If the VM of this provider doesn't exist.
:exc:`~lago.plugins.vm.LagoFailedToGetVMStateError:
If the VM exist, but the query returned an error.
"""
try:
return self._get_domain().state()
except libvirt.libvirtError as e:
raise vm_plugin.LagoFailedToGetVMStateError(str(e)) | python | def raw_state(self):
"""
Return the state of the domain in Libvirt's terms
Retruns:
tuple of ints: The state and its reason
Raises:
:exc:`~lago.plugins.vm.LagoVMDoesNotExistError`:
If the VM of this provider doesn't exist.
:exc:`~lago.plugins.vm.LagoFailedToGetVMStateError:
If the VM exist, but the query returned an error.
"""
try:
return self._get_domain().state()
except libvirt.libvirtError as e:
raise vm_plugin.LagoFailedToGetVMStateError(str(e)) | [
"def",
"raw_state",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_get_domain",
"(",
")",
".",
"state",
"(",
")",
"except",
"libvirt",
".",
"libvirtError",
"as",
"e",
":",
"raise",
"vm_plugin",
".",
"LagoFailedToGetVMStateError",
"(",
"str",
... | Return the state of the domain in Libvirt's terms
Retruns:
tuple of ints: The state and its reason
Raises:
:exc:`~lago.plugins.vm.LagoVMDoesNotExistError`:
If the VM of this provider doesn't exist.
:exc:`~lago.plugins.vm.LagoFailedToGetVMStateError:
If the VM exist, but the query returned an error. | [
"Return",
"the",
"state",
"of",
"the",
"domain",
"in",
"Libvirt",
"s",
"terms"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/vm.py#L294-L310 | train | 31,616 |
lago-project/lago | lago/providers/libvirt/vm.py | LocalLibvirtVMProvider.state | def state(self):
"""
Return a small description of the current status of the domain
Returns:
str: small description of the domain status, 'down' if it's not
found at all.
"""
try:
return libvirt_utils.Domain.resolve_state(self.raw_state())
except vm_plugin.LagoVMDoesNotExistError:
return 'down'
except vm_plugin.LagoFailedToGetVMStateError:
return 'failed to get state'
except KeyError:
return 'unknown state' | python | def state(self):
"""
Return a small description of the current status of the domain
Returns:
str: small description of the domain status, 'down' if it's not
found at all.
"""
try:
return libvirt_utils.Domain.resolve_state(self.raw_state())
except vm_plugin.LagoVMDoesNotExistError:
return 'down'
except vm_plugin.LagoFailedToGetVMStateError:
return 'failed to get state'
except KeyError:
return 'unknown state' | [
"def",
"state",
"(",
"self",
")",
":",
"try",
":",
"return",
"libvirt_utils",
".",
"Domain",
".",
"resolve_state",
"(",
"self",
".",
"raw_state",
"(",
")",
")",
"except",
"vm_plugin",
".",
"LagoVMDoesNotExistError",
":",
"return",
"'down'",
"except",
"vm_plu... | Return a small description of the current status of the domain
Returns:
str: small description of the domain status, 'down' if it's not
found at all. | [
"Return",
"a",
"small",
"description",
"of",
"the",
"current",
"status",
"of",
"the",
"domain"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/vm.py#L312-L327 | train | 31,617 |
lago-project/lago | lago/providers/libvirt/vm.py | LocalLibvirtVMProvider.extract_paths | def extract_paths(self, paths, ignore_nopath):
"""
Extract the given paths from the domain
Attempt to extract all files defined in ``paths`` with the method
defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`,
if it fails, and `guestfs` is available it will try extracting the
files with guestfs.
Args:
paths(list of tuples): files to extract in
`[(src1, dst1), (src2, dst2)...]` format.
ignore_nopath(boolean): if True will ignore none existing paths.
Returns:
None
Raises:
:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing
path was found on the VM, and `ignore_nopath` is False.
:exc:`~lago.plugins.vm.ExtractPathError`: on all other failures.
"""
try:
super().extract_paths(
paths=paths,
ignore_nopath=ignore_nopath,
)
except ExtractPathError as err:
LOGGER.debug(
'%s: failed extracting files: %s', self.vm.name(), err.message
)
if self._has_guestfs:
self.extract_paths_dead(paths, ignore_nopath)
else:
raise | python | def extract_paths(self, paths, ignore_nopath):
"""
Extract the given paths from the domain
Attempt to extract all files defined in ``paths`` with the method
defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`,
if it fails, and `guestfs` is available it will try extracting the
files with guestfs.
Args:
paths(list of tuples): files to extract in
`[(src1, dst1), (src2, dst2)...]` format.
ignore_nopath(boolean): if True will ignore none existing paths.
Returns:
None
Raises:
:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing
path was found on the VM, and `ignore_nopath` is False.
:exc:`~lago.plugins.vm.ExtractPathError`: on all other failures.
"""
try:
super().extract_paths(
paths=paths,
ignore_nopath=ignore_nopath,
)
except ExtractPathError as err:
LOGGER.debug(
'%s: failed extracting files: %s', self.vm.name(), err.message
)
if self._has_guestfs:
self.extract_paths_dead(paths, ignore_nopath)
else:
raise | [
"def",
"extract_paths",
"(",
"self",
",",
"paths",
",",
"ignore_nopath",
")",
":",
"try",
":",
"super",
"(",
")",
".",
"extract_paths",
"(",
"paths",
"=",
"paths",
",",
"ignore_nopath",
"=",
"ignore_nopath",
",",
")",
"except",
"ExtractPathError",
"as",
"e... | Extract the given paths from the domain
Attempt to extract all files defined in ``paths`` with the method
defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`,
if it fails, and `guestfs` is available it will try extracting the
files with guestfs.
Args:
paths(list of tuples): files to extract in
`[(src1, dst1), (src2, dst2)...]` format.
ignore_nopath(boolean): if True will ignore none existing paths.
Returns:
None
Raises:
:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing
path was found on the VM, and `ignore_nopath` is False.
:exc:`~lago.plugins.vm.ExtractPathError`: on all other failures. | [
"Extract",
"the",
"given",
"paths",
"from",
"the",
"domain"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/vm.py#L371-L407 | train | 31,618 |
lago-project/lago | lago/providers/libvirt/vm.py | LocalLibvirtVMProvider.extract_paths_dead | def extract_paths_dead(self, paths, ignore_nopath):
"""
Extract the given paths from the domain using guestfs.
Using guestfs can have side-effects and should be used as a second
option, mainly when SSH is not available.
Args:
paths(list of str): paths to extract
ignore_nopath(boolean): if True will ignore none existing paths.
Returns:
None
Raises:
:exc:`~lago.utils.LagoException`: if :mod:`guestfs` is not
importable.
:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing
path was found on the VM, and `ignore_nopath` is True.
:exc:`~lago.plugins.vm.ExtractPathError`: on failure extracting
the files.
"""
if not self._has_guestfs:
raise LagoException(
('guestfs module not available, cannot '
)('extract files with libguestfs')
)
LOGGER.debug(
'%s: attempting to extract files with libguestfs', self.vm.name()
)
guestfs_tools.extract_paths(
disk_path=self.vm.spec['disks'][0]['path'],
disk_root=self.vm.spec['disks'][0]['metadata'].get(
'root-partition', 'root'
),
paths=paths,
ignore_nopath=ignore_nopath
) | python | def extract_paths_dead(self, paths, ignore_nopath):
"""
Extract the given paths from the domain using guestfs.
Using guestfs can have side-effects and should be used as a second
option, mainly when SSH is not available.
Args:
paths(list of str): paths to extract
ignore_nopath(boolean): if True will ignore none existing paths.
Returns:
None
Raises:
:exc:`~lago.utils.LagoException`: if :mod:`guestfs` is not
importable.
:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing
path was found on the VM, and `ignore_nopath` is True.
:exc:`~lago.plugins.vm.ExtractPathError`: on failure extracting
the files.
"""
if not self._has_guestfs:
raise LagoException(
('guestfs module not available, cannot '
)('extract files with libguestfs')
)
LOGGER.debug(
'%s: attempting to extract files with libguestfs', self.vm.name()
)
guestfs_tools.extract_paths(
disk_path=self.vm.spec['disks'][0]['path'],
disk_root=self.vm.spec['disks'][0]['metadata'].get(
'root-partition', 'root'
),
paths=paths,
ignore_nopath=ignore_nopath
) | [
"def",
"extract_paths_dead",
"(",
"self",
",",
"paths",
",",
"ignore_nopath",
")",
":",
"if",
"not",
"self",
".",
"_has_guestfs",
":",
"raise",
"LagoException",
"(",
"(",
"'guestfs module not available, cannot '",
")",
"(",
"'extract files with libguestfs'",
")",
")... | Extract the given paths from the domain using guestfs.
Using guestfs can have side-effects and should be used as a second
option, mainly when SSH is not available.
Args:
paths(list of str): paths to extract
ignore_nopath(boolean): if True will ignore none existing paths.
Returns:
None
Raises:
:exc:`~lago.utils.LagoException`: if :mod:`guestfs` is not
importable.
:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing
path was found on the VM, and `ignore_nopath` is True.
:exc:`~lago.plugins.vm.ExtractPathError`: on failure extracting
the files. | [
"Extract",
"the",
"given",
"paths",
"from",
"the",
"domain",
"using",
"guestfs",
".",
"Using",
"guestfs",
"can",
"have",
"side",
"-",
"effects",
"and",
"should",
"be",
"used",
"as",
"a",
"second",
"option",
"mainly",
"when",
"SSH",
"is",
"not",
"available"... | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/vm.py#L409-L446 | train | 31,619 |
lago-project/lago | lago/providers/libvirt/vm.py | LocalLibvirtVMProvider.export_disks | def export_disks(
self,
standalone,
dst_dir,
compress,
collect_only=False,
with_threads=True,
*args,
**kwargs
):
"""
Export all the disks of self.
Args:
standalone (bool): if true, merge the base images and the layered
image into a new file (Supported only in qcow2 format)
dst_dir (str): dir to place the exported disks
compress(bool): if true, compress each disk.
collect_only(bool): If true, return only a dict which maps between
the name of the vm to the paths of the disks that will be
exported (don't export anything).
with_threads(bool): If True, export disks in parallel
Returns:
(dict): which maps between the name of the vm to the paths of
the disks that will be exported
"""
vm_export_mgr = export.VMExportManager(
disks=self.vm.disks,
dst=dst_dir,
compress=compress,
with_threads=with_threads,
standalone=standalone,
*args,
**kwargs
)
if collect_only:
return {self.vm.name(): vm_export_mgr.collect_paths()}
else:
return {self.vm.name(): vm_export_mgr.export()} | python | def export_disks(
self,
standalone,
dst_dir,
compress,
collect_only=False,
with_threads=True,
*args,
**kwargs
):
"""
Export all the disks of self.
Args:
standalone (bool): if true, merge the base images and the layered
image into a new file (Supported only in qcow2 format)
dst_dir (str): dir to place the exported disks
compress(bool): if true, compress each disk.
collect_only(bool): If true, return only a dict which maps between
the name of the vm to the paths of the disks that will be
exported (don't export anything).
with_threads(bool): If True, export disks in parallel
Returns:
(dict): which maps between the name of the vm to the paths of
the disks that will be exported
"""
vm_export_mgr = export.VMExportManager(
disks=self.vm.disks,
dst=dst_dir,
compress=compress,
with_threads=with_threads,
standalone=standalone,
*args,
**kwargs
)
if collect_only:
return {self.vm.name(): vm_export_mgr.collect_paths()}
else:
return {self.vm.name(): vm_export_mgr.export()} | [
"def",
"export_disks",
"(",
"self",
",",
"standalone",
",",
"dst_dir",
",",
"compress",
",",
"collect_only",
"=",
"False",
",",
"with_threads",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"vm_export_mgr",
"=",
"export",
".",
"VMExpo... | Export all the disks of self.
Args:
standalone (bool): if true, merge the base images and the layered
image into a new file (Supported only in qcow2 format)
dst_dir (str): dir to place the exported disks
compress(bool): if true, compress each disk.
collect_only(bool): If true, return only a dict which maps between
the name of the vm to the paths of the disks that will be
exported (don't export anything).
with_threads(bool): If True, export disks in parallel
Returns:
(dict): which maps between the name of the vm to the paths of
the disks that will be exported | [
"Export",
"all",
"the",
"disks",
"of",
"self",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/vm.py#L448-L488 | train | 31,620 |
lago-project/lago | lago/providers/libvirt/vm.py | LocalLibvirtVMProvider.interactive_console | def interactive_console(self):
"""
Opens an interactive console
Returns:
lago.utils.CommandStatus: result of the virsh command execution
"""
if not self.running():
raise RuntimeError('VM %s is not running' % self._libvirt_.name)
virsh_command = [
"virsh",
"-c",
config.get('libvirt_url'),
"console",
self._libvirt_name(),
]
return utils.run_interactive_command(command=virsh_command, ) | python | def interactive_console(self):
"""
Opens an interactive console
Returns:
lago.utils.CommandStatus: result of the virsh command execution
"""
if not self.running():
raise RuntimeError('VM %s is not running' % self._libvirt_.name)
virsh_command = [
"virsh",
"-c",
config.get('libvirt_url'),
"console",
self._libvirt_name(),
]
return utils.run_interactive_command(command=virsh_command, ) | [
"def",
"interactive_console",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"running",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"'VM %s is not running'",
"%",
"self",
".",
"_libvirt_",
".",
"name",
")",
"virsh_command",
"=",
"[",
"\"virsh\"",
",",
"... | Opens an interactive console
Returns:
lago.utils.CommandStatus: result of the virsh command execution | [
"Opens",
"an",
"interactive",
"console"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/vm.py#L490-L506 | train | 31,621 |
lago-project/lago | lago/sdk.py | init | def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs):
"""
Initialize the Lago environment
Args:
config(str): Path to LagoInitFile
workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago"
**kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init`
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
:class:`~lago.sdk.SDK`: Initialized Lago enviornment
Raises:
:exc:`~lago.utils.LagoException`: If initialization failed
"""
setup_sdk_logging(logfile, loglevel)
defaults = lago_config.get_section('init')
if workdir is None:
workdir = os.path.abspath('.lago')
defaults['workdir'] = workdir
defaults['virt_config'] = config
defaults.update(kwargs)
workdir, prefix = cmd.do_init(**defaults)
return SDK(workdir, prefix) | python | def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs):
"""
Initialize the Lago environment
Args:
config(str): Path to LagoInitFile
workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago"
**kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init`
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
:class:`~lago.sdk.SDK`: Initialized Lago enviornment
Raises:
:exc:`~lago.utils.LagoException`: If initialization failed
"""
setup_sdk_logging(logfile, loglevel)
defaults = lago_config.get_section('init')
if workdir is None:
workdir = os.path.abspath('.lago')
defaults['workdir'] = workdir
defaults['virt_config'] = config
defaults.update(kwargs)
workdir, prefix = cmd.do_init(**defaults)
return SDK(workdir, prefix) | [
"def",
"init",
"(",
"config",
",",
"workdir",
"=",
"None",
",",
"logfile",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"INFO",
",",
"*",
"*",
"kwargs",
")",
":",
"setup_sdk_logging",
"(",
"logfile",
",",
"loglevel",
")",
"defaults",
"=",
"lago_c... | Initialize the Lago environment
Args:
config(str): Path to LagoInitFile
workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago"
**kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init`
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
:class:`~lago.sdk.SDK`: Initialized Lago enviornment
Raises:
:exc:`~lago.utils.LagoException`: If initialization failed | [
"Initialize",
"the",
"Lago",
"environment"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/sdk.py#L38-L64 | train | 31,622 |
lago-project/lago | lago/sdk.py | load_env | def load_env(workdir, logfile=None, loglevel=logging.INFO):
"""
Load an existing Lago environment
Args:
workdir(str): Path to the workdir directory, as created by
:func:`~lago.sdk.init` or created by the CLI.
logfile(str): A Path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
:class:`~lago.sdk.SDK`: Initialized Lago environment
Raises:
:exc:`~lago.utils.LagoException`: If loading the environment failed.
"""
setup_sdk_logging(logfile, loglevel)
workdir = os.path.abspath(workdir)
loaded_workdir = lago_workdir.Workdir(path=workdir)
prefix = loaded_workdir.get_prefix('current')
return SDK(loaded_workdir, prefix) | python | def load_env(workdir, logfile=None, loglevel=logging.INFO):
"""
Load an existing Lago environment
Args:
workdir(str): Path to the workdir directory, as created by
:func:`~lago.sdk.init` or created by the CLI.
logfile(str): A Path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
:class:`~lago.sdk.SDK`: Initialized Lago environment
Raises:
:exc:`~lago.utils.LagoException`: If loading the environment failed.
"""
setup_sdk_logging(logfile, loglevel)
workdir = os.path.abspath(workdir)
loaded_workdir = lago_workdir.Workdir(path=workdir)
prefix = loaded_workdir.get_prefix('current')
return SDK(loaded_workdir, prefix) | [
"def",
"load_env",
"(",
"workdir",
",",
"logfile",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"INFO",
")",
":",
"setup_sdk_logging",
"(",
"logfile",
",",
"loglevel",
")",
"workdir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"workdir",
")",
"... | Load an existing Lago environment
Args:
workdir(str): Path to the workdir directory, as created by
:func:`~lago.sdk.init` or created by the CLI.
logfile(str): A Path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
:class:`~lago.sdk.SDK`: Initialized Lago environment
Raises:
:exc:`~lago.utils.LagoException`: If loading the environment failed. | [
"Load",
"an",
"existing",
"Lago",
"environment"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/sdk.py#L67-L88 | train | 31,623 |
lago-project/lago | lago/sdk.py | SDK.ansible_inventory | def ansible_inventory(
self,
keys=['vm-type', 'groups', 'vm-provider'],
):
"""
Get an Ansible inventory as a string, ``keys`` should be list on which
to group the hosts by. You can use any key defined in LagoInitFile.
Examples of possible `keys`:
`keys=['disks/0/metadata/arch']`, would group the hosts by the
architecture.
`keys=['/disks/0/metadata/distro', 'disks/0/metadata/arch']`,
would create groups by architecture and also by distro.
`keys=['groups']` - would group hosts by the groups defined for
each VM in the LagoInitFile, i.e.:
domains:
vm-01:
...
groups: web-server
..
vm-02:
..
groups: db-server
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Returns:
str: INI-like Ansible inventory
"""
lansible = LagoAnsible(self._prefix)
return lansible.get_inventory_str(keys=keys) | python | def ansible_inventory(
self,
keys=['vm-type', 'groups', 'vm-provider'],
):
"""
Get an Ansible inventory as a string, ``keys`` should be list on which
to group the hosts by. You can use any key defined in LagoInitFile.
Examples of possible `keys`:
`keys=['disks/0/metadata/arch']`, would group the hosts by the
architecture.
`keys=['/disks/0/metadata/distro', 'disks/0/metadata/arch']`,
would create groups by architecture and also by distro.
`keys=['groups']` - would group hosts by the groups defined for
each VM in the LagoInitFile, i.e.:
domains:
vm-01:
...
groups: web-server
..
vm-02:
..
groups: db-server
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Returns:
str: INI-like Ansible inventory
"""
lansible = LagoAnsible(self._prefix)
return lansible.get_inventory_str(keys=keys) | [
"def",
"ansible_inventory",
"(",
"self",
",",
"keys",
"=",
"[",
"'vm-type'",
",",
"'groups'",
",",
"'vm-provider'",
"]",
",",
")",
":",
"lansible",
"=",
"LagoAnsible",
"(",
"self",
".",
"_prefix",
")",
"return",
"lansible",
".",
"get_inventory_str",
"(",
"... | Get an Ansible inventory as a string, ``keys`` should be list on which
to group the hosts by. You can use any key defined in LagoInitFile.
Examples of possible `keys`:
`keys=['disks/0/metadata/arch']`, would group the hosts by the
architecture.
`keys=['/disks/0/metadata/distro', 'disks/0/metadata/arch']`,
would create groups by architecture and also by distro.
`keys=['groups']` - would group hosts by the groups defined for
each VM in the LagoInitFile, i.e.:
domains:
vm-01:
...
groups: web-server
..
vm-02:
..
groups: db-server
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Returns:
str: INI-like Ansible inventory | [
"Get",
"an",
"Ansible",
"inventory",
"as",
"a",
"string",
"keys",
"should",
"be",
"list",
"on",
"which",
"to",
"group",
"the",
"hosts",
"by",
".",
"You",
"can",
"use",
"any",
"key",
"defined",
"in",
"LagoInitFile",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/sdk.py#L160-L199 | train | 31,624 |
lago-project/lago | lago/export.py | DiskExportManager.calc_sha | def calc_sha(self, checksum):
"""
Calculate the checksum of the new exported disk, write it to
a file, and update this managers 'exported_metadata'.
Args:
checksum(str): The type of the checksum
"""
with LogTask('Calculating {}'.format(checksum)):
with open(self.dst + '.hash', 'wt') as f:
sha = utils.get_hash(self.dst, checksum)
f.write(sha)
self.exported_metadata[checksum] = sha | python | def calc_sha(self, checksum):
"""
Calculate the checksum of the new exported disk, write it to
a file, and update this managers 'exported_metadata'.
Args:
checksum(str): The type of the checksum
"""
with LogTask('Calculating {}'.format(checksum)):
with open(self.dst + '.hash', 'wt') as f:
sha = utils.get_hash(self.dst, checksum)
f.write(sha)
self.exported_metadata[checksum] = sha | [
"def",
"calc_sha",
"(",
"self",
",",
"checksum",
")",
":",
"with",
"LogTask",
"(",
"'Calculating {}'",
".",
"format",
"(",
"checksum",
")",
")",
":",
"with",
"open",
"(",
"self",
".",
"dst",
"+",
"'.hash'",
",",
"'wt'",
")",
"as",
"f",
":",
"sha",
... | Calculate the checksum of the new exported disk, write it to
a file, and update this managers 'exported_metadata'.
Args:
checksum(str): The type of the checksum | [
"Calculate",
"the",
"checksum",
"of",
"the",
"new",
"exported",
"disk",
"write",
"it",
"to",
"a",
"file",
"and",
"update",
"this",
"managers",
"exported_metadata",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/export.py#L112-L124 | train | 31,625 |
lago-project/lago | lago/export.py | DiskExportManager.compress | def compress(self):
"""
Compress the new exported image,
Block size was taken from virt-builder page
"""
if not self.do_compress:
return
with LogTask('Compressing disk'):
utils.compress(self.dst, 16777216)
os.unlink(self.dst) | python | def compress(self):
"""
Compress the new exported image,
Block size was taken from virt-builder page
"""
if not self.do_compress:
return
with LogTask('Compressing disk'):
utils.compress(self.dst, 16777216)
os.unlink(self.dst) | [
"def",
"compress",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"do_compress",
":",
"return",
"with",
"LogTask",
"(",
"'Compressing disk'",
")",
":",
"utils",
".",
"compress",
"(",
"self",
".",
"dst",
",",
"16777216",
")",
"os",
".",
"unlink",
"(",... | Compress the new exported image,
Block size was taken from virt-builder page | [
"Compress",
"the",
"new",
"exported",
"image",
"Block",
"size",
"was",
"taken",
"from",
"virt",
"-",
"builder",
"page"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/export.py#L126-L135 | train | 31,626 |
lago-project/lago | lago/export.py | TemplateExportManager.rebase | def rebase(self):
"""
Change the backing-file entry of the exported disk.
Please refer to 'qemu-img rebase' manual for more info.
"""
if self.standalone:
rebase_msg = 'Merging layered image with base'
else:
rebase_msg = 'Rebase'
with LogTask(rebase_msg):
if len(self.src_qemu_info) == 1:
# Base image (doesn't have predecessors)
return
if self.standalone:
# Consolidate the layers and base image
utils.qemu_rebase(target=self.dst, backing_file="")
else:
if len(self.src_qemu_info) > 2:
raise utils.LagoUserException(
'Layered export is currently supported for one '
'layer only. You can try to use Standalone export.'
)
# Put an identifier in the metadata of the copied layer,
# this identifier will be used later by Lago in order
# to resolve and download the base image
parent = self.src_qemu_info[0]['backing-filename']
# Hack for working with lago images naming convention
# For example: /var/lib/lago/store/phx_repo:el7.3-base:v1
# Extract only the image name and the version
# (in the example el7.3-base:v1)
parent = os.path.basename(parent)
try:
parent = parent.split(':', 1)[1]
except IndexError:
pass
parent = './{}'.format(parent)
utils.qemu_rebase(
target=self.dst, backing_file=parent, safe=False
) | python | def rebase(self):
"""
Change the backing-file entry of the exported disk.
Please refer to 'qemu-img rebase' manual for more info.
"""
if self.standalone:
rebase_msg = 'Merging layered image with base'
else:
rebase_msg = 'Rebase'
with LogTask(rebase_msg):
if len(self.src_qemu_info) == 1:
# Base image (doesn't have predecessors)
return
if self.standalone:
# Consolidate the layers and base image
utils.qemu_rebase(target=self.dst, backing_file="")
else:
if len(self.src_qemu_info) > 2:
raise utils.LagoUserException(
'Layered export is currently supported for one '
'layer only. You can try to use Standalone export.'
)
# Put an identifier in the metadata of the copied layer,
# this identifier will be used later by Lago in order
# to resolve and download the base image
parent = self.src_qemu_info[0]['backing-filename']
# Hack for working with lago images naming convention
# For example: /var/lib/lago/store/phx_repo:el7.3-base:v1
# Extract only the image name and the version
# (in the example el7.3-base:v1)
parent = os.path.basename(parent)
try:
parent = parent.split(':', 1)[1]
except IndexError:
pass
parent = './{}'.format(parent)
utils.qemu_rebase(
target=self.dst, backing_file=parent, safe=False
) | [
"def",
"rebase",
"(",
"self",
")",
":",
"if",
"self",
".",
"standalone",
":",
"rebase_msg",
"=",
"'Merging layered image with base'",
"else",
":",
"rebase_msg",
"=",
"'Rebase'",
"with",
"LogTask",
"(",
"rebase_msg",
")",
":",
"if",
"len",
"(",
"self",
".",
... | Change the backing-file entry of the exported disk.
Please refer to 'qemu-img rebase' manual for more info. | [
"Change",
"the",
"backing",
"-",
"file",
"entry",
"of",
"the",
"exported",
"disk",
".",
"Please",
"refer",
"to",
"qemu",
"-",
"img",
"rebase",
"manual",
"for",
"more",
"info",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/export.py#L162-L204 | train | 31,627 |
lago-project/lago | lago/export.py | FileExportManager.export | def export(self):
"""
See DiskExportManager.export
"""
with LogTask('Exporting disk {} to {}'.format(self.name, self.dst)):
with utils.RollbackContext() as rollback:
rollback.prependDefer(
shutil.rmtree, self.dst, ignore_errors=True
)
self.copy()
if not self.disk['format'] == 'iso':
self.sparse()
self.calc_sha('sha1')
self.update_lago_metadata()
self.write_lago_metadata()
self.compress()
rollback.clear() | python | def export(self):
"""
See DiskExportManager.export
"""
with LogTask('Exporting disk {} to {}'.format(self.name, self.dst)):
with utils.RollbackContext() as rollback:
rollback.prependDefer(
shutil.rmtree, self.dst, ignore_errors=True
)
self.copy()
if not self.disk['format'] == 'iso':
self.sparse()
self.calc_sha('sha1')
self.update_lago_metadata()
self.write_lago_metadata()
self.compress()
rollback.clear() | [
"def",
"export",
"(",
"self",
")",
":",
"with",
"LogTask",
"(",
"'Exporting disk {} to {}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"dst",
")",
")",
":",
"with",
"utils",
".",
"RollbackContext",
"(",
")",
"as",
"rollback",
":",
"rol... | See DiskExportManager.export | [
"See",
"DiskExportManager",
".",
"export"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/export.py#L246-L262 | train | 31,628 |
lago-project/lago | lago/build.py | Build.normalize_build_spec | def normalize_build_spec(self, build_spec):
"""
Convert a build spec into a list of Command tuples.
After running this command, self.build_cmds should hold all
the commands that should be run on the disk in self.disk_path.
Args:
build_spec (dict): The buildspec part from the init file
"""
for cmd in build_spec:
if not cmd:
continue
cmd_name = cmd.keys()[0]
cmd_options = cmd.values()[0]
cmd_handler = self.get_cmd_handler(cmd_name)
self.build_cmds.append(cmd_handler(cmd_options)) | python | def normalize_build_spec(self, build_spec):
"""
Convert a build spec into a list of Command tuples.
After running this command, self.build_cmds should hold all
the commands that should be run on the disk in self.disk_path.
Args:
build_spec (dict): The buildspec part from the init file
"""
for cmd in build_spec:
if not cmd:
continue
cmd_name = cmd.keys()[0]
cmd_options = cmd.values()[0]
cmd_handler = self.get_cmd_handler(cmd_name)
self.build_cmds.append(cmd_handler(cmd_options)) | [
"def",
"normalize_build_spec",
"(",
"self",
",",
"build_spec",
")",
":",
"for",
"cmd",
"in",
"build_spec",
":",
"if",
"not",
"cmd",
":",
"continue",
"cmd_name",
"=",
"cmd",
".",
"keys",
"(",
")",
"[",
"0",
"]",
"cmd_options",
"=",
"cmd",
".",
"values",... | Convert a build spec into a list of Command tuples.
After running this command, self.build_cmds should hold all
the commands that should be run on the disk in self.disk_path.
Args:
build_spec (dict): The buildspec part from the init file | [
"Convert",
"a",
"build",
"spec",
"into",
"a",
"list",
"of",
"Command",
"tuples",
".",
"After",
"running",
"this",
"command",
"self",
".",
"build_cmds",
"should",
"hold",
"all",
"the",
"commands",
"that",
"should",
"be",
"run",
"on",
"the",
"disk",
"in",
... | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/build.py#L120-L135 | train | 31,629 |
lago-project/lago | lago/build.py | Build.get_cmd_handler | def get_cmd_handler(self, cmd):
"""
Return an handler for cmd.
The handler and the command should have the same name.
See class description for more info about handlers.
Args:
cmd (str): The name of the command
Returns:
callable: which handles cmd
Raises:
lago.build.BuildException: If an handler for cmd doesn't exist
"""
cmd = cmd.replace('-', '_')
handler = getattr(self, cmd, None)
if not handler:
raise BuildException(
'Command {} is not supported as a '
'build command'.format(cmd)
)
return handler | python | def get_cmd_handler(self, cmd):
"""
Return an handler for cmd.
The handler and the command should have the same name.
See class description for more info about handlers.
Args:
cmd (str): The name of the command
Returns:
callable: which handles cmd
Raises:
lago.build.BuildException: If an handler for cmd doesn't exist
"""
cmd = cmd.replace('-', '_')
handler = getattr(self, cmd, None)
if not handler:
raise BuildException(
'Command {} is not supported as a '
'build command'.format(cmd)
)
return handler | [
"def",
"get_cmd_handler",
"(",
"self",
",",
"cmd",
")",
":",
"cmd",
"=",
"cmd",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"handler",
"=",
"getattr",
"(",
"self",
",",
"cmd",
",",
"None",
")",
"if",
"not",
"handler",
":",
"raise",
"BuildException",... | Return an handler for cmd.
The handler and the command should have the same name.
See class description for more info about handlers.
Args:
cmd (str): The name of the command
Returns:
callable: which handles cmd
Raises:
lago.build.BuildException: If an handler for cmd doesn't exist | [
"Return",
"an",
"handler",
"for",
"cmd",
".",
"The",
"handler",
"and",
"the",
"command",
"should",
"have",
"the",
"same",
"name",
".",
"See",
"class",
"description",
"for",
"more",
"info",
"about",
"handlers",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/build.py#L137-L159 | train | 31,630 |
lago-project/lago | lago/build.py | Build.build | def build(self):
"""
Run all the commands in self.build_cmds
Raises:
lago.build.BuildException: If a command returned a non-zero code
"""
if not self.build_cmds:
LOGGER.debug('No build commands were found, skipping build step')
with LogTask('Building {} disk {}'.format(self.name, self.disk_path)):
for command in self.build_cmds:
with LogTask('Running command {}'.format(command.name)):
LOGGER.debug(command.cmd)
result = utils.run_command(command.cmd)
if result:
raise BuildException(result.err) | python | def build(self):
"""
Run all the commands in self.build_cmds
Raises:
lago.build.BuildException: If a command returned a non-zero code
"""
if not self.build_cmds:
LOGGER.debug('No build commands were found, skipping build step')
with LogTask('Building {} disk {}'.format(self.name, self.disk_path)):
for command in self.build_cmds:
with LogTask('Running command {}'.format(command.name)):
LOGGER.debug(command.cmd)
result = utils.run_command(command.cmd)
if result:
raise BuildException(result.err) | [
"def",
"build",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"build_cmds",
":",
"LOGGER",
".",
"debug",
"(",
"'No build commands were found, skipping build step'",
")",
"with",
"LogTask",
"(",
"'Building {} disk {}'",
".",
"format",
"(",
"self",
".",
"name",... | Run all the commands in self.build_cmds
Raises:
lago.build.BuildException: If a command returned a non-zero code | [
"Run",
"all",
"the",
"commands",
"in",
"self",
".",
"build_cmds"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/build.py#L186-L202 | train | 31,631 |
lago-project/lago | lago/templates.py | FileSystemTemplateProvider.download_image | def download_image(self, handle, dest):
"""
Copies over the handl to the destination
Args:
handle (str): path to copy over
dest (str): path to copy to
Returns:
None
"""
shutil.copyfile(self._prefixed(handle), dest) | python | def download_image(self, handle, dest):
"""
Copies over the handl to the destination
Args:
handle (str): path to copy over
dest (str): path to copy to
Returns:
None
"""
shutil.copyfile(self._prefixed(handle), dest) | [
"def",
"download_image",
"(",
"self",
",",
"handle",
",",
"dest",
")",
":",
"shutil",
".",
"copyfile",
"(",
"self",
".",
"_prefixed",
"(",
"handle",
")",
",",
"dest",
")"
] | Copies over the handl to the destination
Args:
handle (str): path to copy over
dest (str): path to copy to
Returns:
None | [
"Copies",
"over",
"the",
"handl",
"to",
"the",
"destination"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/templates.py#L66-L77 | train | 31,632 |
lago-project/lago | lago/templates.py | HttpTemplateProvider.download_image | def download_image(self, handle, dest):
"""
Downloads the image from the http server
Args:
handle (str): url from the `self.baseurl` to the remote template
dest (str): Path to store the downloaded url to, must be a file
path
Returns:
None
"""
with log_utils.LogTask('Download image %s' % handle, logger=LOGGER):
self.open_url(url=handle, dest=dest)
self.extract_image_xz(dest) | python | def download_image(self, handle, dest):
"""
Downloads the image from the http server
Args:
handle (str): url from the `self.baseurl` to the remote template
dest (str): Path to store the downloaded url to, must be a file
path
Returns:
None
"""
with log_utils.LogTask('Download image %s' % handle, logger=LOGGER):
self.open_url(url=handle, dest=dest)
self.extract_image_xz(dest) | [
"def",
"download_image",
"(",
"self",
",",
"handle",
",",
"dest",
")",
":",
"with",
"log_utils",
".",
"LogTask",
"(",
"'Download image %s'",
"%",
"handle",
",",
"logger",
"=",
"LOGGER",
")",
":",
"self",
".",
"open_url",
"(",
"url",
"=",
"handle",
",",
... | Downloads the image from the http server
Args:
handle (str): url from the `self.baseurl` to the remote template
dest (str): Path to store the downloaded url to, must be a file
path
Returns:
None | [
"Downloads",
"the",
"image",
"from",
"the",
"http",
"server"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/templates.py#L182-L197 | train | 31,633 |
lago-project/lago | lago/templates.py | TemplateRepository.get_by_name | def get_by_name(self, name):
"""
Retrieve a template by it's name
Args:
name (str): Name of the template to retrieve
Raises:
LagoMissingTemplateError: if no template is found
"""
try:
spec = self._dom.get('templates', {})[name]
except KeyError:
raise LagoMissingTemplateError(name, self._path)
return Template(
name=name,
versions={
ver_name: TemplateVersion(
name='%s:%s:%s' % (self.name, name, ver_name),
source=self._providers[ver_spec['source']],
handle=ver_spec['handle'],
timestamp=ver_spec['timestamp'],
)
for ver_name, ver_spec in spec['versions'].items()
},
) | python | def get_by_name(self, name):
"""
Retrieve a template by it's name
Args:
name (str): Name of the template to retrieve
Raises:
LagoMissingTemplateError: if no template is found
"""
try:
spec = self._dom.get('templates', {})[name]
except KeyError:
raise LagoMissingTemplateError(name, self._path)
return Template(
name=name,
versions={
ver_name: TemplateVersion(
name='%s:%s:%s' % (self.name, name, ver_name),
source=self._providers[ver_spec['source']],
handle=ver_spec['handle'],
timestamp=ver_spec['timestamp'],
)
for ver_name, ver_spec in spec['versions'].items()
},
) | [
"def",
"get_by_name",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"spec",
"=",
"self",
".",
"_dom",
".",
"get",
"(",
"'templates'",
",",
"{",
"}",
")",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"LagoMissingTemplateError",
"(",
"name",
... | Retrieve a template by it's name
Args:
name (str): Name of the template to retrieve
Raises:
LagoMissingTemplateError: if no template is found | [
"Retrieve",
"a",
"template",
"by",
"it",
"s",
"name"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/templates.py#L388-L414 | train | 31,634 |
lago-project/lago | lago/templates.py | TemplateVersion.get_hash | def get_hash(self):
"""
Returns the associated hash for this template version
Returns:
str: Hash for this version
"""
if self._hash is None:
self._hash = self._source.get_hash(self._handle).strip()
return self._hash | python | def get_hash(self):
"""
Returns the associated hash for this template version
Returns:
str: Hash for this version
"""
if self._hash is None:
self._hash = self._source.get_hash(self._handle).strip()
return self._hash | [
"def",
"get_hash",
"(",
"self",
")",
":",
"if",
"self",
".",
"_hash",
"is",
"None",
":",
"self",
".",
"_hash",
"=",
"self",
".",
"_source",
".",
"get_hash",
"(",
"self",
".",
"_handle",
")",
".",
"strip",
"(",
")",
"return",
"self",
".",
"_hash"
] | Returns the associated hash for this template version
Returns:
str: Hash for this version | [
"Returns",
"the",
"associated",
"hash",
"for",
"this",
"template",
"version"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/templates.py#L494-L503 | train | 31,635 |
lago-project/lago | lago/templates.py | TemplateVersion.get_metadata | def get_metadata(self):
"""
Returns the associated metadata info for this template version
Returns:
dict: Metadata for this version
"""
if self._metadata is None:
self._metadata = self._source.get_metadata(self._handle)
return self._metadata | python | def get_metadata(self):
"""
Returns the associated metadata info for this template version
Returns:
dict: Metadata for this version
"""
if self._metadata is None:
self._metadata = self._source.get_metadata(self._handle)
return self._metadata | [
"def",
"get_metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_metadata",
"is",
"None",
":",
"self",
".",
"_metadata",
"=",
"self",
".",
"_source",
".",
"get_metadata",
"(",
"self",
".",
"_handle",
")",
"return",
"self",
".",
"_metadata"
] | Returns the associated metadata info for this template version
Returns:
dict: Metadata for this version | [
"Returns",
"the",
"associated",
"metadata",
"info",
"for",
"this",
"template",
"version"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/templates.py#L505-L515 | train | 31,636 |
lago-project/lago | lago/templates.py | TemplateStore.get_path | def get_path(self, temp_ver):
"""
Get the path of the given version in this store
Args:
temp_ver TemplateVersion: version to look for
Returns:
str: The path to the template version inside the store
Raises:
RuntimeError: if the template is not in the store
"""
if temp_ver not in self:
raise RuntimeError(
'Template: {} not present'.format(temp_ver.name)
)
return self._prefixed(temp_ver.name) | python | def get_path(self, temp_ver):
"""
Get the path of the given version in this store
Args:
temp_ver TemplateVersion: version to look for
Returns:
str: The path to the template version inside the store
Raises:
RuntimeError: if the template is not in the store
"""
if temp_ver not in self:
raise RuntimeError(
'Template: {} not present'.format(temp_ver.name)
)
return self._prefixed(temp_ver.name) | [
"def",
"get_path",
"(",
"self",
",",
"temp_ver",
")",
":",
"if",
"temp_ver",
"not",
"in",
"self",
":",
"raise",
"RuntimeError",
"(",
"'Template: {} not present'",
".",
"format",
"(",
"temp_ver",
".",
"name",
")",
")",
"return",
"self",
".",
"_prefixed",
"(... | Get the path of the given version in this store
Args:
temp_ver TemplateVersion: version to look for
Returns:
str: The path to the template version inside the store
Raises:
RuntimeError: if the template is not in the store | [
"Get",
"the",
"path",
"of",
"the",
"given",
"version",
"in",
"this",
"store"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/templates.py#L605-L622 | train | 31,637 |
lago-project/lago | lago/templates.py | TemplateStore.download | def download(self, temp_ver, store_metadata=True):
"""
Retrieve the given template version
Args:
temp_ver (TemplateVersion): template version to retrieve
store_metadata (bool): If set to ``False``, will not refresh the
local metadata with the retrieved one
Returns:
None
"""
dest = self._prefixed(temp_ver.name)
temp_dest = '%s.tmp' % dest
with utils.LockFile(dest + '.lock'):
# Image was downloaded while we were waiting
if os.path.exists(dest):
return
temp_ver.download(temp_dest)
if store_metadata:
with open('%s.metadata' % dest, 'w') as f:
utils.json_dump(temp_ver.get_metadata(), f)
sha1 = utils.get_hash(temp_dest)
if temp_ver.get_hash() != sha1:
raise RuntimeError(
'Image %s does not match the expected hash %s' % (
temp_ver.name,
sha1,
)
)
with open('%s.hash' % dest, 'w') as f:
f.write(sha1)
with log_utils.LogTask('Convert image', logger=LOGGER):
result = utils.run_command(
[
'qemu-img',
'convert',
'-O',
'raw',
temp_dest,
dest,
],
)
os.unlink(temp_dest)
if result:
raise RuntimeError(result.err) | python | def download(self, temp_ver, store_metadata=True):
"""
Retrieve the given template version
Args:
temp_ver (TemplateVersion): template version to retrieve
store_metadata (bool): If set to ``False``, will not refresh the
local metadata with the retrieved one
Returns:
None
"""
dest = self._prefixed(temp_ver.name)
temp_dest = '%s.tmp' % dest
with utils.LockFile(dest + '.lock'):
# Image was downloaded while we were waiting
if os.path.exists(dest):
return
temp_ver.download(temp_dest)
if store_metadata:
with open('%s.metadata' % dest, 'w') as f:
utils.json_dump(temp_ver.get_metadata(), f)
sha1 = utils.get_hash(temp_dest)
if temp_ver.get_hash() != sha1:
raise RuntimeError(
'Image %s does not match the expected hash %s' % (
temp_ver.name,
sha1,
)
)
with open('%s.hash' % dest, 'w') as f:
f.write(sha1)
with log_utils.LogTask('Convert image', logger=LOGGER):
result = utils.run_command(
[
'qemu-img',
'convert',
'-O',
'raw',
temp_dest,
dest,
],
)
os.unlink(temp_dest)
if result:
raise RuntimeError(result.err) | [
"def",
"download",
"(",
"self",
",",
"temp_ver",
",",
"store_metadata",
"=",
"True",
")",
":",
"dest",
"=",
"self",
".",
"_prefixed",
"(",
"temp_ver",
".",
"name",
")",
"temp_dest",
"=",
"'%s.tmp'",
"%",
"dest",
"with",
"utils",
".",
"LockFile",
"(",
"... | Retrieve the given template version
Args:
temp_ver (TemplateVersion): template version to retrieve
store_metadata (bool): If set to ``False``, will not refresh the
local metadata with the retrieved one
Returns:
None | [
"Retrieve",
"the",
"given",
"template",
"version"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/templates.py#L624-L675 | train | 31,638 |
lago-project/lago | lago/templates.py | TemplateStore.get_stored_metadata | def get_stored_metadata(self, temp_ver):
"""
Retrieves the metadata for the given template version from the store
Args:
temp_ver (TemplateVersion): template version to retrieve the
metadata for
Returns:
dict: the metadata of the given template version
"""
with open(self._prefixed('%s.metadata' % temp_ver.name)) as f:
return json.load(f) | python | def get_stored_metadata(self, temp_ver):
"""
Retrieves the metadata for the given template version from the store
Args:
temp_ver (TemplateVersion): template version to retrieve the
metadata for
Returns:
dict: the metadata of the given template version
"""
with open(self._prefixed('%s.metadata' % temp_ver.name)) as f:
return json.load(f) | [
"def",
"get_stored_metadata",
"(",
"self",
",",
"temp_ver",
")",
":",
"with",
"open",
"(",
"self",
".",
"_prefixed",
"(",
"'%s.metadata'",
"%",
"temp_ver",
".",
"name",
")",
")",
"as",
"f",
":",
"return",
"json",
".",
"load",
"(",
"f",
")"
] | Retrieves the metadata for the given template version from the store
Args:
temp_ver (TemplateVersion): template version to retrieve the
metadata for
Returns:
dict: the metadata of the given template version | [
"Retrieves",
"the",
"metadata",
"for",
"the",
"given",
"template",
"version",
"from",
"the",
"store"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/templates.py#L677-L689 | train | 31,639 |
lago-project/lago | lago/templates.py | TemplateStore.get_stored_hash | def get_stored_hash(self, temp_ver):
"""
Retrieves the hash for the given template version from the store
Args:
temp_ver (TemplateVersion): template version to retrieve the hash
for
Returns:
str: hash of the given template version
"""
with open(self._prefixed('%s.hash' % temp_ver.name)) as f:
return f.read().strip() | python | def get_stored_hash(self, temp_ver):
"""
Retrieves the hash for the given template version from the store
Args:
temp_ver (TemplateVersion): template version to retrieve the hash
for
Returns:
str: hash of the given template version
"""
with open(self._prefixed('%s.hash' % temp_ver.name)) as f:
return f.read().strip() | [
"def",
"get_stored_hash",
"(",
"self",
",",
"temp_ver",
")",
":",
"with",
"open",
"(",
"self",
".",
"_prefixed",
"(",
"'%s.hash'",
"%",
"temp_ver",
".",
"name",
")",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")"
... | Retrieves the hash for the given template version from the store
Args:
temp_ver (TemplateVersion): template version to retrieve the hash
for
Returns:
str: hash of the given template version | [
"Retrieves",
"the",
"hash",
"for",
"the",
"given",
"template",
"version",
"from",
"the",
"store"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/templates.py#L691-L703 | train | 31,640 |
lago-project/lago | lago/lago_ansible.py | LagoAnsible.get_inventory | def get_inventory(self, keys=None):
"""
Create an Ansible inventory based on python dicts and lists.
The returned value is a dict in which every key represents a group
and every value is a list of entries for that group.
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Returns:
dict: dict based Ansible inventory
"""
inventory = defaultdict(list)
keys = keys or ['vm-type', 'groups', 'vm-provider']
vms = self.prefix.get_vms().values()
for vm in vms:
entry = self._generate_entry(vm)
vm_spec = vm.spec
for key in keys:
value = self.get_key(key, vm_spec)
if value is None:
continue
if isinstance(value, list):
for sub_value in value:
inventory['{}={}'.format(key, sub_value)].append(entry)
else:
inventory['{}={}'.format(key, value)].append(entry)
# Adding a special case for the group key.
# Most of the times the user wants that the host
# will be a part of the group "group", and not a part of
# "group=something"
for group in vm_spec.get('groups', []):
inventory[group].append(entry)
return inventory | python | def get_inventory(self, keys=None):
"""
Create an Ansible inventory based on python dicts and lists.
The returned value is a dict in which every key represents a group
and every value is a list of entries for that group.
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Returns:
dict: dict based Ansible inventory
"""
inventory = defaultdict(list)
keys = keys or ['vm-type', 'groups', 'vm-provider']
vms = self.prefix.get_vms().values()
for vm in vms:
entry = self._generate_entry(vm)
vm_spec = vm.spec
for key in keys:
value = self.get_key(key, vm_spec)
if value is None:
continue
if isinstance(value, list):
for sub_value in value:
inventory['{}={}'.format(key, sub_value)].append(entry)
else:
inventory['{}={}'.format(key, value)].append(entry)
# Adding a special case for the group key.
# Most of the times the user wants that the host
# will be a part of the group "group", and not a part of
# "group=something"
for group in vm_spec.get('groups', []):
inventory[group].append(entry)
return inventory | [
"def",
"get_inventory",
"(",
"self",
",",
"keys",
"=",
"None",
")",
":",
"inventory",
"=",
"defaultdict",
"(",
"list",
")",
"keys",
"=",
"keys",
"or",
"[",
"'vm-type'",
",",
"'groups'",
",",
"'vm-provider'",
"]",
"vms",
"=",
"self",
".",
"prefix",
".",... | Create an Ansible inventory based on python dicts and lists.
The returned value is a dict in which every key represents a group
and every value is a list of entries for that group.
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Returns:
dict: dict based Ansible inventory | [
"Create",
"an",
"Ansible",
"inventory",
"based",
"on",
"python",
"dicts",
"and",
"lists",
".",
"The",
"returned",
"value",
"is",
"a",
"dict",
"in",
"which",
"every",
"key",
"represents",
"a",
"group",
"and",
"every",
"value",
"is",
"a",
"list",
"of",
"en... | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/lago_ansible.py#L49-L86 | train | 31,641 |
lago-project/lago | lago/lago_ansible.py | LagoAnsible.get_key | def get_key(key, data_structure):
"""
Helper method for extracting values from a nested data structure.
Args:
key (str): The path to the vales (a series of keys and indexes
separated by '/')
data_structure (dict or list): The data structure from which the
value will be extracted.
Returns:
str: The values associated with key
"""
if key == '/':
return data_structure
path = key.split('/')
# If the path start with '/', remove the empty string from the list
path[0] or path.pop(0)
current_value = data_structure
while path:
current_key = path.pop(0)
try:
current_key = int(current_key)
except ValueError:
pass
try:
current_value = current_value[current_key]
except (KeyError, IndexError):
LOGGER.debug('failed to extract path {}'.format(key))
return None
return current_value | python | def get_key(key, data_structure):
"""
Helper method for extracting values from a nested data structure.
Args:
key (str): The path to the vales (a series of keys and indexes
separated by '/')
data_structure (dict or list): The data structure from which the
value will be extracted.
Returns:
str: The values associated with key
"""
if key == '/':
return data_structure
path = key.split('/')
# If the path start with '/', remove the empty string from the list
path[0] or path.pop(0)
current_value = data_structure
while path:
current_key = path.pop(0)
try:
current_key = int(current_key)
except ValueError:
pass
try:
current_value = current_value[current_key]
except (KeyError, IndexError):
LOGGER.debug('failed to extract path {}'.format(key))
return None
return current_value | [
"def",
"get_key",
"(",
"key",
",",
"data_structure",
")",
":",
"if",
"key",
"==",
"'/'",
":",
"return",
"data_structure",
"path",
"=",
"key",
".",
"split",
"(",
"'/'",
")",
"# If the path start with '/', remove the empty string from the list",
"path",
"[",
"0",
... | Helper method for extracting values from a nested data structure.
Args:
key (str): The path to the vales (a series of keys and indexes
separated by '/')
data_structure (dict or list): The data structure from which the
value will be extracted.
Returns:
str: The values associated with key | [
"Helper",
"method",
"for",
"extracting",
"values",
"from",
"a",
"nested",
"data",
"structure",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/lago_ansible.py#L108-L141 | train | 31,642 |
lago-project/lago | lago/lago_ansible.py | LagoAnsible.get_inventory_temp_file | def get_inventory_temp_file(self, keys=None):
"""
Context manager which returns the inventory written on a tempfile.
The tempfile will be deleted as soon as this context manger ends.
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Yields:
tempfile.NamedTemporaryFile: Temp file containing the inventory
"""
temp_file = tempfile.NamedTemporaryFile(mode='r+t')
inventory = self.get_inventory_str(keys)
LOGGER.debug(
'Writing inventory to temp file {} \n{}'.format(
temp_file.name, inventory
)
)
temp_file.write(inventory)
temp_file.flush()
temp_file.seek(0)
yield temp_file
temp_file.close() | python | def get_inventory_temp_file(self, keys=None):
"""
Context manager which returns the inventory written on a tempfile.
The tempfile will be deleted as soon as this context manger ends.
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Yields:
tempfile.NamedTemporaryFile: Temp file containing the inventory
"""
temp_file = tempfile.NamedTemporaryFile(mode='r+t')
inventory = self.get_inventory_str(keys)
LOGGER.debug(
'Writing inventory to temp file {} \n{}'.format(
temp_file.name, inventory
)
)
temp_file.write(inventory)
temp_file.flush()
temp_file.seek(0)
yield temp_file
temp_file.close() | [
"def",
"get_inventory_temp_file",
"(",
"self",
",",
"keys",
"=",
"None",
")",
":",
"temp_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'r+t'",
")",
"inventory",
"=",
"self",
".",
"get_inventory_str",
"(",
"keys",
")",
"LOGGER",
".",
... | Context manager which returns the inventory written on a tempfile.
The tempfile will be deleted as soon as this context manger ends.
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Yields:
tempfile.NamedTemporaryFile: Temp file containing the inventory | [
"Context",
"manager",
"which",
"returns",
"the",
"inventory",
"written",
"on",
"a",
"tempfile",
".",
"The",
"tempfile",
"will",
"be",
"deleted",
"as",
"soon",
"as",
"this",
"context",
"manger",
"ends",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/lago_ansible.py#L144-L167 | train | 31,643 |
lago-project/lago | lago/cmd.py | exit_handler | def exit_handler(signum, frame):
"""
Catch SIGTERM and SIGHUP and call "sys.exit" which raises
"SystemExit" exception.
This will trigger all the cleanup code defined in ContextManagers
and "finally" statements.
For more details about the arguments see "signal" documentation.
Args:
signum(int): The signal's number
frame(frame): The current stack frame, can be None
"""
LOGGER.debug('signal {} was caught'.format(signum))
sys.exit(128 + signum) | python | def exit_handler(signum, frame):
"""
Catch SIGTERM and SIGHUP and call "sys.exit" which raises
"SystemExit" exception.
This will trigger all the cleanup code defined in ContextManagers
and "finally" statements.
For more details about the arguments see "signal" documentation.
Args:
signum(int): The signal's number
frame(frame): The current stack frame, can be None
"""
LOGGER.debug('signal {} was caught'.format(signum))
sys.exit(128 + signum) | [
"def",
"exit_handler",
"(",
"signum",
",",
"frame",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'signal {} was caught'",
".",
"format",
"(",
"signum",
")",
")",
"sys",
".",
"exit",
"(",
"128",
"+",
"signum",
")"
] | Catch SIGTERM and SIGHUP and call "sys.exit" which raises
"SystemExit" exception.
This will trigger all the cleanup code defined in ContextManagers
and "finally" statements.
For more details about the arguments see "signal" documentation.
Args:
signum(int): The signal's number
frame(frame): The current stack frame, can be None | [
"Catch",
"SIGTERM",
"and",
"SIGHUP",
"and",
"call",
"sys",
".",
"exit",
"which",
"raises",
"SystemExit",
"exception",
".",
"This",
"will",
"trigger",
"all",
"the",
"cleanup",
"code",
"defined",
"in",
"ContextManagers",
"and",
"finally",
"statements",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/cmd.py#L907-L922 | train | 31,644 |
lago-project/lago | lago/providers/libvirt/network.py | Network.start | def start(self, attempts=5, timeout=2):
"""
Start the network, will check if the network is active ``attempts``
times, waiting ``timeout`` between each attempt.
Args:
attempts (int): number of attempts to check the network is active
timeout (int): timeout for each attempt
Returns:
None
Raises:
RuntimeError: if network creation failed, or failed to verify it is
active.
"""
if not self.alive():
with LogTask('Create network %s' % self.name()):
net = self.libvirt_con.networkCreateXML(self._libvirt_xml())
if net is None:
raise RuntimeError(
'failed to create network, XML: %s' %
(self._libvirt_xml())
)
for _ in range(attempts):
if net.isActive():
return
LOGGER.debug(
'waiting for network %s to become active', net.name()
)
time.sleep(timeout)
raise RuntimeError(
'failed to verify network %s is active' % net.name()
) | python | def start(self, attempts=5, timeout=2):
"""
Start the network, will check if the network is active ``attempts``
times, waiting ``timeout`` between each attempt.
Args:
attempts (int): number of attempts to check the network is active
timeout (int): timeout for each attempt
Returns:
None
Raises:
RuntimeError: if network creation failed, or failed to verify it is
active.
"""
if not self.alive():
with LogTask('Create network %s' % self.name()):
net = self.libvirt_con.networkCreateXML(self._libvirt_xml())
if net is None:
raise RuntimeError(
'failed to create network, XML: %s' %
(self._libvirt_xml())
)
for _ in range(attempts):
if net.isActive():
return
LOGGER.debug(
'waiting for network %s to become active', net.name()
)
time.sleep(timeout)
raise RuntimeError(
'failed to verify network %s is active' % net.name()
) | [
"def",
"start",
"(",
"self",
",",
"attempts",
"=",
"5",
",",
"timeout",
"=",
"2",
")",
":",
"if",
"not",
"self",
".",
"alive",
"(",
")",
":",
"with",
"LogTask",
"(",
"'Create network %s'",
"%",
"self",
".",
"name",
"(",
")",
")",
":",
"net",
"=",... | Start the network, will check if the network is active ``attempts``
times, waiting ``timeout`` between each attempt.
Args:
attempts (int): number of attempts to check the network is active
timeout (int): timeout for each attempt
Returns:
None
Raises:
RuntimeError: if network creation failed, or failed to verify it is
active. | [
"Start",
"the",
"network",
"will",
"check",
"if",
"the",
"network",
"is",
"active",
"attempts",
"times",
"waiting",
"timeout",
"between",
"each",
"attempt",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/network.py#L96-L130 | train | 31,645 |
lago-project/lago | lago/providers/libvirt/cpu.py | CPU.generate_cpu_xml | def generate_cpu_xml(self):
"""
Get CPU XML
Returns:
lxml.etree.Element: cpu node
"""
if self.cpu_custom:
return self.generate_custom(
cpu=self.cpu,
vcpu_num=self.vcpu_num,
fill_topology=self.vcpu_set
)
elif self.cpu_model:
return self.generate_exact(
self.cpu_model, vcpu_num=self.vcpu_num, host_cpu=self.host_cpu
)
else:
return self.generate_host_passthrough(self.vcpu_num) | python | def generate_cpu_xml(self):
"""
Get CPU XML
Returns:
lxml.etree.Element: cpu node
"""
if self.cpu_custom:
return self.generate_custom(
cpu=self.cpu,
vcpu_num=self.vcpu_num,
fill_topology=self.vcpu_set
)
elif self.cpu_model:
return self.generate_exact(
self.cpu_model, vcpu_num=self.vcpu_num, host_cpu=self.host_cpu
)
else:
return self.generate_host_passthrough(self.vcpu_num) | [
"def",
"generate_cpu_xml",
"(",
"self",
")",
":",
"if",
"self",
".",
"cpu_custom",
":",
"return",
"self",
".",
"generate_custom",
"(",
"cpu",
"=",
"self",
".",
"cpu",
",",
"vcpu_num",
"=",
"self",
".",
"vcpu_num",
",",
"fill_topology",
"=",
"self",
".",
... | Get CPU XML
Returns:
lxml.etree.Element: cpu node | [
"Get",
"CPU",
"XML"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/cpu.py#L100-L118 | train | 31,646 |
lago-project/lago | lago/providers/libvirt/cpu.py | CPU.generate_host_passthrough | def generate_host_passthrough(self, vcpu_num):
"""
Generate host-passthrough XML cpu node
Args:
vcpu_num(str): number of virtual CPUs
Returns:
lxml.etree.Element: CPU XML node
"""
cpu = ET.Element('cpu', mode='host-passthrough')
cpu.append(self.generate_topology(vcpu_num))
if vcpu_num > 1:
cpu.append(self.generate_numa(vcpu_num))
return cpu | python | def generate_host_passthrough(self, vcpu_num):
"""
Generate host-passthrough XML cpu node
Args:
vcpu_num(str): number of virtual CPUs
Returns:
lxml.etree.Element: CPU XML node
"""
cpu = ET.Element('cpu', mode='host-passthrough')
cpu.append(self.generate_topology(vcpu_num))
if vcpu_num > 1:
cpu.append(self.generate_numa(vcpu_num))
return cpu | [
"def",
"generate_host_passthrough",
"(",
"self",
",",
"vcpu_num",
")",
":",
"cpu",
"=",
"ET",
".",
"Element",
"(",
"'cpu'",
",",
"mode",
"=",
"'host-passthrough'",
")",
"cpu",
".",
"append",
"(",
"self",
".",
"generate_topology",
"(",
"vcpu_num",
")",
")",... | Generate host-passthrough XML cpu node
Args:
vcpu_num(str): number of virtual CPUs
Returns:
lxml.etree.Element: CPU XML node | [
"Generate",
"host",
"-",
"passthrough",
"XML",
"cpu",
"node"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/cpu.py#L133-L148 | train | 31,647 |
lago-project/lago | lago/providers/libvirt/cpu.py | CPU.generate_custom | def generate_custom(self, cpu, vcpu_num, fill_topology):
"""
Generate custom CPU model. This method attempts to convert the dict to
XML, as defined by ``xmltodict.unparse`` method.
Args:
cpu(dict): CPU spec
vcpu_num(int): number of virtual cpus
fill_topology(bool): if topology is not defined in ``cpu`` and
``vcpu`` was not set, will add CPU topology to the generated
CPU.
Returns:
lxml.etree.Element: CPU XML node
Raises:
:exc:`~LagoInitException`: when failed to convert dict to XML
"""
try:
cpu = utils.dict_to_xml({'cpu': cpu})
except:
# TO-DO: print an example here
raise LagoInitException('conversion of \'cpu\' to XML failed')
if not cpu.xpath('topology') and fill_topology:
cpu.append(self.generate_topology(vcpu_num))
return cpu | python | def generate_custom(self, cpu, vcpu_num, fill_topology):
"""
Generate custom CPU model. This method attempts to convert the dict to
XML, as defined by ``xmltodict.unparse`` method.
Args:
cpu(dict): CPU spec
vcpu_num(int): number of virtual cpus
fill_topology(bool): if topology is not defined in ``cpu`` and
``vcpu`` was not set, will add CPU topology to the generated
CPU.
Returns:
lxml.etree.Element: CPU XML node
Raises:
:exc:`~LagoInitException`: when failed to convert dict to XML
"""
try:
cpu = utils.dict_to_xml({'cpu': cpu})
except:
# TO-DO: print an example here
raise LagoInitException('conversion of \'cpu\' to XML failed')
if not cpu.xpath('topology') and fill_topology:
cpu.append(self.generate_topology(vcpu_num))
return cpu | [
"def",
"generate_custom",
"(",
"self",
",",
"cpu",
",",
"vcpu_num",
",",
"fill_topology",
")",
":",
"try",
":",
"cpu",
"=",
"utils",
".",
"dict_to_xml",
"(",
"{",
"'cpu'",
":",
"cpu",
"}",
")",
"except",
":",
"# TO-DO: print an example here",
"raise",
"Lag... | Generate custom CPU model. This method attempts to convert the dict to
XML, as defined by ``xmltodict.unparse`` method.
Args:
cpu(dict): CPU spec
vcpu_num(int): number of virtual cpus
fill_topology(bool): if topology is not defined in ``cpu`` and
``vcpu`` was not set, will add CPU topology to the generated
CPU.
Returns:
lxml.etree.Element: CPU XML node
Raises:
:exc:`~LagoInitException`: when failed to convert dict to XML | [
"Generate",
"custom",
"CPU",
"model",
".",
"This",
"method",
"attempts",
"to",
"convert",
"the",
"dict",
"to",
"XML",
"as",
"defined",
"by",
"xmltodict",
".",
"unparse",
"method",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/cpu.py#L150-L177 | train | 31,648 |
lago-project/lago | lago/providers/libvirt/cpu.py | CPU.generate_exact | def generate_exact(self, model, vcpu_num, host_cpu):
"""
Generate exact CPU model with nested virtualization CPU feature.
Args:
model(str): libvirt supported CPU model
vcpu_num(int): number of virtual cpus
host_cpu(lxml.etree.Element): the host CPU model
Returns:
lxml.etree.Element: CPU XML node
"""
nested = {'Intel': 'vmx', 'AMD': 'svm'}
cpu = ET.Element('cpu', match='exact')
ET.SubElement(cpu, 'model').text = model
cpu.append(self.generate_topology(vcpu_num))
vendor = host_cpu.findtext('vendor')
if not nested.get(vendor):
LOGGER.debug(
'Unknown vendor: {0}, did not configure nested '
'virtualization cpu flag on guest.'.format(vendor)
)
return cpu
model_vendor = LibvirtCPU.get_cpu_vendor(family=model)
if vendor != model_vendor:
LOGGER.debug(
(
'Not enabling nested virtualization feature, host '
'vendor is: {0}, guest vendor: '
'{1}'.format(vendor, model_vendor)
)
)
return cpu
flag = nested[vendor]
if host_cpu.find('feature/[@name="{0}"]'.format(flag)) is not None:
cpu.append(self.generate_feature(name=flag))
else:
LOGGER.debug(
(
'missing {0} cpu flag on host, nested '
'virtualization will probably not '
'work.'
).format(flag)
)
return cpu | python | def generate_exact(self, model, vcpu_num, host_cpu):
"""
Generate exact CPU model with nested virtualization CPU feature.
Args:
model(str): libvirt supported CPU model
vcpu_num(int): number of virtual cpus
host_cpu(lxml.etree.Element): the host CPU model
Returns:
lxml.etree.Element: CPU XML node
"""
nested = {'Intel': 'vmx', 'AMD': 'svm'}
cpu = ET.Element('cpu', match='exact')
ET.SubElement(cpu, 'model').text = model
cpu.append(self.generate_topology(vcpu_num))
vendor = host_cpu.findtext('vendor')
if not nested.get(vendor):
LOGGER.debug(
'Unknown vendor: {0}, did not configure nested '
'virtualization cpu flag on guest.'.format(vendor)
)
return cpu
model_vendor = LibvirtCPU.get_cpu_vendor(family=model)
if vendor != model_vendor:
LOGGER.debug(
(
'Not enabling nested virtualization feature, host '
'vendor is: {0}, guest vendor: '
'{1}'.format(vendor, model_vendor)
)
)
return cpu
flag = nested[vendor]
if host_cpu.find('feature/[@name="{0}"]'.format(flag)) is not None:
cpu.append(self.generate_feature(name=flag))
else:
LOGGER.debug(
(
'missing {0} cpu flag on host, nested '
'virtualization will probably not '
'work.'
).format(flag)
)
return cpu | [
"def",
"generate_exact",
"(",
"self",
",",
"model",
",",
"vcpu_num",
",",
"host_cpu",
")",
":",
"nested",
"=",
"{",
"'Intel'",
":",
"'vmx'",
",",
"'AMD'",
":",
"'svm'",
"}",
"cpu",
"=",
"ET",
".",
"Element",
"(",
"'cpu'",
",",
"match",
"=",
"'exact'"... | Generate exact CPU model with nested virtualization CPU feature.
Args:
model(str): libvirt supported CPU model
vcpu_num(int): number of virtual cpus
host_cpu(lxml.etree.Element): the host CPU model
Returns:
lxml.etree.Element: CPU XML node | [
"Generate",
"exact",
"CPU",
"model",
"with",
"nested",
"virtualization",
"CPU",
"feature",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/cpu.py#L179-L228 | train | 31,649 |
lago-project/lago | lago/providers/libvirt/cpu.py | CPU.generate_feature | def generate_feature(self, name, policy='require'):
"""
Generate CPU feature element
Args:
name(str): feature name
policy(str): libvirt feature policy
Returns:
lxml.etree.Element: feature XML element
"""
return ET.Element('feature', policy=policy, name=name) | python | def generate_feature(self, name, policy='require'):
"""
Generate CPU feature element
Args:
name(str): feature name
policy(str): libvirt feature policy
Returns:
lxml.etree.Element: feature XML element
"""
return ET.Element('feature', policy=policy, name=name) | [
"def",
"generate_feature",
"(",
"self",
",",
"name",
",",
"policy",
"=",
"'require'",
")",
":",
"return",
"ET",
".",
"Element",
"(",
"'feature'",
",",
"policy",
"=",
"policy",
",",
"name",
"=",
"name",
")"
] | Generate CPU feature element
Args:
name(str): feature name
policy(str): libvirt feature policy
Returns:
lxml.etree.Element: feature XML element | [
"Generate",
"CPU",
"feature",
"element"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/cpu.py#L332-L344 | train | 31,650 |
lago-project/lago | lago/providers/libvirt/cpu.py | LibvirtCPU.get_cpu_vendor | def get_cpu_vendor(cls, family, arch='x86'):
"""
Get CPU vendor, if vendor is not available will return 'generic'
Args:
family(str): CPU family
arch(str): CPU arch
Returns:
str: CPU vendor if found otherwise 'generic'
"""
props = cls.get_cpu_props(family, arch)
vendor = 'generic'
try:
vendor = props.xpath('vendor/@name')[0]
except IndexError:
pass
return vendor | python | def get_cpu_vendor(cls, family, arch='x86'):
"""
Get CPU vendor, if vendor is not available will return 'generic'
Args:
family(str): CPU family
arch(str): CPU arch
Returns:
str: CPU vendor if found otherwise 'generic'
"""
props = cls.get_cpu_props(family, arch)
vendor = 'generic'
try:
vendor = props.xpath('vendor/@name')[0]
except IndexError:
pass
return vendor | [
"def",
"get_cpu_vendor",
"(",
"cls",
",",
"family",
",",
"arch",
"=",
"'x86'",
")",
":",
"props",
"=",
"cls",
".",
"get_cpu_props",
"(",
"family",
",",
"arch",
")",
"vendor",
"=",
"'generic'",
"try",
":",
"vendor",
"=",
"props",
".",
"xpath",
"(",
"'... | Get CPU vendor, if vendor is not available will return 'generic'
Args:
family(str): CPU family
arch(str): CPU arch
Returns:
str: CPU vendor if found otherwise 'generic' | [
"Get",
"CPU",
"vendor",
"if",
"vendor",
"is",
"not",
"available",
"will",
"return",
"generic"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/cpu.py#L351-L369 | train | 31,651 |
lago-project/lago | lago/providers/libvirt/cpu.py | LibvirtCPU.get_cpu_props | def get_cpu_props(cls, family, arch='x86'):
"""
Get CPU info XML
Args:
family(str): CPU family
arch(str): CPU arch
Returns:
lxml.etree.Element: CPU xml
Raises:
:exc:`~LagoException`: If no such CPU family exists
"""
cpus = cls.get_cpus_by_arch(arch)
try:
return cpus.xpath('model[@name="{0}"]'.format(family))[0]
except IndexError:
raise LagoException('No such CPU family: {0}'.format(family)) | python | def get_cpu_props(cls, family, arch='x86'):
"""
Get CPU info XML
Args:
family(str): CPU family
arch(str): CPU arch
Returns:
lxml.etree.Element: CPU xml
Raises:
:exc:`~LagoException`: If no such CPU family exists
"""
cpus = cls.get_cpus_by_arch(arch)
try:
return cpus.xpath('model[@name="{0}"]'.format(family))[0]
except IndexError:
raise LagoException('No such CPU family: {0}'.format(family)) | [
"def",
"get_cpu_props",
"(",
"cls",
",",
"family",
",",
"arch",
"=",
"'x86'",
")",
":",
"cpus",
"=",
"cls",
".",
"get_cpus_by_arch",
"(",
"arch",
")",
"try",
":",
"return",
"cpus",
".",
"xpath",
"(",
"'model[@name=\"{0}\"]'",
".",
"format",
"(",
"family"... | Get CPU info XML
Args:
family(str): CPU family
arch(str): CPU arch
Returns:
lxml.etree.Element: CPU xml
Raises:
:exc:`~LagoException`: If no such CPU family exists | [
"Get",
"CPU",
"info",
"XML"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/cpu.py#L372-L391 | train | 31,652 |
lago-project/lago | lago/providers/libvirt/cpu.py | LibvirtCPU.get_cpus_by_arch | def get_cpus_by_arch(cls, arch):
"""
Get all CPUs info by arch
Args:
arch(str): CPU architecture
Returns:
lxml.etree.element: CPUs by arch XML
Raises:
:exc:`~LagoException`: If no such ARCH is found
"""
with open('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map:
cpu_xml = ET.parse(cpu_map)
try:
return cpu_xml.xpath('/cpus/arch[@name="{0}"]'.format(arch))[0]
except IndexError:
raise LagoException('No such arch: {0}'.format(arch)) | python | def get_cpus_by_arch(cls, arch):
"""
Get all CPUs info by arch
Args:
arch(str): CPU architecture
Returns:
lxml.etree.element: CPUs by arch XML
Raises:
:exc:`~LagoException`: If no such ARCH is found
"""
with open('/usr/share/libvirt/cpu_map.xml', 'r') as cpu_map:
cpu_xml = ET.parse(cpu_map)
try:
return cpu_xml.xpath('/cpus/arch[@name="{0}"]'.format(arch))[0]
except IndexError:
raise LagoException('No such arch: {0}'.format(arch)) | [
"def",
"get_cpus_by_arch",
"(",
"cls",
",",
"arch",
")",
":",
"with",
"open",
"(",
"'/usr/share/libvirt/cpu_map.xml'",
",",
"'r'",
")",
"as",
"cpu_map",
":",
"cpu_xml",
"=",
"ET",
".",
"parse",
"(",
"cpu_map",
")",
"try",
":",
"return",
"cpu_xml",
".",
"... | Get all CPUs info by arch
Args:
arch(str): CPU architecture
Returns:
lxml.etree.element: CPUs by arch XML
Raises:
:exc:`~LagoException`: If no such ARCH is found | [
"Get",
"all",
"CPUs",
"info",
"by",
"arch"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/providers/libvirt/cpu.py#L394-L413 | train | 31,653 |
lago-project/lago | lago/log_utils.py | log_task | def log_task(
task, logger=logging, level='info', propagate_fail=True, uuid=None
):
"""
Parameterized decorator to wrap a function in a log task
Example:
>>> @log_task('mytask')
... def do_something():
... pass
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
with LogTask(
task,
logger=logger,
level=level,
propagate_fail=propagate_fail,
uuid=uuid
):
return func(*args, **kwargs)
return wrapper
return decorator | python | def log_task(
task, logger=logging, level='info', propagate_fail=True, uuid=None
):
"""
Parameterized decorator to wrap a function in a log task
Example:
>>> @log_task('mytask')
... def do_something():
... pass
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
with LogTask(
task,
logger=logger,
level=level,
propagate_fail=propagate_fail,
uuid=uuid
):
return func(*args, **kwargs)
return wrapper
return decorator | [
"def",
"log_task",
"(",
"task",
",",
"logger",
"=",
"logging",
",",
"level",
"=",
"'info'",
",",
"propagate_fail",
"=",
"True",
",",
"uuid",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"w... | Parameterized decorator to wrap a function in a log task
Example:
>>> @log_task('mytask')
... def do_something():
... pass | [
"Parameterized",
"decorator",
"to",
"wrap",
"a",
"function",
"in",
"a",
"log",
"task"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L614-L640 | train | 31,654 |
lago-project/lago | lago/log_utils.py | start_log_task | def start_log_task(task, logger=logging, level='info'):
"""
Starts a log task
Args:
task (str): name of the log task to start
logger (logging.Logger): logger to use
level (str): log level to use
Returns:
None
"""
getattr(logger, level)(START_TASK_TRIGGER_MSG % task) | python | def start_log_task(task, logger=logging, level='info'):
"""
Starts a log task
Args:
task (str): name of the log task to start
logger (logging.Logger): logger to use
level (str): log level to use
Returns:
None
"""
getattr(logger, level)(START_TASK_TRIGGER_MSG % task) | [
"def",
"start_log_task",
"(",
"task",
",",
"logger",
"=",
"logging",
",",
"level",
"=",
"'info'",
")",
":",
"getattr",
"(",
"logger",
",",
"level",
")",
"(",
"START_TASK_TRIGGER_MSG",
"%",
"task",
")"
] | Starts a log task
Args:
task (str): name of the log task to start
logger (logging.Logger): logger to use
level (str): log level to use
Returns:
None | [
"Starts",
"a",
"log",
"task"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L643-L655 | train | 31,655 |
lago-project/lago | lago/log_utils.py | end_log_task | def end_log_task(task, logger=logging, level='info'):
"""
Ends a log task
Args:
task (str): name of the log task to end
logger (logging.Logger): logger to use
level (str): log level to use
Returns:
None
"""
getattr(logger, level)(END_TASK_TRIGGER_MSG % task) | python | def end_log_task(task, logger=logging, level='info'):
"""
Ends a log task
Args:
task (str): name of the log task to end
logger (logging.Logger): logger to use
level (str): log level to use
Returns:
None
"""
getattr(logger, level)(END_TASK_TRIGGER_MSG % task) | [
"def",
"end_log_task",
"(",
"task",
",",
"logger",
"=",
"logging",
",",
"level",
"=",
"'info'",
")",
":",
"getattr",
"(",
"logger",
",",
"level",
")",
"(",
"END_TASK_TRIGGER_MSG",
"%",
"task",
")"
] | Ends a log task
Args:
task (str): name of the log task to end
logger (logging.Logger): logger to use
level (str): log level to use
Returns:
None | [
"Ends",
"a",
"log",
"task"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L658-L670 | train | 31,656 |
lago-project/lago | lago/log_utils.py | hide_stevedore_logs | def hide_stevedore_logs():
"""
Hides the logs of stevedore, this function was
added in order to support older versions of stevedore
We are using the NullHandler in order to get rid from
'No handlers could be found for logger...' msg
Returns:
None
"""
stevedore_logger = logging.getLogger('stevedore.extension')
stevedore_logger.propagate = False
stevedore_logger.setLevel(logging.ERROR)
stevedore_logger.addHandler(logging.NullHandler()) | python | def hide_stevedore_logs():
"""
Hides the logs of stevedore, this function was
added in order to support older versions of stevedore
We are using the NullHandler in order to get rid from
'No handlers could be found for logger...' msg
Returns:
None
"""
stevedore_logger = logging.getLogger('stevedore.extension')
stevedore_logger.propagate = False
stevedore_logger.setLevel(logging.ERROR)
stevedore_logger.addHandler(logging.NullHandler()) | [
"def",
"hide_stevedore_logs",
"(",
")",
":",
"stevedore_logger",
"=",
"logging",
".",
"getLogger",
"(",
"'stevedore.extension'",
")",
"stevedore_logger",
".",
"propagate",
"=",
"False",
"stevedore_logger",
".",
"setLevel",
"(",
"logging",
".",
"ERROR",
")",
"steve... | Hides the logs of stevedore, this function was
added in order to support older versions of stevedore
We are using the NullHandler in order to get rid from
'No handlers could be found for logger...' msg
Returns:
None | [
"Hides",
"the",
"logs",
"of",
"stevedore",
"this",
"function",
"was",
"added",
"in",
"order",
"to",
"support",
"older",
"versions",
"of",
"stevedore"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L694-L708 | train | 31,657 |
lago-project/lago | lago/log_utils.py | ColorFormatter.colored | def colored(cls, color, message):
"""
Small function to wrap a string around a color
Args:
color (str): name of the color to wrap the string with, must be one
of the class properties
message (str): String to wrap with the color
Returns:
str: the colored string
"""
return getattr(cls, color.upper()) + message + cls.DEFAULT | python | def colored(cls, color, message):
"""
Small function to wrap a string around a color
Args:
color (str): name of the color to wrap the string with, must be one
of the class properties
message (str): String to wrap with the color
Returns:
str: the colored string
"""
return getattr(cls, color.upper()) + message + cls.DEFAULT | [
"def",
"colored",
"(",
"cls",
",",
"color",
",",
"message",
")",
":",
"return",
"getattr",
"(",
"cls",
",",
"color",
".",
"upper",
"(",
")",
")",
"+",
"message",
"+",
"cls",
".",
"DEFAULT"
] | Small function to wrap a string around a color
Args:
color (str): name of the color to wrap the string with, must be one
of the class properties
message (str): String to wrap with the color
Returns:
str: the colored string | [
"Small",
"function",
"to",
"wrap",
"a",
"string",
"around",
"a",
"color"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L75-L87 | train | 31,658 |
lago-project/lago | lago/log_utils.py | ColorFormatter.format | def format(self, record):
"""
Adds colors to a log record and formats it with the default
Args:
record (logging.LogRecord): log record to format
Returns:
str: The colored and formatted record string
"""
level = record.levelno
if level >= logging.CRITICAL:
color = self.CRITICAL
elif level >= logging.ERROR:
color = self.ERROR
elif level >= logging.WARNING:
color = self.WARNING
elif level >= logging.INFO:
color = self.INFO
elif level >= logging.DEBUG:
color = self.DEBUG
else:
color = self.DEFAULT
message = super().format(record)
if record.args:
try:
message = message % record.args
except TypeError:
# this happens when the message itself has some %s symbols, as
# in traces for tracedumps
pass
return color + message + self.DEFAULT | python | def format(self, record):
"""
Adds colors to a log record and formats it with the default
Args:
record (logging.LogRecord): log record to format
Returns:
str: The colored and formatted record string
"""
level = record.levelno
if level >= logging.CRITICAL:
color = self.CRITICAL
elif level >= logging.ERROR:
color = self.ERROR
elif level >= logging.WARNING:
color = self.WARNING
elif level >= logging.INFO:
color = self.INFO
elif level >= logging.DEBUG:
color = self.DEBUG
else:
color = self.DEFAULT
message = super().format(record)
if record.args:
try:
message = message % record.args
except TypeError:
# this happens when the message itself has some %s symbols, as
# in traces for tracedumps
pass
return color + message + self.DEFAULT | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"level",
"=",
"record",
".",
"levelno",
"if",
"level",
">=",
"logging",
".",
"CRITICAL",
":",
"color",
"=",
"self",
".",
"CRITICAL",
"elif",
"level",
">=",
"logging",
".",
"ERROR",
":",
"color",
... | Adds colors to a log record and formats it with the default
Args:
record (logging.LogRecord): log record to format
Returns:
str: The colored and formatted record string | [
"Adds",
"colors",
"to",
"a",
"log",
"record",
"and",
"formats",
"it",
"with",
"the",
"default"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L89-L123 | train | 31,659 |
lago-project/lago | lago/log_utils.py | TaskHandler.handle_new_task | def handle_new_task(self, task_name, record):
"""
Do everything needed when a task is starting
Params:
task_name (str): name of the task that is starting
record (logging.LogRecord): log record with all the info
Returns:
None
"""
record.msg = ColorFormatter.colored('default', START_TASK_MSG)
record.task = task_name
self.tasks[task_name] = Task(name=task_name, maxlen=self.buffer_size)
if self.should_show_by_depth():
self.pretty_emit(record, is_header=True) | python | def handle_new_task(self, task_name, record):
"""
Do everything needed when a task is starting
Params:
task_name (str): name of the task that is starting
record (logging.LogRecord): log record with all the info
Returns:
None
"""
record.msg = ColorFormatter.colored('default', START_TASK_MSG)
record.task = task_name
self.tasks[task_name] = Task(name=task_name, maxlen=self.buffer_size)
if self.should_show_by_depth():
self.pretty_emit(record, is_header=True) | [
"def",
"handle_new_task",
"(",
"self",
",",
"task_name",
",",
"record",
")",
":",
"record",
".",
"msg",
"=",
"ColorFormatter",
".",
"colored",
"(",
"'default'",
",",
"START_TASK_MSG",
")",
"record",
".",
"task",
"=",
"task_name",
"self",
".",
"tasks",
"[",... | Do everything needed when a task is starting
Params:
task_name (str): name of the task that is starting
record (logging.LogRecord): log record with all the info
Returns:
None | [
"Do",
"everything",
"needed",
"when",
"a",
"task",
"is",
"starting"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L343-L359 | train | 31,660 |
lago-project/lago | lago/log_utils.py | TaskHandler.mark_parent_tasks_as_failed | def mark_parent_tasks_as_failed(self, task_name, flush_logs=False):
"""
Marks all the parent tasks as failed
Args:
task_name (str): Name of the child task
flush_logs (bool): If ``True`` will discard all the logs form
parent tasks
Returns:
None
"""
for existing_task_name in self.tasks:
if existing_task_name == task_name:
break
if flush_logs:
self.tasks[existing_task_name].clear()
self.tasks[existing_task_name].failed = True
self.mark_main_tasks_as_failed() | python | def mark_parent_tasks_as_failed(self, task_name, flush_logs=False):
"""
Marks all the parent tasks as failed
Args:
task_name (str): Name of the child task
flush_logs (bool): If ``True`` will discard all the logs form
parent tasks
Returns:
None
"""
for existing_task_name in self.tasks:
if existing_task_name == task_name:
break
if flush_logs:
self.tasks[existing_task_name].clear()
self.tasks[existing_task_name].failed = True
self.mark_main_tasks_as_failed() | [
"def",
"mark_parent_tasks_as_failed",
"(",
"self",
",",
"task_name",
",",
"flush_logs",
"=",
"False",
")",
":",
"for",
"existing_task_name",
"in",
"self",
".",
"tasks",
":",
"if",
"existing_task_name",
"==",
"task_name",
":",
"break",
"if",
"flush_logs",
":",
... | Marks all the parent tasks as failed
Args:
task_name (str): Name of the child task
flush_logs (bool): If ``True`` will discard all the logs form
parent tasks
Returns:
None | [
"Marks",
"all",
"the",
"parent",
"tasks",
"as",
"failed"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L361-L382 | train | 31,661 |
lago-project/lago | lago/log_utils.py | TaskHandler.close_children_tasks | def close_children_tasks(self, parent_task_name):
"""
Closes all the children tasks that were open
Args:
parent_task_name (str): Name of the parent task
Returns:
None
"""
if parent_task_name not in self.tasks:
return
while self.tasks:
next_task = reversed(self.tasks.keys()).next()
if next_task == parent_task_name:
break
del self.tasks[next_task] | python | def close_children_tasks(self, parent_task_name):
"""
Closes all the children tasks that were open
Args:
parent_task_name (str): Name of the parent task
Returns:
None
"""
if parent_task_name not in self.tasks:
return
while self.tasks:
next_task = reversed(self.tasks.keys()).next()
if next_task == parent_task_name:
break
del self.tasks[next_task] | [
"def",
"close_children_tasks",
"(",
"self",
",",
"parent_task_name",
")",
":",
"if",
"parent_task_name",
"not",
"in",
"self",
".",
"tasks",
":",
"return",
"while",
"self",
".",
"tasks",
":",
"next_task",
"=",
"reversed",
"(",
"self",
".",
"tasks",
".",
"ke... | Closes all the children tasks that were open
Args:
parent_task_name (str): Name of the parent task
Returns:
None | [
"Closes",
"all",
"the",
"children",
"tasks",
"that",
"were",
"open"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L384-L401 | train | 31,662 |
lago-project/lago | lago/log_utils.py | TaskHandler.handle_closed_task | def handle_closed_task(self, task_name, record):
"""
Do everything needed when a task is closed
Params:
task_name (str): name of the task that is finishing
record (logging.LogRecord): log record with all the info
Returns:
None
"""
if task_name not in self.tasks:
return
if self.main_failed:
self.mark_parent_tasks_as_failed(self.cur_task)
if self.tasks[task_name].failed:
record.msg = ColorFormatter.colored('red', END_TASK_ON_ERROR_MSG)
else:
record.msg = ColorFormatter.colored('green', END_TASK_MSG)
record.msg += ' (in %s)' % self.tasks[task_name].elapsed_time()
if self.should_show_by_depth() or self.tasks[task_name].force_show:
if self.tasks[task_name].force_show:
self.handle_error()
self.pretty_emit(record, is_header=True)
self.close_children_tasks(task_name)
self.tasks.pop(task_name) | python | def handle_closed_task(self, task_name, record):
"""
Do everything needed when a task is closed
Params:
task_name (str): name of the task that is finishing
record (logging.LogRecord): log record with all the info
Returns:
None
"""
if task_name not in self.tasks:
return
if self.main_failed:
self.mark_parent_tasks_as_failed(self.cur_task)
if self.tasks[task_name].failed:
record.msg = ColorFormatter.colored('red', END_TASK_ON_ERROR_MSG)
else:
record.msg = ColorFormatter.colored('green', END_TASK_MSG)
record.msg += ' (in %s)' % self.tasks[task_name].elapsed_time()
if self.should_show_by_depth() or self.tasks[task_name].force_show:
if self.tasks[task_name].force_show:
self.handle_error()
self.pretty_emit(record, is_header=True)
self.close_children_tasks(task_name)
self.tasks.pop(task_name) | [
"def",
"handle_closed_task",
"(",
"self",
",",
"task_name",
",",
"record",
")",
":",
"if",
"task_name",
"not",
"in",
"self",
".",
"tasks",
":",
"return",
"if",
"self",
".",
"main_failed",
":",
"self",
".",
"mark_parent_tasks_as_failed",
"(",
"self",
".",
"... | Do everything needed when a task is closed
Params:
task_name (str): name of the task that is finishing
record (logging.LogRecord): log record with all the info
Returns:
None | [
"Do",
"everything",
"needed",
"when",
"a",
"task",
"is",
"closed"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L403-L434 | train | 31,663 |
lago-project/lago | lago/log_utils.py | TaskHandler.handle_error | def handle_error(self):
"""
Handles an error log record that should be shown
Returns:
None
"""
if not self.tasks:
return
# All the parents inherit the failure
self.mark_parent_tasks_as_failed(
self.cur_task,
flush_logs=True,
)
# Show the start headers for all the parent tasks if they were not
# shown by the depth level limit
for index, task in enumerate(self.tasks.values()):
if self.should_show_by_depth(index + 1):
continue
start_task_header = logging.LogRecord(
'', logging.INFO, '', 0, '', [], None
)
start_task_header.msg = ColorFormatter.colored(
'default',
START_TASK_MSG,
)
start_task_header.task = task.name
self.pretty_emit(
start_task_header,
is_header=True,
task_level=index + 1,
)
# Show now all the cached logs for the current task
for old_record in self.tasks[self.cur_task]:
self.pretty_emit(old_record)
self.tasks[self.cur_task].clear() | python | def handle_error(self):
"""
Handles an error log record that should be shown
Returns:
None
"""
if not self.tasks:
return
# All the parents inherit the failure
self.mark_parent_tasks_as_failed(
self.cur_task,
flush_logs=True,
)
# Show the start headers for all the parent tasks if they were not
# shown by the depth level limit
for index, task in enumerate(self.tasks.values()):
if self.should_show_by_depth(index + 1):
continue
start_task_header = logging.LogRecord(
'', logging.INFO, '', 0, '', [], None
)
start_task_header.msg = ColorFormatter.colored(
'default',
START_TASK_MSG,
)
start_task_header.task = task.name
self.pretty_emit(
start_task_header,
is_header=True,
task_level=index + 1,
)
# Show now all the cached logs for the current task
for old_record in self.tasks[self.cur_task]:
self.pretty_emit(old_record)
self.tasks[self.cur_task].clear() | [
"def",
"handle_error",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"tasks",
":",
"return",
"# All the parents inherit the failure",
"self",
".",
"mark_parent_tasks_as_failed",
"(",
"self",
".",
"cur_task",
",",
"flush_logs",
"=",
"True",
",",
")",
"# Show t... | Handles an error log record that should be shown
Returns:
None | [
"Handles",
"an",
"error",
"log",
"record",
"that",
"should",
"be",
"shown"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L436-L476 | train | 31,664 |
lago-project/lago | lago/log_utils.py | TaskHandler.emit | def emit(self, record):
"""
Handle the given record, this is the entry point from the python
logging facility
Params:
record (logging.LogRecord): log record to handle
Returns:
None
"""
record.task = self.cur_task
if record.levelno >= self.dump_level and self.cur_task:
self.tasks[self.cur_task].failed = True
self.tasks[self.cur_task].force_show = True
# Makes no sense to start a task with an error log
is_start = START_TASK_REG.match(str(record.msg))
if is_start:
self.handle_new_task(is_start.groupdict()['task_name'], record)
return
is_end = END_TASK_REG.match(str(record.msg))
if is_end:
self.handle_closed_task(is_end.groupdict()['task_name'], record)
return
force_show_record = ALWAYS_SHOW_REG.match(str(record.msg))
if force_show_record:
record.msg = force_show_record.groupdict()['message']
self.pretty_emit(record)
if (
not force_show_record and self.should_show_by_level(record)
and self.should_show_by_depth()
):
self.pretty_emit(record)
return
if self.cur_task:
self.tasks[self.cur_task].append(record) | python | def emit(self, record):
"""
Handle the given record, this is the entry point from the python
logging facility
Params:
record (logging.LogRecord): log record to handle
Returns:
None
"""
record.task = self.cur_task
if record.levelno >= self.dump_level and self.cur_task:
self.tasks[self.cur_task].failed = True
self.tasks[self.cur_task].force_show = True
# Makes no sense to start a task with an error log
is_start = START_TASK_REG.match(str(record.msg))
if is_start:
self.handle_new_task(is_start.groupdict()['task_name'], record)
return
is_end = END_TASK_REG.match(str(record.msg))
if is_end:
self.handle_closed_task(is_end.groupdict()['task_name'], record)
return
force_show_record = ALWAYS_SHOW_REG.match(str(record.msg))
if force_show_record:
record.msg = force_show_record.groupdict()['message']
self.pretty_emit(record)
if (
not force_show_record and self.should_show_by_level(record)
and self.should_show_by_depth()
):
self.pretty_emit(record)
return
if self.cur_task:
self.tasks[self.cur_task].append(record) | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"record",
".",
"task",
"=",
"self",
".",
"cur_task",
"if",
"record",
".",
"levelno",
">=",
"self",
".",
"dump_level",
"and",
"self",
".",
"cur_task",
":",
"self",
".",
"tasks",
"[",
"self",
".",
... | Handle the given record, this is the entry point from the python
logging facility
Params:
record (logging.LogRecord): log record to handle
Returns:
None | [
"Handle",
"the",
"given",
"record",
"this",
"is",
"the",
"entry",
"point",
"from",
"the",
"python",
"logging",
"facility"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/log_utils.py#L528-L569 | train | 31,665 |
lago-project/lago | lago/subnet_lease.py | SubnetStore._validate_lease_dir | def _validate_lease_dir(self):
"""
Validate that the directory used by this store exist,
otherwise create it.
"""
try:
if not os.path.isdir(self.path):
os.makedirs(self.path)
except OSError as e:
raise_from(
LagoSubnetLeaseBadPermissionsException(self.path, e.strerror),
e
) | python | def _validate_lease_dir(self):
"""
Validate that the directory used by this store exist,
otherwise create it.
"""
try:
if not os.path.isdir(self.path):
os.makedirs(self.path)
except OSError as e:
raise_from(
LagoSubnetLeaseBadPermissionsException(self.path, e.strerror),
e
) | [
"def",
"_validate_lease_dir",
"(",
"self",
")",
":",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"path",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"raise_fro... | Validate that the directory used by this store exist,
otherwise create it. | [
"Validate",
"that",
"the",
"directory",
"used",
"by",
"this",
"store",
"exist",
"otherwise",
"create",
"it",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/subnet_lease.py#L105-L117 | train | 31,666 |
lago-project/lago | lago/subnet_lease.py | SubnetStore.acquire | def acquire(self, uuid_path, subnet=None):
"""
Lease a free subnet for the given uuid path.
If subnet is given, try to lease that subnet, otherwise try to lease a
free subnet.
Args:
uuid_path (str): Path to the uuid file of a :class:`lago.Prefix`
subnet (str): A subnet to lease.
Returns:
netaddr.IPAddress: An object which represents the subnet.
Raises:
LagoSubnetLeaseException:
1. If this store is full
2. If the requested subnet is already taken.
LagoSubnetLeaseLockException:
If the lock to self.path can't be acquired.
"""
try:
with self._create_lock():
if subnet:
LOGGER.debug('Trying to acquire subnet {}'.format(subnet))
acquired_subnet = self._acquire_given_subnet(
uuid_path, subnet
)
else:
LOGGER.debug('Trying to acquire a free subnet')
acquired_subnet = self._acquire(uuid_path)
return acquired_subnet
except (utils.TimerException, IOError):
raise LagoSubnetLeaseLockException(self.path) | python | def acquire(self, uuid_path, subnet=None):
"""
Lease a free subnet for the given uuid path.
If subnet is given, try to lease that subnet, otherwise try to lease a
free subnet.
Args:
uuid_path (str): Path to the uuid file of a :class:`lago.Prefix`
subnet (str): A subnet to lease.
Returns:
netaddr.IPAddress: An object which represents the subnet.
Raises:
LagoSubnetLeaseException:
1. If this store is full
2. If the requested subnet is already taken.
LagoSubnetLeaseLockException:
If the lock to self.path can't be acquired.
"""
try:
with self._create_lock():
if subnet:
LOGGER.debug('Trying to acquire subnet {}'.format(subnet))
acquired_subnet = self._acquire_given_subnet(
uuid_path, subnet
)
else:
LOGGER.debug('Trying to acquire a free subnet')
acquired_subnet = self._acquire(uuid_path)
return acquired_subnet
except (utils.TimerException, IOError):
raise LagoSubnetLeaseLockException(self.path) | [
"def",
"acquire",
"(",
"self",
",",
"uuid_path",
",",
"subnet",
"=",
"None",
")",
":",
"try",
":",
"with",
"self",
".",
"_create_lock",
"(",
")",
":",
"if",
"subnet",
":",
"LOGGER",
".",
"debug",
"(",
"'Trying to acquire subnet {}'",
".",
"format",
"(",
... | Lease a free subnet for the given uuid path.
If subnet is given, try to lease that subnet, otherwise try to lease a
free subnet.
Args:
uuid_path (str): Path to the uuid file of a :class:`lago.Prefix`
subnet (str): A subnet to lease.
Returns:
netaddr.IPAddress: An object which represents the subnet.
Raises:
LagoSubnetLeaseException:
1. If this store is full
2. If the requested subnet is already taken.
LagoSubnetLeaseLockException:
If the lock to self.path can't be acquired. | [
"Lease",
"a",
"free",
"subnet",
"for",
"the",
"given",
"uuid",
"path",
".",
"If",
"subnet",
"is",
"given",
"try",
"to",
"lease",
"that",
"subnet",
"otherwise",
"try",
"to",
"lease",
"a",
"free",
"subnet",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/subnet_lease.py#L119-L151 | train | 31,667 |
lago-project/lago | lago/subnet_lease.py | SubnetStore._acquire | def _acquire(self, uuid_path):
"""
Lease a free network for the given uuid path
Args:
uuid_path (str): Path to the uuid file of a :class:`lago.Prefix`
Returns:
netaddr.IPNetwork: Which represents the selected subnet
Raises:
LagoSubnetLeaseException: If the store is full
"""
for index in range(self._min_third_octet, self._max_third_octet + 1):
lease = self.create_lease_object_from_idx(index)
if self._lease_valid(lease):
continue
self._take_lease(lease, uuid_path, safe=False)
return lease.to_ip_network()
raise LagoSubnetLeaseStoreFullException(self.get_allowed_range()) | python | def _acquire(self, uuid_path):
"""
Lease a free network for the given uuid path
Args:
uuid_path (str): Path to the uuid file of a :class:`lago.Prefix`
Returns:
netaddr.IPNetwork: Which represents the selected subnet
Raises:
LagoSubnetLeaseException: If the store is full
"""
for index in range(self._min_third_octet, self._max_third_octet + 1):
lease = self.create_lease_object_from_idx(index)
if self._lease_valid(lease):
continue
self._take_lease(lease, uuid_path, safe=False)
return lease.to_ip_network()
raise LagoSubnetLeaseStoreFullException(self.get_allowed_range()) | [
"def",
"_acquire",
"(",
"self",
",",
"uuid_path",
")",
":",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"_min_third_octet",
",",
"self",
".",
"_max_third_octet",
"+",
"1",
")",
":",
"lease",
"=",
"self",
".",
"create_lease_object_from_idx",
"(",
"inde... | Lease a free network for the given uuid path
Args:
uuid_path (str): Path to the uuid file of a :class:`lago.Prefix`
Returns:
netaddr.IPNetwork: Which represents the selected subnet
Raises:
LagoSubnetLeaseException: If the store is full | [
"Lease",
"a",
"free",
"network",
"for",
"the",
"given",
"uuid",
"path"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/subnet_lease.py#L153-L173 | train | 31,668 |
lago-project/lago | lago/subnet_lease.py | SubnetStore._acquire_given_subnet | def _acquire_given_subnet(self, uuid_path, subnet):
"""
Try to create a lease for subnet
Args:
uuid_path (str): Path to the uuid file of a :class:`lago.Prefix`
subnet (str): dotted ipv4 subnet
(for example ```192.168.200.0```)
Returns:
netaddr.IPNetwork: Which represents the selected subnet
Raises:
LagoSubnetLeaseException: If the requested subnet is not in the
range of this store or its already been taken
"""
lease = self.create_lease_object_from_subnet(subnet)
self._take_lease(lease, uuid_path)
return lease.to_ip_network() | python | def _acquire_given_subnet(self, uuid_path, subnet):
"""
Try to create a lease for subnet
Args:
uuid_path (str): Path to the uuid file of a :class:`lago.Prefix`
subnet (str): dotted ipv4 subnet
(for example ```192.168.200.0```)
Returns:
netaddr.IPNetwork: Which represents the selected subnet
Raises:
LagoSubnetLeaseException: If the requested subnet is not in the
range of this store or its already been taken
"""
lease = self.create_lease_object_from_subnet(subnet)
self._take_lease(lease, uuid_path)
return lease.to_ip_network() | [
"def",
"_acquire_given_subnet",
"(",
"self",
",",
"uuid_path",
",",
"subnet",
")",
":",
"lease",
"=",
"self",
".",
"create_lease_object_from_subnet",
"(",
"subnet",
")",
"self",
".",
"_take_lease",
"(",
"lease",
",",
"uuid_path",
")",
"return",
"lease",
".",
... | Try to create a lease for subnet
Args:
uuid_path (str): Path to the uuid file of a :class:`lago.Prefix`
subnet (str): dotted ipv4 subnet
(for example ```192.168.200.0```)
Returns:
netaddr.IPNetwork: Which represents the selected subnet
Raises:
LagoSubnetLeaseException: If the requested subnet is not in the
range of this store or its already been taken | [
"Try",
"to",
"create",
"a",
"lease",
"for",
"subnet"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/subnet_lease.py#L175-L194 | train | 31,669 |
lago-project/lago | lago/subnet_lease.py | SubnetStore._lease_valid | def _lease_valid(self, lease):
"""
Check if the given lease exist and still has a prefix that owns it.
If the lease exist but its prefix isn't, remove the lease from this
store.
Args:
lease (lago.subnet_lease.Lease): Object representation of the
lease
Returns:
str or None: If the lease and its prefix exists, return the path
to the uuid of the prefix, else return None.
"""
if not lease.exist:
return None
if lease.has_env:
return lease.uuid_path
else:
self._release(lease)
return None | python | def _lease_valid(self, lease):
"""
Check if the given lease exist and still has a prefix that owns it.
If the lease exist but its prefix isn't, remove the lease from this
store.
Args:
lease (lago.subnet_lease.Lease): Object representation of the
lease
Returns:
str or None: If the lease and its prefix exists, return the path
to the uuid of the prefix, else return None.
"""
if not lease.exist:
return None
if lease.has_env:
return lease.uuid_path
else:
self._release(lease)
return None | [
"def",
"_lease_valid",
"(",
"self",
",",
"lease",
")",
":",
"if",
"not",
"lease",
".",
"exist",
":",
"return",
"None",
"if",
"lease",
".",
"has_env",
":",
"return",
"lease",
".",
"uuid_path",
"else",
":",
"self",
".",
"_release",
"(",
"lease",
")",
"... | Check if the given lease exist and still has a prefix that owns it.
If the lease exist but its prefix isn't, remove the lease from this
store.
Args:
lease (lago.subnet_lease.Lease): Object representation of the
lease
Returns:
str or None: If the lease and its prefix exists, return the path
to the uuid of the prefix, else return None. | [
"Check",
"if",
"the",
"given",
"lease",
"exist",
"and",
"still",
"has",
"a",
"prefix",
"that",
"owns",
"it",
".",
"If",
"the",
"lease",
"exist",
"but",
"its",
"prefix",
"isn",
"t",
"remove",
"the",
"lease",
"from",
"this",
"store",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/subnet_lease.py#L196-L217 | train | 31,670 |
lago-project/lago | lago/subnet_lease.py | SubnetStore._take_lease | def _take_lease(self, lease, uuid_path, safe=True):
"""
Persist the given lease to the store and make the prefix in uuid_path
his owner
Args:
lease(lago.subnet_lease.Lease): Object representation of the lease
uuid_path (str): Path to the prefix uuid
safe (bool): If true (the default), validate the the lease
isn't taken.
Raises:
LagoSubnetLeaseException: If safe == True and the lease is already
taken.
"""
if safe:
lease_taken_by = self._lease_valid(lease)
if lease_taken_by and lease_taken_by != uuid_path:
raise LagoSubnetLeaseTakenException(
lease.subnet, lease_taken_by
)
with open(uuid_path) as f:
uuid = f.read()
with open(lease.path, 'wt') as f:
utils.json_dump((uuid_path, uuid), f)
LOGGER.debug(
'Assigned subnet lease {} to {}'.format(lease.path, uuid_path)
) | python | def _take_lease(self, lease, uuid_path, safe=True):
"""
Persist the given lease to the store and make the prefix in uuid_path
his owner
Args:
lease(lago.subnet_lease.Lease): Object representation of the lease
uuid_path (str): Path to the prefix uuid
safe (bool): If true (the default), validate the the lease
isn't taken.
Raises:
LagoSubnetLeaseException: If safe == True and the lease is already
taken.
"""
if safe:
lease_taken_by = self._lease_valid(lease)
if lease_taken_by and lease_taken_by != uuid_path:
raise LagoSubnetLeaseTakenException(
lease.subnet, lease_taken_by
)
with open(uuid_path) as f:
uuid = f.read()
with open(lease.path, 'wt') as f:
utils.json_dump((uuid_path, uuid), f)
LOGGER.debug(
'Assigned subnet lease {} to {}'.format(lease.path, uuid_path)
) | [
"def",
"_take_lease",
"(",
"self",
",",
"lease",
",",
"uuid_path",
",",
"safe",
"=",
"True",
")",
":",
"if",
"safe",
":",
"lease_taken_by",
"=",
"self",
".",
"_lease_valid",
"(",
"lease",
")",
"if",
"lease_taken_by",
"and",
"lease_taken_by",
"!=",
"uuid_pa... | Persist the given lease to the store and make the prefix in uuid_path
his owner
Args:
lease(lago.subnet_lease.Lease): Object representation of the lease
uuid_path (str): Path to the prefix uuid
safe (bool): If true (the default), validate the the lease
isn't taken.
Raises:
LagoSubnetLeaseException: If safe == True and the lease is already
taken. | [
"Persist",
"the",
"given",
"lease",
"to",
"the",
"store",
"and",
"make",
"the",
"prefix",
"in",
"uuid_path",
"his",
"owner"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/subnet_lease.py#L219-L248 | train | 31,671 |
lago-project/lago | lago/subnet_lease.py | SubnetStore.list_leases | def list_leases(self, uuid=None):
"""
List current subnet leases
Args:
uuid(str): Filter the leases by uuid
Returns:
list of :class:~Lease: current leases
"""
try:
lease_files = os.listdir(self.path)
except OSError as e:
raise_from(
LagoSubnetLeaseBadPermissionsException(self.path, e.strerror),
e
)
leases = [
self.create_lease_object_from_idx(lease_file.split('.')[0])
for lease_file in lease_files if lease_file != LOCK_NAME
]
if not uuid:
return leases
else:
return [lease for lease in leases if lease.uuid == uuid] | python | def list_leases(self, uuid=None):
"""
List current subnet leases
Args:
uuid(str): Filter the leases by uuid
Returns:
list of :class:~Lease: current leases
"""
try:
lease_files = os.listdir(self.path)
except OSError as e:
raise_from(
LagoSubnetLeaseBadPermissionsException(self.path, e.strerror),
e
)
leases = [
self.create_lease_object_from_idx(lease_file.split('.')[0])
for lease_file in lease_files if lease_file != LOCK_NAME
]
if not uuid:
return leases
else:
return [lease for lease in leases if lease.uuid == uuid] | [
"def",
"list_leases",
"(",
"self",
",",
"uuid",
"=",
"None",
")",
":",
"try",
":",
"lease_files",
"=",
"os",
".",
"listdir",
"(",
"self",
".",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"raise_from",
"(",
"LagoSubnetLeaseBadPermissionsException",
"(... | List current subnet leases
Args:
uuid(str): Filter the leases by uuid
Returns:
list of :class:~Lease: current leases | [
"List",
"current",
"subnet",
"leases"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/subnet_lease.py#L250-L276 | train | 31,672 |
lago-project/lago | lago/subnet_lease.py | SubnetStore.release | def release(self, subnets):
"""
Free the lease of the given subnets
Args:
subnets (list of str or netaddr.IPAddress): dotted ipv4 subnet in
CIDR notation (for example ```192.168.200.0/24```) or IPAddress
object.
Raises:
LagoSubnetLeaseException: If subnet is a str and can't be parsed
LagoSubnetLeaseLockException:
If the lock to self.path can't be acquired.
"""
if isinstance(subnets, str) or isinstance(subnets, IPNetwork):
subnets = [subnets]
subnets_iter = (
str(subnet) if isinstance(subnet, IPNetwork) else subnet
for subnet in subnets
)
try:
with self._create_lock():
for subnet in subnets_iter:
self._release(self.create_lease_object_from_subnet(subnet))
except (utils.TimerException, IOError):
raise LagoSubnetLeaseLockException(self.path) | python | def release(self, subnets):
"""
Free the lease of the given subnets
Args:
subnets (list of str or netaddr.IPAddress): dotted ipv4 subnet in
CIDR notation (for example ```192.168.200.0/24```) or IPAddress
object.
Raises:
LagoSubnetLeaseException: If subnet is a str and can't be parsed
LagoSubnetLeaseLockException:
If the lock to self.path can't be acquired.
"""
if isinstance(subnets, str) or isinstance(subnets, IPNetwork):
subnets = [subnets]
subnets_iter = (
str(subnet) if isinstance(subnet, IPNetwork) else subnet
for subnet in subnets
)
try:
with self._create_lock():
for subnet in subnets_iter:
self._release(self.create_lease_object_from_subnet(subnet))
except (utils.TimerException, IOError):
raise LagoSubnetLeaseLockException(self.path) | [
"def",
"release",
"(",
"self",
",",
"subnets",
")",
":",
"if",
"isinstance",
"(",
"subnets",
",",
"str",
")",
"or",
"isinstance",
"(",
"subnets",
",",
"IPNetwork",
")",
":",
"subnets",
"=",
"[",
"subnets",
"]",
"subnets_iter",
"=",
"(",
"str",
"(",
"... | Free the lease of the given subnets
Args:
subnets (list of str or netaddr.IPAddress): dotted ipv4 subnet in
CIDR notation (for example ```192.168.200.0/24```) or IPAddress
object.
Raises:
LagoSubnetLeaseException: If subnet is a str and can't be parsed
LagoSubnetLeaseLockException:
If the lock to self.path can't be acquired. | [
"Free",
"the",
"lease",
"of",
"the",
"given",
"subnets"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/subnet_lease.py#L278-L304 | train | 31,673 |
lago-project/lago | lago/subnet_lease.py | SubnetStore._release | def _release(self, lease):
"""
Free the given lease
Args:
lease (lago.subnet_lease.Lease): The lease to free
"""
if lease.exist:
os.unlink(lease.path)
LOGGER.debug('Removed subnet lease {}'.format(lease.path)) | python | def _release(self, lease):
"""
Free the given lease
Args:
lease (lago.subnet_lease.Lease): The lease to free
"""
if lease.exist:
os.unlink(lease.path)
LOGGER.debug('Removed subnet lease {}'.format(lease.path)) | [
"def",
"_release",
"(",
"self",
",",
"lease",
")",
":",
"if",
"lease",
".",
"exist",
":",
"os",
".",
"unlink",
"(",
"lease",
".",
"path",
")",
"LOGGER",
".",
"debug",
"(",
"'Removed subnet lease {}'",
".",
"format",
"(",
"lease",
".",
"path",
")",
")... | Free the given lease
Args:
lease (lago.subnet_lease.Lease): The lease to free | [
"Free",
"the",
"given",
"lease"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/subnet_lease.py#L306-L315 | train | 31,674 |
lago-project/lago | lago/subnet_lease.py | SubnetStore._lease_owned | def _lease_owned(self, lease, current_uuid_path):
"""
Checks if the given lease is owned by the prefix whose uuid is in
the given path
Note:
The prefix must be also in the same path it was when it took the
lease
Args:
path (str): Path to the lease
current_uuid_path (str): Path to the uuid to check ownership of
Returns:
bool: ``True`` if the given lease in owned by the prefix,
``False`` otherwise
"""
prev_uuid_path, prev_uuid = lease.metadata
with open(current_uuid_path) as f:
current_uuid = f.read()
return \
current_uuid_path == prev_uuid_path and \
prev_uuid == current_uuid | python | def _lease_owned(self, lease, current_uuid_path):
"""
Checks if the given lease is owned by the prefix whose uuid is in
the given path
Note:
The prefix must be also in the same path it was when it took the
lease
Args:
path (str): Path to the lease
current_uuid_path (str): Path to the uuid to check ownership of
Returns:
bool: ``True`` if the given lease in owned by the prefix,
``False`` otherwise
"""
prev_uuid_path, prev_uuid = lease.metadata
with open(current_uuid_path) as f:
current_uuid = f.read()
return \
current_uuid_path == prev_uuid_path and \
prev_uuid == current_uuid | [
"def",
"_lease_owned",
"(",
"self",
",",
"lease",
",",
"current_uuid_path",
")",
":",
"prev_uuid_path",
",",
"prev_uuid",
"=",
"lease",
".",
"metadata",
"with",
"open",
"(",
"current_uuid_path",
")",
"as",
"f",
":",
"current_uuid",
"=",
"f",
".",
"read",
"... | Checks if the given lease is owned by the prefix whose uuid is in
the given path
Note:
The prefix must be also in the same path it was when it took the
lease
Args:
path (str): Path to the lease
current_uuid_path (str): Path to the uuid to check ownership of
Returns:
bool: ``True`` if the given lease in owned by the prefix,
``False`` otherwise | [
"Checks",
"if",
"the",
"given",
"lease",
"is",
"owned",
"by",
"the",
"prefix",
"whose",
"uuid",
"is",
"in",
"the",
"given",
"path"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/subnet_lease.py#L317-L342 | train | 31,675 |
lago-project/lago | lago/utils.py | _run_command | def _run_command(
command,
input_data=None,
stdin=None,
out_pipe=subprocess.PIPE,
err_pipe=subprocess.PIPE,
env=None,
uuid=None,
**kwargs
):
"""
Runs a command
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
input_data(str): If passed, will feed that data to the subprocess
through stdin
out_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stdout
stdin(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stdin
err_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stderr
env(dict of str:str): If set, will use the given dict as env for the
subprocess
uuid(uuid): If set the command will be logged with the given uuid
converted to string, otherwise, a uuid v4 will be generated.
**kwargs: Any other keyword args passed will be passed to the
:ref:subprocess.Popen call
Returns:
lago.utils.CommandStatus: result of the interactive execution
"""
# add libexec to PATH if needed
if uuid is None:
uuid = uuid_m.uuid4()
if constants.LIBEXEC_DIR not in os.environ['PATH'].split(':'):
os.environ['PATH'
] = '%s:%s' % (constants.LIBEXEC_DIR, os.environ['PATH'])
if input_data and not stdin:
kwargs['stdin'] = subprocess.PIPE
elif stdin:
kwargs['stdin'] = stdin
if env is None:
env = os.environ.copy()
else:
env['PATH'] = ':'.join(
list(
set(
env.get('PATH', '').split(':') + os.environ['PATH']
.split(':')
),
),
)
popen = subprocess.Popen(
' '.join('"%s"' % arg for arg in command),
stdout=out_pipe,
stderr=err_pipe,
shell=True,
env=env,
**kwargs
)
out, err = popen.communicate(input_data)
LOGGER.debug(
'%s: command exit with return code: %d', str(uuid), popen.returncode
)
if out:
LOGGER.debug('%s: command stdout: %s', str(uuid), out)
if err:
LOGGER.debug('%s: command stderr: %s', str(uuid), err)
return CommandStatus(popen.returncode, out, err) | python | def _run_command(
command,
input_data=None,
stdin=None,
out_pipe=subprocess.PIPE,
err_pipe=subprocess.PIPE,
env=None,
uuid=None,
**kwargs
):
"""
Runs a command
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
input_data(str): If passed, will feed that data to the subprocess
through stdin
out_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stdout
stdin(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stdin
err_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stderr
env(dict of str:str): If set, will use the given dict as env for the
subprocess
uuid(uuid): If set the command will be logged with the given uuid
converted to string, otherwise, a uuid v4 will be generated.
**kwargs: Any other keyword args passed will be passed to the
:ref:subprocess.Popen call
Returns:
lago.utils.CommandStatus: result of the interactive execution
"""
# add libexec to PATH if needed
if uuid is None:
uuid = uuid_m.uuid4()
if constants.LIBEXEC_DIR not in os.environ['PATH'].split(':'):
os.environ['PATH'
] = '%s:%s' % (constants.LIBEXEC_DIR, os.environ['PATH'])
if input_data and not stdin:
kwargs['stdin'] = subprocess.PIPE
elif stdin:
kwargs['stdin'] = stdin
if env is None:
env = os.environ.copy()
else:
env['PATH'] = ':'.join(
list(
set(
env.get('PATH', '').split(':') + os.environ['PATH']
.split(':')
),
),
)
popen = subprocess.Popen(
' '.join('"%s"' % arg for arg in command),
stdout=out_pipe,
stderr=err_pipe,
shell=True,
env=env,
**kwargs
)
out, err = popen.communicate(input_data)
LOGGER.debug(
'%s: command exit with return code: %d', str(uuid), popen.returncode
)
if out:
LOGGER.debug('%s: command stdout: %s', str(uuid), out)
if err:
LOGGER.debug('%s: command stderr: %s', str(uuid), err)
return CommandStatus(popen.returncode, out, err) | [
"def",
"_run_command",
"(",
"command",
",",
"input_data",
"=",
"None",
",",
"stdin",
"=",
"None",
",",
"out_pipe",
"=",
"subprocess",
".",
"PIPE",
",",
"err_pipe",
"=",
"subprocess",
".",
"PIPE",
",",
"env",
"=",
"None",
",",
"uuid",
"=",
"None",
",",
... | Runs a command
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
input_data(str): If passed, will feed that data to the subprocess
through stdin
out_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stdout
stdin(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stdin
err_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stderr
env(dict of str:str): If set, will use the given dict as env for the
subprocess
uuid(uuid): If set the command will be logged with the given uuid
converted to string, otherwise, a uuid v4 will be generated.
**kwargs: Any other keyword args passed will be passed to the
:ref:subprocess.Popen call
Returns:
lago.utils.CommandStatus: result of the interactive execution | [
"Runs",
"a",
"command"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/utils.py#L123-L199 | train | 31,676 |
lago-project/lago | lago/utils.py | run_command | def run_command(
command,
input_data=None,
out_pipe=subprocess.PIPE,
err_pipe=subprocess.PIPE,
env=None,
**kwargs
):
"""
Runs a command non-interactively
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
input_data(str): If passed, will feed that data to the subprocess
through stdin
out_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stdout
err_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stderr
env(dict of str:str): If set, will use the given dict as env for the
subprocess
**kwargs: Any other keyword args passed will be passed to the
:ref:subprocess.Popen call
Returns:
lago.utils.CommandStatus: result of the interactive execution
"""
if env is None:
env = os.environ.copy()
with LogTask(
'Run command: %s' % ' '.join('"%s"' % arg for arg in command),
logger=LOGGER,
level='debug',
) as task:
command_result = _run_command(
command=command,
input_data=input_data,
out_pipe=out_pipe,
err_pipe=err_pipe,
env=env,
uuid=task.uuid,
**kwargs
)
return command_result | python | def run_command(
command,
input_data=None,
out_pipe=subprocess.PIPE,
err_pipe=subprocess.PIPE,
env=None,
**kwargs
):
"""
Runs a command non-interactively
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
input_data(str): If passed, will feed that data to the subprocess
through stdin
out_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stdout
err_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stderr
env(dict of str:str): If set, will use the given dict as env for the
subprocess
**kwargs: Any other keyword args passed will be passed to the
:ref:subprocess.Popen call
Returns:
lago.utils.CommandStatus: result of the interactive execution
"""
if env is None:
env = os.environ.copy()
with LogTask(
'Run command: %s' % ' '.join('"%s"' % arg for arg in command),
logger=LOGGER,
level='debug',
) as task:
command_result = _run_command(
command=command,
input_data=input_data,
out_pipe=out_pipe,
err_pipe=err_pipe,
env=env,
uuid=task.uuid,
**kwargs
)
return command_result | [
"def",
"run_command",
"(",
"command",
",",
"input_data",
"=",
"None",
",",
"out_pipe",
"=",
"subprocess",
".",
"PIPE",
",",
"err_pipe",
"=",
"subprocess",
".",
"PIPE",
",",
"env",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"env",
"is",
"No... | Runs a command non-interactively
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
input_data(str): If passed, will feed that data to the subprocess
through stdin
out_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stdout
err_pipe(int or file): File descriptor as passed to
:ref:subprocess.Popen to use as stderr
env(dict of str:str): If set, will use the given dict as env for the
subprocess
**kwargs: Any other keyword args passed will be passed to the
:ref:subprocess.Popen call
Returns:
lago.utils.CommandStatus: result of the interactive execution | [
"Runs",
"a",
"command",
"non",
"-",
"interactively"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/utils.py#L202-L247 | train | 31,677 |
lago-project/lago | lago/utils.py | run_interactive_command | def run_interactive_command(command, env=None, **kwargs):
"""
Runs a command interactively, reusing the current stdin, stdout and stderr
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
env(dict of str:str): If set, will use the given dict as env for the
subprocess
**kwargs: Any other keyword args passed will be passed to the
:ref:subprocess.Popen call
Returns:
lago.utils.CommandStatus: result of the interactive execution
"""
command_result = _run_command(
command=command,
out_pipe=sys.stdout,
err_pipe=sys.stderr,
stdin=sys.stdin,
env=env,
**kwargs
)
return command_result | python | def run_interactive_command(command, env=None, **kwargs):
"""
Runs a command interactively, reusing the current stdin, stdout and stderr
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
env(dict of str:str): If set, will use the given dict as env for the
subprocess
**kwargs: Any other keyword args passed will be passed to the
:ref:subprocess.Popen call
Returns:
lago.utils.CommandStatus: result of the interactive execution
"""
command_result = _run_command(
command=command,
out_pipe=sys.stdout,
err_pipe=sys.stderr,
stdin=sys.stdin,
env=env,
**kwargs
)
return command_result | [
"def",
"run_interactive_command",
"(",
"command",
",",
"env",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"command_result",
"=",
"_run_command",
"(",
"command",
"=",
"command",
",",
"out_pipe",
"=",
"sys",
".",
"stdout",
",",
"err_pipe",
"=",
"sys",
... | Runs a command interactively, reusing the current stdin, stdout and stderr
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
env(dict of str:str): If set, will use the given dict as env for the
subprocess
**kwargs: Any other keyword args passed will be passed to the
:ref:subprocess.Popen call
Returns:
lago.utils.CommandStatus: result of the interactive execution | [
"Runs",
"a",
"command",
"interactively",
"reusing",
"the",
"current",
"stdin",
"stdout",
"and",
"stderr"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/utils.py#L250-L273 | train | 31,678 |
lago-project/lago | lago/utils.py | deepcopy | def deepcopy(original_obj):
"""
Creates a deep copy of an object with no crossed referenced lists or dicts,
useful when loading from yaml as anchors generate those cross-referenced
dicts and lists
Args:
original_obj(object): Object to deep copy
Return:
object: deep copy of the object
"""
if isinstance(original_obj, list):
return list(deepcopy(item) for item in original_obj)
elif isinstance(original_obj, dict):
return dict((key, deepcopy(val)) for key, val in original_obj.items())
else:
return original_obj | python | def deepcopy(original_obj):
"""
Creates a deep copy of an object with no crossed referenced lists or dicts,
useful when loading from yaml as anchors generate those cross-referenced
dicts and lists
Args:
original_obj(object): Object to deep copy
Return:
object: deep copy of the object
"""
if isinstance(original_obj, list):
return list(deepcopy(item) for item in original_obj)
elif isinstance(original_obj, dict):
return dict((key, deepcopy(val)) for key, val in original_obj.items())
else:
return original_obj | [
"def",
"deepcopy",
"(",
"original_obj",
")",
":",
"if",
"isinstance",
"(",
"original_obj",
",",
"list",
")",
":",
"return",
"list",
"(",
"deepcopy",
"(",
"item",
")",
"for",
"item",
"in",
"original_obj",
")",
"elif",
"isinstance",
"(",
"original_obj",
",",... | Creates a deep copy of an object with no crossed referenced lists or dicts,
useful when loading from yaml as anchors generate those cross-referenced
dicts and lists
Args:
original_obj(object): Object to deep copy
Return:
object: deep copy of the object | [
"Creates",
"a",
"deep",
"copy",
"of",
"an",
"object",
"with",
"no",
"crossed",
"referenced",
"lists",
"or",
"dicts",
"useful",
"when",
"loading",
"from",
"yaml",
"as",
"anchors",
"generate",
"those",
"cross",
"-",
"referenced",
"dicts",
"and",
"lists"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/utils.py#L493-L510 | train | 31,679 |
lago-project/lago | lago/utils.py | load_virt_stream | def load_virt_stream(virt_fd):
"""
Loads the given conf stream into a dict, trying different formats if
needed
Args:
virt_fd (str): file like objcect with the virt config to load
Returns:
dict: Loaded virt config
"""
try:
virt_conf = json.load(virt_fd)
except ValueError:
virt_fd.seek(0)
virt_conf = yaml.load(virt_fd)
return deepcopy(virt_conf) | python | def load_virt_stream(virt_fd):
"""
Loads the given conf stream into a dict, trying different formats if
needed
Args:
virt_fd (str): file like objcect with the virt config to load
Returns:
dict: Loaded virt config
"""
try:
virt_conf = json.load(virt_fd)
except ValueError:
virt_fd.seek(0)
virt_conf = yaml.load(virt_fd)
return deepcopy(virt_conf) | [
"def",
"load_virt_stream",
"(",
"virt_fd",
")",
":",
"try",
":",
"virt_conf",
"=",
"json",
".",
"load",
"(",
"virt_fd",
")",
"except",
"ValueError",
":",
"virt_fd",
".",
"seek",
"(",
"0",
")",
"virt_conf",
"=",
"yaml",
".",
"load",
"(",
"virt_fd",
")",... | Loads the given conf stream into a dict, trying different formats if
needed
Args:
virt_fd (str): file like objcect with the virt config to load
Returns:
dict: Loaded virt config | [
"Loads",
"the",
"given",
"conf",
"stream",
"into",
"a",
"dict",
"trying",
"different",
"formats",
"if",
"needed"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/utils.py#L513-L530 | train | 31,680 |
lago-project/lago | lago/utils.py | get_qemu_info | def get_qemu_info(path, backing_chain=False, fail_on_error=True):
"""
Get info on a given qemu disk
Args:
path(str): Path to the required disk
backing_chain(boo): if true, include also info about
the image predecessors.
Return:
object: if backing_chain == True then a list of dicts else a dict
"""
cmd = ['qemu-img', 'info', '--output=json', path]
if backing_chain:
cmd.insert(-1, '--backing-chain')
result = run_command_with_validation(
cmd, fail_on_error, msg='Failed to get info for {}'.format(path)
)
return json.loads(result.out) | python | def get_qemu_info(path, backing_chain=False, fail_on_error=True):
"""
Get info on a given qemu disk
Args:
path(str): Path to the required disk
backing_chain(boo): if true, include also info about
the image predecessors.
Return:
object: if backing_chain == True then a list of dicts else a dict
"""
cmd = ['qemu-img', 'info', '--output=json', path]
if backing_chain:
cmd.insert(-1, '--backing-chain')
result = run_command_with_validation(
cmd, fail_on_error, msg='Failed to get info for {}'.format(path)
)
return json.loads(result.out) | [
"def",
"get_qemu_info",
"(",
"path",
",",
"backing_chain",
"=",
"False",
",",
"fail_on_error",
"=",
"True",
")",
":",
"cmd",
"=",
"[",
"'qemu-img'",
",",
"'info'",
",",
"'--output=json'",
",",
"path",
"]",
"if",
"backing_chain",
":",
"cmd",
".",
"insert",
... | Get info on a given qemu disk
Args:
path(str): Path to the required disk
backing_chain(boo): if true, include also info about
the image predecessors.
Return:
object: if backing_chain == True then a list of dicts else a dict | [
"Get",
"info",
"on",
"a",
"given",
"qemu",
"disk"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/utils.py#L661-L682 | train | 31,681 |
lago-project/lago | lago/utils.py | get_hash | def get_hash(file_path, checksum='sha1'):
"""
Generate a hash for the given file
Args:
file_path (str): Path to the file to generate the hash for
checksum (str): hash to apply, one of the supported by hashlib, for
example sha1 or sha512
Returns:
str: hash for that file
"""
sha = getattr(hashlib, checksum)()
with open(file_path) as file_descriptor:
while True:
chunk = file_descriptor.read(65536)
if not chunk:
break
sha.update(chunk)
return sha.hexdigest() | python | def get_hash(file_path, checksum='sha1'):
"""
Generate a hash for the given file
Args:
file_path (str): Path to the file to generate the hash for
checksum (str): hash to apply, one of the supported by hashlib, for
example sha1 or sha512
Returns:
str: hash for that file
"""
sha = getattr(hashlib, checksum)()
with open(file_path) as file_descriptor:
while True:
chunk = file_descriptor.read(65536)
if not chunk:
break
sha.update(chunk)
return sha.hexdigest() | [
"def",
"get_hash",
"(",
"file_path",
",",
"checksum",
"=",
"'sha1'",
")",
":",
"sha",
"=",
"getattr",
"(",
"hashlib",
",",
"checksum",
")",
"(",
")",
"with",
"open",
"(",
"file_path",
")",
"as",
"file_descriptor",
":",
"while",
"True",
":",
"chunk",
"=... | Generate a hash for the given file
Args:
file_path (str): Path to the file to generate the hash for
checksum (str): hash to apply, one of the supported by hashlib, for
example sha1 or sha512
Returns:
str: hash for that file | [
"Generate",
"a",
"hash",
"for",
"the",
"given",
"file"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/utils.py#L749-L769 | train | 31,682 |
lago-project/lago | lago/utils.py | ver_cmp | def ver_cmp(ver1, ver2):
"""
Compare lago versions
Args:
ver1(str): version string
ver2(str): version string
Returns:
Return negative if ver1<ver2, zero if ver1==ver2, positive if
ver1>ver2.
"""
return cmp(
pkg_resources.parse_version(ver1), pkg_resources.parse_version(ver2)
) | python | def ver_cmp(ver1, ver2):
"""
Compare lago versions
Args:
ver1(str): version string
ver2(str): version string
Returns:
Return negative if ver1<ver2, zero if ver1==ver2, positive if
ver1>ver2.
"""
return cmp(
pkg_resources.parse_version(ver1), pkg_resources.parse_version(ver2)
) | [
"def",
"ver_cmp",
"(",
"ver1",
",",
"ver2",
")",
":",
"return",
"cmp",
"(",
"pkg_resources",
".",
"parse_version",
"(",
"ver1",
")",
",",
"pkg_resources",
".",
"parse_version",
"(",
"ver2",
")",
")"
] | Compare lago versions
Args:
ver1(str): version string
ver2(str): version string
Returns:
Return negative if ver1<ver2, zero if ver1==ver2, positive if
ver1>ver2. | [
"Compare",
"lago",
"versions"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/utils.py#L850-L865 | train | 31,683 |
lago-project/lago | lago/utils.py | Flock.acquire | def acquire(self):
"""Acquire the lock
Raises:
IOError: if the call to flock fails
"""
self._fd = open(self._path, mode='w+')
os.chmod(self._path, 0o660)
fcntl.flock(self._fd, self._op) | python | def acquire(self):
"""Acquire the lock
Raises:
IOError: if the call to flock fails
"""
self._fd = open(self._path, mode='w+')
os.chmod(self._path, 0o660)
fcntl.flock(self._fd, self._op) | [
"def",
"acquire",
"(",
"self",
")",
":",
"self",
".",
"_fd",
"=",
"open",
"(",
"self",
".",
"_path",
",",
"mode",
"=",
"'w+'",
")",
"os",
".",
"chmod",
"(",
"self",
".",
"_path",
",",
"0o660",
")",
"fcntl",
".",
"flock",
"(",
"self",
".",
"_fd"... | Acquire the lock
Raises:
IOError: if the call to flock fails | [
"Acquire",
"the",
"lock"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/utils.py#L392-L400 | train | 31,684 |
lago-project/lago | lago/plugins/output.py | FlatOutFormatPlugin.format | def format(self, info_dict, delimiter='/'):
"""
This formatter will take a data structure that
represent a tree and will print all the paths
from the root to the leaves
in our case it will print each value and the keys
that needed to get to it, for example:
vm0:
net: lago
memory: 1024
will be output as:
vm0/net/lago
vm0/memory/1024
Args:
info_dict (dict): information to reformat
delimiter (str): a delimiter for the path components
Returns:
str: String representing the formatted info
"""
def dfs(father, path, acc):
if isinstance(father, list):
for child in father:
dfs(child, path, acc)
elif isinstance(father, collections.Mapping):
for child in sorted(father.items(), key=itemgetter(0)), :
dfs(child, path, acc)
elif isinstance(father, tuple):
path = copy.copy(path)
path.append(father[0])
dfs(father[1], path, acc)
else:
# join the last key with it's value
path[-1] = '{}: {}'.format(path[-1], str(father))
acc.append(delimiter.join(path))
result = []
dfs(info_dict.get('Prefix') or info_dict, [], result)
return '\n'.join(result) | python | def format(self, info_dict, delimiter='/'):
"""
This formatter will take a data structure that
represent a tree and will print all the paths
from the root to the leaves
in our case it will print each value and the keys
that needed to get to it, for example:
vm0:
net: lago
memory: 1024
will be output as:
vm0/net/lago
vm0/memory/1024
Args:
info_dict (dict): information to reformat
delimiter (str): a delimiter for the path components
Returns:
str: String representing the formatted info
"""
def dfs(father, path, acc):
if isinstance(father, list):
for child in father:
dfs(child, path, acc)
elif isinstance(father, collections.Mapping):
for child in sorted(father.items(), key=itemgetter(0)), :
dfs(child, path, acc)
elif isinstance(father, tuple):
path = copy.copy(path)
path.append(father[0])
dfs(father[1], path, acc)
else:
# join the last key with it's value
path[-1] = '{}: {}'.format(path[-1], str(father))
acc.append(delimiter.join(path))
result = []
dfs(info_dict.get('Prefix') or info_dict, [], result)
return '\n'.join(result) | [
"def",
"format",
"(",
"self",
",",
"info_dict",
",",
"delimiter",
"=",
"'/'",
")",
":",
"def",
"dfs",
"(",
"father",
",",
"path",
",",
"acc",
")",
":",
"if",
"isinstance",
"(",
"father",
",",
"list",
")",
":",
"for",
"child",
"in",
"father",
":",
... | This formatter will take a data structure that
represent a tree and will print all the paths
from the root to the leaves
in our case it will print each value and the keys
that needed to get to it, for example:
vm0:
net: lago
memory: 1024
will be output as:
vm0/net/lago
vm0/memory/1024
Args:
info_dict (dict): information to reformat
delimiter (str): a delimiter for the path components
Returns:
str: String representing the formatted info | [
"This",
"formatter",
"will",
"take",
"a",
"data",
"structure",
"that",
"represent",
"a",
"tree",
"and",
"will",
"print",
"all",
"the",
"paths",
"from",
"the",
"root",
"to",
"the",
"leaves"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/plugins/output.py#L111-L155 | train | 31,685 |
lago-project/lago | lago/workdir.py | workdir_loaded | def workdir_loaded(func):
"""
Decorator to make sure that the workdir is loaded when calling the
decorated function
"""
@wraps(func)
def decorator(workdir, *args, **kwargs):
if not workdir.loaded:
workdir.load()
return func(workdir, *args, **kwargs)
return decorator | python | def workdir_loaded(func):
"""
Decorator to make sure that the workdir is loaded when calling the
decorated function
"""
@wraps(func)
def decorator(workdir, *args, **kwargs):
if not workdir.loaded:
workdir.load()
return func(workdir, *args, **kwargs)
return decorator | [
"def",
"workdir_loaded",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"decorator",
"(",
"workdir",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"workdir",
".",
"loaded",
":",
"workdir",
".",
"load",
"(",
")",
... | Decorator to make sure that the workdir is loaded when calling the
decorated function | [
"Decorator",
"to",
"make",
"sure",
"that",
"the",
"workdir",
"is",
"loaded",
"when",
"calling",
"the",
"decorated",
"function"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/workdir.py#L63-L76 | train | 31,686 |
lago-project/lago | lago/workdir.py | Workdir.initialize | def initialize(self, prefix_name='default', *args, **kwargs):
"""
Initializes a workdir by adding a new prefix to the workdir.
Args:
prefix_name(str): Name of the new prefix to add
*args: args to pass along to the prefix constructor
*kwargs: kwargs to pass along to the prefix constructor
Returns:
The newly created prefix
Raises:
PrefixAlreadyExists: if the prefix name already exists in the
workdir
"""
if self.loaded:
raise WorkdirError('Workdir %s already initialized' % self.path)
if not os.path.exists(self.path):
LOGGER.debug('Creating workdir %s', self.path)
os.makedirs(self.path)
self.prefixes[prefix_name] = self.prefix_class(
self.join(prefix_name), *args, **kwargs
)
self.prefixes[prefix_name].initialize()
if self.current is None:
self._set_current(prefix_name)
self.load()
return self.prefixes[prefix_name] | python | def initialize(self, prefix_name='default', *args, **kwargs):
"""
Initializes a workdir by adding a new prefix to the workdir.
Args:
prefix_name(str): Name of the new prefix to add
*args: args to pass along to the prefix constructor
*kwargs: kwargs to pass along to the prefix constructor
Returns:
The newly created prefix
Raises:
PrefixAlreadyExists: if the prefix name already exists in the
workdir
"""
if self.loaded:
raise WorkdirError('Workdir %s already initialized' % self.path)
if not os.path.exists(self.path):
LOGGER.debug('Creating workdir %s', self.path)
os.makedirs(self.path)
self.prefixes[prefix_name] = self.prefix_class(
self.join(prefix_name), *args, **kwargs
)
self.prefixes[prefix_name].initialize()
if self.current is None:
self._set_current(prefix_name)
self.load()
return self.prefixes[prefix_name] | [
"def",
"initialize",
"(",
"self",
",",
"prefix_name",
"=",
"'default'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"loaded",
":",
"raise",
"WorkdirError",
"(",
"'Workdir %s already initialized'",
"%",
"self",
".",
"path",
")",
... | Initializes a workdir by adding a new prefix to the workdir.
Args:
prefix_name(str): Name of the new prefix to add
*args: args to pass along to the prefix constructor
*kwargs: kwargs to pass along to the prefix constructor
Returns:
The newly created prefix
Raises:
PrefixAlreadyExists: if the prefix name already exists in the
workdir | [
"Initializes",
"a",
"workdir",
"by",
"adding",
"a",
"new",
"prefix",
"to",
"the",
"workdir",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/workdir.py#L111-L143 | train | 31,687 |
lago-project/lago | lago/workdir.py | Workdir.load | def load(self):
"""
Loads the prefixes that are available is the workdir
Returns:
None
Raises:
MalformedWorkdir: if the wordir is malformed
"""
if self.loaded:
LOGGER.debug('Already loaded')
return
try:
basepath, dirs, _ = os.walk(self.path).next()
except StopIteration:
raise MalformedWorkdir('Empty dir %s' % self.path)
full_path = partial(os.path.join, basepath)
found_current = False
for dirname in dirs:
if dirname == 'current' and os.path.islink(full_path('current')):
self.current = os.path.basename(
os.readlink(full_path('current'))
)
found_current = True
continue
elif dirname == 'current':
raise MalformedWorkdir(
'"%s/current" should be a soft link' % self.path
)
self.prefixes[dirname] = self.prefix_class(
prefix=self.join(dirname)
)
if not found_current:
raise MalformedWorkdir(
'"%s/current" should exist and be a soft link' % self.path
)
self._update_current() | python | def load(self):
"""
Loads the prefixes that are available is the workdir
Returns:
None
Raises:
MalformedWorkdir: if the wordir is malformed
"""
if self.loaded:
LOGGER.debug('Already loaded')
return
try:
basepath, dirs, _ = os.walk(self.path).next()
except StopIteration:
raise MalformedWorkdir('Empty dir %s' % self.path)
full_path = partial(os.path.join, basepath)
found_current = False
for dirname in dirs:
if dirname == 'current' and os.path.islink(full_path('current')):
self.current = os.path.basename(
os.readlink(full_path('current'))
)
found_current = True
continue
elif dirname == 'current':
raise MalformedWorkdir(
'"%s/current" should be a soft link' % self.path
)
self.prefixes[dirname] = self.prefix_class(
prefix=self.join(dirname)
)
if not found_current:
raise MalformedWorkdir(
'"%s/current" should exist and be a soft link' % self.path
)
self._update_current() | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"self",
".",
"loaded",
":",
"LOGGER",
".",
"debug",
"(",
"'Already loaded'",
")",
"return",
"try",
":",
"basepath",
",",
"dirs",
",",
"_",
"=",
"os",
".",
"walk",
"(",
"self",
".",
"path",
")",
".",
"ne... | Loads the prefixes that are available is the workdir
Returns:
None
Raises:
MalformedWorkdir: if the wordir is malformed | [
"Loads",
"the",
"prefixes",
"that",
"are",
"available",
"is",
"the",
"workdir"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/workdir.py#L145-L188 | train | 31,688 |
lago-project/lago | lago/workdir.py | Workdir._update_current | def _update_current(self):
"""
Makes sure that a current is set
"""
if not self.current or self.current not in self.prefixes:
if 'default' in self.prefixes:
selected_current = 'default'
elif self.prefixes:
selected_current = sorted(self.prefixes.keys()).pop()
else:
# should never get here
raise MalformedWorkdir(
'No current link and no prefixes in workdir %s' % self.path
)
logging.info(
'Missing current link, setting it to %s',
selected_current,
)
self._set_current(selected_current) | python | def _update_current(self):
"""
Makes sure that a current is set
"""
if not self.current or self.current not in self.prefixes:
if 'default' in self.prefixes:
selected_current = 'default'
elif self.prefixes:
selected_current = sorted(self.prefixes.keys()).pop()
else:
# should never get here
raise MalformedWorkdir(
'No current link and no prefixes in workdir %s' % self.path
)
logging.info(
'Missing current link, setting it to %s',
selected_current,
)
self._set_current(selected_current) | [
"def",
"_update_current",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"current",
"or",
"self",
".",
"current",
"not",
"in",
"self",
".",
"prefixes",
":",
"if",
"'default'",
"in",
"self",
".",
"prefixes",
":",
"selected_current",
"=",
"'default'",
"e... | Makes sure that a current is set | [
"Makes",
"sure",
"that",
"a",
"current",
"is",
"set"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/workdir.py#L190-L209 | train | 31,689 |
lago-project/lago | lago/workdir.py | Workdir._set_current | def _set_current(self, new_current):
"""
Change the current default prefix, for internal usage
Args:
new_current(str): Name of the new current prefix, it must already
exist
Returns:
None
Raises:
PrefixNotFound: if the given prefix name does not exist in the
workdir
"""
new_cur_full_path = self.join(new_current)
if not os.path.exists(new_cur_full_path):
raise PrefixNotFound(
'Prefix "%s" does not exist in workdir %s' %
(new_current, self.path)
)
if os.path.lexists(self.join('current')):
os.unlink(self.join('current'))
os.symlink(new_current, self.join('current'))
self.current = new_current | python | def _set_current(self, new_current):
"""
Change the current default prefix, for internal usage
Args:
new_current(str): Name of the new current prefix, it must already
exist
Returns:
None
Raises:
PrefixNotFound: if the given prefix name does not exist in the
workdir
"""
new_cur_full_path = self.join(new_current)
if not os.path.exists(new_cur_full_path):
raise PrefixNotFound(
'Prefix "%s" does not exist in workdir %s' %
(new_current, self.path)
)
if os.path.lexists(self.join('current')):
os.unlink(self.join('current'))
os.symlink(new_current, self.join('current'))
self.current = new_current | [
"def",
"_set_current",
"(",
"self",
",",
"new_current",
")",
":",
"new_cur_full_path",
"=",
"self",
".",
"join",
"(",
"new_current",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"new_cur_full_path",
")",
":",
"raise",
"PrefixNotFound",
"(",
"'P... | Change the current default prefix, for internal usage
Args:
new_current(str): Name of the new current prefix, it must already
exist
Returns:
None
Raises:
PrefixNotFound: if the given prefix name does not exist in the
workdir | [
"Change",
"the",
"current",
"default",
"prefix",
"for",
"internal",
"usage"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/workdir.py#L211-L237 | train | 31,690 |
lago-project/lago | lago/workdir.py | Workdir.add_prefix | def add_prefix(self, name, *args, **kwargs):
"""
Adds a new prefix to the workdir.
Args:
name(str): Name of the new prefix to add
*args: args to pass along to the prefix constructor
*kwargs: kwargs to pass along to the prefix constructor
Returns:
The newly created prefix
Raises:
LagoPrefixAlreadyExistsError: if prefix name already exists in the
workdir
"""
if os.path.exists(self.join(name)):
raise LagoPrefixAlreadyExistsError(name, self.path)
self.prefixes[name] = self.prefix_class(
self.join(name), *args, **kwargs
)
self.prefixes[name].initialize()
if self.current is None:
self.set_current(name)
return self.prefixes[name] | python | def add_prefix(self, name, *args, **kwargs):
"""
Adds a new prefix to the workdir.
Args:
name(str): Name of the new prefix to add
*args: args to pass along to the prefix constructor
*kwargs: kwargs to pass along to the prefix constructor
Returns:
The newly created prefix
Raises:
LagoPrefixAlreadyExistsError: if prefix name already exists in the
workdir
"""
if os.path.exists(self.join(name)):
raise LagoPrefixAlreadyExistsError(name, self.path)
self.prefixes[name] = self.prefix_class(
self.join(name), *args, **kwargs
)
self.prefixes[name].initialize()
if self.current is None:
self.set_current(name)
return self.prefixes[name] | [
"def",
"add_prefix",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"join",
"(",
"name",
")",
")",
":",
"raise",
"LagoPrefixAlreadyExistsError",
"(",
"name",
... | Adds a new prefix to the workdir.
Args:
name(str): Name of the new prefix to add
*args: args to pass along to the prefix constructor
*kwargs: kwargs to pass along to the prefix constructor
Returns:
The newly created prefix
Raises:
LagoPrefixAlreadyExistsError: if prefix name already exists in the
workdir | [
"Adds",
"a",
"new",
"prefix",
"to",
"the",
"workdir",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/workdir.py#L258-L284 | train | 31,691 |
lago-project/lago | lago/workdir.py | Workdir.get_prefix | def get_prefix(self, name):
"""
Retrieve a prefix, resolving the current one if needed
Args:
name(str): name of the prefix to retrieve, or current to get the
current one
Returns:
self.prefix_class: instance of the prefix with the given name
"""
if name == 'current':
name = self.current
try:
return self.prefixes[name]
except KeyError:
raise KeyError(
'Unable to find prefix "%s" in workdir %s' % (name, self.path)
) | python | def get_prefix(self, name):
"""
Retrieve a prefix, resolving the current one if needed
Args:
name(str): name of the prefix to retrieve, or current to get the
current one
Returns:
self.prefix_class: instance of the prefix with the given name
"""
if name == 'current':
name = self.current
try:
return self.prefixes[name]
except KeyError:
raise KeyError(
'Unable to find prefix "%s" in workdir %s' % (name, self.path)
) | [
"def",
"get_prefix",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"==",
"'current'",
":",
"name",
"=",
"self",
".",
"current",
"try",
":",
"return",
"self",
".",
"prefixes",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
... | Retrieve a prefix, resolving the current one if needed
Args:
name(str): name of the prefix to retrieve, or current to get the
current one
Returns:
self.prefix_class: instance of the prefix with the given name | [
"Retrieve",
"a",
"prefix",
"resolving",
"the",
"current",
"one",
"if",
"needed"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/workdir.py#L287-L306 | train | 31,692 |
lago-project/lago | lago/workdir.py | Workdir.destroy | def destroy(self, prefix_names=None):
"""
Destroy all the given prefixes and remove any left files if no more
prefixes are left
Args:
prefix_names(list of str): list of prefix names to destroy, if None
passed (default) will destroy all of them
"""
if prefix_names is None:
self.destroy(prefix_names=self.prefixes.keys())
return
for prefix_name in prefix_names:
if prefix_name == 'current' and self.current in prefix_names:
continue
elif prefix_name == 'current':
prefix_name = self.current
self.get_prefix(prefix_name).destroy()
self.prefixes.pop(prefix_name)
if self.prefixes:
self._update_current()
if not self.prefixes:
shutil.rmtree(self.path) | python | def destroy(self, prefix_names=None):
"""
Destroy all the given prefixes and remove any left files if no more
prefixes are left
Args:
prefix_names(list of str): list of prefix names to destroy, if None
passed (default) will destroy all of them
"""
if prefix_names is None:
self.destroy(prefix_names=self.prefixes.keys())
return
for prefix_name in prefix_names:
if prefix_name == 'current' and self.current in prefix_names:
continue
elif prefix_name == 'current':
prefix_name = self.current
self.get_prefix(prefix_name).destroy()
self.prefixes.pop(prefix_name)
if self.prefixes:
self._update_current()
if not self.prefixes:
shutil.rmtree(self.path) | [
"def",
"destroy",
"(",
"self",
",",
"prefix_names",
"=",
"None",
")",
":",
"if",
"prefix_names",
"is",
"None",
":",
"self",
".",
"destroy",
"(",
"prefix_names",
"=",
"self",
".",
"prefixes",
".",
"keys",
"(",
")",
")",
"return",
"for",
"prefix_name",
"... | Destroy all the given prefixes and remove any left files if no more
prefixes are left
Args:
prefix_names(list of str): list of prefix names to destroy, if None
passed (default) will destroy all of them | [
"Destroy",
"all",
"the",
"given",
"prefixes",
"and",
"remove",
"any",
"left",
"files",
"if",
"no",
"more",
"prefixes",
"are",
"left"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/workdir.py#L309-L335 | train | 31,693 |
lago-project/lago | lago/workdir.py | Workdir.is_workdir | def is_workdir(cls, path):
"""
Check if the given path is a workdir
Args:
path(str): Path to check
Return:
bool: True if the given path is a workdir
"""
try:
cls(path=path).load()
except MalformedWorkdir:
return False
return True | python | def is_workdir(cls, path):
"""
Check if the given path is a workdir
Args:
path(str): Path to check
Return:
bool: True if the given path is a workdir
"""
try:
cls(path=path).load()
except MalformedWorkdir:
return False
return True | [
"def",
"is_workdir",
"(",
"cls",
",",
"path",
")",
":",
"try",
":",
"cls",
"(",
"path",
"=",
"path",
")",
".",
"load",
"(",
")",
"except",
"MalformedWorkdir",
":",
"return",
"False",
"return",
"True"
] | Check if the given path is a workdir
Args:
path(str): Path to check
Return:
bool: True if the given path is a workdir | [
"Check",
"if",
"the",
"given",
"path",
"is",
"a",
"workdir"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/workdir.py#L432-L447 | train | 31,694 |
lago-project/lago | lago/workdir.py | Workdir.cleanup | def cleanup(self):
"""
Attempt to set a new current symlink if it is broken. If no other
prefixes exist and the workdir is empty, try to delete the entire
workdir.
Raises:
:exc:`~MalformedWorkdir`: if no prefixes were found, but the
workdir is not empty.
"""
current = self.join('current')
if not os.path.exists(current):
LOGGER.debug('found broken current symlink, removing: %s', current)
os.unlink(self.join('current'))
self.current = None
try:
self._update_current()
except PrefixNotFound:
if not os.listdir(self.path):
LOGGER.debug('workdir is empty, removing %s', self.path)
os.rmdir(self.path)
else:
raise MalformedWorkdir(
(
'Unable to find any prefixes in {0}, '
'but the directory looks malformed. '
'Try deleting it manually.'
).format(self.path)
) | python | def cleanup(self):
"""
Attempt to set a new current symlink if it is broken. If no other
prefixes exist and the workdir is empty, try to delete the entire
workdir.
Raises:
:exc:`~MalformedWorkdir`: if no prefixes were found, but the
workdir is not empty.
"""
current = self.join('current')
if not os.path.exists(current):
LOGGER.debug('found broken current symlink, removing: %s', current)
os.unlink(self.join('current'))
self.current = None
try:
self._update_current()
except PrefixNotFound:
if not os.listdir(self.path):
LOGGER.debug('workdir is empty, removing %s', self.path)
os.rmdir(self.path)
else:
raise MalformedWorkdir(
(
'Unable to find any prefixes in {0}, '
'but the directory looks malformed. '
'Try deleting it manually.'
).format(self.path)
) | [
"def",
"cleanup",
"(",
"self",
")",
":",
"current",
"=",
"self",
".",
"join",
"(",
"'current'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"current",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'found broken current symlink, removing: %s'",
",",
... | Attempt to set a new current symlink if it is broken. If no other
prefixes exist and the workdir is empty, try to delete the entire
workdir.
Raises:
:exc:`~MalformedWorkdir`: if no prefixes were found, but the
workdir is not empty. | [
"Attempt",
"to",
"set",
"a",
"new",
"current",
"symlink",
"if",
"it",
"is",
"broken",
".",
"If",
"no",
"other",
"prefixes",
"exist",
"and",
"the",
"workdir",
"is",
"empty",
"try",
"to",
"delete",
"the",
"entire",
"workdir",
"."
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/workdir.py#L449-L478 | train | 31,695 |
lago-project/lago | lago/plugins/__init__.py | _load_plugins | def _load_plugins(namespace, instantiate=True):
"""
Loads all the plugins for the given namespace
Args:
namespace(str): Namespace string, as in the setuptools entry_points
instantiate(bool): If true, will instantiate the plugins too
Returns:
dict of str, object: Returns the list of loaded plugins
"""
mgr = ExtensionManager(
namespace=namespace,
on_load_failure_callback=(
lambda _, ep, err: LOGGER.
warning('Could not load plugin {}: {}'.format(ep.name, err))
)
)
if instantiate:
plugins = dict(
(
ext.name,
ext.plugin if isinstance(ext.plugin, Plugin) else ext.plugin()
) for ext in mgr
)
else:
plugins = dict((ext.name, ext.plugin) for ext in mgr)
return plugins | python | def _load_plugins(namespace, instantiate=True):
"""
Loads all the plugins for the given namespace
Args:
namespace(str): Namespace string, as in the setuptools entry_points
instantiate(bool): If true, will instantiate the plugins too
Returns:
dict of str, object: Returns the list of loaded plugins
"""
mgr = ExtensionManager(
namespace=namespace,
on_load_failure_callback=(
lambda _, ep, err: LOGGER.
warning('Could not load plugin {}: {}'.format(ep.name, err))
)
)
if instantiate:
plugins = dict(
(
ext.name,
ext.plugin if isinstance(ext.plugin, Plugin) else ext.plugin()
) for ext in mgr
)
else:
plugins = dict((ext.name, ext.plugin) for ext in mgr)
return plugins | [
"def",
"_load_plugins",
"(",
"namespace",
",",
"instantiate",
"=",
"True",
")",
":",
"mgr",
"=",
"ExtensionManager",
"(",
"namespace",
"=",
"namespace",
",",
"on_load_failure_callback",
"=",
"(",
"lambda",
"_",
",",
"ep",
",",
"err",
":",
"LOGGER",
".",
"w... | Loads all the plugins for the given namespace
Args:
namespace(str): Namespace string, as in the setuptools entry_points
instantiate(bool): If true, will instantiate the plugins too
Returns:
dict of str, object: Returns the list of loaded plugins | [
"Loads",
"all",
"the",
"plugins",
"for",
"the",
"given",
"namespace"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/plugins/__init__.py#L71-L99 | train | 31,696 |
lago-project/lago | lago/prefix.py | Prefix.metadata | def metadata(self):
"""
Retrieve the metadata info for this prefix
Returns:
dict: metadata info
"""
if self._metadata is None:
try:
with open(self.paths.metadata()) as metadata_fd:
self._metadata = json.load(metadata_fd)
except IOError:
self._metadata = {}
return self._metadata | python | def metadata(self):
"""
Retrieve the metadata info for this prefix
Returns:
dict: metadata info
"""
if self._metadata is None:
try:
with open(self.paths.metadata()) as metadata_fd:
self._metadata = json.load(metadata_fd)
except IOError:
self._metadata = {}
return self._metadata | [
"def",
"metadata",
"(",
"self",
")",
":",
"if",
"self",
".",
"_metadata",
"is",
"None",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"paths",
".",
"metadata",
"(",
")",
")",
"as",
"metadata_fd",
":",
"self",
".",
"_metadata",
"=",
"json",
"."... | Retrieve the metadata info for this prefix
Returns:
dict: metadata info | [
"Retrieve",
"the",
"metadata",
"info",
"for",
"this",
"prefix"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L118-L131 | train | 31,697 |
lago-project/lago | lago/prefix.py | Prefix._save_metadata | def _save_metadata(self):
"""
Write this prefix metadata to disk
Returns:
None
"""
with open(self.paths.metadata(), 'w') as metadata_fd:
utils.json_dump(self.metadata, metadata_fd) | python | def _save_metadata(self):
"""
Write this prefix metadata to disk
Returns:
None
"""
with open(self.paths.metadata(), 'w') as metadata_fd:
utils.json_dump(self.metadata, metadata_fd) | [
"def",
"_save_metadata",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"paths",
".",
"metadata",
"(",
")",
",",
"'w'",
")",
"as",
"metadata_fd",
":",
"utils",
".",
"json_dump",
"(",
"self",
".",
"metadata",
",",
"metadata_fd",
")"
] | Write this prefix metadata to disk
Returns:
None | [
"Write",
"this",
"prefix",
"metadata",
"to",
"disk"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L133-L141 | train | 31,698 |
lago-project/lago | lago/prefix.py | Prefix.save | def save(self):
"""
Save this prefix to persistent storage
Returns:
None
"""
if not os.path.exists(self.paths.virt()):
os.makedirs(self.paths.virt())
self._save_metadata()
self.virt_env.save() | python | def save(self):
"""
Save this prefix to persistent storage
Returns:
None
"""
if not os.path.exists(self.paths.virt()):
os.makedirs(self.paths.virt())
self._save_metadata()
self.virt_env.save() | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"paths",
".",
"virt",
"(",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"paths",
".",
"virt",
"(",
")",
")",
"self",
".",
"_save... | Save this prefix to persistent storage
Returns:
None | [
"Save",
"this",
"prefix",
"to",
"persistent",
"storage"
] | 5b8970f7687e063e4619066d5b8093ca997678c9 | https://github.com/lago-project/lago/blob/5b8970f7687e063e4619066d5b8093ca997678c9/lago/prefix.py#L143-L154 | train | 31,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.