docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Return the hourly offset(s) of a (list of) time from a given time.
Arguments:
t0 -- time from which offsets are sought
t -- times to find hourly offsets from t0. | def _hours(t0, t):
if not isinstance(t, Iterable):
return Tide._hours(t0, [t])[0]
elif isinstance(t[0], datetime):
return np.array([(ti-t0).total_seconds() / 3600.0 for ti in t])
else:
return t | 558,413 |
Partition a sorted list of numbers (or in this case hours).
Arguments:
hours -- sorted ndarray of hours.
partition -- maximum partition length (default: 3600.0) | def _partition(hours, partition = 3600.0):
partition = float(partition)
relative = hours - hours[0]
total_partitions = np.ceil(relative[-1] / partition + 10*np.finfo(np.float).eps).astype('int')
return [hours[np.floor(np.divide(relative, partition)) == i] for i in range(total_partitions)] | 558,414 |
Return a (list of) datetime(s) given an initial time and an (list of) hourly offset(s).
Arguments:
t0 -- initial time
hours -- hourly offsets from t0 | def _times(t0, hours):
if not isinstance(hours, Iterable):
return Tide._times(t0, [hours])[0]
elif not isinstance(hours[0], datetime):
return np.array([t0 + timedelta(hours=h) for h in hours])
else:
return np.array(hours) | 558,415 |
Parses string as toml
Args:
s: String to be parsed
_dict: (optional) Specifies the class of the returned toml dictionary
Returns:
Parsed toml file represented as a dictionary
Raises:
TypeError: When a non-string is passed
TomlDecodeError: Error while decoding toml | def loads(s, _dict=dict):
implicitgroups = []
retval = _dict()
currentlevel = retval
if not isinstance(s, basestring):
raise TypeError("Expecting something like a string")
if not isinstance(s, unicode):
s = s.decode('utf8')
sl = list(s)
openarr = 0
openstring = Fa... | 558,419 |
Stringifies input dict as toml
Args:
o: Object to dump into toml
preserve: Boolean parameter. If true, preserve inline tables.
Returns:
String containing the toml corresponding to dict | def dumps(o, preserve=False):
retval = ""
addtoretval, sections = _dump_sections(o, "")
retval += addtoretval
while sections != {}:
newsections = {}
for section in sections:
addtoretval, addtosections = _dump_sections(sections[section],
... | 558,428 |
Replace logger's handlers with a queue handler while adding existing
handlers to a queue listener.
This is useful when you want to use a default logging config but then
optionally add a logger's handlers to a queue during runtime.
Args:
logger (mixed): Logger instance or string name of logger ... | def queuify_logger(logger, queue_handler, queue_listener):
if isinstance(logger, str):
logger = logging.getLogger(logger)
# Get handlers that aren't being listened for.
handlers = [handler for handler in logger.handlers
if handler not in queue_listener.handlers]
if handler... | 558,695 |
Set the brightness of the LED to `brightness`.
`brightness` can be a boolean for on/off, or integer value for a
specific brightness.
Args:
brightness (bool, int): Brightness value to set.
Raises:
LEDError: if an I/O or OS error occurs.
TypeError: if... | def write(self, brightness):
if not isinstance(brightness, (bool, int)):
raise TypeError("Invalid brightness type, should be bool or int.")
if isinstance(brightness, bool):
brightness = self._max_brightness if brightness else 0
else:
if not 0 <= brig... | 558,886 |
Instantiate an I2C object and open the i2c-dev device at the
specified path.
Args:
devpath (str): i2c-dev device path.
Returns:
I2C: I2C object.
Raises:
I2CError: if an I/O or OS error occurs. | def __init__(self, devpath):
self._fd = None
self._devpath = None
self._open(devpath) | 558,888 |
Transfer `messages` to the specified I2C `address`. Modifies the
`messages` array with the results of any read transactions.
Args:
address (int): I2C address.
messages (list): list of I2C.Message messages.
Raises:
I2CError: if an I/O or OS error occurs.
... | def transfer(self, address, messages):
if not isinstance(messages, list):
raise TypeError("Invalid messages type, should be list of I2C.Message.")
elif len(messages) == 0:
raise ValueError("Invalid messages data, should be non-zero length.")
# Convert I2C.Messag... | 558,890 |
Instantiate a PWM object and open the sysfs PWM corresponding to the
specified channel and pin.
Args:
channel (int): Linux channel number.
pin (int): Linux pin number.
Returns:
PWM: PWM object.
Raises:
PWMError: if an I/O or OS error occ... | def __init__(self, channel, pin):
self._channel = None
self._pin = None
self._open(channel, pin) | 558,891 |
Write `data` to the serial port and return the number of bytes
written.
Args:
data (bytes, bytearray, list): a byte array or list of 8-bit integers to write.
Returns:
int: number of bytes written.
Raises:
SerialError: if an I/O or OS error occurs.
... | def write(self, data):
if not isinstance(data, (bytes, bytearray, list)):
raise TypeError("Invalid data type, should be bytes, bytearray, or list.")
if isinstance(data, list):
data = bytearray(data)
try:
return os.write(self._fd, data)
excep... | 558,907 |
Poll for data available for reading from the serial port.
`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking poll, or negative or None for a blocking poll. Default is
a blocking poll.
Args:
timeout (int, float, None): timeout duration in seconds.
... | def poll(self, timeout=None):
p = select.poll()
p.register(self._fd, select.POLLIN | select.POLLPRI)
events = p.poll(int(timeout * 1000))
if len(events) > 0:
return True
return False | 558,908 |
Set the state of the GPIO to `value`.
Args:
value (bool): ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs.
TypeError: if `value` type is not bool. | def write(self, value):
if not isinstance(value, bool):
raise TypeError("Invalid value type, should be bool.")
# Write value
try:
if value:
os.write(self._fd, b"1\n")
else:
os.write(self._fd, b"0\n")
except OSE... | 558,928 |
Instantiate an MMIO object and map the region of physical memory
specified by the address base `physaddr` and size `size` in bytes.
Args:
physaddr (int, long): base physical address of memory region.
size (int, long): size of memory region.
Returns:
MMIO: MM... | def __init__(self, physaddr, size):
self.mapping = None
self._open(physaddr, size) | 558,935 |
Read 32-bits from the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
Returns:
int: 32-bit value read.
Raises:
TypeError: if `offset` type ... | def read32(self, offset):
if not isinstance(offset, (int, long)):
raise TypeError("Invalid offset type, should be integer.")
offset = self._adjust_offset(offset)
self._validate_offset(offset, 4)
return struct.unpack("=L", self.mapping[offset:offset + 4])[0] | 558,937 |
Read a string of bytes from the specified `offset` in bytes,
relative to the base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
length (int): number of bytes to read.
Returns:
bytes: bytes read.
... | def read(self, offset, length):
if not isinstance(offset, (int, long)):
raise TypeError("Invalid offset type, should be integer.")
offset = self._adjust_offset(offset)
self._validate_offset(offset, length)
return bytes(self.mapping[offset:offset + length]) | 558,938 |
Write 8-bits to the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
value (int, long): 8-bit value to write.
Raises:
TypeError: if `offset` or `valu... | def write8(self, offset, value):
if not isinstance(offset, (int, long)):
raise TypeError("Invalid offset type, should be integer.")
if not isinstance(value, (int, long)):
raise TypeError("Invalid value type, should be integer.")
if value < 0 or value > 0xff:
... | 558,939 |
Shift out `data` and return shifted in data.
Args:
data (bytes, bytearray, list): a byte array or list of 8-bit integers to shift out.
Returns:
bytes, bytearray, list: data shifted in.
Raises:
SPIError: if an I/O or OS error occurs.
TypeError: i... | def transfer(self, data):
if not isinstance(data, (bytes, bytearray, list)):
raise TypeError("Invalid data type, should be bytes, bytearray, or list.")
# Create mutable array
try:
buf = array.array('B', data)
except OverflowError:
raise Value... | 558,945 |
Return an LDAP entry by DN
Args:
ldap_dn (str): LDAP DN | def get(self, ldap_dn):
self.base_dn = ldap_dn
self.sub_tree = BASE
return self.first() | 559,053 |
Set the query filter to perform the query with
Args:
*query_filter: Simplified Query Language filter | def filter(self, *query_filter):
for query in query_filter:
self.query.append(query)
return self | 559,054 |
Decorator to be used with :class:`SDKWrapper`. This decorator indicates
that the wrapped method or class should be exposed in the proxied object.
Args:
func(types.FunctionType/types.MethodType): function to decorate
Returns:
None | def expose(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
return func(*args, **kwargs)
if inspect.isclass(func):
wrapped._sdkmetaclass = SDKMethod(func.__name__)
else:
wrapped._sdkmeta = SDKMethod(func.__name__)
return wrapped | 559,100 |
Filter SDK attributes
Args:
attr(attribute): Attribute as returned by :func:`getattr`.
name(str): Attribute name.
Returns:
`attr` if passed. | def getattr_sdk(attr, name):
if inspect.isroutine(attr):
if hasattr(attr, '_sdkmeta'):
return attr
raise AttributeError(name) | 559,101 |
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 | def setup_sdk_logging(logfile=None, loglevel=logging.INFO):
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.... | 559,102 |
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 | def get_domain_template(distro, libvirt_ver, **kwargs):
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(... | 559,117 |
Convert dict to XML
Args:
spec(dict): dict to convert
full_document(bool): whether to add XML headers
Returns:
lxml.etree.Element: XML tree | def dict_to_xml(spec, full_document=False):
middle = xmltodict.unparse(spec, full_document=full_document, pretty=True)
return lxml.etree.fromstring(middle) | 559,118 |
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 | def guestfs_conn_ro(disk):
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)
... | 559,119 |
Extract the given paths from the domain
Args:
paths(list of str): paths to extract
ignore_nopath(boolean): if True will ignore none existing paths.
Returns:
None
Raises:
:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing
... | def extract_paths(self, paths, ignore_nopath):
try:
if self._has_tar_and_gzip():
self._extract_paths_tar_gz(paths, ignore_nopath)
else:
self._extract_paths_scp(paths, ignore_nopath)
except (ssh.LagoSSHTimeoutException, LagoVMNotRunningErro... | 559,133 |
Check if the VM is reachable with ssh
Args:
tries(int): Number of tries to try connecting to the host
propagate_fail(bool): If set to true, this event will appear
in the log and fail the outter stage. Otherwise, it will be
discarded.
Returns:
b... | def ssh_reachable(self, tries=None, propagate_fail=True):
if not self.running():
return False
try:
ssh.get_ssh_client(
ip_addr=self.ip(),
host_name=self.name(),
ssh_tries=tries,
propagate_fail=propagate_fai... | 559,155 |
Add a stream logger. This can be used for printing all SDK calls to stdout
while working in an interactive session. Note this is a logger for the
entire module, which will apply to all environments started in the same
session. If you need a specific logger pass a ``logfile`` to
:func:`~sdk.init`
Ar... | def add_stream_logger(level=logging.DEBUG, name=None):
logger = logging.getLogger(name)
logger.setLevel(level)
handler = logging.StreamHandler()
handler.setFormatter(get_default_log_formatter())
handler.setLevel(level)
logger.addHandler(handler) | 559,203 |
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` l... | def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs):
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
defau... | 559,204 |
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`: Initializ... | def load_env(workdir, logfile=None, loglevel=logging.INFO):
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) | 559,205 |
__init__
Args:
workdir(:class:`~lago.workdir.Workdir`): The enviornment
workdir.
prefix(:class:~lago.prefix.Prefix): The enviornment Prefix.
Returns:
None | def __init__(self, workdir, prefix):
self._workdir = workdir
self._prefix = prefix
# Proxy object to the prefix to expose
self._pprefix = SDKWrapper(weakref.proxy(self._prefix)) | 559,206 |
Context manager which returns Ansible inventory written on a tempfile.
This is the same as :func:`~ansible_inventory`, only the inventory file
is written to a tempfile.
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Yields:
... | def ansible_inventory_temp_file(
self, keys=['vm-type', 'groups', 'vm-provider']
):
lansible = LagoAnsible(self._prefix)
return lansible.get_inventory_temp_file(keys=keys) | 559,208 |
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 | def calc_sha(self, 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 | 559,212 |
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 | 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()[0]
cmd_handler = self.get_cmd_handler(cmd_name)
self.build_cmds.append(cmd_handler(cmd_... | 559,228 |
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.BuildExcep... | def get_cmd_handler(self, cmd):
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 | 559,229 |
Handler for 'virt-customize'
note: if 'ssh-inject' option was specified without a path to a key,
the prefix' key will be copied to the vm.
Args:
options (lst of str): Options and arguments for 'virt-customize'
Returns:
callable: which handles cmd
Raises... | def virt_customize(self, options):
cmd = ['virt-customize', '-a', self.disk_path]
if 'ssh-inject' in options and not options['ssh-inject']:
options['ssh-inject'] = 'root:file:{}'.format(
self.paths.ssh_id_rsa_pub()
)
options = self.normalize_opti... | 559,230 |
Searches the given repo name inside the repo_dir (will use the config value
'template_repos' if no repo dir passed), will rise an exception if not
found
Args:
name (str): Name of the repo to search
repo_dir (str): Directory where to search the repo
Return:
str: path to the repo... | def find_repo_by_name(name, repo_dir=None):
if repo_dir is None:
repo_dir = config.get('template_repos')
ret, out, _ = utils.run_command([
'find',
repo_dir,
'-name',
'*.json',
], )
repos = [
TemplateRepository.from_url(line.strip()) for line in out.... | 559,232 |
Copies over the handl to the destination
Args:
handle (str): path to copy over
dest (str): path to copy to
Returns:
None | def download_image(self, handle, dest):
shutil.copyfile(self._prefixed(handle), dest) | 559,234 |
Returns the associated hash for the given handle, the hash file must
exist (``handle + '.hash'``).
Args:
handle (str): Path to the template to get the hash from
Returns:
str: Hash for the given handle | def get_hash(self, handle):
handle = os.path.expanduser(os.path.expandvars(handle))
with open(self._prefixed('%s.hash' % handle)) as f:
return f.read() | 559,235 |
Returns the associated metadata info for the given handle, the metadata
file must exist (``handle + '.metadata'``).
Args:
handle (str): Path to the template to get the metadata from
Returns:
dict: Metadata for the given handle | def get_metadata(self, handle):
handle = os.path.expanduser(os.path.expandvars(handle))
with open(self._prefixed('%s.metadata' % handle)) as f:
return json.load(f) | 559,236 |
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 | def download_image(self, handle, dest):
with log_utils.LogTask('Download image %s' % handle, logger=LOGGER):
self.open_url(url=handle, dest=dest)
self.extract_image_xz(dest) | 559,238 |
Get the associated hash for the given handle, the hash file must
exist (``handle + '.hash'``).
Args:
handle (str): Path to the template to get the hash from
Returns:
str: Hash for the given handle | def get_hash(self, handle):
response = self.open_url(url=handle, suffix='.hash')
try:
return response.read()
finally:
response.close() | 559,240 |
Returns the associated metadata info for the given handle, the metadata
file must exist (``handle + '.metadata'``). If the given handle has an
``.xz`` extension, it will get removed when calculating the handle
metadata path
Args:
handle (str): Path to the template to get the... | def get_metadata(self, handle):
response = self.open_url(url=handle, suffix='.metadata')
try:
return json.load(response)
finally:
response.close() | 559,241 |
You would usually use the
:func:`TemplateRepository.from_url` method instead of
directly using this
Args:
dom (dict): Specification of the template repository (not confuse
with xml dom) | def __init__(self, dom, path):
self._dom = dom
self._providers = {
name: self._get_provider(spec)
for name, spec in self._dom.get('sources', {}).items()
}
self._path = path | 559,242 |
Instantiate a :class:`TemplateRepository` instance from the data in a
file or url
Args:
path (str): Path or url to the json file to load
Returns:
TemplateRepository: A new instance | def from_url(cls, path):
if os.path.isfile(path):
with open(path) as fd:
data = fd.read()
else:
try:
response = urllib.urlopen(path)
if response.code >= 300:
raise RuntimeError('Unable to load repo from ... | 559,243 |
Retrieve a template by it's name
Args:
name (str): Name of the template to retrieve
Raises:
LagoMissingTemplateError: if no template is found | def get_by_name(self, name):
try:
spec = self._dom.get('templates', {})[name]
except KeyError:
raise LagoMissingTemplateError(name, self._path)
return Template(
name=name,
versions={
ver_name: TemplateVersion(
... | 559,244 |
Checks if a given version is in this store
Args:
temp_ver (TemplateVersion): Version to look for
Returns:
bool: ``True`` if the version is in this store | def __contains__(self, temp_ver):
return os.path.exists(self._prefixed(temp_ver.name)) | 559,250 |
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 | def get_path(self, temp_ver):
if temp_ver not in self:
raise RuntimeError(
'Template: {} not present'.format(temp_ver.name)
)
return self._prefixed(temp_ver.name) | 559,251 |
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 | def download(self, temp_ver, store_metadata=True):
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
tem... | 559,252 |
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 | def get_stored_metadata(self, temp_ver):
with open(self._prefixed('%s.metadata' % temp_ver.name)) as f:
return json.load(f) | 559,253 |
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 | def get_stored_hash(self, temp_ver):
with open(self._prefixed('%s.hash' % temp_ver.name)) as f:
return f.read().strip() | 559,254 |
Convert a dict generated by ansible.LagoAnsible.get_inventory
to an INI-like file.
Args:
keys (list of str): Path to the keys that will be used to
create groups.
Returns:
str: INI-like Ansible inventory | def get_inventory_str(self, keys=None):
inventory = self.get_inventory(keys)
lines = []
for name, hosts in inventory.viewitems():
lines.append('[{name}]'.format(name=name))
for host in sorted(hosts):
lines.append(host)
return '\n'.join(li... | 559,255 |
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.
... | def get_inventory(self, keys=None):
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:
... | 559,256 |
Generate host entry for the given VM
Args:
vm (lago.plugins.vm.VMPlugin): The VM for which the entry
should be created for.
Returns:
str: An entry for vm | def _generate_entry(self, vm):
return \
'{name} ' \
'ansible_host={ip} ' \
'ansible_ssh_private_key_file={key}'.format(
name=vm.name(),
ip=vm.ip(),
key=self.prefix.paths.ssh_id_rsa()
) | 559,257 |
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.
Ret... | 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] or path.pop(0)
current_value = data_structure
while path:
current_key... | 559,258 |
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 ... | def get_inventory_temp_file(self, keys=None):
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
)
)
... | 559,259 |
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
fram... | def exit_handler(signum, frame):
LOGGER.debug('signal {} was caught'.format(signum))
sys.exit(128 + signum) | 559,272 |
Given a repo path and an option commit/tag/refspec to start from, will
get the rpm compatible changelog
Args:
repo_path (str): path to the git repo
from_commit (str): refspec (partial commit hash, tag, branch, full
refspec, partial refspec) to start the changelog from
Returns:
... | def get_changelog(repo_path, from_commit=None):
repo = dulwich.repo.Repo(repo_path)
tags = get_tags(repo)
refs = get_refs(repo)
changelog = []
maj_version = 0
feat_version = 0
fix_version = 0
start_including = False
cur_line = ''
if from_commit is None:
start_includ... | 559,280 |
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
Raise... | def start(self, attempts=5, timeout=2):
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... | 559,287 |
Generate CPU XML node.
Args:
spec(dict): VM Lago spec
host_cpu(lxml.etree.Element): Host cpu capabilities | def __init__(self, spec, host_cpu):
self.vcpu_set = False
# TO-DO: deduce recommended defaults for vcpu_num from host CPU caps
self.vcpu_num = '2'
if spec.get('vcpu'):
self.vcpu_set = True
self.vcpu_num = spec['vcpu']
self.cpu_custom = spec.get('... | 559,299 |
Generate host-passthrough XML cpu node
Args:
vcpu_num(str): number of virtual CPUs
Returns:
lxml.etree.Element: CPU XML node | def generate_host_passthrough(self, vcpu_num):
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 | 559,303 |
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 | def generate_exact(self, model, vcpu_num, host_cpu):
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... | 559,305 |
Generate CPU <topology> XML child
Args:
vcpu_num(str): number of virtual CPUs
cores(int): number of cores
threads(int): number of threads
Returns:
lxml.etree.Element: topology XML element | def generate_topology(self, vcpu_num, cores=1, threads=1):
return ET.Element(
'topology',
sockets=str(vcpu_num),
cores=str(cores),
threads=str(threads),
) | 559,306 |
Generate guest CPU <numa> XML child
Configures 1, 2 or 4 vCPUs per cell.
Args:
vcpu_num(str): number of virtual CPUs
Returns:
lxml.etree.Element: numa XML element | def generate_numa(self, vcpu_num):
if int(vcpu_num) == 2:
# 2 vCPUs is a special case.
# We wish to have 2 cells,
# with 1 vCPU in each.
# This is also the common case.
total_cells = 2
cpus_per_cell = 1
elif int(vcpu_num) ... | 559,307 |
Generate <vcpu> domain XML child
Args:
vcpu_num(str): number of virtual cpus
Returns:
lxml.etree.Element: vcpu XML element | def generate_vcpu(self, vcpu_num):
vcpu = ET.Element('vcpu')
vcpu.text = str(vcpu_num)
return vcpu | 559,308 |
Generate CPU feature element
Args:
name(str): feature name
policy(str): libvirt feature policy
Returns:
lxml.etree.Element: feature XML element | def generate_feature(self, name, policy='require'):
return ET.Element('feature', policy=policy, name=name) | 559,309 |
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' | def get_cpu_vendor(cls, family, arch='x86'):
props = cls.get_cpu_props(family, arch)
vendor = 'generic'
try:
vendor = props.xpath('vendor/@name')[0]
except IndexError:
pass
return vendor | 559,310 |
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 | def get_cpu_props(cls, family, arch='x86'):
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)) | 559,311 |
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 | 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.xpath('/cpus/arch[@name="{0}"]'.format(arch))[0]
except IndexError:
raise LagoException('No such arch: {0}'.... | 559,312 |
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 | def start_log_task(task, logger=logging, level='info'):
getattr(logger, level)(START_TASK_TRIGGER_MSG % task) | 559,314 |
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 | def end_log_task(task, logger=logging, level='info'):
getattr(logger, level)(END_TASK_TRIGGER_MSG % task) | 559,315 |
Sets up a file logger that will create a log in the given logdir (usually a
lago prefix)
Args:
logdir (str): path to create the log into, will be created if it does
not exist
Returns:
None | def setup_prefix_logging(logdir):
if not os.path.exists(logdir):
os.mkdir(logdir)
file_handler = logging.FileHandler(
filename=os.path.join(logdir, 'lago.log'),
)
file_formatter = get_default_log_formatter()
file_handler.setFormatter(file_formatter)
logging.root.addHandler(... | 559,318 |
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 | def colored(cls, color, message):
return getattr(cls, color.upper()) + message + cls.DEFAULT | 559,319 |
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 | def format(self, record):
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:
... | 559,320 |
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 | def handle_new_task(self, task_name, record):
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_hea... | 559,328 |
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 | 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:
self.tasks[existing_task_name].clear()
self.tasks[existing_task_name].... | 559,329 |
Closes all the children tasks that were open
Args:
parent_task_name (str): Name of the parent task
Returns:
None | 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.keys()).next()
if next_task == parent_task_name:
break
del self.tasks[next_task] | 559,330 |
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 | 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.cur_task)
if self.tasks[task_name].failed:
record.msg = ColorFormatter.colored('red', END_TASK_ON_ERRO... | 559,331 |
Wrapper around the :class:`logging.StreamHandler` emit method to add
some decoration stuff to the message
Args:
record (logging.LogRecord): log record to emit
is_header (bool): if this record is a header, usually, a start or
end task message
task_leve... | def pretty_emit(self, record, is_header=False, task_level=None):
task = record.task or self.cur_task
if task_level is None:
task_level = self.cur_depth_level
if is_header:
extra_prefix = (
self.get_task_indicator(task_level - 1) + ' ' +
... | 559,334 |
Handle the given record, this is the entry point from the python
logging facility
Params:
record (logging.LogRecord): log record to handle
Returns:
None | def emit(self, record):
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 =... | 559,335 |
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 | 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(index)
if self._lease_valid(lease):
continue
self._take_lease(lease, uuid_path, safe=False)
retu... | 559,343 |
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
Raise... | def _acquire_given_subnet(self, uuid_path, subnet):
lease = self.create_lease_object_from_subnet(subnet)
self._take_lease(lease, uuid_path)
return lease.to_ip_network() | 559,344 |
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 ... | def _lease_valid(self, lease):
if not lease.exist:
return None
if lease.has_env:
return lease.uuid_path
else:
self._release(lease)
return None | 559,345 |
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
... | 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_path:
raise LagoSubnetLeaseTakenException(
lease.subnet, lease_taken_by
)
... | 559,346 |
List current subnet leases
Args:
uuid(str): Filter the leases by uuid
Returns:
list of :class:~Lease: current leases | def list_leases(self, uuid=None):
try:
lease_files = os.listdir(self.path)
except OSError as e:
raise_from(
LagoSubnetLeaseBadPermissionsException(self.path, e.strerror),
e
)
leases = [
self.create_lease_o... | 559,347 |
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 ... | def release(self, subnets):
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._creat... | 559,348 |
Free the given lease
Args:
lease (lago.subnet_lease.Lease): The lease to free | def _release(self, lease):
if lease.exist:
os.unlink(lease.path)
LOGGER.debug('Removed subnet lease {}'.format(lease.path)) | 559,349 |
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 o... | 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()
return \
current_uuid_path == prev_uuid_path and \
prev_uuid == current_uuid | 559,350 |
Create a lease from ip in a dotted decimal format,
(for example `192.168.200.0/24`). the _cidr will be added if not exist
in `subnet`.
Args:
subnet (str): The value of the third octet
Returns:
Lease: Lease object which represents the requested subnet.
R... | def create_lease_object_from_subnet(self, subnet):
if '/' not in subnet:
subnet = '{}/{}'.format(subnet, self._cidr)
try:
if not self.is_leasable_subnet(subnet):
raise LagoSubnetLeaseOutOfRangeException(
subnet, self.get_allowed_range... | 559,351 |
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 | def deepcopy(original_obj):
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 | 559,367 |
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 | 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)
return deepcopy(virt_conf) | 559,368 |
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 | def get_qemu_info(path, backing_chain=False, fail_on_error=True):
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)
)
re... | 559,375 |
changes the backing file of 'source' to 'backing_file'
If backing_file is specified as "" (the empty string),
then the image is rebased onto no backing file
(i.e. it will exist independently of any backing file).
(Taken from qemu-img man page)
Args:
target(str): Path to the source disk
... | def qemu_rebase(target, backing_file, safe=True, fail_on_error=True):
cmd = ['qemu-img', 'rebase', '-b', backing_file, target]
if not safe:
cmd.insert(2, '-u')
return run_command_with_validation(
cmd,
fail_on_error,
msg='Failed to rebase {target} onto {backing_file}'.fo... | 559,376 |
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 | def get_hash(file_path, checksum='sha1'):
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() | 559,380 |
Remove keys from a spec file.
For example, with the following path: domains/*/disks/*/metadata
all the metadata dicts from all domains disks will be removed.
Args:
spec (dict): spec to remove keys from
paths (list): list of paths to the keys that should be removed
wildcard (str): wi... | def filter_spec(spec, paths, wildcard='*', separator='/'):
def remove_key(path, spec):
if len(path) == 0:
return
elif len(path) == 1:
key = path.pop()
if not isinstance(spec, collections.Mapping):
raise LagoUserException(
... | 559,381 |
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. | def ver_cmp(ver1, ver2):
return cmp(
pkg_resources.parse_version(ver1), pkg_resources.parse_version(ver2)
) | 559,382 |
Returns a uuid pefixed identifier
Args:
unprefixed_name(str): Name to add a prefix to
max_length(int): maximum length of the resultant prefixed name,
will adapt the given name and the length of the uuid ot fit it
Returns:
str: prefixed identifier for t... | def prefixed_name(self, unprefixed_name, max_length=0):
if max_length == 0:
prefixed_name = '%s-%s' % (self.uuid[:8], unprefixed_name)
else:
if max_length < 6:
raise RuntimeError(
"Can't prefix with less than 6 chars (%s)" %
... | 559,402 |
Get the spec of the current env.
The spec will hold the info about all the domains and
networks associated with this env.
Args:
filters (list): list of paths to keys that should be removed from
the init file
Returns:
dict: the spec of the current e... | def get_env_spec(self, filters=None):
spec = {
'domains':
{
vm_name: deepcopy(vm_object.spec)
for vm_name, vm_object in self._vms.viewitems()
},
'nets':
{
net_name: deepco... | 559,406 |
Get the common arguments for stop and shutdown commands
Args:
vm_names (list of str): The names of the requested vms
Returns
list of plugins.vm.VMProviderPlugin:
vms objects that should be stopped
list of virt.Network: net objects that should be stoppe... | def _get_stop_shutdown_common_args(self, vm_names):
vms_to_stop = self.get_vms(vm_names).values()
if not vm_names:
log_msg = '{} prefix'
nets = self._nets.values()
else:
log_msg = '{} specified VMs'
nets = self._get_unused_nets(vms_to_st... | 559,408 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.