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
maas/python-libmaas
maas/client/__init__.py
connect
async def connect(url, *, apikey=None, insecure=False): """Connect to MAAS at `url` using a previously obtained API key. :param url: The URL of MAAS, e.g. http://maas.example.com:5240/MAAS/ :param apikey: The API key to use, e.g. SkTvsyHhzkREvvdtNk:Ywn5FvXVupVPvNUhrN:cm3Q2f5naXYPYsrPDPfQy9Q9cUFaEgbM :param insecure: Whether to check TLS certificates when using HTTPS. :return: A client object. """ from .facade import Client # Lazy. from .viscera import Origin # Lazy. profile, origin = await Origin.connect( url, apikey=apikey, insecure=insecure) return Client(origin)
python
async def connect(url, *, apikey=None, insecure=False): """Connect to MAAS at `url` using a previously obtained API key. :param url: The URL of MAAS, e.g. http://maas.example.com:5240/MAAS/ :param apikey: The API key to use, e.g. SkTvsyHhzkREvvdtNk:Ywn5FvXVupVPvNUhrN:cm3Q2f5naXYPYsrPDPfQy9Q9cUFaEgbM :param insecure: Whether to check TLS certificates when using HTTPS. :return: A client object. """ from .facade import Client # Lazy. from .viscera import Origin # Lazy. profile, origin = await Origin.connect( url, apikey=apikey, insecure=insecure) return Client(origin)
[ "async", "def", "connect", "(", "url", ",", "*", ",", "apikey", "=", "None", ",", "insecure", "=", "False", ")", ":", "from", ".", "facade", "import", "Client", "# Lazy.", "from", ".", "viscera", "import", "Origin", "# Lazy.", "profile", ",", "origin", ...
Connect to MAAS at `url` using a previously obtained API key. :param url: The URL of MAAS, e.g. http://maas.example.com:5240/MAAS/ :param apikey: The API key to use, e.g. SkTvsyHhzkREvvdtNk:Ywn5FvXVupVPvNUhrN:cm3Q2f5naXYPYsrPDPfQy9Q9cUFaEgbM :param insecure: Whether to check TLS certificates when using HTTPS. :return: A client object.
[ "Connect", "to", "MAAS", "at", "url", "using", "a", "previously", "obtained", "API", "key", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/__init__.py#L12-L26
train
28,700
maas/python-libmaas
maas/client/__init__.py
login
async def login(url, *, username=None, password=None, insecure=False): """Connect to MAAS at `url` with a user name and password. :param url: The URL of MAAS, e.g. http://maas.example.com:5240/MAAS/ :param username: The user name to use, e.g. fred. :param password: The user's password. :param insecure: Whether to check TLS certificates when using HTTPS. :return: A client object. """ from .facade import Client # Lazy. from .viscera import Origin # Lazy. profile, origin = await Origin.login( url, username=username, password=password, insecure=insecure) return Client(origin)
python
async def login(url, *, username=None, password=None, insecure=False): """Connect to MAAS at `url` with a user name and password. :param url: The URL of MAAS, e.g. http://maas.example.com:5240/MAAS/ :param username: The user name to use, e.g. fred. :param password: The user's password. :param insecure: Whether to check TLS certificates when using HTTPS. :return: A client object. """ from .facade import Client # Lazy. from .viscera import Origin # Lazy. profile, origin = await Origin.login( url, username=username, password=password, insecure=insecure) return Client(origin)
[ "async", "def", "login", "(", "url", ",", "*", ",", "username", "=", "None", ",", "password", "=", "None", ",", "insecure", "=", "False", ")", ":", "from", ".", "facade", "import", "Client", "# Lazy.", "from", ".", "viscera", "import", "Origin", "# Laz...
Connect to MAAS at `url` with a user name and password. :param url: The URL of MAAS, e.g. http://maas.example.com:5240/MAAS/ :param username: The user name to use, e.g. fred. :param password: The user's password. :param insecure: Whether to check TLS certificates when using HTTPS. :return: A client object.
[ "Connect", "to", "MAAS", "at", "url", "with", "a", "user", "name", "and", "password", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/__init__.py#L30-L44
train
28,701
maas/python-libmaas
maas/client/viscera/nodes.py
NodesType.read
async def read(cls, *, hostnames: typing.Sequence[str] = None): """List nodes. :param hostnames: Sequence of hostnames to only return. :type hostnames: sequence of `str` """ params = {} if hostnames: params["hostname"] = [ normalize_hostname(hostname) for hostname in hostnames ] data = await cls._handler.read(**params) return cls(map(cls._object, data))
python
async def read(cls, *, hostnames: typing.Sequence[str] = None): """List nodes. :param hostnames: Sequence of hostnames to only return. :type hostnames: sequence of `str` """ params = {} if hostnames: params["hostname"] = [ normalize_hostname(hostname) for hostname in hostnames ] data = await cls._handler.read(**params) return cls(map(cls._object, data))
[ "async", "def", "read", "(", "cls", ",", "*", ",", "hostnames", ":", "typing", ".", "Sequence", "[", "str", "]", "=", "None", ")", ":", "params", "=", "{", "}", "if", "hostnames", ":", "params", "[", "\"hostname\"", "]", "=", "[", "normalize_hostname...
List nodes. :param hostnames: Sequence of hostnames to only return. :type hostnames: sequence of `str`
[ "List", "nodes", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/nodes.py#L37-L50
train
28,702
maas/python-libmaas
maas/client/viscera/nodes.py
Node.as_machine
def as_machine(self): """Convert to a `Machine` object. `node_type` must be `NodeType.MACHINE`. """ if self.node_type != NodeType.MACHINE: raise ValueError( 'Cannot convert to `Machine`, node_type is not a machine.') return self._origin.Machine(self._data)
python
def as_machine(self): """Convert to a `Machine` object. `node_type` must be `NodeType.MACHINE`. """ if self.node_type != NodeType.MACHINE: raise ValueError( 'Cannot convert to `Machine`, node_type is not a machine.') return self._origin.Machine(self._data)
[ "def", "as_machine", "(", "self", ")", ":", "if", "self", ".", "node_type", "!=", "NodeType", ".", "MACHINE", ":", "raise", "ValueError", "(", "'Cannot convert to `Machine`, node_type is not a machine.'", ")", "return", "self", ".", "_origin", ".", "Machine", "(",...
Convert to a `Machine` object. `node_type` must be `NodeType.MACHINE`.
[ "Convert", "to", "a", "Machine", "object", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/nodes.py#L93-L101
train
28,703
maas/python-libmaas
maas/client/viscera/nodes.py
Node.as_device
def as_device(self): """Convert to a `Device` object. `node_type` must be `NodeType.DEVICE`. """ if self.node_type != NodeType.DEVICE: raise ValueError( 'Cannot convert to `Device`, node_type is not a device.') return self._origin.Device(self._data)
python
def as_device(self): """Convert to a `Device` object. `node_type` must be `NodeType.DEVICE`. """ if self.node_type != NodeType.DEVICE: raise ValueError( 'Cannot convert to `Device`, node_type is not a device.') return self._origin.Device(self._data)
[ "def", "as_device", "(", "self", ")", ":", "if", "self", ".", "node_type", "!=", "NodeType", ".", "DEVICE", ":", "raise", "ValueError", "(", "'Cannot convert to `Device`, node_type is not a device.'", ")", "return", "self", ".", "_origin", ".", "Device", "(", "s...
Convert to a `Device` object. `node_type` must be `NodeType.DEVICE`.
[ "Convert", "to", "a", "Device", "object", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/nodes.py#L103-L111
train
28,704
maas/python-libmaas
maas/client/viscera/nodes.py
Node.as_rack_controller
def as_rack_controller(self): """Convert to a `RackController` object. `node_type` must be `NodeType.RACK_CONTROLLER` or `NodeType.REGION_AND_RACK_CONTROLLER`. """ if self.node_type not in [ NodeType.RACK_CONTROLLER, NodeType.REGION_AND_RACK_CONTROLLER]: raise ValueError( 'Cannot convert to `RackController`, node_type is not a ' 'rack controller.') return self._origin.RackController(self._data)
python
def as_rack_controller(self): """Convert to a `RackController` object. `node_type` must be `NodeType.RACK_CONTROLLER` or `NodeType.REGION_AND_RACK_CONTROLLER`. """ if self.node_type not in [ NodeType.RACK_CONTROLLER, NodeType.REGION_AND_RACK_CONTROLLER]: raise ValueError( 'Cannot convert to `RackController`, node_type is not a ' 'rack controller.') return self._origin.RackController(self._data)
[ "def", "as_rack_controller", "(", "self", ")", ":", "if", "self", ".", "node_type", "not", "in", "[", "NodeType", ".", "RACK_CONTROLLER", ",", "NodeType", ".", "REGION_AND_RACK_CONTROLLER", "]", ":", "raise", "ValueError", "(", "'Cannot convert to `RackController`, ...
Convert to a `RackController` object. `node_type` must be `NodeType.RACK_CONTROLLER` or `NodeType.REGION_AND_RACK_CONTROLLER`.
[ "Convert", "to", "a", "RackController", "object", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/nodes.py#L113-L124
train
28,705
maas/python-libmaas
maas/client/viscera/nodes.py
Node.as_region_controller
def as_region_controller(self): """Convert to a `RegionController` object. `node_type` must be `NodeType.REGION_CONTROLLER` or `NodeType.REGION_AND_RACK_CONTROLLER`. """ if self.node_type not in [ NodeType.REGION_CONTROLLER, NodeType.REGION_AND_RACK_CONTROLLER]: raise ValueError( 'Cannot convert to `RegionController`, node_type is not a ' 'region controller.') return self._origin.RegionController(self._data)
python
def as_region_controller(self): """Convert to a `RegionController` object. `node_type` must be `NodeType.REGION_CONTROLLER` or `NodeType.REGION_AND_RACK_CONTROLLER`. """ if self.node_type not in [ NodeType.REGION_CONTROLLER, NodeType.REGION_AND_RACK_CONTROLLER]: raise ValueError( 'Cannot convert to `RegionController`, node_type is not a ' 'region controller.') return self._origin.RegionController(self._data)
[ "def", "as_region_controller", "(", "self", ")", ":", "if", "self", ".", "node_type", "not", "in", "[", "NodeType", ".", "REGION_CONTROLLER", ",", "NodeType", ".", "REGION_AND_RACK_CONTROLLER", "]", ":", "raise", "ValueError", "(", "'Cannot convert to `RegionControl...
Convert to a `RegionController` object. `node_type` must be `NodeType.REGION_CONTROLLER` or `NodeType.REGION_AND_RACK_CONTROLLER`.
[ "Convert", "to", "a", "RegionController", "object", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/nodes.py#L126-L138
train
28,706
maas/python-libmaas
maas/client/viscera/nodes.py
Node.get_power_parameters
async def get_power_parameters(self): """Get the power paramters for this node.""" data = await self._handler.power_parameters(system_id=self.system_id) return data
python
async def get_power_parameters(self): """Get the power paramters for this node.""" data = await self._handler.power_parameters(system_id=self.system_id) return data
[ "async", "def", "get_power_parameters", "(", "self", ")", ":", "data", "=", "await", "self", ".", "_handler", ".", "power_parameters", "(", "system_id", "=", "self", ".", "system_id", ")", "return", "data" ]
Get the power paramters for this node.
[ "Get", "the", "power", "paramters", "for", "this", "node", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/nodes.py#L140-L143
train
28,707
maas/python-libmaas
maas/client/viscera/nodes.py
Node.set_power
async def set_power( self, power_type: str, power_parameters: typing.Mapping[str, typing.Any] = {}): """Set the power type and power parameters for this node.""" data = await self._handler.update( system_id=self.system_id, power_type=power_type, power_parameters=power_parameters) self.power_type = data['power_type']
python
async def set_power( self, power_type: str, power_parameters: typing.Mapping[str, typing.Any] = {}): """Set the power type and power parameters for this node.""" data = await self._handler.update( system_id=self.system_id, power_type=power_type, power_parameters=power_parameters) self.power_type = data['power_type']
[ "async", "def", "set_power", "(", "self", ",", "power_type", ":", "str", ",", "power_parameters", ":", "typing", ".", "Mapping", "[", "str", ",", "typing", ".", "Any", "]", "=", "{", "}", ")", ":", "data", "=", "await", "self", ".", "_handler", ".", ...
Set the power type and power parameters for this node.
[ "Set", "the", "power", "type", "and", "power", "parameters", "for", "this", "node", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/nodes.py#L145-L152
train
28,708
maas/python-libmaas
maas/client/viscera/boot_source_selections.py
BootSourceSelectionsType.create
async def create( cls, boot_source, os, release, *, arches=None, subarches=None, labels=None): """Create a new `BootSourceSelection`.""" if not isinstance(boot_source, BootSource): raise TypeError( "boot_source must be a BootSource, not %s" % type(boot_source).__name__) if arches is None: arches = ['*'] if subarches is None: subarches = ['*'] if labels is None: labels = ['*'] data = await cls._handler.create( boot_source_id=boot_source.id, os=os, release=release, arches=arches, subarches=subarches, labels=labels) return cls._object(data, {"boot_source_id": boot_source.id})
python
async def create( cls, boot_source, os, release, *, arches=None, subarches=None, labels=None): """Create a new `BootSourceSelection`.""" if not isinstance(boot_source, BootSource): raise TypeError( "boot_source must be a BootSource, not %s" % type(boot_source).__name__) if arches is None: arches = ['*'] if subarches is None: subarches = ['*'] if labels is None: labels = ['*'] data = await cls._handler.create( boot_source_id=boot_source.id, os=os, release=release, arches=arches, subarches=subarches, labels=labels) return cls._object(data, {"boot_source_id": boot_source.id})
[ "async", "def", "create", "(", "cls", ",", "boot_source", ",", "os", ",", "release", ",", "*", ",", "arches", "=", "None", ",", "subarches", "=", "None", ",", "labels", "=", "None", ")", ":", "if", "not", "isinstance", "(", "boot_source", ",", "BootS...
Create a new `BootSourceSelection`.
[ "Create", "a", "new", "BootSourceSelection", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/boot_source_selections.py#L24-L42
train
28,709
maas/python-libmaas
maas/client/viscera/boot_source_selections.py
BootSourceSelectionType.read
async def read(cls, boot_source, id): """Get `BootSourceSelection` by `id`.""" if isinstance(boot_source, int): boot_source_id = boot_source elif isinstance(boot_source, BootSource): boot_source_id = boot_source.id else: raise TypeError( "boot_source must be a BootSource or int, not %s" % type(boot_source).__name__) data = await cls._handler.read(boot_source_id=boot_source_id, id=id) return cls(data, {"boot_source_id": boot_source_id})
python
async def read(cls, boot_source, id): """Get `BootSourceSelection` by `id`.""" if isinstance(boot_source, int): boot_source_id = boot_source elif isinstance(boot_source, BootSource): boot_source_id = boot_source.id else: raise TypeError( "boot_source must be a BootSource or int, not %s" % type(boot_source).__name__) data = await cls._handler.read(boot_source_id=boot_source_id, id=id) return cls(data, {"boot_source_id": boot_source_id})
[ "async", "def", "read", "(", "cls", ",", "boot_source", ",", "id", ")", ":", "if", "isinstance", "(", "boot_source", ",", "int", ")", ":", "boot_source_id", "=", "boot_source", "elif", "isinstance", "(", "boot_source", ",", "BootSource", ")", ":", "boot_so...
Get `BootSourceSelection` by `id`.
[ "Get", "BootSourceSelection", "by", "id", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/boot_source_selections.py#L66-L77
train
28,710
maas/python-libmaas
maas/client/viscera/boot_source_selections.py
BootSourceSelection.delete
async def delete(self): """Delete boot source selection.""" await self._handler.delete( boot_source_id=self.boot_source.id, id=self.id)
python
async def delete(self): """Delete boot source selection.""" await self._handler.delete( boot_source_id=self.boot_source.id, id=self.id)
[ "async", "def", "delete", "(", "self", ")", ":", "await", "self", ".", "_handler", ".", "delete", "(", "boot_source_id", "=", "self", ".", "boot_source", ".", "id", ",", "id", "=", "self", ".", "id", ")" ]
Delete boot source selection.
[ "Delete", "boot", "source", "selection", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/boot_source_selections.py#L105-L108
train
28,711
maas/python-libmaas
maas/client/viscera/boot_resources.py
calc_size_and_sha265
def calc_size_and_sha265(content: io.IOBase, chunk_size: int): """Calculates the size and the sha2566 value of the content.""" size = 0 sha256 = hashlib.sha256() content.seek(0, io.SEEK_SET) while True: buf = content.read(chunk_size) length = len(buf) size += length sha256.update(buf) if length != chunk_size: break return size, sha256.hexdigest()
python
def calc_size_and_sha265(content: io.IOBase, chunk_size: int): """Calculates the size and the sha2566 value of the content.""" size = 0 sha256 = hashlib.sha256() content.seek(0, io.SEEK_SET) while True: buf = content.read(chunk_size) length = len(buf) size += length sha256.update(buf) if length != chunk_size: break return size, sha256.hexdigest()
[ "def", "calc_size_and_sha265", "(", "content", ":", "io", ".", "IOBase", ",", "chunk_size", ":", "int", ")", ":", "size", "=", "0", "sha256", "=", "hashlib", ".", "sha256", "(", ")", "content", ".", "seek", "(", "0", ",", "io", ".", "SEEK_SET", ")", ...
Calculates the size and the sha2566 value of the content.
[ "Calculates", "the", "size", "and", "the", "sha2566", "value", "of", "the", "content", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/boot_resources.py#L28-L40
train
28,712
maas/python-libmaas
maas/client/viscera/boot_resources.py
BootResourcesType.create
async def create( cls, name: str, architecture: str, content: io.IOBase, *, title: str = "", filetype: BootResourceFileType = BootResourceFileType.TGZ, chunk_size=(1 << 22), progress_callback=None): """Create a `BootResource`. Creates an uploaded boot resource with `content`. The `content` is uploaded in chunks of `chunk_size`. `content` must be seekable as the first pass through the `content` will calculate the size and sha256 value then the second pass will perform the actual upload. :param name: Name of the boot resource. Must be in format 'os/release'. :type name: `str` :param architecture: Architecture of the boot resource. Must be in format 'arch/subarch'. :type architecture: `str` :param content: Content of the boot resource. :type content: `io.IOBase` :param title: Title of the boot resource. :type title: `str` :param filetype: Type of file in content. :type filetype: `str` :param chunk_size: Size in bytes to upload to MAAS in chunks. (Default is 4 MiB). :type chunk_size: `int` :param progress_callback: Called to inform the current progress of the upload. One argument is passed with the progress as a precentage. If the resource was already complete and no content needed to be uploaded then this callback will never be called. :type progress_callback: Callable :returns: Create boot resource. :rtype: `BootResource`. """ if '/' not in name: raise ValueError( "name must be in format os/release; missing '/'") if '/' not in architecture: raise ValueError( "architecture must be in format arch/subarch; missing '/'") if not content.readable(): raise ValueError("content must be readable") elif not content.seekable(): raise ValueError("content must be seekable") if chunk_size <= 0: raise ValueError( "chunk_size must be greater than 0, not %d" % chunk_size) size, sha256 = calc_size_and_sha265(content, chunk_size) resource = cls._object(await cls._handler.create( name=name, architecture=architecture, title=title, filetype=filetype.value, size=str(size), sha256=sha256)) newest_set = max(resource.sets, default=None) assert newest_set is not None resource_set = resource.sets[newest_set] assert len(resource_set.files) == 1 rfile = list(resource_set.files.values())[0] if rfile.complete: # Already created and fully up-to-date. return resource else: # Upload in chunks and reload boot resource. await cls._upload_chunks( rfile, content, chunk_size, progress_callback) return cls._object.read(resource.id)
python
async def create( cls, name: str, architecture: str, content: io.IOBase, *, title: str = "", filetype: BootResourceFileType = BootResourceFileType.TGZ, chunk_size=(1 << 22), progress_callback=None): """Create a `BootResource`. Creates an uploaded boot resource with `content`. The `content` is uploaded in chunks of `chunk_size`. `content` must be seekable as the first pass through the `content` will calculate the size and sha256 value then the second pass will perform the actual upload. :param name: Name of the boot resource. Must be in format 'os/release'. :type name: `str` :param architecture: Architecture of the boot resource. Must be in format 'arch/subarch'. :type architecture: `str` :param content: Content of the boot resource. :type content: `io.IOBase` :param title: Title of the boot resource. :type title: `str` :param filetype: Type of file in content. :type filetype: `str` :param chunk_size: Size in bytes to upload to MAAS in chunks. (Default is 4 MiB). :type chunk_size: `int` :param progress_callback: Called to inform the current progress of the upload. One argument is passed with the progress as a precentage. If the resource was already complete and no content needed to be uploaded then this callback will never be called. :type progress_callback: Callable :returns: Create boot resource. :rtype: `BootResource`. """ if '/' not in name: raise ValueError( "name must be in format os/release; missing '/'") if '/' not in architecture: raise ValueError( "architecture must be in format arch/subarch; missing '/'") if not content.readable(): raise ValueError("content must be readable") elif not content.seekable(): raise ValueError("content must be seekable") if chunk_size <= 0: raise ValueError( "chunk_size must be greater than 0, not %d" % chunk_size) size, sha256 = calc_size_and_sha265(content, chunk_size) resource = cls._object(await cls._handler.create( name=name, architecture=architecture, title=title, filetype=filetype.value, size=str(size), sha256=sha256)) newest_set = max(resource.sets, default=None) assert newest_set is not None resource_set = resource.sets[newest_set] assert len(resource_set.files) == 1 rfile = list(resource_set.files.values())[0] if rfile.complete: # Already created and fully up-to-date. return resource else: # Upload in chunks and reload boot resource. await cls._upload_chunks( rfile, content, chunk_size, progress_callback) return cls._object.read(resource.id)
[ "async", "def", "create", "(", "cls", ",", "name", ":", "str", ",", "architecture", ":", "str", ",", "content", ":", "io", ".", "IOBase", ",", "*", ",", "title", ":", "str", "=", "\"\"", ",", "filetype", ":", "BootResourceFileType", "=", "BootResourceF...
Create a `BootResource`. Creates an uploaded boot resource with `content`. The `content` is uploaded in chunks of `chunk_size`. `content` must be seekable as the first pass through the `content` will calculate the size and sha256 value then the second pass will perform the actual upload. :param name: Name of the boot resource. Must be in format 'os/release'. :type name: `str` :param architecture: Architecture of the boot resource. Must be in format 'arch/subarch'. :type architecture: `str` :param content: Content of the boot resource. :type content: `io.IOBase` :param title: Title of the boot resource. :type title: `str` :param filetype: Type of file in content. :type filetype: `str` :param chunk_size: Size in bytes to upload to MAAS in chunks. (Default is 4 MiB). :type chunk_size: `int` :param progress_callback: Called to inform the current progress of the upload. One argument is passed with the progress as a precentage. If the resource was already complete and no content needed to be uploaded then this callback will never be called. :type progress_callback: Callable :returns: Create boot resource. :rtype: `BootResource`.
[ "Create", "a", "BootResource", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/boot_resources.py#L108-L172
train
28,713
maas/python-libmaas
maas/client/viscera/boot_resources.py
BootResourcesType._upload_chunks
async def _upload_chunks( cls, rfile: BootResourceFile, content: io.IOBase, chunk_size: int, progress_callback=None): """Upload the `content` to `rfile` in chunks using `chunk_size`.""" content.seek(0, io.SEEK_SET) upload_uri = urlparse( cls._handler.uri)._replace(path=rfile._data['upload_uri']).geturl() uploaded_size = 0 insecure = cls._handler.session.insecure connector = aiohttp.TCPConnector(verify_ssl=(not insecure)) session = aiohttp.ClientSession(connector=connector) async with session: while True: buf = content.read(chunk_size) length = len(buf) if length > 0: uploaded_size += length await cls._put_chunk(session, upload_uri, buf) if progress_callback is not None: progress_callback(uploaded_size / rfile.size) if length != chunk_size: break
python
async def _upload_chunks( cls, rfile: BootResourceFile, content: io.IOBase, chunk_size: int, progress_callback=None): """Upload the `content` to `rfile` in chunks using `chunk_size`.""" content.seek(0, io.SEEK_SET) upload_uri = urlparse( cls._handler.uri)._replace(path=rfile._data['upload_uri']).geturl() uploaded_size = 0 insecure = cls._handler.session.insecure connector = aiohttp.TCPConnector(verify_ssl=(not insecure)) session = aiohttp.ClientSession(connector=connector) async with session: while True: buf = content.read(chunk_size) length = len(buf) if length > 0: uploaded_size += length await cls._put_chunk(session, upload_uri, buf) if progress_callback is not None: progress_callback(uploaded_size / rfile.size) if length != chunk_size: break
[ "async", "def", "_upload_chunks", "(", "cls", ",", "rfile", ":", "BootResourceFile", ",", "content", ":", "io", ".", "IOBase", ",", "chunk_size", ":", "int", ",", "progress_callback", "=", "None", ")", ":", "content", ".", "seek", "(", "0", ",", "io", ...
Upload the `content` to `rfile` in chunks using `chunk_size`.
[ "Upload", "the", "content", "to", "rfile", "in", "chunks", "using", "chunk_size", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/boot_resources.py#L174-L197
train
28,714
maas/python-libmaas
maas/client/viscera/boot_resources.py
BootResourcesType._put_chunk
async def _put_chunk( cls, session: aiohttp.ClientSession, upload_uri: str, buf: bytes): """Upload one chunk to `upload_uri`.""" # Build the correct headers. headers = { 'Content-Type': 'application/octet-stream', 'Content-Length': '%s' % len(buf), } credentials = cls._handler.session.credentials if credentials is not None: utils.sign(upload_uri, headers, credentials) # Perform upload of chunk. async with await session.put( upload_uri, data=buf, headers=headers) as response: if response.status != 200: content = await response.read() request = { "body": buf, "headers": headers, "method": "PUT", "uri": upload_uri, } raise CallError(request, response, content, None)
python
async def _put_chunk( cls, session: aiohttp.ClientSession, upload_uri: str, buf: bytes): """Upload one chunk to `upload_uri`.""" # Build the correct headers. headers = { 'Content-Type': 'application/octet-stream', 'Content-Length': '%s' % len(buf), } credentials = cls._handler.session.credentials if credentials is not None: utils.sign(upload_uri, headers, credentials) # Perform upload of chunk. async with await session.put( upload_uri, data=buf, headers=headers) as response: if response.status != 200: content = await response.read() request = { "body": buf, "headers": headers, "method": "PUT", "uri": upload_uri, } raise CallError(request, response, content, None)
[ "async", "def", "_put_chunk", "(", "cls", ",", "session", ":", "aiohttp", ".", "ClientSession", ",", "upload_uri", ":", "str", ",", "buf", ":", "bytes", ")", ":", "# Build the correct headers.", "headers", "=", "{", "'Content-Type'", ":", "'application/octet-str...
Upload one chunk to `upload_uri`.
[ "Upload", "one", "chunk", "to", "upload_uri", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/boot_resources.py#L199-L223
train
28,715
maas/python-libmaas
maas/client/viscera/boot_resources.py
BootResourceType.read
async def read(cls, id: int): """Get `BootResource` by `id`.""" data = await cls._handler.read(id=id) return cls(data)
python
async def read(cls, id: int): """Get `BootResource` by `id`.""" data = await cls._handler.read(id=id) return cls(data)
[ "async", "def", "read", "(", "cls", ",", "id", ":", "int", ")", ":", "data", "=", "await", "cls", ".", "_handler", ".", "read", "(", "id", "=", "id", ")", "return", "cls", "(", "data", ")" ]
Get `BootResource` by `id`.
[ "Get", "BootResource", "by", "id", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/boot_resources.py#L232-L235
train
28,716
maas/python-libmaas
maas/client/viscera/bcaches.py
BcacheType.read
async def read(cls, node, id): """Get `Bcache` by `id`.""" if isinstance(node, str): system_id = node elif isinstance(node, Node): system_id = node.system_id else: raise TypeError( "node must be a Node or str, not %s" % type(node).__name__) return cls(await cls._handler.read(system_id=system_id, id=id))
python
async def read(cls, node, id): """Get `Bcache` by `id`.""" if isinstance(node, str): system_id = node elif isinstance(node, Node): system_id = node.system_id else: raise TypeError( "node must be a Node or str, not %s" % type(node).__name__) return cls(await cls._handler.read(system_id=system_id, id=id))
[ "async", "def", "read", "(", "cls", ",", "node", ",", "id", ")", ":", "if", "isinstance", "(", "node", ",", "str", ")", ":", "system_id", "=", "node", "elif", "isinstance", "(", "node", ",", "Node", ")", ":", "system_id", "=", "node", ".", "system_...
Get `Bcache` by `id`.
[ "Get", "Bcache", "by", "id", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/bcaches.py#L32-L42
train
28,717
maas/python-libmaas
maas/client/viscera/bcaches.py
Bcache.delete
async def delete(self): """Delete this Bcache.""" await self._handler.delete( system_id=self.node.system_id, id=self.id)
python
async def delete(self): """Delete this Bcache.""" await self._handler.delete( system_id=self.node.system_id, id=self.id)
[ "async", "def", "delete", "(", "self", ")", ":", "await", "self", ".", "_handler", ".", "delete", "(", "system_id", "=", "self", ".", "node", ".", "system_id", ",", "id", "=", "self", ".", "id", ")" ]
Delete this Bcache.
[ "Delete", "this", "Bcache", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/bcaches.py#L62-L65
train
28,718
maas/python-libmaas
maas/client/viscera/bcaches.py
BcachesType.read
async def read(cls, node): """Get list of `Bcache`'s for `node`.""" if isinstance(node, str): system_id = node elif isinstance(node, Node): system_id = node.system_id else: raise TypeError( "node must be a Node or str, not %s" % type(node).__name__) data = await cls._handler.read(system_id=system_id) return cls( cls._object( item, local_data={"node_system_id": system_id}) for item in data)
python
async def read(cls, node): """Get list of `Bcache`'s for `node`.""" if isinstance(node, str): system_id = node elif isinstance(node, Node): system_id = node.system_id else: raise TypeError( "node must be a Node or str, not %s" % type(node).__name__) data = await cls._handler.read(system_id=system_id) return cls( cls._object( item, local_data={"node_system_id": system_id}) for item in data)
[ "async", "def", "read", "(", "cls", ",", "node", ")", ":", "if", "isinstance", "(", "node", ",", "str", ")", ":", "system_id", "=", "node", "elif", "isinstance", "(", "node", ",", "Node", ")", ":", "system_id", "=", "node", ".", "system_id", "else", ...
Get list of `Bcache`'s for `node`.
[ "Get", "list", "of", "Bcache", "s", "for", "node", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/bcaches.py#L71-L85
train
28,719
maas/python-libmaas
maas/client/viscera/bcaches.py
BcachesType.create
async def create( cls, node: Union[Node, str], name: str, backing_device: Union[BlockDevice, Partition], cache_set: Union[BcacheCacheSet, int], cache_mode: CacheMode, *, uuid: str = None): """ Create a Bcache on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param name: Name of the Bcache. :type name: `str` :param backing_device: Either a block device or partition to create the Bcache from. :type backing_device: `BlockDevice` or `Partition` :param cache_set: Bcache cache set to use in front of backing device. :type cache_set: `BcacheCacheSet` or `int` :param cache_mode: Caching mode to use for this device. :type cache_mode: `CacheMode` :type backing_device: `BlockDevice` or `Partition` :param uuid: The UUID for the Bcache (optional). :type uuid: `str` """ params = { 'name': name, } if isinstance(node, str): params['system_id'] = node elif isinstance(node, Node): params['system_id'] = node.system_id else: raise TypeError( 'node must be a Node or str, not %s' % ( type(node).__name__)) if isinstance(backing_device, BlockDevice): params['backing_device'] = backing_device.id elif isinstance(backing_device, Partition): params['backing_partition'] = backing_device.id else: raise TypeError( "backing_device must be a BlockDevice or Partition, " "not %s" % type(backing_device).__name__) if isinstance(cache_set, BcacheCacheSet): params['cache_set'] = cache_set.id elif isinstance(cache_set, int): params['cache_set'] = cache_set else: raise TypeError( "cache_set must be a BcacheCacheSet or int, " "not %s" % type(cache_set).__name__) if isinstance(cache_mode, CacheMode): params['cache_mode'] = cache_mode.value else: raise TypeError( "cache_mode must be a CacheMode, " "not %s" % type(cache_mode).__name__) if uuid is not None: params['uuid'] = uuid return cls._object(await cls._handler.create(**params))
python
async def create( cls, node: Union[Node, str], name: str, backing_device: Union[BlockDevice, Partition], cache_set: Union[BcacheCacheSet, int], cache_mode: CacheMode, *, uuid: str = None): """ Create a Bcache on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param name: Name of the Bcache. :type name: `str` :param backing_device: Either a block device or partition to create the Bcache from. :type backing_device: `BlockDevice` or `Partition` :param cache_set: Bcache cache set to use in front of backing device. :type cache_set: `BcacheCacheSet` or `int` :param cache_mode: Caching mode to use for this device. :type cache_mode: `CacheMode` :type backing_device: `BlockDevice` or `Partition` :param uuid: The UUID for the Bcache (optional). :type uuid: `str` """ params = { 'name': name, } if isinstance(node, str): params['system_id'] = node elif isinstance(node, Node): params['system_id'] = node.system_id else: raise TypeError( 'node must be a Node or str, not %s' % ( type(node).__name__)) if isinstance(backing_device, BlockDevice): params['backing_device'] = backing_device.id elif isinstance(backing_device, Partition): params['backing_partition'] = backing_device.id else: raise TypeError( "backing_device must be a BlockDevice or Partition, " "not %s" % type(backing_device).__name__) if isinstance(cache_set, BcacheCacheSet): params['cache_set'] = cache_set.id elif isinstance(cache_set, int): params['cache_set'] = cache_set else: raise TypeError( "cache_set must be a BcacheCacheSet or int, " "not %s" % type(cache_set).__name__) if isinstance(cache_mode, CacheMode): params['cache_mode'] = cache_mode.value else: raise TypeError( "cache_mode must be a CacheMode, " "not %s" % type(cache_mode).__name__) if uuid is not None: params['uuid'] = uuid return cls._object(await cls._handler.create(**params))
[ "async", "def", "create", "(", "cls", ",", "node", ":", "Union", "[", "Node", ",", "str", "]", ",", "name", ":", "str", ",", "backing_device", ":", "Union", "[", "BlockDevice", ",", "Partition", "]", ",", "cache_set", ":", "Union", "[", "BcacheCacheSet...
Create a Bcache on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param name: Name of the Bcache. :type name: `str` :param backing_device: Either a block device or partition to create the Bcache from. :type backing_device: `BlockDevice` or `Partition` :param cache_set: Bcache cache set to use in front of backing device. :type cache_set: `BcacheCacheSet` or `int` :param cache_mode: Caching mode to use for this device. :type cache_mode: `CacheMode` :type backing_device: `BlockDevice` or `Partition` :param uuid: The UUID for the Bcache (optional). :type uuid: `str`
[ "Create", "a", "Bcache", "on", "a", "Node", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/bcaches.py#L87-L151
train
28,720
maas/python-libmaas
maas/client/viscera/machines.py
get_param_arg
def get_param_arg(param, idx, klass, arg, attr='id'): """Return the correct value for a fabric from `arg`.""" if isinstance(arg, klass): return getattr(arg, attr) elif isinstance(arg, (int, str)): return arg else: raise TypeError( "%s[%d] must be int, str, or %s, not %s" % ( param, idx, klass.__name__, type(arg).__name__))
python
def get_param_arg(param, idx, klass, arg, attr='id'): """Return the correct value for a fabric from `arg`.""" if isinstance(arg, klass): return getattr(arg, attr) elif isinstance(arg, (int, str)): return arg else: raise TypeError( "%s[%d] must be int, str, or %s, not %s" % ( param, idx, klass.__name__, type(arg).__name__))
[ "def", "get_param_arg", "(", "param", ",", "idx", ",", "klass", ",", "arg", ",", "attr", "=", "'id'", ")", ":", "if", "isinstance", "(", "arg", ",", "klass", ")", ":", "return", "getattr", "(", "arg", ",", "attr", ")", "elif", "isinstance", "(", "a...
Return the correct value for a fabric from `arg`.
[ "Return", "the", "correct", "value", "for", "a", "fabric", "from", "arg", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L55-L64
train
28,721
maas/python-libmaas
maas/client/viscera/machines.py
MachinesType.create
async def create( cls, architecture: str, mac_addresses: typing.Sequence[str], power_type: str, power_parameters: typing.Mapping[str, typing.Any] = None, *, subarchitecture: str = None, min_hwe_kernel: str = None, hostname: str = None, domain: typing.Union[int, str] = None): """ Create a new machine. :param architecture: The architecture of the machine (required). :type architecture: `str` :param mac_addresses: The MAC address of the machine (required). :type mac_addresses: sequence of `str` :param power_type: The power type of the machine (required). :type power_type: `str` :param power_parameters: The power parameters for the machine (optional). :type power_parameters: mapping of `str` to any value. :param subarchitecture: The subarchitecture of the machine (optional). :type subarchitecture: `str` :param min_hwe_kernel: The minimal HWE kernel for the machine (optional). :param hostname: The hostname for the machine (optional). :type hostname: `str` :param domain: The domain for the machine (optional). :type domain: `int` or `str` """ params = { "architecture": architecture, "mac_addresses": mac_addresses, "power_type": power_type, } if power_parameters is not None: params["power_parameters"] = json.dumps( power_parameters, sort_keys=True) if subarchitecture is not None: params["subarchitecture"] = subarchitecture if min_hwe_kernel is not None: params["min_hwe_kernel"] = min_hwe_kernel if hostname is not None: params["hostname"] = hostname if domain is not None: params["domain"] = domain return cls._object(await cls._handler.create(**params))
python
async def create( cls, architecture: str, mac_addresses: typing.Sequence[str], power_type: str, power_parameters: typing.Mapping[str, typing.Any] = None, *, subarchitecture: str = None, min_hwe_kernel: str = None, hostname: str = None, domain: typing.Union[int, str] = None): """ Create a new machine. :param architecture: The architecture of the machine (required). :type architecture: `str` :param mac_addresses: The MAC address of the machine (required). :type mac_addresses: sequence of `str` :param power_type: The power type of the machine (required). :type power_type: `str` :param power_parameters: The power parameters for the machine (optional). :type power_parameters: mapping of `str` to any value. :param subarchitecture: The subarchitecture of the machine (optional). :type subarchitecture: `str` :param min_hwe_kernel: The minimal HWE kernel for the machine (optional). :param hostname: The hostname for the machine (optional). :type hostname: `str` :param domain: The domain for the machine (optional). :type domain: `int` or `str` """ params = { "architecture": architecture, "mac_addresses": mac_addresses, "power_type": power_type, } if power_parameters is not None: params["power_parameters"] = json.dumps( power_parameters, sort_keys=True) if subarchitecture is not None: params["subarchitecture"] = subarchitecture if min_hwe_kernel is not None: params["min_hwe_kernel"] = min_hwe_kernel if hostname is not None: params["hostname"] = hostname if domain is not None: params["domain"] = domain return cls._object(await cls._handler.create(**params))
[ "async", "def", "create", "(", "cls", ",", "architecture", ":", "str", ",", "mac_addresses", ":", "typing", ".", "Sequence", "[", "str", "]", ",", "power_type", ":", "str", ",", "power_parameters", ":", "typing", ".", "Mapping", "[", "str", ",", "typing"...
Create a new machine. :param architecture: The architecture of the machine (required). :type architecture: `str` :param mac_addresses: The MAC address of the machine (required). :type mac_addresses: sequence of `str` :param power_type: The power type of the machine (required). :type power_type: `str` :param power_parameters: The power parameters for the machine (optional). :type power_parameters: mapping of `str` to any value. :param subarchitecture: The subarchitecture of the machine (optional). :type subarchitecture: `str` :param min_hwe_kernel: The minimal HWE kernel for the machine (optional). :param hostname: The hostname for the machine (optional). :type hostname: `str` :param domain: The domain for the machine (optional). :type domain: `int` or `str`
[ "Create", "a", "new", "machine", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L70-L113
train
28,722
maas/python-libmaas
maas/client/viscera/machines.py
Machine.save
async def save(self): """Save the machine in MAAS.""" orig_owner_data = self._orig_data['owner_data'] new_owner_data = dict(self._data['owner_data']) self._changed_data.pop('owner_data', None) await super(Machine, self).save() params_diff = calculate_dict_diff(orig_owner_data, new_owner_data) if len(params_diff) > 0: params_diff['system_id'] = self.system_id await self._handler.set_owner_data(**params_diff) self._data['owner_data'] = self._data['owner_data']
python
async def save(self): """Save the machine in MAAS.""" orig_owner_data = self._orig_data['owner_data'] new_owner_data = dict(self._data['owner_data']) self._changed_data.pop('owner_data', None) await super(Machine, self).save() params_diff = calculate_dict_diff(orig_owner_data, new_owner_data) if len(params_diff) > 0: params_diff['system_id'] = self.system_id await self._handler.set_owner_data(**params_diff) self._data['owner_data'] = self._data['owner_data']
[ "async", "def", "save", "(", "self", ")", ":", "orig_owner_data", "=", "self", ".", "_orig_data", "[", "'owner_data'", "]", "new_owner_data", "=", "dict", "(", "self", ".", "_data", "[", "'owner_data'", "]", ")", "self", ".", "_changed_data", ".", "pop", ...
Save the machine in MAAS.
[ "Save", "the", "machine", "in", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L388-L398
train
28,723
maas/python-libmaas
maas/client/viscera/machines.py
Machine.abort
async def abort(self, *, comment: str = None): """Abort the current action. :param comment: Reason for aborting the action. :param type: `str` """ params = { "system_id": self.system_id } if comment: params["comment"] = comment self._data = await self._handler.abort(**params) return self
python
async def abort(self, *, comment: str = None): """Abort the current action. :param comment: Reason for aborting the action. :param type: `str` """ params = { "system_id": self.system_id } if comment: params["comment"] = comment self._data = await self._handler.abort(**params) return self
[ "async", "def", "abort", "(", "self", ",", "*", ",", "comment", ":", "str", "=", "None", ")", ":", "params", "=", "{", "\"system_id\"", ":", "self", ".", "system_id", "}", "if", "comment", ":", "params", "[", "\"comment\"", "]", "=", "comment", "self...
Abort the current action. :param comment: Reason for aborting the action. :param type: `str`
[ "Abort", "the", "current", "action", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L400-L412
train
28,724
maas/python-libmaas
maas/client/viscera/machines.py
Machine.clear_default_gateways
async def clear_default_gateways(self): """Clear default gateways.""" self._data = await self._handler.clear_default_gateways( system_id=self.system_id) return self
python
async def clear_default_gateways(self): """Clear default gateways.""" self._data = await self._handler.clear_default_gateways( system_id=self.system_id) return self
[ "async", "def", "clear_default_gateways", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "clear_default_gateways", "(", "system_id", "=", "self", ".", "system_id", ")", "return", "self" ]
Clear default gateways.
[ "Clear", "default", "gateways", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L414-L418
train
28,725
maas/python-libmaas
maas/client/viscera/machines.py
Machine.commission
async def commission( self, *, enable_ssh: bool = None, skip_networking: bool = None, skip_storage: bool = None, commissioning_scripts: typing.Sequence[str] = None, testing_scripts: typing.Sequence[str] = None, wait: bool = False, wait_interval: int = 5): """Commission this machine. :param enable_ssh: Prevent the machine from powering off after running commissioning scripts and enable your user to SSH into the machine. :type enable_ssh: `bool` :param skip_networking: Skip updating the MAAS interfaces for the machine. :type skip_networking: `bool` :param skip_storage: Skip update the MAAS block devices for the machine. :type skip_storage: `bool` :param commissioning_scripts: List of extra commisisoning scripts to run. If the name of the commissioning scripts match a tag, then all commissioning scripts with that tag will be used. :type commissioning_scripts: sequence of `str` :param testing_scripts: List of testing scripts to run after commissioning. By default a small set of testing scripts will run by default. Passing empty list will disable running any testing scripts during commissioning. If the name of the testing scripts match a tag, then all testing scripts with that tag will be used. :type testing_scripts: sequence of `str` :param wait: If specified, wait until the commissioning is complete. :param wait_interval: How often to poll, defaults to 5 seconds """ params = {"system_id": self.system_id} if enable_ssh is not None: params["enable_ssh"] = enable_ssh if skip_networking is not None: params["skip_networking"] = skip_networking if skip_storage is not None: params["skip_storage"] = skip_storage if (commissioning_scripts is not None and len(commissioning_scripts) > 0): params["commissioning_scripts"] = ",".join(commissioning_scripts) if testing_scripts is not None: if len(testing_scripts) == 0 or testing_scripts == "none": params["testing_scripts"] = ["none"] else: params["testing_scripts"] = ",".join(testing_scripts) self._data = await self._handler.commission(**params) if not wait: return self else: # Wait for the machine to be fully commissioned. while self.status in [ NodeStatus.COMMISSIONING, NodeStatus.TESTING]: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) if self.status == NodeStatus.FAILED_COMMISSIONING: msg = "{hostname} failed to commission.".format( hostname=self.hostname) raise FailedCommissioning(msg, self) if self.status == NodeStatus.FAILED_TESTING: msg = "{hostname} failed testing.".format( hostname=self.hostname) raise FailedTesting(msg, self) return self
python
async def commission( self, *, enable_ssh: bool = None, skip_networking: bool = None, skip_storage: bool = None, commissioning_scripts: typing.Sequence[str] = None, testing_scripts: typing.Sequence[str] = None, wait: bool = False, wait_interval: int = 5): """Commission this machine. :param enable_ssh: Prevent the machine from powering off after running commissioning scripts and enable your user to SSH into the machine. :type enable_ssh: `bool` :param skip_networking: Skip updating the MAAS interfaces for the machine. :type skip_networking: `bool` :param skip_storage: Skip update the MAAS block devices for the machine. :type skip_storage: `bool` :param commissioning_scripts: List of extra commisisoning scripts to run. If the name of the commissioning scripts match a tag, then all commissioning scripts with that tag will be used. :type commissioning_scripts: sequence of `str` :param testing_scripts: List of testing scripts to run after commissioning. By default a small set of testing scripts will run by default. Passing empty list will disable running any testing scripts during commissioning. If the name of the testing scripts match a tag, then all testing scripts with that tag will be used. :type testing_scripts: sequence of `str` :param wait: If specified, wait until the commissioning is complete. :param wait_interval: How often to poll, defaults to 5 seconds """ params = {"system_id": self.system_id} if enable_ssh is not None: params["enable_ssh"] = enable_ssh if skip_networking is not None: params["skip_networking"] = skip_networking if skip_storage is not None: params["skip_storage"] = skip_storage if (commissioning_scripts is not None and len(commissioning_scripts) > 0): params["commissioning_scripts"] = ",".join(commissioning_scripts) if testing_scripts is not None: if len(testing_scripts) == 0 or testing_scripts == "none": params["testing_scripts"] = ["none"] else: params["testing_scripts"] = ",".join(testing_scripts) self._data = await self._handler.commission(**params) if not wait: return self else: # Wait for the machine to be fully commissioned. while self.status in [ NodeStatus.COMMISSIONING, NodeStatus.TESTING]: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) if self.status == NodeStatus.FAILED_COMMISSIONING: msg = "{hostname} failed to commission.".format( hostname=self.hostname) raise FailedCommissioning(msg, self) if self.status == NodeStatus.FAILED_TESTING: msg = "{hostname} failed testing.".format( hostname=self.hostname) raise FailedTesting(msg, self) return self
[ "async", "def", "commission", "(", "self", ",", "*", ",", "enable_ssh", ":", "bool", "=", "None", ",", "skip_networking", ":", "bool", "=", "None", ",", "skip_storage", ":", "bool", "=", "None", ",", "commissioning_scripts", ":", "typing", ".", "Sequence",...
Commission this machine. :param enable_ssh: Prevent the machine from powering off after running commissioning scripts and enable your user to SSH into the machine. :type enable_ssh: `bool` :param skip_networking: Skip updating the MAAS interfaces for the machine. :type skip_networking: `bool` :param skip_storage: Skip update the MAAS block devices for the machine. :type skip_storage: `bool` :param commissioning_scripts: List of extra commisisoning scripts to run. If the name of the commissioning scripts match a tag, then all commissioning scripts with that tag will be used. :type commissioning_scripts: sequence of `str` :param testing_scripts: List of testing scripts to run after commissioning. By default a small set of testing scripts will run by default. Passing empty list will disable running any testing scripts during commissioning. If the name of the testing scripts match a tag, then all testing scripts with that tag will be used. :type testing_scripts: sequence of `str` :param wait: If specified, wait until the commissioning is complete. :param wait_interval: How often to poll, defaults to 5 seconds
[ "Commission", "this", "machine", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L420-L482
train
28,726
maas/python-libmaas
maas/client/viscera/machines.py
Machine.deploy
async def deploy( self, *, user_data: typing.Union[bytes, str] = None, distro_series: str = None, hwe_kernel: str = None, comment: str = None, wait: bool = False, wait_interval: int = 5): """Deploy this machine. :param user_data: User-data to provide to the machine when booting. If provided as a byte string, it will be base-64 encoded prior to transmission. If provided as a Unicode string it will be assumed to be already base-64 encoded. :param distro_series: The OS to deploy. :param hwe_kernel: The HWE kernel to deploy. Probably only relevant when deploying Ubuntu. :param comment: A comment for the event log. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds """ params = {"system_id": self.system_id} if user_data is not None: if isinstance(user_data, bytes): params["user_data"] = base64.encodebytes(user_data) else: # Already base-64 encoded. Convert to a byte string in # preparation for multipart assembly. params["user_data"] = user_data.encode("ascii") if distro_series is not None: params["distro_series"] = distro_series if hwe_kernel is not None: params["hwe_kernel"] = hwe_kernel if comment is not None: params["comment"] = comment self._data = await self._handler.deploy(**params) if not wait: return self else: # Wait for the machine to be fully deployed while self.status == NodeStatus.DEPLOYING: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) if self.status == NodeStatus.FAILED_DEPLOYMENT: msg = "{hostname} failed to deploy.".format( hostname=self.hostname ) raise FailedDeployment(msg, self) return self
python
async def deploy( self, *, user_data: typing.Union[bytes, str] = None, distro_series: str = None, hwe_kernel: str = None, comment: str = None, wait: bool = False, wait_interval: int = 5): """Deploy this machine. :param user_data: User-data to provide to the machine when booting. If provided as a byte string, it will be base-64 encoded prior to transmission. If provided as a Unicode string it will be assumed to be already base-64 encoded. :param distro_series: The OS to deploy. :param hwe_kernel: The HWE kernel to deploy. Probably only relevant when deploying Ubuntu. :param comment: A comment for the event log. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds """ params = {"system_id": self.system_id} if user_data is not None: if isinstance(user_data, bytes): params["user_data"] = base64.encodebytes(user_data) else: # Already base-64 encoded. Convert to a byte string in # preparation for multipart assembly. params["user_data"] = user_data.encode("ascii") if distro_series is not None: params["distro_series"] = distro_series if hwe_kernel is not None: params["hwe_kernel"] = hwe_kernel if comment is not None: params["comment"] = comment self._data = await self._handler.deploy(**params) if not wait: return self else: # Wait for the machine to be fully deployed while self.status == NodeStatus.DEPLOYING: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) if self.status == NodeStatus.FAILED_DEPLOYMENT: msg = "{hostname} failed to deploy.".format( hostname=self.hostname ) raise FailedDeployment(msg, self) return self
[ "async", "def", "deploy", "(", "self", ",", "*", ",", "user_data", ":", "typing", ".", "Union", "[", "bytes", ",", "str", "]", "=", "None", ",", "distro_series", ":", "str", "=", "None", ",", "hwe_kernel", ":", "str", "=", "None", ",", "comment", "...
Deploy this machine. :param user_data: User-data to provide to the machine when booting. If provided as a byte string, it will be base-64 encoded prior to transmission. If provided as a Unicode string it will be assumed to be already base-64 encoded. :param distro_series: The OS to deploy. :param hwe_kernel: The HWE kernel to deploy. Probably only relevant when deploying Ubuntu. :param comment: A comment for the event log. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds
[ "Deploy", "this", "machine", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L484-L528
train
28,727
maas/python-libmaas
maas/client/viscera/machines.py
Machine.enter_rescue_mode
async def enter_rescue_mode( self, wait: bool = False, wait_interval: int = 5): """ Send this machine into 'rescue mode'. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds """ try: self._data = await self._handler.rescue_mode( system_id=self.system_id) except CallError as error: if error.status == HTTPStatus.FORBIDDEN: message = "Not allowed to enter rescue mode" raise OperationNotAllowed(message) from error else: raise if not wait: return self else: # Wait for machine to finish entering rescue mode while self.status == NodeStatus.ENTERING_RESCUE_MODE: await asyncio.sleep(wait) self._data = await self._handler.read(system_id=self.system_id) if self.status == NodeStatus.FAILED_ENTERING_RESCUE_MODE: msg = "{hostname} failed to enter rescue mode.".format( hostname=self.hostname ) raise RescueModeFailure(msg, self) return self
python
async def enter_rescue_mode( self, wait: bool = False, wait_interval: int = 5): """ Send this machine into 'rescue mode'. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds """ try: self._data = await self._handler.rescue_mode( system_id=self.system_id) except CallError as error: if error.status == HTTPStatus.FORBIDDEN: message = "Not allowed to enter rescue mode" raise OperationNotAllowed(message) from error else: raise if not wait: return self else: # Wait for machine to finish entering rescue mode while self.status == NodeStatus.ENTERING_RESCUE_MODE: await asyncio.sleep(wait) self._data = await self._handler.read(system_id=self.system_id) if self.status == NodeStatus.FAILED_ENTERING_RESCUE_MODE: msg = "{hostname} failed to enter rescue mode.".format( hostname=self.hostname ) raise RescueModeFailure(msg, self) return self
[ "async", "def", "enter_rescue_mode", "(", "self", ",", "wait", ":", "bool", "=", "False", ",", "wait_interval", ":", "int", "=", "5", ")", ":", "try", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "rescue_mode", "(", "system_id...
Send this machine into 'rescue mode'. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds
[ "Send", "this", "machine", "into", "rescue", "mode", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L530-L560
train
28,728
maas/python-libmaas
maas/client/viscera/machines.py
Machine.exit_rescue_mode
async def exit_rescue_mode( self, wait: bool = False, wait_interval: int = 5): """ Exit rescue mode. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds """ try: self._data = await self._handler.exit_rescue_mode( system_id=self.system_id ) except CallError as error: if error.status == HTTPStatus.FORBIDDEN: message = "Not allowed to exit rescue mode." raise OperationNotAllowed(message) from error else: raise if not wait: return self else: # Wait for machine to finish exiting rescue mode while self.status == NodeStatus.EXITING_RESCUE_MODE: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) if self.status == NodeStatus.FAILED_EXITING_RESCUE_MODE: msg = "{hostname} failed to exit rescue mode.".format( hostname=self.hostname ) raise RescueModeFailure(msg, self) return self
python
async def exit_rescue_mode( self, wait: bool = False, wait_interval: int = 5): """ Exit rescue mode. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds """ try: self._data = await self._handler.exit_rescue_mode( system_id=self.system_id ) except CallError as error: if error.status == HTTPStatus.FORBIDDEN: message = "Not allowed to exit rescue mode." raise OperationNotAllowed(message) from error else: raise if not wait: return self else: # Wait for machine to finish exiting rescue mode while self.status == NodeStatus.EXITING_RESCUE_MODE: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) if self.status == NodeStatus.FAILED_EXITING_RESCUE_MODE: msg = "{hostname} failed to exit rescue mode.".format( hostname=self.hostname ) raise RescueModeFailure(msg, self) return self
[ "async", "def", "exit_rescue_mode", "(", "self", ",", "wait", ":", "bool", "=", "False", ",", "wait_interval", ":", "int", "=", "5", ")", ":", "try", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "exit_rescue_mode", "(", "syste...
Exit rescue mode. :param wait: If specified, wait until the deploy is complete. :param wait_interval: How often to poll, defaults to 5 seconds
[ "Exit", "rescue", "mode", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L562-L592
train
28,729
maas/python-libmaas
maas/client/viscera/machines.py
Machine.get_details
async def get_details(self): """Get machine details information. :returns: Mapping of hardware details. """ data = await self._handler.details(system_id=self.system_id) return bson.decode_all(data)[0]
python
async def get_details(self): """Get machine details information. :returns: Mapping of hardware details. """ data = await self._handler.details(system_id=self.system_id) return bson.decode_all(data)[0]
[ "async", "def", "get_details", "(", "self", ")", ":", "data", "=", "await", "self", ".", "_handler", ".", "details", "(", "system_id", "=", "self", ".", "system_id", ")", "return", "bson", ".", "decode_all", "(", "data", ")", "[", "0", "]" ]
Get machine details information. :returns: Mapping of hardware details.
[ "Get", "machine", "details", "information", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L602-L608
train
28,730
maas/python-libmaas
maas/client/viscera/machines.py
Machine.mark_broken
async def mark_broken(self, *, comment: str = None): """Mark broken. :param comment: Reason machine is broken. :type comment: `str` """ params = { "system_id": self.system_id } if comment: params["comment"] = comment self._data = await self._handler.mark_broken(**params) return self
python
async def mark_broken(self, *, comment: str = None): """Mark broken. :param comment: Reason machine is broken. :type comment: `str` """ params = { "system_id": self.system_id } if comment: params["comment"] = comment self._data = await self._handler.mark_broken(**params) return self
[ "async", "def", "mark_broken", "(", "self", ",", "*", ",", "comment", ":", "str", "=", "None", ")", ":", "params", "=", "{", "\"system_id\"", ":", "self", ".", "system_id", "}", "if", "comment", ":", "params", "[", "\"comment\"", "]", "=", "comment", ...
Mark broken. :param comment: Reason machine is broken. :type comment: `str`
[ "Mark", "broken", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L610-L622
train
28,731
maas/python-libmaas
maas/client/viscera/machines.py
Machine.mark_fixed
async def mark_fixed(self, *, comment: str = None): """Mark fixes. :param comment: Reason machine is fixed. :type comment: `str` """ params = { "system_id": self.system_id } if comment: params["comment"] = comment self._data = await self._handler.mark_fixed(**params) return self
python
async def mark_fixed(self, *, comment: str = None): """Mark fixes. :param comment: Reason machine is fixed. :type comment: `str` """ params = { "system_id": self.system_id } if comment: params["comment"] = comment self._data = await self._handler.mark_fixed(**params) return self
[ "async", "def", "mark_fixed", "(", "self", ",", "*", ",", "comment", ":", "str", "=", "None", ")", ":", "params", "=", "{", "\"system_id\"", ":", "self", ".", "system_id", "}", "if", "comment", ":", "params", "[", "\"comment\"", "]", "=", "comment", ...
Mark fixes. :param comment: Reason machine is fixed. :type comment: `str`
[ "Mark", "fixes", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L624-L636
train
28,732
maas/python-libmaas
maas/client/viscera/machines.py
Machine.release
async def release( self, *, comment: str = None, erase: bool = None, secure_erase: bool = None, quick_erase: bool = None, wait: bool = False, wait_interval: int = 5): """ Release the machine. :param comment: Reason machine was released. :type comment: `str` :param erase: Erase the disk when release. :type erase: `bool` :param secure_erase: Use the drive's secure erase feature if available. :type secure_erase: `bool` :param quick_erase: Wipe the just the beginning and end of the disk. This is not secure. :param wait: If specified, wait until the deploy is complete. :type wait: `bool` :param wait_interval: How often to poll, defaults to 5 seconds. :type wait_interval: `int` """ params = remove_None({ "system_id": self.system_id, "comment": comment, "erase": erase, "secure_erase": secure_erase, "quick_erase": quick_erase, }) self._data = await self._handler.release(**params) if not wait: return self else: # Wait for machine to be released while self.status in [ NodeStatus.RELEASING, NodeStatus.DISK_ERASING]: await asyncio.sleep(wait_interval) try: self._data = await self._handler.read( system_id=self.system_id) except CallError as error: if error.status == HTTPStatus.NOT_FOUND: # Release must have been on a machine in a pod. This # machine no longer exists. Just return the machine # as it has been released. return self else: raise if self.status == NodeStatus.FAILED_RELEASING: msg = "{hostname} failed to be released.".format( hostname=self.hostname ) raise FailedReleasing(msg, self) elif self.status == NodeStatus.FAILED_DISK_ERASING: msg = "{hostname} failed to erase disk.".format( hostname=self.hostname ) raise FailedDiskErasing(msg, self) return self
python
async def release( self, *, comment: str = None, erase: bool = None, secure_erase: bool = None, quick_erase: bool = None, wait: bool = False, wait_interval: int = 5): """ Release the machine. :param comment: Reason machine was released. :type comment: `str` :param erase: Erase the disk when release. :type erase: `bool` :param secure_erase: Use the drive's secure erase feature if available. :type secure_erase: `bool` :param quick_erase: Wipe the just the beginning and end of the disk. This is not secure. :param wait: If specified, wait until the deploy is complete. :type wait: `bool` :param wait_interval: How often to poll, defaults to 5 seconds. :type wait_interval: `int` """ params = remove_None({ "system_id": self.system_id, "comment": comment, "erase": erase, "secure_erase": secure_erase, "quick_erase": quick_erase, }) self._data = await self._handler.release(**params) if not wait: return self else: # Wait for machine to be released while self.status in [ NodeStatus.RELEASING, NodeStatus.DISK_ERASING]: await asyncio.sleep(wait_interval) try: self._data = await self._handler.read( system_id=self.system_id) except CallError as error: if error.status == HTTPStatus.NOT_FOUND: # Release must have been on a machine in a pod. This # machine no longer exists. Just return the machine # as it has been released. return self else: raise if self.status == NodeStatus.FAILED_RELEASING: msg = "{hostname} failed to be released.".format( hostname=self.hostname ) raise FailedReleasing(msg, self) elif self.status == NodeStatus.FAILED_DISK_ERASING: msg = "{hostname} failed to erase disk.".format( hostname=self.hostname ) raise FailedDiskErasing(msg, self) return self
[ "async", "def", "release", "(", "self", ",", "*", ",", "comment", ":", "str", "=", "None", ",", "erase", ":", "bool", "=", "None", ",", "secure_erase", ":", "bool", "=", "None", ",", "quick_erase", ":", "bool", "=", "None", ",", "wait", ":", "bool"...
Release the machine. :param comment: Reason machine was released. :type comment: `str` :param erase: Erase the disk when release. :type erase: `bool` :param secure_erase: Use the drive's secure erase feature if available. :type secure_erase: `bool` :param quick_erase: Wipe the just the beginning and end of the disk. This is not secure. :param wait: If specified, wait until the deploy is complete. :type wait: `bool` :param wait_interval: How often to poll, defaults to 5 seconds. :type wait_interval: `int`
[ "Release", "the", "machine", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L638-L694
train
28,733
maas/python-libmaas
maas/client/viscera/machines.py
Machine.power_on
async def power_on( self, comment: str = None, wait: bool = False, wait_interval: int = 5): """ Power on. :param comment: Reason machine was powered on. :type comment: `str` :param wait: If specified, wait until the machine is powered on. :type wait: `bool` :param wait_interval: How often to poll, defaults to 5 seconds. :type wait_interval: `int` """ params = {"system_id": self.system_id} if comment is not None: params["comment"] = comment try: self._data = await self._handler.power_on(**params) except CallError as error: if error.status == HTTPStatus.FORBIDDEN: message = "Not allowed to power on machine." raise OperationNotAllowed(message) from error else: raise if not wait or self.power_state == PowerState.UNKNOWN: # Don't wait for a machine that always shows power state as # unknown as the driver cannot query the power state. return self else: # Wait for machine to be powered on. while self.power_state == PowerState.OFF: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) if self.power_state == PowerState.ERROR: msg = "{hostname} failed to power on.".format( hostname=self.hostname ) raise PowerError(msg, self) return self
python
async def power_on( self, comment: str = None, wait: bool = False, wait_interval: int = 5): """ Power on. :param comment: Reason machine was powered on. :type comment: `str` :param wait: If specified, wait until the machine is powered on. :type wait: `bool` :param wait_interval: How often to poll, defaults to 5 seconds. :type wait_interval: `int` """ params = {"system_id": self.system_id} if comment is not None: params["comment"] = comment try: self._data = await self._handler.power_on(**params) except CallError as error: if error.status == HTTPStatus.FORBIDDEN: message = "Not allowed to power on machine." raise OperationNotAllowed(message) from error else: raise if not wait or self.power_state == PowerState.UNKNOWN: # Don't wait for a machine that always shows power state as # unknown as the driver cannot query the power state. return self else: # Wait for machine to be powered on. while self.power_state == PowerState.OFF: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) if self.power_state == PowerState.ERROR: msg = "{hostname} failed to power on.".format( hostname=self.hostname ) raise PowerError(msg, self) return self
[ "async", "def", "power_on", "(", "self", ",", "comment", ":", "str", "=", "None", ",", "wait", ":", "bool", "=", "False", ",", "wait_interval", ":", "int", "=", "5", ")", ":", "params", "=", "{", "\"system_id\"", ":", "self", ".", "system_id", "}", ...
Power on. :param comment: Reason machine was powered on. :type comment: `str` :param wait: If specified, wait until the machine is powered on. :type wait: `bool` :param wait_interval: How often to poll, defaults to 5 seconds. :type wait_interval: `int`
[ "Power", "on", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L696-L734
train
28,734
maas/python-libmaas
maas/client/viscera/machines.py
Machine.power_off
async def power_off( self, stop_mode: PowerStopMode = PowerStopMode.HARD, comment: str = None, wait: bool = False, wait_interval: int = 5): """ Power off. :param stop_mode: How to perform the power off. :type stop_mode: `PowerStopMode` :param comment: Reason machine was powered on. :type comment: `str` :param wait: If specified, wait until the machine is powered on. :type wait: `bool` :param wait_interval: How often to poll, defaults to 5 seconds. :type wait_interval: `int` """ params = {"system_id": self.system_id, 'stop_mode': stop_mode.value} if comment is not None: params["comment"] = comment try: self._data = await self._handler.power_off(**params) except CallError as error: if error.status == HTTPStatus.FORBIDDEN: message = "Not allowed to power off machine." raise OperationNotAllowed(message) from error else: raise if not wait or self.power_state == PowerState.UNKNOWN: # Don't wait for a machine that always shows power state as # unknown as the driver cannot query the power state. return self else: # Wait for machine to be powered off. while self.power_state == PowerState.ON: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) if self.power_state == PowerState.ERROR: msg = "{hostname} failed to power off.".format( hostname=self.hostname ) raise PowerError(msg, self) return self
python
async def power_off( self, stop_mode: PowerStopMode = PowerStopMode.HARD, comment: str = None, wait: bool = False, wait_interval: int = 5): """ Power off. :param stop_mode: How to perform the power off. :type stop_mode: `PowerStopMode` :param comment: Reason machine was powered on. :type comment: `str` :param wait: If specified, wait until the machine is powered on. :type wait: `bool` :param wait_interval: How often to poll, defaults to 5 seconds. :type wait_interval: `int` """ params = {"system_id": self.system_id, 'stop_mode': stop_mode.value} if comment is not None: params["comment"] = comment try: self._data = await self._handler.power_off(**params) except CallError as error: if error.status == HTTPStatus.FORBIDDEN: message = "Not allowed to power off machine." raise OperationNotAllowed(message) from error else: raise if not wait or self.power_state == PowerState.UNKNOWN: # Don't wait for a machine that always shows power state as # unknown as the driver cannot query the power state. return self else: # Wait for machine to be powered off. while self.power_state == PowerState.ON: await asyncio.sleep(wait_interval) self._data = await self._handler.read(system_id=self.system_id) if self.power_state == PowerState.ERROR: msg = "{hostname} failed to power off.".format( hostname=self.hostname ) raise PowerError(msg, self) return self
[ "async", "def", "power_off", "(", "self", ",", "stop_mode", ":", "PowerStopMode", "=", "PowerStopMode", ".", "HARD", ",", "comment", ":", "str", "=", "None", ",", "wait", ":", "bool", "=", "False", ",", "wait_interval", ":", "int", "=", "5", ")", ":", ...
Power off. :param stop_mode: How to perform the power off. :type stop_mode: `PowerStopMode` :param comment: Reason machine was powered on. :type comment: `str` :param wait: If specified, wait until the machine is powered on. :type wait: `bool` :param wait_interval: How often to poll, defaults to 5 seconds. :type wait_interval: `int`
[ "Power", "off", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L736-L776
train
28,735
maas/python-libmaas
maas/client/viscera/machines.py
Machine.query_power_state
async def query_power_state(self): """ Query the machine's BMC for the current power state. :returns: Current power state. :rtype: `PowerState` """ power_data = await self._handler.query_power_state( system_id=self.system_id) # Update the internal state of this object as well, since we have the # updated power state from the BMC directly. MAAS server does this as # well, just do it client side to make it nice for a developer. self._data['power_state'] = power_data['state'] return PowerState(power_data['state'])
python
async def query_power_state(self): """ Query the machine's BMC for the current power state. :returns: Current power state. :rtype: `PowerState` """ power_data = await self._handler.query_power_state( system_id=self.system_id) # Update the internal state of this object as well, since we have the # updated power state from the BMC directly. MAAS server does this as # well, just do it client side to make it nice for a developer. self._data['power_state'] = power_data['state'] return PowerState(power_data['state'])
[ "async", "def", "query_power_state", "(", "self", ")", ":", "power_data", "=", "await", "self", ".", "_handler", ".", "query_power_state", "(", "system_id", "=", "self", ".", "system_id", ")", "# Update the internal state of this object as well, since we have the", "# u...
Query the machine's BMC for the current power state. :returns: Current power state. :rtype: `PowerState`
[ "Query", "the", "machine", "s", "BMC", "for", "the", "current", "power", "state", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L778-L791
train
28,736
maas/python-libmaas
maas/client/viscera/machines.py
Machine.restore_default_configuration
async def restore_default_configuration(self): """ Restore machine's configuration to its initial state. """ self._data = await self._handler.restore_default_configuration( system_id=self.system_id)
python
async def restore_default_configuration(self): """ Restore machine's configuration to its initial state. """ self._data = await self._handler.restore_default_configuration( system_id=self.system_id)
[ "async", "def", "restore_default_configuration", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "restore_default_configuration", "(", "system_id", "=", "self", ".", "system_id", ")" ]
Restore machine's configuration to its initial state.
[ "Restore", "machine", "s", "configuration", "to", "its", "initial", "state", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L793-L798
train
28,737
maas/python-libmaas
maas/client/viscera/machines.py
Machine.restore_networking_configuration
async def restore_networking_configuration(self): """ Restore machine's networking configuration to its initial state. """ self._data = await self._handler.restore_networking_configuration( system_id=self.system_id)
python
async def restore_networking_configuration(self): """ Restore machine's networking configuration to its initial state. """ self._data = await self._handler.restore_networking_configuration( system_id=self.system_id)
[ "async", "def", "restore_networking_configuration", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "restore_networking_configuration", "(", "system_id", "=", "self", ".", "system_id", ")" ]
Restore machine's networking configuration to its initial state.
[ "Restore", "machine", "s", "networking", "configuration", "to", "its", "initial", "state", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L800-L805
train
28,738
maas/python-libmaas
maas/client/viscera/machines.py
Machine.restore_storage_configuration
async def restore_storage_configuration(self): """ Restore machine's storage configuration to its initial state. """ self._data = await self._handler.restore_storage_configuration( system_id=self.system_id)
python
async def restore_storage_configuration(self): """ Restore machine's storage configuration to its initial state. """ self._data = await self._handler.restore_storage_configuration( system_id=self.system_id)
[ "async", "def", "restore_storage_configuration", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "restore_storage_configuration", "(", "system_id", "=", "self", ".", "system_id", ")" ]
Restore machine's storage configuration to its initial state.
[ "Restore", "machine", "s", "storage", "configuration", "to", "its", "initial", "state", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L807-L812
train
28,739
maas/python-libmaas
maas/client/viscera/spaces.py
SpacesType.create
async def create( cls, *, name: str = None, description: str = None): """ Create a `Space` in MAAS. :param name: The name of the `Space` (optional, will be given a default value if not specified). :type name: `str` :param description: A description of the `Space` (optional). :type description: `str` :returns: The created Space :rtype: `Space` """ params = {} if name is not None: params["name"] = name if description is not None: params["description"] = description return cls._object(await cls._handler.create(**params))
python
async def create( cls, *, name: str = None, description: str = None): """ Create a `Space` in MAAS. :param name: The name of the `Space` (optional, will be given a default value if not specified). :type name: `str` :param description: A description of the `Space` (optional). :type description: `str` :returns: The created Space :rtype: `Space` """ params = {} if name is not None: params["name"] = name if description is not None: params["description"] = description return cls._object(await cls._handler.create(**params))
[ "async", "def", "create", "(", "cls", ",", "*", ",", "name", ":", "str", "=", "None", ",", "description", ":", "str", "=", "None", ")", ":", "params", "=", "{", "}", "if", "name", "is", "not", "None", ":", "params", "[", "\"name\"", "]", "=", "...
Create a `Space` in MAAS. :param name: The name of the `Space` (optional, will be given a default value if not specified). :type name: `str` :param description: A description of the `Space` (optional). :type description: `str` :returns: The created Space :rtype: `Space`
[ "Create", "a", "Space", "in", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/spaces.py#L25-L43
train
28,740
maas/python-libmaas
maas/client/viscera/spaces.py
SpaceType.get_default
async def get_default(cls): """Get the 'default' Space for the MAAS.""" data = await cls._handler.read(id=cls._default_space_id) return cls(data)
python
async def get_default(cls): """Get the 'default' Space for the MAAS.""" data = await cls._handler.read(id=cls._default_space_id) return cls(data)
[ "async", "def", "get_default", "(", "cls", ")", ":", "data", "=", "await", "cls", ".", "_handler", ".", "read", "(", "id", "=", "cls", ".", "_default_space_id", ")", "return", "cls", "(", "data", ")" ]
Get the 'default' Space for the MAAS.
[ "Get", "the", "default", "Space", "for", "the", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/spaces.py#L54-L57
train
28,741
maas/python-libmaas
maas/client/viscera/spaces.py
Space.delete
async def delete(self): """Delete this Space.""" if self.id == self._origin.Space._default_space_id: raise DeleteDefaultSpace("Cannot delete default space.") await self._handler.delete(id=self.id)
python
async def delete(self): """Delete this Space.""" if self.id == self._origin.Space._default_space_id: raise DeleteDefaultSpace("Cannot delete default space.") await self._handler.delete(id=self.id)
[ "async", "def", "delete", "(", "self", ")", ":", "if", "self", ".", "id", "==", "self", ".", "_origin", ".", "Space", ".", "_default_space_id", ":", "raise", "DeleteDefaultSpace", "(", "\"Cannot delete default space.\"", ")", "await", "self", ".", "_handler", ...
Delete this Space.
[ "Delete", "this", "Space", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/spaces.py#L77-L81
train
28,742
maas/python-libmaas
maas/client/viscera/vlans.py
VlanType.read
async def read(cls, fabric: Union[Fabric, int], vid: int): """Get `Vlan` by `vid`. :param fabric: Fabric to get the VLAN from. :type fabric: `Fabric` or `int` :param vid: VID of VLAN. :type vid: `int` """ if isinstance(fabric, int): fabric_id = fabric elif isinstance(fabric, Fabric): fabric_id = fabric.id else: raise TypeError( "fabric must be a Fabric or int, not %s" % type(fabric).__name__) data = await cls._handler.read(fabric_id=fabric_id, vid=vid) return cls(data, {"fabric_id": fabric_id})
python
async def read(cls, fabric: Union[Fabric, int], vid: int): """Get `Vlan` by `vid`. :param fabric: Fabric to get the VLAN from. :type fabric: `Fabric` or `int` :param vid: VID of VLAN. :type vid: `int` """ if isinstance(fabric, int): fabric_id = fabric elif isinstance(fabric, Fabric): fabric_id = fabric.id else: raise TypeError( "fabric must be a Fabric or int, not %s" % type(fabric).__name__) data = await cls._handler.read(fabric_id=fabric_id, vid=vid) return cls(data, {"fabric_id": fabric_id})
[ "async", "def", "read", "(", "cls", ",", "fabric", ":", "Union", "[", "Fabric", ",", "int", "]", ",", "vid", ":", "int", ")", ":", "if", "isinstance", "(", "fabric", ",", "int", ")", ":", "fabric_id", "=", "fabric", "elif", "isinstance", "(", "fabr...
Get `Vlan` by `vid`. :param fabric: Fabric to get the VLAN from. :type fabric: `Fabric` or `int` :param vid: VID of VLAN. :type vid: `int`
[ "Get", "Vlan", "by", "vid", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/vlans.py#L28-L45
train
28,743
maas/python-libmaas
maas/client/viscera/vlans.py
Vlan.delete
async def delete(self): """Delete this VLAN.""" # Since the VID can be changed for the VLAN, we always use the vid # from the original data. That way if the user changes the vid the # delete still works, until the VLAN has been saved. await self._handler.delete( fabric_id=self.fabric.id, vid=self._orig_data['vid'])
python
async def delete(self): """Delete this VLAN.""" # Since the VID can be changed for the VLAN, we always use the vid # from the original data. That way if the user changes the vid the # delete still works, until the VLAN has been saved. await self._handler.delete( fabric_id=self.fabric.id, vid=self._orig_data['vid'])
[ "async", "def", "delete", "(", "self", ")", ":", "# Since the VID can be changed for the VLAN, we always use the vid", "# from the original data. That way if the user changes the vid the", "# delete still works, until the VLAN has been saved.", "await", "self", ".", "_handler", ".", "d...
Delete this VLAN.
[ "Delete", "this", "VLAN", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/vlans.py#L130-L136
train
28,744
maas/python-libmaas
maas/client/viscera/vlans.py
VlansType.read
async def read(cls, fabric: Union[Fabric, int]): """Get list of `Vlan`'s for `fabric`. :param fabric: Fabric to get all VLAN's for. :type fabric: `Fabric` or `int` """ if isinstance(fabric, int): fabric_id = fabric elif isinstance(fabric, Fabric): fabric_id = fabric.id else: raise TypeError( "fabric must be a Fabric or int, not %s" % type(fabric).__name__) data = await cls._handler.read(fabric_id=fabric_id) return cls( cls._object( item, local_data={"fabric_id": fabric_id}) for item in data)
python
async def read(cls, fabric: Union[Fabric, int]): """Get list of `Vlan`'s for `fabric`. :param fabric: Fabric to get all VLAN's for. :type fabric: `Fabric` or `int` """ if isinstance(fabric, int): fabric_id = fabric elif isinstance(fabric, Fabric): fabric_id = fabric.id else: raise TypeError( "fabric must be a Fabric or int, not %s" % type(fabric).__name__) data = await cls._handler.read(fabric_id=fabric_id) return cls( cls._object( item, local_data={"fabric_id": fabric_id}) for item in data)
[ "async", "def", "read", "(", "cls", ",", "fabric", ":", "Union", "[", "Fabric", ",", "int", "]", ")", ":", "if", "isinstance", "(", "fabric", ",", "int", ")", ":", "fabric_id", "=", "fabric", "elif", "isinstance", "(", "fabric", ",", "Fabric", ")", ...
Get list of `Vlan`'s for `fabric`. :param fabric: Fabric to get all VLAN's for. :type fabric: `Fabric` or `int`
[ "Get", "list", "of", "Vlan", "s", "for", "fabric", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/vlans.py#L142-L160
train
28,745
maas/python-libmaas
maas/client/viscera/vlans.py
VlansType.create
async def create( cls, fabric: Union[Fabric, int], vid: int, *, name: str = None, description: str = None, mtu: int = None, relay_vlan: Union[Vlan, int] = None, dhcp_on: bool = False, primary_rack: Union[RackController, str] = None, secondary_rack: Union[RackController, str] = None, space: Union[Space, int] = None): """ Create a `Vlan` in MAAS. :param fabric: Fabric to create the VLAN on. :type fabric: `Fabric` or `int` :param vid: VID for the VLAN. :type vid: `int` :param name: The name of the VLAN (optional). :type name: `str` :param description: A description of the VLAN (optional). :type description: `str` :param mtu: The MTU for VLAN (optional, default of 1500 will be used). :type mtu: `int` :param relay_vlan: VLAN to relay this VLAN through. :type relay_vlan: `Vlan` or `int` :param dhcp_on: True turns the DHCP on, false keeps the DHCP off. True requires that `primary_rack` is also set. :type dhcp_on: `bool` :param primary_rack: Primary rack controller to run the DCHP service on. :type primary_rack: `RackController` or `int` :parma secondary_rack: Secondary rack controller to run the DHCP service on. This will enable HA operation of the DHCP service. :type secondary_rack: `RackController` or `int` :returns: The created VLAN. :rtype: `Vlan` """ params = {} if isinstance(fabric, int): params['fabric_id'] = fabric elif isinstance(fabric, Fabric): params['fabric_id'] = fabric.id else: raise TypeError( "fabric must be Fabric or int, not %s" % ( type(fabric).__class__)) params['vid'] = vid if name is not None: params['name'] = name if description is not None: params['description'] = description if mtu is not None: params['mtu'] = mtu if relay_vlan is not None: if isinstance(relay_vlan, int): params['relay_vlan'] = relay_vlan elif isinstance(relay_vlan, Vlan): params['relay_vlan'] = relay_vlan.id else: raise TypeError( "relay_vlan must be Vlan or int, not %s" % ( type(relay_vlan).__class__)) params['dhcp_on'] = dhcp_on if primary_rack is not None: if isinstance(primary_rack, str): params['primary_rack'] = primary_rack elif isinstance(primary_rack, RackController): params['primary_rack'] = primary_rack.system_id else: raise TypeError( "primary_rack must be RackController or str, not %s" % ( type(primary_rack).__class__)) if secondary_rack is not None: if isinstance(secondary_rack, str): params['secondary_rack'] = secondary_rack elif isinstance(secondary_rack, RackController): params['secondary_rack'] = secondary_rack.system_id else: raise TypeError( "secondary_rack must be RackController or str, not %s" % ( type(secondary_rack).__class__)) if space is not None: if isinstance(space, int): params['space'] = space elif isinstance(space, Space): params['space'] = space.id else: raise TypeError( "space must be Space or int, not %s" % ( type(space).__class__)) return cls._object(await cls._handler.create(**params))
python
async def create( cls, fabric: Union[Fabric, int], vid: int, *, name: str = None, description: str = None, mtu: int = None, relay_vlan: Union[Vlan, int] = None, dhcp_on: bool = False, primary_rack: Union[RackController, str] = None, secondary_rack: Union[RackController, str] = None, space: Union[Space, int] = None): """ Create a `Vlan` in MAAS. :param fabric: Fabric to create the VLAN on. :type fabric: `Fabric` or `int` :param vid: VID for the VLAN. :type vid: `int` :param name: The name of the VLAN (optional). :type name: `str` :param description: A description of the VLAN (optional). :type description: `str` :param mtu: The MTU for VLAN (optional, default of 1500 will be used). :type mtu: `int` :param relay_vlan: VLAN to relay this VLAN through. :type relay_vlan: `Vlan` or `int` :param dhcp_on: True turns the DHCP on, false keeps the DHCP off. True requires that `primary_rack` is also set. :type dhcp_on: `bool` :param primary_rack: Primary rack controller to run the DCHP service on. :type primary_rack: `RackController` or `int` :parma secondary_rack: Secondary rack controller to run the DHCP service on. This will enable HA operation of the DHCP service. :type secondary_rack: `RackController` or `int` :returns: The created VLAN. :rtype: `Vlan` """ params = {} if isinstance(fabric, int): params['fabric_id'] = fabric elif isinstance(fabric, Fabric): params['fabric_id'] = fabric.id else: raise TypeError( "fabric must be Fabric or int, not %s" % ( type(fabric).__class__)) params['vid'] = vid if name is not None: params['name'] = name if description is not None: params['description'] = description if mtu is not None: params['mtu'] = mtu if relay_vlan is not None: if isinstance(relay_vlan, int): params['relay_vlan'] = relay_vlan elif isinstance(relay_vlan, Vlan): params['relay_vlan'] = relay_vlan.id else: raise TypeError( "relay_vlan must be Vlan or int, not %s" % ( type(relay_vlan).__class__)) params['dhcp_on'] = dhcp_on if primary_rack is not None: if isinstance(primary_rack, str): params['primary_rack'] = primary_rack elif isinstance(primary_rack, RackController): params['primary_rack'] = primary_rack.system_id else: raise TypeError( "primary_rack must be RackController or str, not %s" % ( type(primary_rack).__class__)) if secondary_rack is not None: if isinstance(secondary_rack, str): params['secondary_rack'] = secondary_rack elif isinstance(secondary_rack, RackController): params['secondary_rack'] = secondary_rack.system_id else: raise TypeError( "secondary_rack must be RackController or str, not %s" % ( type(secondary_rack).__class__)) if space is not None: if isinstance(space, int): params['space'] = space elif isinstance(space, Space): params['space'] = space.id else: raise TypeError( "space must be Space or int, not %s" % ( type(space).__class__)) return cls._object(await cls._handler.create(**params))
[ "async", "def", "create", "(", "cls", ",", "fabric", ":", "Union", "[", "Fabric", ",", "int", "]", ",", "vid", ":", "int", ",", "*", ",", "name", ":", "str", "=", "None", ",", "description", ":", "str", "=", "None", ",", "mtu", ":", "int", "=",...
Create a `Vlan` in MAAS. :param fabric: Fabric to create the VLAN on. :type fabric: `Fabric` or `int` :param vid: VID for the VLAN. :type vid: `int` :param name: The name of the VLAN (optional). :type name: `str` :param description: A description of the VLAN (optional). :type description: `str` :param mtu: The MTU for VLAN (optional, default of 1500 will be used). :type mtu: `int` :param relay_vlan: VLAN to relay this VLAN through. :type relay_vlan: `Vlan` or `int` :param dhcp_on: True turns the DHCP on, false keeps the DHCP off. True requires that `primary_rack` is also set. :type dhcp_on: `bool` :param primary_rack: Primary rack controller to run the DCHP service on. :type primary_rack: `RackController` or `int` :parma secondary_rack: Secondary rack controller to run the DHCP service on. This will enable HA operation of the DHCP service. :type secondary_rack: `RackController` or `int` :returns: The created VLAN. :rtype: `Vlan`
[ "Create", "a", "Vlan", "in", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/vlans.py#L162-L249
train
28,746
maas/python-libmaas
maas/client/viscera/vlans.py
Vlans.get_default
def get_default(self): """Return the default VLAN from the set.""" length = len(self) if length == 0: return None elif length == 1: return self[0] else: return sorted(self, key=attrgetter('id'))[0]
python
def get_default(self): """Return the default VLAN from the set.""" length = len(self) if length == 0: return None elif length == 1: return self[0] else: return sorted(self, key=attrgetter('id'))[0]
[ "def", "get_default", "(", "self", ")", ":", "length", "=", "len", "(", "self", ")", "if", "length", "==", "0", ":", "return", "None", "elif", "length", "==", "1", ":", "return", "self", "[", "0", "]", "else", ":", "return", "sorted", "(", "self", ...
Return the default VLAN from the set.
[ "Return", "the", "default", "VLAN", "from", "the", "set", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/vlans.py#L255-L263
train
28,747
maas/python-libmaas
maas/client/utils/multipart.py
get_content_type
def get_content_type(*names): """Return the MIME content type for the file with the given name.""" for name in names: if name is not None: mimetype, encoding = mimetypes.guess_type(name) if mimetype is not None: if isinstance(mimetype, bytes): return mimetype.decode("ascii") else: return mimetype else: return "application/octet-stream"
python
def get_content_type(*names): """Return the MIME content type for the file with the given name.""" for name in names: if name is not None: mimetype, encoding = mimetypes.guess_type(name) if mimetype is not None: if isinstance(mimetype, bytes): return mimetype.decode("ascii") else: return mimetype else: return "application/octet-stream"
[ "def", "get_content_type", "(", "*", "names", ")", ":", "for", "name", "in", "names", ":", "if", "name", "is", "not", "None", ":", "mimetype", ",", "encoding", "=", "mimetypes", ".", "guess_type", "(", "name", ")", "if", "mimetype", "is", "not", "None"...
Return the MIME content type for the file with the given name.
[ "Return", "the", "MIME", "content", "type", "for", "the", "file", "with", "the", "given", "name", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/multipart.py#L36-L47
train
28,748
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.set_http_proxy
async def set_http_proxy(cls, url: typing.Optional[str]): """See `get_http_proxy`.""" await cls.set_config("http_proxy", "" if url is None else url)
python
async def set_http_proxy(cls, url: typing.Optional[str]): """See `get_http_proxy`.""" await cls.set_config("http_proxy", "" if url is None else url)
[ "async", "def", "set_http_proxy", "(", "cls", ",", "url", ":", "typing", ".", "Optional", "[", "str", "]", ")", ":", "await", "cls", ".", "set_config", "(", "\"http_proxy\"", ",", "\"\"", "if", "url", "is", "None", "else", "url", ")" ]
See `get_http_proxy`.
[ "See", "get_http_proxy", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L127-L129
train
28,749
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.get_kernel_options
async def get_kernel_options(cls) -> typing.Optional[str]: """Kernel options. Boot parameters to pass to the kernel by default. """ data = await cls.get_config("kernel_opts") return None if data is None or data == "" else data
python
async def get_kernel_options(cls) -> typing.Optional[str]: """Kernel options. Boot parameters to pass to the kernel by default. """ data = await cls.get_config("kernel_opts") return None if data is None or data == "" else data
[ "async", "def", "get_kernel_options", "(", "cls", ")", "->", "typing", ".", "Optional", "[", "str", "]", ":", "data", "=", "await", "cls", ".", "get_config", "(", "\"kernel_opts\"", ")", "return", "None", "if", "data", "is", "None", "or", "data", "==", ...
Kernel options. Boot parameters to pass to the kernel by default.
[ "Kernel", "options", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L155-L161
train
28,750
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.set_kernel_options
async def set_kernel_options(cls, options: typing.Optional[str]): """See `get_kernel_options`.""" await cls.set_config("kernel_opts", "" if options is None else options)
python
async def set_kernel_options(cls, options: typing.Optional[str]): """See `get_kernel_options`.""" await cls.set_config("kernel_opts", "" if options is None else options)
[ "async", "def", "set_kernel_options", "(", "cls", ",", "options", ":", "typing", ".", "Optional", "[", "str", "]", ")", ":", "await", "cls", ".", "set_config", "(", "\"kernel_opts\"", ",", "\"\"", "if", "options", "is", "None", "else", "options", ")" ]
See `get_kernel_options`.
[ "See", "get_kernel_options", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L163-L165
train
28,751
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.get_upstream_dns
async def get_upstream_dns(cls) -> list: """Upstream DNS server addresses. Upstream DNS servers used to resolve domains not managed by this MAAS (space-separated IP addresses). Only used when MAAS is running its own DNS server. This value is used as the value of 'forwarders' in the DNS server config. """ data = await cls.get_config("upstream_dns") return [] if data is None else re.split(r'[,\s]+', data)
python
async def get_upstream_dns(cls) -> list: """Upstream DNS server addresses. Upstream DNS servers used to resolve domains not managed by this MAAS (space-separated IP addresses). Only used when MAAS is running its own DNS server. This value is used as the value of 'forwarders' in the DNS server config. """ data = await cls.get_config("upstream_dns") return [] if data is None else re.split(r'[,\s]+', data)
[ "async", "def", "get_upstream_dns", "(", "cls", ")", "->", "list", ":", "data", "=", "await", "cls", ".", "get_config", "(", "\"upstream_dns\"", ")", "return", "[", "]", "if", "data", "is", "None", "else", "re", ".", "split", "(", "r'[,\\s]+'", ",", "d...
Upstream DNS server addresses. Upstream DNS servers used to resolve domains not managed by this MAAS (space-separated IP addresses). Only used when MAAS is running its own DNS server. This value is used as the value of 'forwarders' in the DNS server config.
[ "Upstream", "DNS", "server", "addresses", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L167-L176
train
28,752
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.set_upstream_dns
async def set_upstream_dns( cls, addresses: typing.Optional[typing.Sequence[str]]): """See `get_upstream_dns`.""" await cls.set_config("upstream_dns", ( "" if addresses is None else",".join(addresses)))
python
async def set_upstream_dns( cls, addresses: typing.Optional[typing.Sequence[str]]): """See `get_upstream_dns`.""" await cls.set_config("upstream_dns", ( "" if addresses is None else",".join(addresses)))
[ "async", "def", "set_upstream_dns", "(", "cls", ",", "addresses", ":", "typing", ".", "Optional", "[", "typing", ".", "Sequence", "[", "str", "]", "]", ")", ":", "await", "cls", ".", "set_config", "(", "\"upstream_dns\"", ",", "(", "\"\"", "if", "address...
See `get_upstream_dns`.
[ "See", "get_upstream_dns", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L178-L182
train
28,753
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.get_dnssec_validation
async def get_dnssec_validation(cls) -> DNSSEC: """Enable DNSSEC validation of upstream zones. Only used when MAAS is running its own DNS server. This value is used as the value of 'dnssec_validation' in the DNS server config. """ data = await cls.get_config("dnssec_validation") return cls.DNSSEC.lookup(data)
python
async def get_dnssec_validation(cls) -> DNSSEC: """Enable DNSSEC validation of upstream zones. Only used when MAAS is running its own DNS server. This value is used as the value of 'dnssec_validation' in the DNS server config. """ data = await cls.get_config("dnssec_validation") return cls.DNSSEC.lookup(data)
[ "async", "def", "get_dnssec_validation", "(", "cls", ")", "->", "DNSSEC", ":", "data", "=", "await", "cls", ".", "get_config", "(", "\"dnssec_validation\"", ")", "return", "cls", ".", "DNSSEC", ".", "lookup", "(", "data", ")" ]
Enable DNSSEC validation of upstream zones. Only used when MAAS is running its own DNS server. This value is used as the value of 'dnssec_validation' in the DNS server config.
[ "Enable", "DNSSEC", "validation", "of", "upstream", "zones", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L194-L201
train
28,754
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.get_windows_kms_host
async def get_windows_kms_host(cls) -> typing.Optional[str]: """Windows KMS activation host. FQDN or IP address of the host that provides the KMS Windows activation service. (Only needed for Windows deployments using KMS activation.) """ data = await cls.get_config("windows_kms_host") return None if data is None or data == "" else data
python
async def get_windows_kms_host(cls) -> typing.Optional[str]: """Windows KMS activation host. FQDN or IP address of the host that provides the KMS Windows activation service. (Only needed for Windows deployments using KMS activation.) """ data = await cls.get_config("windows_kms_host") return None if data is None or data == "" else data
[ "async", "def", "get_windows_kms_host", "(", "cls", ")", "->", "typing", ".", "Optional", "[", "str", "]", ":", "data", "=", "await", "cls", ".", "get_config", "(", "\"windows_kms_host\"", ")", "return", "None", "if", "data", "is", "None", "or", "data", ...
Windows KMS activation host. FQDN or IP address of the host that provides the KMS Windows activation service. (Only needed for Windows deployments using KMS activation.)
[ "Windows", "KMS", "activation", "host", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L228-L236
train
28,755
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.set_windows_kms_host
async def set_windows_kms_host(cls, host: typing.Optional[str]): """See `get_windows_kms_host`.""" await cls.set_config("windows_kms_host", "" if host is None else host)
python
async def set_windows_kms_host(cls, host: typing.Optional[str]): """See `get_windows_kms_host`.""" await cls.set_config("windows_kms_host", "" if host is None else host)
[ "async", "def", "set_windows_kms_host", "(", "cls", ",", "host", ":", "typing", ".", "Optional", "[", "str", "]", ")", ":", "await", "cls", ".", "set_config", "(", "\"windows_kms_host\"", ",", "\"\"", "if", "host", "is", "None", "else", "host", ")" ]
See `get_windows_kms_host`.
[ "See", "get_windows_kms_host", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L238-L240
train
28,756
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.get_default_storage_layout
async def get_default_storage_layout(cls) -> StorageLayout: """Default storage layout. Storage layout that is applied to a node when it is deployed. """ data = await cls.get_config("default_storage_layout") return cls.StorageLayout.lookup(data)
python
async def get_default_storage_layout(cls) -> StorageLayout: """Default storage layout. Storage layout that is applied to a node when it is deployed. """ data = await cls.get_config("default_storage_layout") return cls.StorageLayout.lookup(data)
[ "async", "def", "get_default_storage_layout", "(", "cls", ")", "->", "StorageLayout", ":", "data", "=", "await", "cls", ".", "get_config", "(", "\"default_storage_layout\"", ")", "return", "cls", ".", "StorageLayout", ".", "lookup", "(", "data", ")" ]
Default storage layout. Storage layout that is applied to a node when it is deployed.
[ "Default", "storage", "layout", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L268-L274
train
28,757
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.get_default_min_hwe_kernel
async def get_default_min_hwe_kernel(cls) -> typing.Optional[str]: """Default minimum kernel version. The minimum kernel version used on new and commissioned nodes. """ data = await cls.get_config("default_min_hwe_kernel") return None if data is None or data == "" else data
python
async def get_default_min_hwe_kernel(cls) -> typing.Optional[str]: """Default minimum kernel version. The minimum kernel version used on new and commissioned nodes. """ data = await cls.get_config("default_min_hwe_kernel") return None if data is None or data == "" else data
[ "async", "def", "get_default_min_hwe_kernel", "(", "cls", ")", "->", "typing", ".", "Optional", "[", "str", "]", ":", "data", "=", "await", "cls", ".", "get_config", "(", "\"default_min_hwe_kernel\"", ")", "return", "None", "if", "data", "is", "None", "or", ...
Default minimum kernel version. The minimum kernel version used on new and commissioned nodes.
[ "Default", "minimum", "kernel", "version", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L280-L286
train
28,758
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.set_default_min_hwe_kernel
async def set_default_min_hwe_kernel(cls, version: typing.Optional[str]): """See `get_default_min_hwe_kernel`.""" await cls.set_config( "default_min_hwe_kernel", "" if version is None else version)
python
async def set_default_min_hwe_kernel(cls, version: typing.Optional[str]): """See `get_default_min_hwe_kernel`.""" await cls.set_config( "default_min_hwe_kernel", "" if version is None else version)
[ "async", "def", "set_default_min_hwe_kernel", "(", "cls", ",", "version", ":", "typing", ".", "Optional", "[", "str", "]", ")", ":", "await", "cls", ".", "set_config", "(", "\"default_min_hwe_kernel\"", ",", "\"\"", "if", "version", "is", "None", "else", "ve...
See `get_default_min_hwe_kernel`.
[ "See", "get_default_min_hwe_kernel", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L288-L291
train
28,759
maas/python-libmaas
maas/client/viscera/maas.py
MAASType.set_config
async def set_config(cls, name: str, value): """Set a configuration value in MAAS. Consult your MAAS server for recognised settings. Alternatively, use the pre-canned functions also defined on this object. """ return await cls._handler.set_config(name=[name], value=[value])
python
async def set_config(cls, name: str, value): """Set a configuration value in MAAS. Consult your MAAS server for recognised settings. Alternatively, use the pre-canned functions also defined on this object. """ return await cls._handler.set_config(name=[name], value=[value])
[ "async", "def", "set_config", "(", "cls", ",", "name", ":", "str", ",", "value", ")", ":", "return", "await", "cls", ".", "_handler", ".", "set_config", "(", "name", "=", "[", "name", "]", ",", "value", "=", "[", "value", "]", ")" ]
Set a configuration value in MAAS. Consult your MAAS server for recognised settings. Alternatively, use the pre-canned functions also defined on this object.
[ "Set", "a", "configuration", "value", "in", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/maas.py#L310-L316
train
28,760
maas/python-libmaas
maas/client/viscera/volume_groups.py
VolumeGroupsType.create
async def create( cls, node: Union[Node, str], name: str, devices: Iterable[Union[BlockDevice, Partition]], *, uuid: str = None): """ Create a volume group on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param name: Name of the volume group. :type name: `str` :param devices: Mixed list of block devices or partitions to create the volume group from. :type devices: iterable of mixed type of `BlockDevice` or `Partition` :param uuid: The UUID for the volume group (optional). :type uuid: `str` """ params = { 'name': name, } if isinstance(node, str): params['system_id'] = node elif isinstance(node, Node): params['system_id'] = node.system_id else: raise TypeError( 'node must be a Node or str, not %s' % ( type(node).__name__)) if len(devices) == 0: raise ValueError("devices must contain at least one device.") block_devices = [] partitions = [] for idx, device in enumerate(devices): if isinstance(device, BlockDevice): block_devices.append(device.id) elif isinstance(device, Partition): partitions.append(device.id) else: raise TypeError( "devices[%d] must be a BlockDevice or " "Partition, not %s" % type(device).__name__) if len(block_devices) > 0: params['block_devices'] = block_devices if len(partitions) > 0: params['partitions'] = partitions if uuid is not None: params['uuid'] = uuid return cls._object(await cls._handler.create(**params))
python
async def create( cls, node: Union[Node, str], name: str, devices: Iterable[Union[BlockDevice, Partition]], *, uuid: str = None): """ Create a volume group on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param name: Name of the volume group. :type name: `str` :param devices: Mixed list of block devices or partitions to create the volume group from. :type devices: iterable of mixed type of `BlockDevice` or `Partition` :param uuid: The UUID for the volume group (optional). :type uuid: `str` """ params = { 'name': name, } if isinstance(node, str): params['system_id'] = node elif isinstance(node, Node): params['system_id'] = node.system_id else: raise TypeError( 'node must be a Node or str, not %s' % ( type(node).__name__)) if len(devices) == 0: raise ValueError("devices must contain at least one device.") block_devices = [] partitions = [] for idx, device in enumerate(devices): if isinstance(device, BlockDevice): block_devices.append(device.id) elif isinstance(device, Partition): partitions.append(device.id) else: raise TypeError( "devices[%d] must be a BlockDevice or " "Partition, not %s" % type(device).__name__) if len(block_devices) > 0: params['block_devices'] = block_devices if len(partitions) > 0: params['partitions'] = partitions if uuid is not None: params['uuid'] = uuid return cls._object(await cls._handler.create(**params))
[ "async", "def", "create", "(", "cls", ",", "node", ":", "Union", "[", "Node", ",", "str", "]", ",", "name", ":", "str", ",", "devices", ":", "Iterable", "[", "Union", "[", "BlockDevice", ",", "Partition", "]", "]", ",", "*", ",", "uuid", ":", "st...
Create a volume group on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param name: Name of the volume group. :type name: `str` :param devices: Mixed list of block devices or partitions to create the volume group from. :type devices: iterable of mixed type of `BlockDevice` or `Partition` :param uuid: The UUID for the volume group (optional). :type uuid: `str`
[ "Create", "a", "volume", "group", "on", "a", "Node", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/volume_groups.py#L87-L136
train
28,761
maas/python-libmaas
maas/client/utils/profiles.py
schema_create
def schema_create(conn): """Create the index for storing profiles. This is idempotent; it can be called every time a database is opened to make sure it's ready to use and up-to-date. :param conn: A connection to an SQLite3 database. """ conn.execute(dedent("""\ CREATE TABLE IF NOT EXISTS profiles (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, data BLOB NOT NULL, selected BOOLEAN NOT NULL DEFAULT FALSE) """)) # Partial indexes are only available in >=3.8.0 and expressions in indexes # are only available in >=3.9.0 (https://www.sqlite.org/partialindex.html # & https://www.sqlite.org/expridx.html). Don't bother with any kind of # index before that because it would complicate upgrades. if sqlite3.sqlite_version_info >= (3, 9, 0): # This index is for data integrity -- ensuring that only one profile # is the default ("selected") profile -- and speed a distant second. conn.execute(dedent("""\ CREATE UNIQUE INDEX IF NOT EXISTS only_one_profile_selected ON profiles (selected IS NOT NULL) WHERE selected """))
python
def schema_create(conn): """Create the index for storing profiles. This is idempotent; it can be called every time a database is opened to make sure it's ready to use and up-to-date. :param conn: A connection to an SQLite3 database. """ conn.execute(dedent("""\ CREATE TABLE IF NOT EXISTS profiles (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, data BLOB NOT NULL, selected BOOLEAN NOT NULL DEFAULT FALSE) """)) # Partial indexes are only available in >=3.8.0 and expressions in indexes # are only available in >=3.9.0 (https://www.sqlite.org/partialindex.html # & https://www.sqlite.org/expridx.html). Don't bother with any kind of # index before that because it would complicate upgrades. if sqlite3.sqlite_version_info >= (3, 9, 0): # This index is for data integrity -- ensuring that only one profile # is the default ("selected") profile -- and speed a distant second. conn.execute(dedent("""\ CREATE UNIQUE INDEX IF NOT EXISTS only_one_profile_selected ON profiles (selected IS NOT NULL) WHERE selected """))
[ "def", "schema_create", "(", "conn", ")", ":", "conn", ".", "execute", "(", "dedent", "(", "\"\"\"\\\n CREATE TABLE IF NOT EXISTS profiles\n (id INTEGER PRIMARY KEY,\n name TEXT NOT NULL UNIQUE,\n data BLOB NOT NULL,\n selected BOOLEAN NOT NULL DEFAULT FALSE)\n \...
Create the index for storing profiles. This is idempotent; it can be called every time a database is opened to make sure it's ready to use and up-to-date. :param conn: A connection to an SQLite3 database.
[ "Create", "the", "index", "for", "storing", "profiles", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/profiles.py#L125-L151
train
28,762
maas/python-libmaas
maas/client/utils/profiles.py
schema_import
def schema_import(conn, dbpath): """Import profiles from another database. This does not overwrite existing profiles in the target database. Profiles in the source database that share names with those in the target database are ignored. :param conn: A connection to an SQLite3 database into which to copy profiles. :param dbpath: The filesystem path to the source SQLite3 database. """ conn.execute( "ATTACH DATABASE ? AS source", (str(dbpath),)) conn.execute( "INSERT OR IGNORE INTO profiles (name, data)" " SELECT name, data FROM source.profiles" " WHERE data IS NOT NULL") conn.commit() # need to commit before detaching the other db conn.execute( "DETACH DATABASE source")
python
def schema_import(conn, dbpath): """Import profiles from another database. This does not overwrite existing profiles in the target database. Profiles in the source database that share names with those in the target database are ignored. :param conn: A connection to an SQLite3 database into which to copy profiles. :param dbpath: The filesystem path to the source SQLite3 database. """ conn.execute( "ATTACH DATABASE ? AS source", (str(dbpath),)) conn.execute( "INSERT OR IGNORE INTO profiles (name, data)" " SELECT name, data FROM source.profiles" " WHERE data IS NOT NULL") conn.commit() # need to commit before detaching the other db conn.execute( "DETACH DATABASE source")
[ "def", "schema_import", "(", "conn", ",", "dbpath", ")", ":", "conn", ".", "execute", "(", "\"ATTACH DATABASE ? AS source\"", ",", "(", "str", "(", "dbpath", ")", ",", ")", ")", "conn", ".", "execute", "(", "\"INSERT OR IGNORE INTO profiles (name, data)\"", "\" ...
Import profiles from another database. This does not overwrite existing profiles in the target database. Profiles in the source database that share names with those in the target database are ignored. :param conn: A connection to an SQLite3 database into which to copy profiles. :param dbpath: The filesystem path to the source SQLite3 database.
[ "Import", "profiles", "from", "another", "database", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/profiles.py#L154-L173
train
28,763
maas/python-libmaas
maas/client/utils/profiles.py
Profile.replace
def replace(self, **updates): """Return a new profile with the given updates. Unspecified fields will be the same as this instance. See `__new__` for details on the arguments. """ state = self.dump() state.update(updates) return self.__class__(**state)
python
def replace(self, **updates): """Return a new profile with the given updates. Unspecified fields will be the same as this instance. See `__new__` for details on the arguments. """ state = self.dump() state.update(updates) return self.__class__(**state)
[ "def", "replace", "(", "self", ",", "*", "*", "updates", ")", ":", "state", "=", "self", ".", "dump", "(", ")", "state", ".", "update", "(", "updates", ")", "return", "self", ".", "__class__", "(", "*", "*", "state", ")" ]
Return a new profile with the given updates. Unspecified fields will be the same as this instance. See `__new__` for details on the arguments.
[ "Return", "a", "new", "profile", "with", "the", "given", "updates", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/profiles.py#L82-L90
train
28,764
maas/python-libmaas
maas/client/utils/profiles.py
Profile.dump
def dump(self): """Return a dict of fields that can be used to recreate this profile. For example:: >>> profile = Profile(name="foobar", ...) >>> profile == Profile(**profile.dump()) True Use this value when persisting a profile. """ return dict( self.other, name=self.name, url=self.url, credentials=self.credentials, description=self.description, )
python
def dump(self): """Return a dict of fields that can be used to recreate this profile. For example:: >>> profile = Profile(name="foobar", ...) >>> profile == Profile(**profile.dump()) True Use this value when persisting a profile. """ return dict( self.other, name=self.name, url=self.url, credentials=self.credentials, description=self.description, )
[ "def", "dump", "(", "self", ")", ":", "return", "dict", "(", "self", ".", "other", ",", "name", "=", "self", ".", "name", ",", "url", "=", "self", ".", "url", ",", "credentials", "=", "self", ".", "credentials", ",", "description", "=", "self", "."...
Return a dict of fields that can be used to recreate this profile. For example:: >>> profile = Profile(name="foobar", ...) >>> profile == Profile(**profile.dump()) True Use this value when persisting a profile.
[ "Return", "a", "dict", "of", "fields", "that", "can", "be", "used", "to", "recreate", "this", "profile", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/profiles.py#L92-L106
train
28,765
maas/python-libmaas
maas/client/utils/profiles.py
ProfileStore.default
def default(self) -> typing.Optional[Profile]: """The name of the default profile to use, or `None`.""" found = self.database.execute( "SELECT name, data FROM profiles WHERE selected" " ORDER BY name LIMIT 1").fetchone() if found is None: return None else: state = json.loads(found[1]) state["name"] = found[0] # Belt-n-braces. return Profile(**state)
python
def default(self) -> typing.Optional[Profile]: """The name of the default profile to use, or `None`.""" found = self.database.execute( "SELECT name, data FROM profiles WHERE selected" " ORDER BY name LIMIT 1").fetchone() if found is None: return None else: state = json.loads(found[1]) state["name"] = found[0] # Belt-n-braces. return Profile(**state)
[ "def", "default", "(", "self", ")", "->", "typing", ".", "Optional", "[", "Profile", "]", ":", "found", "=", "self", ".", "database", ".", "execute", "(", "\"SELECT name, data FROM profiles WHERE selected\"", "\" ORDER BY name LIMIT 1\"", ")", ".", "fetchone", "("...
The name of the default profile to use, or `None`.
[ "The", "name", "of", "the", "default", "profile", "to", "use", "or", "None", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/profiles.py#L220-L230
train
28,766
maas/python-libmaas
maas/client/utils/profiles.py
ProfileStore.open
def open(cls, dbpath=Path("~/.maas.db").expanduser(), migrate_from=Path("~/.maascli.db").expanduser()): """Load a profiles database. Called without arguments this will open (and create) a database in the user's home directory. **Note** that this returns a context manager which will close the database on exit, saving if the exit is clean. :param dbpath: The path to the database file to create and open. :param migrate_from: Path to a database file to migrate from. """ # Ensure we're working with a Path instance. dbpath = Path(dbpath) migrate_from = Path(migrate_from) # See if we ought to do a one-time migration. migrate = migrate_from.is_file() and not dbpath.exists() # Initialise filename with restrictive permissions... dbpath.touch(mode=0o600, exist_ok=True) # Final check to see if it's safe to migrate. migrate = migrate and not migrate_from.samefile(dbpath) # before opening it with sqlite. database = sqlite3.connect(str(dbpath)) try: store = cls(database) if migrate: schema_import(database, migrate_from) yield store else: yield store except: # noqa: E722 raise else: database.commit() finally: database.close()
python
def open(cls, dbpath=Path("~/.maas.db").expanduser(), migrate_from=Path("~/.maascli.db").expanduser()): """Load a profiles database. Called without arguments this will open (and create) a database in the user's home directory. **Note** that this returns a context manager which will close the database on exit, saving if the exit is clean. :param dbpath: The path to the database file to create and open. :param migrate_from: Path to a database file to migrate from. """ # Ensure we're working with a Path instance. dbpath = Path(dbpath) migrate_from = Path(migrate_from) # See if we ought to do a one-time migration. migrate = migrate_from.is_file() and not dbpath.exists() # Initialise filename with restrictive permissions... dbpath.touch(mode=0o600, exist_ok=True) # Final check to see if it's safe to migrate. migrate = migrate and not migrate_from.samefile(dbpath) # before opening it with sqlite. database = sqlite3.connect(str(dbpath)) try: store = cls(database) if migrate: schema_import(database, migrate_from) yield store else: yield store except: # noqa: E722 raise else: database.commit() finally: database.close()
[ "def", "open", "(", "cls", ",", "dbpath", "=", "Path", "(", "\"~/.maas.db\"", ")", ".", "expanduser", "(", ")", ",", "migrate_from", "=", "Path", "(", "\"~/.maascli.db\"", ")", ".", "expanduser", "(", ")", ")", ":", "# Ensure we're working with a Path instance...
Load a profiles database. Called without arguments this will open (and create) a database in the user's home directory. **Note** that this returns a context manager which will close the database on exit, saving if the exit is clean. :param dbpath: The path to the database file to create and open. :param migrate_from: Path to a database file to migrate from.
[ "Load", "a", "profiles", "database", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/profiles.py#L247-L283
train
28,767
maas/python-libmaas
maas/client/flesh/__init__.py
print_with_pager
def print_with_pager(output): """Print the output to `stdout` using less when in a tty.""" if sys.stdout.isatty(): try: pager = subprocess.Popen( ['less', '-F', '-r', '-S', '-X', '-K'], stdin=subprocess.PIPE, stdout=sys.stdout) except subprocess.CalledProcessError: # Don't use the pager since starting it has failed. print(output) return else: pager.stdin.write(output.encode('utf-8')) pager.stdin.close() pager.wait() else: # Output directly to stdout since not in tty. print(output)
python
def print_with_pager(output): """Print the output to `stdout` using less when in a tty.""" if sys.stdout.isatty(): try: pager = subprocess.Popen( ['less', '-F', '-r', '-S', '-X', '-K'], stdin=subprocess.PIPE, stdout=sys.stdout) except subprocess.CalledProcessError: # Don't use the pager since starting it has failed. print(output) return else: pager.stdin.write(output.encode('utf-8')) pager.stdin.close() pager.wait() else: # Output directly to stdout since not in tty. print(output)
[ "def", "print_with_pager", "(", "output", ")", ":", "if", "sys", ".", "stdout", ".", "isatty", "(", ")", ":", "try", ":", "pager", "=", "subprocess", ".", "Popen", "(", "[", "'less'", ",", "'-F'", ",", "'-r'", ",", "'-S'", ",", "'-X'", ",", "'-K'",...
Print the output to `stdout` using less when in a tty.
[ "Print", "the", "output", "to", "stdout", "using", "less", "when", "in", "a", "tty", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L106-L123
train
28,768
maas/python-libmaas
maas/client/flesh/__init__.py
get_profile_names_and_default
def get_profile_names_and_default() -> ( typing.Tuple[typing.Sequence[str], typing.Optional[Profile]]): """Return the list of profile names and the default profile object. The list of names is sorted. """ with ProfileStore.open() as config: return sorted(config), config.default
python
def get_profile_names_and_default() -> ( typing.Tuple[typing.Sequence[str], typing.Optional[Profile]]): """Return the list of profile names and the default profile object. The list of names is sorted. """ with ProfileStore.open() as config: return sorted(config), config.default
[ "def", "get_profile_names_and_default", "(", ")", "->", "(", "typing", ".", "Tuple", "[", "typing", ".", "Sequence", "[", "str", "]", ",", "typing", ".", "Optional", "[", "Profile", "]", "]", ")", ":", "with", "ProfileStore", ".", "open", "(", ")", "as...
Return the list of profile names and the default profile object. The list of names is sorted.
[ "Return", "the", "list", "of", "profile", "names", "and", "the", "default", "profile", "object", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L126-L133
train
28,769
maas/python-libmaas
maas/client/flesh/__init__.py
prepare_parser
def prepare_parser(program): """Create and populate an argument parser.""" parser = ArgumentParser( description=PROG_DESCRIPTION, prog=program, formatter_class=HelpFormatter, add_help=False) parser.add_argument( "-h", "--help", action=MinimalHelpAction, help=argparse.SUPPRESS) # Register sub-commands. submodules = ( "nodes", "machines", "devices", "controllers", "fabrics", "vlans", "subnets", "spaces", "files", "tags", "users", "profiles", "shell", ) cmd_help.register(parser) for submodule in submodules: module = import_module("." + submodule, __name__) module.register(parser) # Register global options. parser.add_argument( '--debug', action='store_true', default=False, help=argparse.SUPPRESS) return parser
python
def prepare_parser(program): """Create and populate an argument parser.""" parser = ArgumentParser( description=PROG_DESCRIPTION, prog=program, formatter_class=HelpFormatter, add_help=False) parser.add_argument( "-h", "--help", action=MinimalHelpAction, help=argparse.SUPPRESS) # Register sub-commands. submodules = ( "nodes", "machines", "devices", "controllers", "fabrics", "vlans", "subnets", "spaces", "files", "tags", "users", "profiles", "shell", ) cmd_help.register(parser) for submodule in submodules: module = import_module("." + submodule, __name__) module.register(parser) # Register global options. parser.add_argument( '--debug', action='store_true', default=False, help=argparse.SUPPRESS) return parser
[ "def", "prepare_parser", "(", "program", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "PROG_DESCRIPTION", ",", "prog", "=", "program", ",", "formatter_class", "=", "HelpFormatter", ",", "add_help", "=", "False", ")", "parser", ".", "add_...
Create and populate an argument parser.
[ "Create", "and", "populate", "an", "argument", "parser", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L455-L481
train
28,770
maas/python-libmaas
maas/client/flesh/__init__.py
post_mortem
def post_mortem(traceback): """Work with an exception in a post-mortem debugger. Try to use `ipdb` first, falling back to `pdb`. """ try: from ipdb import post_mortem except ImportError: from pdb import post_mortem message = "Entering post-mortem debugger. Type `help` for help." redline = colorized("{autored}%s{/autored}") % "{0:=^{1}}" print() print(redline.format(" CRASH! ", len(message))) print(message) print(redline.format("", len(message))) print() post_mortem(traceback)
python
def post_mortem(traceback): """Work with an exception in a post-mortem debugger. Try to use `ipdb` first, falling back to `pdb`. """ try: from ipdb import post_mortem except ImportError: from pdb import post_mortem message = "Entering post-mortem debugger. Type `help` for help." redline = colorized("{autored}%s{/autored}") % "{0:=^{1}}" print() print(redline.format(" CRASH! ", len(message))) print(message) print(redline.format("", len(message))) print() post_mortem(traceback)
[ "def", "post_mortem", "(", "traceback", ")", ":", "try", ":", "from", "ipdb", "import", "post_mortem", "except", "ImportError", ":", "from", "pdb", "import", "post_mortem", "message", "=", "\"Entering post-mortem debugger. Type `help` for help.\"", "redline", "=", "co...
Work with an exception in a post-mortem debugger. Try to use `ipdb` first, falling back to `pdb`.
[ "Work", "with", "an", "exception", "in", "a", "post", "-", "mortem", "debugger", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L484-L503
train
28,771
maas/python-libmaas
maas/client/flesh/__init__.py
ArgumentParser.subparsers
def subparsers(self): """Obtain the subparser's object.""" try: return self.__subparsers except AttributeError: parent = super(ArgumentParser, self) self.__subparsers = parent.add_subparsers(title="drill down") self.__subparsers.metavar = "COMMAND" return self.__subparsers
python
def subparsers(self): """Obtain the subparser's object.""" try: return self.__subparsers except AttributeError: parent = super(ArgumentParser, self) self.__subparsers = parent.add_subparsers(title="drill down") self.__subparsers.metavar = "COMMAND" return self.__subparsers
[ "def", "subparsers", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__subparsers", "except", "AttributeError", ":", "parent", "=", "super", "(", "ArgumentParser", ",", "self", ")", "self", ".", "__subparsers", "=", "parent", ".", "add_subparsers"...
Obtain the subparser's object.
[ "Obtain", "the", "subparser", "s", "object", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L184-L192
train
28,772
maas/python-libmaas
maas/client/flesh/__init__.py
ArgumentParser.add_argument_group
def add_argument_group(self, title, description=None): """Add an argument group, or return a pre-existing one.""" try: groups = self.__groups except AttributeError: groups = self.__groups = {} if title not in groups: groups[title] = super().add_argument_group( title=title, description=description) return groups[title]
python
def add_argument_group(self, title, description=None): """Add an argument group, or return a pre-existing one.""" try: groups = self.__groups except AttributeError: groups = self.__groups = {} if title not in groups: groups[title] = super().add_argument_group( title=title, description=description) return groups[title]
[ "def", "add_argument_group", "(", "self", ",", "title", ",", "description", "=", "None", ")", ":", "try", ":", "groups", "=", "self", ".", "__groups", "except", "AttributeError", ":", "groups", "=", "self", ".", "__groups", "=", "{", "}", "if", "title", ...
Add an argument group, or return a pre-existing one.
[ "Add", "an", "argument", "group", "or", "return", "a", "pre", "-", "existing", "one", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L194-L205
train
28,773
maas/python-libmaas
maas/client/flesh/__init__.py
ArgumentParser.print_minized_help
def print_minized_help(self, *, no_pager=False): """Return the formatted help text. Override default ArgumentParser to just include the usage and the description. The `help` action is used for provide more detail. """ formatter = self._get_formatter() formatter.add_usage( self.usage, self._actions, self._mutually_exclusive_groups) formatter.add_text(self.description) if no_pager: print(formatter.format_help()) else: print_with_pager(formatter.format_help())
python
def print_minized_help(self, *, no_pager=False): """Return the formatted help text. Override default ArgumentParser to just include the usage and the description. The `help` action is used for provide more detail. """ formatter = self._get_formatter() formatter.add_usage( self.usage, self._actions, self._mutually_exclusive_groups) formatter.add_text(self.description) if no_pager: print(formatter.format_help()) else: print_with_pager(formatter.format_help())
[ "def", "print_minized_help", "(", "self", ",", "*", ",", "no_pager", "=", "False", ")", ":", "formatter", "=", "self", ".", "_get_formatter", "(", ")", "formatter", ".", "add_usage", "(", "self", ".", "usage", ",", "self", ".", "_actions", ",", "self", ...
Return the formatted help text. Override default ArgumentParser to just include the usage and the description. The `help` action is used for provide more detail.
[ "Return", "the", "formatted", "help", "text", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L224-L238
train
28,774
maas/python-libmaas
maas/client/flesh/__init__.py
Command.name
def name(cls): """Return the preferred name as which this command will be known.""" name = cls.__name__.replace("_", "-").lower() name = name[4:] if name.startswith("cmd-") else name return name
python
def name(cls): """Return the preferred name as which this command will be known.""" name = cls.__name__.replace("_", "-").lower() name = name[4:] if name.startswith("cmd-") else name return name
[ "def", "name", "(", "cls", ")", ":", "name", "=", "cls", ".", "__name__", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", ".", "lower", "(", ")", "name", "=", "name", "[", "4", ":", "]", "if", "name", ".", "startswith", "(", "\"cmd-\"", ")", "...
Return the preferred name as which this command will be known.
[ "Return", "the", "preferred", "name", "as", "which", "this", "command", "will", "be", "known", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L260-L264
train
28,775
maas/python-libmaas
maas/client/flesh/__init__.py
Command.register
def register(cls, parser, name=None): """Register this command as a sub-parser of `parser`. :type parser: An instance of `ArgumentParser`. :return: The sub-parser created. """ help_title, help_body = utils.parse_docstring(cls) command_parser = parser.subparsers.add_parser( cls.name() if name is None else name, help=help_title, description=help_title, epilog=help_body, add_help=False, formatter_class=HelpFormatter) command_parser.add_argument( "-h", "--help", action=PagedHelpAction, help=argparse.SUPPRESS) command_parser.set_defaults(execute=cls(command_parser)) return command_parser
python
def register(cls, parser, name=None): """Register this command as a sub-parser of `parser`. :type parser: An instance of `ArgumentParser`. :return: The sub-parser created. """ help_title, help_body = utils.parse_docstring(cls) command_parser = parser.subparsers.add_parser( cls.name() if name is None else name, help=help_title, description=help_title, epilog=help_body, add_help=False, formatter_class=HelpFormatter) command_parser.add_argument( "-h", "--help", action=PagedHelpAction, help=argparse.SUPPRESS) command_parser.set_defaults(execute=cls(command_parser)) return command_parser
[ "def", "register", "(", "cls", ",", "parser", ",", "name", "=", "None", ")", ":", "help_title", ",", "help_body", "=", "utils", ".", "parse_docstring", "(", "cls", ")", "command_parser", "=", "parser", ".", "subparsers", ".", "add_parser", "(", "cls", "....
Register this command as a sub-parser of `parser`. :type parser: An instance of `ArgumentParser`. :return: The sub-parser created.
[ "Register", "this", "command", "as", "a", "sub", "-", "parser", "of", "parser", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L267-L281
train
28,776
maas/python-libmaas
maas/client/flesh/__init__.py
cmd_help.print_all_commands
def print_all_commands(self, *, no_pager=False): """Print help for all commands. Commands are sorted in alphabetical order and wrapping is done based on the width of the terminal. """ formatter = self.parent_parser._get_formatter() command_names = sorted(self.parent_parser.subparsers.choices.keys()) max_name_len = max([len(name) for name in command_names]) + 1 commands = "" for name in command_names: command = self.parent_parser.subparsers.choices[name] extra_padding = max_name_len - len(name) command_line = '%s%s%s' % ( name, ' ' * extra_padding, command.description) while len(command_line) > formatter._width: lines = textwrap.wrap(command_line, formatter._width) commands += "%s\n" % lines[0] if len(lines) > 1: lines[1] = (' ' * max_name_len) + lines[1] command_line = ' '.join(lines[1:]) else: command_line = None if command_line: commands += "%s\n" % command_line if no_pager: print(commands[:-1]) else: print_with_pager(commands[:-1])
python
def print_all_commands(self, *, no_pager=False): """Print help for all commands. Commands are sorted in alphabetical order and wrapping is done based on the width of the terminal. """ formatter = self.parent_parser._get_formatter() command_names = sorted(self.parent_parser.subparsers.choices.keys()) max_name_len = max([len(name) for name in command_names]) + 1 commands = "" for name in command_names: command = self.parent_parser.subparsers.choices[name] extra_padding = max_name_len - len(name) command_line = '%s%s%s' % ( name, ' ' * extra_padding, command.description) while len(command_line) > formatter._width: lines = textwrap.wrap(command_line, formatter._width) commands += "%s\n" % lines[0] if len(lines) > 1: lines[1] = (' ' * max_name_len) + lines[1] command_line = ' '.join(lines[1:]) else: command_line = None if command_line: commands += "%s\n" % command_line if no_pager: print(commands[:-1]) else: print_with_pager(commands[:-1])
[ "def", "print_all_commands", "(", "self", ",", "*", ",", "no_pager", "=", "False", ")", ":", "formatter", "=", "self", ".", "parent_parser", ".", "_get_formatter", "(", ")", "command_names", "=", "sorted", "(", "self", ".", "parent_parser", ".", "subparsers"...
Print help for all commands. Commands are sorted in alphabetical order and wrapping is done based on the width of the terminal.
[ "Print", "help", "for", "all", "commands", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/__init__.py#L409-L437
train
28,777
maas/python-libmaas
maas/client/viscera/events.py
EventsType.query
async def query( cls, *, hostnames: typing.Iterable[str] = None, domains: typing.Iterable[str] = None, zones: typing.Iterable[str] = None, macs: typing.Iterable[str] = None, system_ids: typing.Iterable[str] = None, agent_name: str = None, level: typing.Union[Level, int, str] = None, before: int = None, after: int = None, limit: int = None, owner: typing.Union[User, str] = None): """Query MAAS for matching events.""" if before is not None and after is not None: raise ValueError("Specify either `before` or `after`, not both.") params = {} if hostnames is not None: params["hostname"] = list(hostnames) if domains is not None: params["domain"] = list(domains) if zones is not None: params["zone"] = list(zones) if macs is not None: params["mac_address"] = list(macs) if system_ids is not None: params["id"] = list(system_ids) if agent_name is not None: params["agent_name"] = [agent_name] if level is not None: level = Level.normalise(level) params["level"] = [level.name] if before is not None: params["before"] = ["{:d}".format(before)] if after is not None: params["after"] = ["{:d}".format(after)] if limit is not None: params["limit"] = ["{:d}".format(limit)] if owner is not None: if isinstance(owner, User): params["owner"] = [owner.username] elif isinstance(owner, str): params["owner"] = [owner] else: raise TypeError( "owner must be either User or str, not %s" % ( type(owner).__name__)) data = await cls._handler.query(**params) return cls(data)
python
async def query( cls, *, hostnames: typing.Iterable[str] = None, domains: typing.Iterable[str] = None, zones: typing.Iterable[str] = None, macs: typing.Iterable[str] = None, system_ids: typing.Iterable[str] = None, agent_name: str = None, level: typing.Union[Level, int, str] = None, before: int = None, after: int = None, limit: int = None, owner: typing.Union[User, str] = None): """Query MAAS for matching events.""" if before is not None and after is not None: raise ValueError("Specify either `before` or `after`, not both.") params = {} if hostnames is not None: params["hostname"] = list(hostnames) if domains is not None: params["domain"] = list(domains) if zones is not None: params["zone"] = list(zones) if macs is not None: params["mac_address"] = list(macs) if system_ids is not None: params["id"] = list(system_ids) if agent_name is not None: params["agent_name"] = [agent_name] if level is not None: level = Level.normalise(level) params["level"] = [level.name] if before is not None: params["before"] = ["{:d}".format(before)] if after is not None: params["after"] = ["{:d}".format(after)] if limit is not None: params["limit"] = ["{:d}".format(limit)] if owner is not None: if isinstance(owner, User): params["owner"] = [owner.username] elif isinstance(owner, str): params["owner"] = [owner] else: raise TypeError( "owner must be either User or str, not %s" % ( type(owner).__name__)) data = await cls._handler.query(**params) return cls(data)
[ "async", "def", "query", "(", "cls", ",", "*", ",", "hostnames", ":", "typing", ".", "Iterable", "[", "str", "]", "=", "None", ",", "domains", ":", "typing", ".", "Iterable", "[", "str", "]", "=", "None", ",", "zones", ":", "typing", ".", "Iterable...
Query MAAS for matching events.
[ "Query", "MAAS", "for", "matching", "events", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/events.py#L88-L140
train
28,778
maas/python-libmaas
maas/client/viscera/sshkeys.py
SSHKeysType.create
async def create(cls, key: str): """ Create an SSH key in MAAS with the content in `key`. :param key: The content of the SSH key :type key: `str` :returns: The created SSH key :rtype: `SSHKey` """ return cls._object(await cls._handler.create(key=key))
python
async def create(cls, key: str): """ Create an SSH key in MAAS with the content in `key`. :param key: The content of the SSH key :type key: `str` :returns: The created SSH key :rtype: `SSHKey` """ return cls._object(await cls._handler.create(key=key))
[ "async", "def", "create", "(", "cls", ",", "key", ":", "str", ")", ":", "return", "cls", ".", "_object", "(", "await", "cls", ".", "_handler", ".", "create", "(", "key", "=", "key", ")", ")" ]
Create an SSH key in MAAS with the content in `key`. :param key: The content of the SSH key :type key: `str` :returns: The created SSH key :rtype: `SSHKey`
[ "Create", "an", "SSH", "key", "in", "MAAS", "with", "the", "content", "in", "key", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/sshkeys.py#L25-L34
train
28,779
maas/python-libmaas
maas/client/viscera/block_devices.py
BlockDevice.save
async def save(self): """Save this block device.""" old_tags = list(self._orig_data['tags']) new_tags = list(self.tags) self._changed_data.pop('tags', None) await super(BlockDevice, self).save() for tag_name in new_tags: if tag_name not in old_tags: await self._handler.add_tag( system_id=self.node.system_id, id=self.id, tag=tag_name) else: old_tags.remove(tag_name) for tag_name in old_tags: await self._handler.remove_tag( system_id=self.node.system_id, id=self.id, tag=tag_name) self._orig_data['tags'] = new_tags self._data['tags'] = list(new_tags)
python
async def save(self): """Save this block device.""" old_tags = list(self._orig_data['tags']) new_tags = list(self.tags) self._changed_data.pop('tags', None) await super(BlockDevice, self).save() for tag_name in new_tags: if tag_name not in old_tags: await self._handler.add_tag( system_id=self.node.system_id, id=self.id, tag=tag_name) else: old_tags.remove(tag_name) for tag_name in old_tags: await self._handler.remove_tag( system_id=self.node.system_id, id=self.id, tag=tag_name) self._orig_data['tags'] = new_tags self._data['tags'] = list(new_tags)
[ "async", "def", "save", "(", "self", ")", ":", "old_tags", "=", "list", "(", "self", ".", "_orig_data", "[", "'tags'", "]", ")", "new_tags", "=", "list", "(", "self", ".", "tags", ")", "self", ".", "_changed_data", ".", "pop", "(", "'tags'", ",", "...
Save this block device.
[ "Save", "this", "block", "device", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/block_devices.py#L96-L112
train
28,780
maas/python-libmaas
maas/client/viscera/block_devices.py
BlockDevice.set_as_boot_disk
async def set_as_boot_disk(self): """Set as boot disk for this node.""" await self._handler.set_boot_disk( system_id=self.node.system_id, id=self.id)
python
async def set_as_boot_disk(self): """Set as boot disk for this node.""" await self._handler.set_boot_disk( system_id=self.node.system_id, id=self.id)
[ "async", "def", "set_as_boot_disk", "(", "self", ")", ":", "await", "self", ".", "_handler", ".", "set_boot_disk", "(", "system_id", "=", "self", ".", "node", ".", "system_id", ",", "id", "=", "self", ".", "id", ")" ]
Set as boot disk for this node.
[ "Set", "as", "boot", "disk", "for", "this", "node", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/block_devices.py#L119-L122
train
28,781
maas/python-libmaas
maas/client/viscera/block_devices.py
BlockDevice.format
async def format(self, fstype, *, uuid=None): """Format this block device.""" self._data = await self._handler.format( system_id=self.node.system_id, id=self.id, fstype=fstype, uuid=uuid)
python
async def format(self, fstype, *, uuid=None): """Format this block device.""" self._data = await self._handler.format( system_id=self.node.system_id, id=self.id, fstype=fstype, uuid=uuid)
[ "async", "def", "format", "(", "self", ",", "fstype", ",", "*", ",", "uuid", "=", "None", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "format", "(", "system_id", "=", "self", ".", "node", ".", "system_id", ",", "id",...
Format this block device.
[ "Format", "this", "block", "device", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/block_devices.py#L124-L128
train
28,782
maas/python-libmaas
maas/client/viscera/block_devices.py
BlockDevice.unformat
async def unformat(self): """Unformat this block device.""" self._data = await self._handler.unformat( system_id=self.node.system_id, id=self.id)
python
async def unformat(self): """Unformat this block device.""" self._data = await self._handler.unformat( system_id=self.node.system_id, id=self.id)
[ "async", "def", "unformat", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "unformat", "(", "system_id", "=", "self", ".", "node", ".", "system_id", ",", "id", "=", "self", ".", "id", ")" ]
Unformat this block device.
[ "Unformat", "this", "block", "device", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/block_devices.py#L130-L133
train
28,783
maas/python-libmaas
maas/client/viscera/block_devices.py
BlockDevice.unmount
async def unmount(self): """Unmount this block device.""" self._data = await self._handler.unmount( system_id=self.node.system_id, id=self.id)
python
async def unmount(self): """Unmount this block device.""" self._data = await self._handler.unmount( system_id=self.node.system_id, id=self.id)
[ "async", "def", "unmount", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "unmount", "(", "system_id", "=", "self", ".", "node", ".", "system_id", ",", "id", "=", "self", ".", "id", ")" ]
Unmount this block device.
[ "Unmount", "this", "block", "device", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/block_devices.py#L141-L144
train
28,784
maas/python-libmaas
maas/client/viscera/block_devices.py
BlockDevicesType.create
async def create( cls, node: Union[Node, str], name: str, *, model: str = None, serial: str = None, id_path: str = None, size: int = None, block_size: int = 512, tags: Iterable[str] = None): """ Create a physical block device on a Node. Either model and serial or id_path must be provided when creating a `BlockDevice`. Size (bytes) is always required. NOTE: It is recommended to use the MAAS commissioning process to discover `BlockDevice`'s on a machine. Getting any of this information incorrect can result on the machine failing to deploy. :param node: Node to create the block device on. :type node: `Node` or `str` :param name: The name for the block device. :type name: `str` :param model: The model number for the block device. :type model: `str` :param serial: The serial number for the block device. :type serial: `str` :param id_path: Unique path that identifies the device no matter the kernel the machine boots. Use only when the block device does not have a model and serial number. :type id_path: `str` :param size: The size of the block device in bytes. :type size: `int` :param block_size: The block size of the block device in bytes. :type block_size: `int` :param tags: List of tags to add to the block device. :type tags: sequence of `str` """ params = {} if isinstance(node, str): params['system_id'] = node elif isinstance(node, Node): params['system_id'] = node.system_id else: raise TypeError( 'node must be a Node or str, not %s' % ( type(node).__name__)) if not size or size < 0: raise ValueError("size must be provided and greater than zero.") if not block_size or block_size < 0: raise ValueError( "block_size must be provided and greater than zero.") if model and not serial: raise ValueError("serial must be provided when model is provided.") if not model and serial: raise ValueError("model must be provided when serial is provided.") if not model and not serial and not id_path: raise ValueError( "Either model/serial is provided or id_path must be provided.") params.update(remove_None({ 'name': name, 'model': model, 'serial': serial, 'id_path': id_path, 'size': size, 'block_size': block_size, })) device = cls._object(await cls._handler.create(**params)) if tags: device.tags = tags await device.save() return device
python
async def create( cls, node: Union[Node, str], name: str, *, model: str = None, serial: str = None, id_path: str = None, size: int = None, block_size: int = 512, tags: Iterable[str] = None): """ Create a physical block device on a Node. Either model and serial or id_path must be provided when creating a `BlockDevice`. Size (bytes) is always required. NOTE: It is recommended to use the MAAS commissioning process to discover `BlockDevice`'s on a machine. Getting any of this information incorrect can result on the machine failing to deploy. :param node: Node to create the block device on. :type node: `Node` or `str` :param name: The name for the block device. :type name: `str` :param model: The model number for the block device. :type model: `str` :param serial: The serial number for the block device. :type serial: `str` :param id_path: Unique path that identifies the device no matter the kernel the machine boots. Use only when the block device does not have a model and serial number. :type id_path: `str` :param size: The size of the block device in bytes. :type size: `int` :param block_size: The block size of the block device in bytes. :type block_size: `int` :param tags: List of tags to add to the block device. :type tags: sequence of `str` """ params = {} if isinstance(node, str): params['system_id'] = node elif isinstance(node, Node): params['system_id'] = node.system_id else: raise TypeError( 'node must be a Node or str, not %s' % ( type(node).__name__)) if not size or size < 0: raise ValueError("size must be provided and greater than zero.") if not block_size or block_size < 0: raise ValueError( "block_size must be provided and greater than zero.") if model and not serial: raise ValueError("serial must be provided when model is provided.") if not model and serial: raise ValueError("model must be provided when serial is provided.") if not model and not serial and not id_path: raise ValueError( "Either model/serial is provided or id_path must be provided.") params.update(remove_None({ 'name': name, 'model': model, 'serial': serial, 'id_path': id_path, 'size': size, 'block_size': block_size, })) device = cls._object(await cls._handler.create(**params)) if tags: device.tags = tags await device.save() return device
[ "async", "def", "create", "(", "cls", ",", "node", ":", "Union", "[", "Node", ",", "str", "]", ",", "name", ":", "str", ",", "*", ",", "model", ":", "str", "=", "None", ",", "serial", ":", "str", "=", "None", ",", "id_path", ":", "str", "=", ...
Create a physical block device on a Node. Either model and serial or id_path must be provided when creating a `BlockDevice`. Size (bytes) is always required. NOTE: It is recommended to use the MAAS commissioning process to discover `BlockDevice`'s on a machine. Getting any of this information incorrect can result on the machine failing to deploy. :param node: Node to create the block device on. :type node: `Node` or `str` :param name: The name for the block device. :type name: `str` :param model: The model number for the block device. :type model: `str` :param serial: The serial number for the block device. :type serial: `str` :param id_path: Unique path that identifies the device no matter the kernel the machine boots. Use only when the block device does not have a model and serial number. :type id_path: `str` :param size: The size of the block device in bytes. :type size: `int` :param block_size: The block size of the block device in bytes. :type block_size: `int` :param tags: List of tags to add to the block device. :type tags: sequence of `str`
[ "Create", "a", "physical", "block", "device", "on", "a", "Node", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/block_devices.py#L166-L235
train
28,785
maas/python-libmaas
setup.py
read
def read(filename): """Return the whitespace-stripped content of `filename`.""" path = join(here, filename) with open(path, "r") as fin: return fin.read().strip()
python
def read(filename): """Return the whitespace-stripped content of `filename`.""" path = join(here, filename) with open(path, "r") as fin: return fin.read().strip()
[ "def", "read", "(", "filename", ")", ":", "path", "=", "join", "(", "here", ",", "filename", ")", "with", "open", "(", "path", ",", "\"r\"", ")", "as", "fin", ":", "return", "fin", ".", "read", "(", ")", ".", "strip", "(", ")" ]
Return the whitespace-stripped content of `filename`.
[ "Return", "the", "whitespace", "-", "stripped", "content", "of", "filename", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/setup.py#L18-L22
train
28,786
maas/python-libmaas
maas/client/flesh/tables.py
VlansTable.get_subnets
def get_subnets(self, vlan): """Return the subnets for the `vlan`.""" return vlan._origin.Subnets([ subnet for subnet in self.subnets if subnet.vlan.id == vlan.id ])
python
def get_subnets(self, vlan): """Return the subnets for the `vlan`.""" return vlan._origin.Subnets([ subnet for subnet in self.subnets if subnet.vlan.id == vlan.id ])
[ "def", "get_subnets", "(", "self", ",", "vlan", ")", ":", "return", "vlan", ".", "_origin", ".", "Subnets", "(", "[", "subnet", "for", "subnet", "in", "self", ".", "subnets", "if", "subnet", ".", "vlan", ".", "id", "==", "vlan", ".", "id", "]", ")"...
Return the subnets for the `vlan`.
[ "Return", "the", "subnets", "for", "the", "vlan", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/flesh/tables.py#L648-L654
train
28,787
maas/python-libmaas
maas/client/viscera/boot_sources.py
BootSourcesType.create
async def create(cls, url, *, keyring_filename=None, keyring_data=None): """Create a new `BootSource`. :param url: The URL for the boot source. :param keyring_filename: The path to the keyring file on the server. :param keyring_data: The GPG keyring data, binary. as a file-like object. For example: an open file handle in binary mode, or an instance of `io.BytesIO`. """ data = await cls._handler.create( url=url, keyring_filename=coalesce(keyring_filename, ""), keyring_data=coalesce(keyring_data, "")) return cls._object(data)
python
async def create(cls, url, *, keyring_filename=None, keyring_data=None): """Create a new `BootSource`. :param url: The URL for the boot source. :param keyring_filename: The path to the keyring file on the server. :param keyring_data: The GPG keyring data, binary. as a file-like object. For example: an open file handle in binary mode, or an instance of `io.BytesIO`. """ data = await cls._handler.create( url=url, keyring_filename=coalesce(keyring_filename, ""), keyring_data=coalesce(keyring_data, "")) return cls._object(data)
[ "async", "def", "create", "(", "cls", ",", "url", ",", "*", ",", "keyring_filename", "=", "None", ",", "keyring_data", "=", "None", ")", ":", "data", "=", "await", "cls", ".", "_handler", ".", "create", "(", "url", "=", "url", ",", "keyring_filename", ...
Create a new `BootSource`. :param url: The URL for the boot source. :param keyring_filename: The path to the keyring file on the server. :param keyring_data: The GPG keyring data, binary. as a file-like object. For example: an open file handle in binary mode, or an instance of `io.BytesIO`.
[ "Create", "a", "new", "BootSource", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/boot_sources.py#L22-L34
train
28,788
maas/python-libmaas
maas/client/bones/helpers.py
fetch_api_description
async def fetch_api_description( url: typing.Union[str, ParseResult, SplitResult], insecure: bool = False): """Fetch the API description from the remote MAAS instance.""" url_describe = urljoin(_ensure_url_string(url), "describe/") connector = aiohttp.TCPConnector(verify_ssl=(not insecure)) session = aiohttp.ClientSession(connector=connector) async with session, session.get(url_describe) as response: if response.status != HTTPStatus.OK: raise RemoteError( "{0} -> {1.status} {1.reason}".format( url, response)) elif response.content_type != "application/json": raise RemoteError( "Expected application/json, got: %s" % response.content_type) else: return await response.json()
python
async def fetch_api_description( url: typing.Union[str, ParseResult, SplitResult], insecure: bool = False): """Fetch the API description from the remote MAAS instance.""" url_describe = urljoin(_ensure_url_string(url), "describe/") connector = aiohttp.TCPConnector(verify_ssl=(not insecure)) session = aiohttp.ClientSession(connector=connector) async with session, session.get(url_describe) as response: if response.status != HTTPStatus.OK: raise RemoteError( "{0} -> {1.status} {1.reason}".format( url, response)) elif response.content_type != "application/json": raise RemoteError( "Expected application/json, got: %s" % response.content_type) else: return await response.json()
[ "async", "def", "fetch_api_description", "(", "url", ":", "typing", ".", "Union", "[", "str", ",", "ParseResult", ",", "SplitResult", "]", ",", "insecure", ":", "bool", "=", "False", ")", ":", "url_describe", "=", "urljoin", "(", "_ensure_url_string", "(", ...
Fetch the API description from the remote MAAS instance.
[ "Fetch", "the", "API", "description", "from", "the", "remote", "MAAS", "instance", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/helpers.py#L43-L60
train
28,789
maas/python-libmaas
maas/client/bones/helpers.py
_ensure_url_string
def _ensure_url_string(url): """Convert `url` to a string URL if it isn't one already.""" if isinstance(url, str): return url elif isinstance(url, (ParseResult, SplitResult)): return url.geturl() else: raise TypeError( "Could not convert %r to a string URL." % (url,))
python
def _ensure_url_string(url): """Convert `url` to a string URL if it isn't one already.""" if isinstance(url, str): return url elif isinstance(url, (ParseResult, SplitResult)): return url.geturl() else: raise TypeError( "Could not convert %r to a string URL." % (url,))
[ "def", "_ensure_url_string", "(", "url", ")", ":", "if", "isinstance", "(", "url", ",", "str", ")", ":", "return", "url", "elif", "isinstance", "(", "url", ",", "(", "ParseResult", ",", "SplitResult", ")", ")", ":", "return", "url", ".", "geturl", "(",...
Convert `url` to a string URL if it isn't one already.
[ "Convert", "url", "to", "a", "string", "URL", "if", "it", "isn", "t", "one", "already", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/helpers.py#L63-L71
train
28,790
maas/python-libmaas
maas/client/bones/helpers.py
derive_resource_name
def derive_resource_name(name): """A stable, human-readable name and identifier for a resource.""" if name.startswith("Anon"): name = name[4:] if name.endswith("Handler"): name = name[:-7] if name == "Maas": name = "MAAS" return name
python
def derive_resource_name(name): """A stable, human-readable name and identifier for a resource.""" if name.startswith("Anon"): name = name[4:] if name.endswith("Handler"): name = name[:-7] if name == "Maas": name = "MAAS" return name
[ "def", "derive_resource_name", "(", "name", ")", ":", "if", "name", ".", "startswith", "(", "\"Anon\"", ")", ":", "name", "=", "name", "[", "4", ":", "]", "if", "name", ".", "endswith", "(", "\"Handler\"", ")", ":", "name", "=", "name", "[", ":", "...
A stable, human-readable name and identifier for a resource.
[ "A", "stable", "human", "-", "readable", "name", "and", "identifier", "for", "a", "resource", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/helpers.py#L74-L82
train
28,791
maas/python-libmaas
maas/client/bones/helpers.py
connect
async def connect(url, *, apikey=None, insecure=False): """Connect to a remote MAAS instance with `apikey`. Returns a new :class:`Profile` which has NOT been saved. To connect AND save a new profile:: profile = connect(url, apikey=apikey) profile = profile.replace(name="mad-hatter") with profiles.ProfileStore.open() as config: config.save(profile) # Optionally, set it as the default. config.default = profile.name """ url = api_url(url) url = urlparse(url) if url.username is not None: raise ConnectError( "Cannot provide user-name explicitly in URL (%r) when connecting; " "use login instead." % url.username) if url.password is not None: raise ConnectError( "Cannot provide password explicitly in URL (%r) when connecting; " "use login instead." % url.username) if apikey is None: credentials = None # Anonymous access. else: credentials = Credentials.parse(apikey) description = await fetch_api_description(url, insecure) # Return a new (unsaved) profile. return Profile( name=url.netloc, url=url.geturl(), credentials=credentials, description=description)
python
async def connect(url, *, apikey=None, insecure=False): """Connect to a remote MAAS instance with `apikey`. Returns a new :class:`Profile` which has NOT been saved. To connect AND save a new profile:: profile = connect(url, apikey=apikey) profile = profile.replace(name="mad-hatter") with profiles.ProfileStore.open() as config: config.save(profile) # Optionally, set it as the default. config.default = profile.name """ url = api_url(url) url = urlparse(url) if url.username is not None: raise ConnectError( "Cannot provide user-name explicitly in URL (%r) when connecting; " "use login instead." % url.username) if url.password is not None: raise ConnectError( "Cannot provide password explicitly in URL (%r) when connecting; " "use login instead." % url.username) if apikey is None: credentials = None # Anonymous access. else: credentials = Credentials.parse(apikey) description = await fetch_api_description(url, insecure) # Return a new (unsaved) profile. return Profile( name=url.netloc, url=url.geturl(), credentials=credentials, description=description)
[ "async", "def", "connect", "(", "url", ",", "*", ",", "apikey", "=", "None", ",", "insecure", "=", "False", ")", ":", "url", "=", "api_url", "(", "url", ")", "url", "=", "urlparse", "(", "url", ")", "if", "url", ".", "username", "is", "not", "Non...
Connect to a remote MAAS instance with `apikey`. Returns a new :class:`Profile` which has NOT been saved. To connect AND save a new profile:: profile = connect(url, apikey=apikey) profile = profile.replace(name="mad-hatter") with profiles.ProfileStore.open() as config: config.save(profile) # Optionally, set it as the default. config.default = profile.name
[ "Connect", "to", "a", "remote", "MAAS", "instance", "with", "apikey", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/helpers.py#L90-L127
train
28,792
maas/python-libmaas
maas/client/bones/helpers.py
login
async def login(url, *, anonymous=False, username=None, password=None, insecure=False): """Log-in to a remote MAAS instance. Returns a new :class:`Profile` which has NOT been saved. To log-in AND save a new profile:: profile = login(url, username="alice", password="wonderland") profile = profile.replace(name="mad-hatter") with profiles.ProfileStore.open() as config: config.save(profile) # Optionally, set it as the default. config.default = profile.name :raise RemoteError: An unexpected error from the remote system. :raise LoginError: An error related to logging-in. :raise PasswordWithoutUsername: Password given, but not username. :raise UsernameWithoutPassword: Username given, but not password. :raise LoginNotSupported: Server does not support API client log-in. """ url = api_url(url) url = urlparse(url) if username is None: username = url.username else: if url.username is None: pass # Anonymous access. else: raise LoginError( "User-name provided explicitly (%r) and in URL (%r); " "provide only one." % (username, url.username)) if password is None: password = url.password else: if url.password is None: pass # Anonymous access. else: raise LoginError( "Password provided explicitly (%r) and in URL (%r); " "provide only one." % (password, url.password)) # Remove user-name and password from the URL. userinfo, _, hostinfo = url.netloc.rpartition("@") url = url._replace(netloc=hostinfo) if username is None: if password: raise PasswordWithoutUsername( "Password provided without user-name; specify user-name.") elif anonymous: credentials = None else: credentials = await authenticate_with_macaroon( url.geturl(), insecure=insecure) else: if password is None: raise UsernameWithoutPassword( "User-name provided without password; specify password.") else: credentials = await authenticate( url.geturl(), username, password, insecure=insecure) description = await fetch_api_description(url, insecure) profile_name = username or url.netloc # Return a new (unsaved) profile. return Profile( name=profile_name, url=url.geturl(), credentials=credentials, description=description)
python
async def login(url, *, anonymous=False, username=None, password=None, insecure=False): """Log-in to a remote MAAS instance. Returns a new :class:`Profile` which has NOT been saved. To log-in AND save a new profile:: profile = login(url, username="alice", password="wonderland") profile = profile.replace(name="mad-hatter") with profiles.ProfileStore.open() as config: config.save(profile) # Optionally, set it as the default. config.default = profile.name :raise RemoteError: An unexpected error from the remote system. :raise LoginError: An error related to logging-in. :raise PasswordWithoutUsername: Password given, but not username. :raise UsernameWithoutPassword: Username given, but not password. :raise LoginNotSupported: Server does not support API client log-in. """ url = api_url(url) url = urlparse(url) if username is None: username = url.username else: if url.username is None: pass # Anonymous access. else: raise LoginError( "User-name provided explicitly (%r) and in URL (%r); " "provide only one." % (username, url.username)) if password is None: password = url.password else: if url.password is None: pass # Anonymous access. else: raise LoginError( "Password provided explicitly (%r) and in URL (%r); " "provide only one." % (password, url.password)) # Remove user-name and password from the URL. userinfo, _, hostinfo = url.netloc.rpartition("@") url = url._replace(netloc=hostinfo) if username is None: if password: raise PasswordWithoutUsername( "Password provided without user-name; specify user-name.") elif anonymous: credentials = None else: credentials = await authenticate_with_macaroon( url.geturl(), insecure=insecure) else: if password is None: raise UsernameWithoutPassword( "User-name provided without password; specify password.") else: credentials = await authenticate( url.geturl(), username, password, insecure=insecure) description = await fetch_api_description(url, insecure) profile_name = username or url.netloc # Return a new (unsaved) profile. return Profile( name=profile_name, url=url.geturl(), credentials=credentials, description=description)
[ "async", "def", "login", "(", "url", ",", "*", ",", "anonymous", "=", "False", ",", "username", "=", "None", ",", "password", "=", "None", ",", "insecure", "=", "False", ")", ":", "url", "=", "api_url", "(", "url", ")", "url", "=", "urlparse", "(",...
Log-in to a remote MAAS instance. Returns a new :class:`Profile` which has NOT been saved. To log-in AND save a new profile:: profile = login(url, username="alice", password="wonderland") profile = profile.replace(name="mad-hatter") with profiles.ProfileStore.open() as config: config.save(profile) # Optionally, set it as the default. config.default = profile.name :raise RemoteError: An unexpected error from the remote system. :raise LoginError: An error related to logging-in. :raise PasswordWithoutUsername: Password given, but not username. :raise UsernameWithoutPassword: Username given, but not password. :raise LoginNotSupported: Server does not support API client log-in.
[ "Log", "-", "in", "to", "a", "remote", "MAAS", "instance", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/helpers.py#L151-L222
train
28,793
maas/python-libmaas
maas/client/bones/helpers.py
authenticate_with_macaroon
async def authenticate_with_macaroon(url, insecure=False): """Login via macaroons and generate and return new API keys.""" executor = futures.ThreadPoolExecutor(max_workers=1) def get_token(): client = httpbakery.Client() resp = client.request( 'POST', '{}/account/?op=create_authorisation_token'.format(url), verify=not insecure) if resp.status_code == HTTPStatus.UNAUTHORIZED: # if the auteentication with Candid fails, an exception is raised # above so we don't get here raise MacaroonLoginNotSupported( 'Macaroon authentication not supported') if resp.status_code != HTTPStatus.OK: raise LoginError('Login failed: {}'.format(resp.text)) result = resp.json() return '{consumer_key}:{token_key}:{token_secret}'.format(**result) loop = asyncio.get_event_loop() return await loop.run_in_executor(executor, get_token)
python
async def authenticate_with_macaroon(url, insecure=False): """Login via macaroons and generate and return new API keys.""" executor = futures.ThreadPoolExecutor(max_workers=1) def get_token(): client = httpbakery.Client() resp = client.request( 'POST', '{}/account/?op=create_authorisation_token'.format(url), verify=not insecure) if resp.status_code == HTTPStatus.UNAUTHORIZED: # if the auteentication with Candid fails, an exception is raised # above so we don't get here raise MacaroonLoginNotSupported( 'Macaroon authentication not supported') if resp.status_code != HTTPStatus.OK: raise LoginError('Login failed: {}'.format(resp.text)) result = resp.json() return '{consumer_key}:{token_key}:{token_secret}'.format(**result) loop = asyncio.get_event_loop() return await loop.run_in_executor(executor, get_token)
[ "async", "def", "authenticate_with_macaroon", "(", "url", ",", "insecure", "=", "False", ")", ":", "executor", "=", "futures", ".", "ThreadPoolExecutor", "(", "max_workers", "=", "1", ")", "def", "get_token", "(", ")", ":", "client", "=", "httpbakery", ".", ...
Login via macaroons and generate and return new API keys.
[ "Login", "via", "macaroons", "and", "generate", "and", "return", "new", "API", "keys", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/helpers.py#L225-L245
train
28,794
maas/python-libmaas
maas/client/bones/helpers.py
authenticate
async def authenticate(url, username, password, *, insecure=False): """Obtain a new API key by logging into MAAS. :param url: URL for the MAAS API (i.e. ends with ``/api/x.y/``). :param insecure: If true, don't verify SSL/TLS certificates. :return: A `Credentials` instance. :raise RemoteError: An unexpected error from the remote system. :raise LoginNotSupported: Server does not support API client log-in. """ url_versn = urljoin(url, "version/") url_authn = urljoin(url, "../../accounts/authenticate/") def check_response_is_okay(response): if response.status != HTTPStatus.OK: raise RemoteError( "{0} -> {1.status} {1.reason}".format( response.url_obj.human_repr(), response)) connector = aiohttp.TCPConnector(verify_ssl=(not insecure)) session = aiohttp.ClientSession(connector=connector) async with session: # Check that this server supports `authenticate-api`. async with session.get(url_versn) as response: check_response_is_okay(response) version_info = await response.json() if "authenticate-api" not in version_info["capabilities"]: raise LoginNotSupported( "Server does not support automated client log-in. " "Please obtain an API token via the MAAS UI.") # POST to the `authenticate` endpoint. data = { "username": username, "password": password, "consumer": "%s@%s" % (getuser(), gethostname()) } async with session.post(url_authn, data=data) as response: check_response_is_okay(response) token_info = await response.json() return Credentials( token_info["consumer_key"], token_info["token_key"], token_info["token_secret"], )
python
async def authenticate(url, username, password, *, insecure=False): """Obtain a new API key by logging into MAAS. :param url: URL for the MAAS API (i.e. ends with ``/api/x.y/``). :param insecure: If true, don't verify SSL/TLS certificates. :return: A `Credentials` instance. :raise RemoteError: An unexpected error from the remote system. :raise LoginNotSupported: Server does not support API client log-in. """ url_versn = urljoin(url, "version/") url_authn = urljoin(url, "../../accounts/authenticate/") def check_response_is_okay(response): if response.status != HTTPStatus.OK: raise RemoteError( "{0} -> {1.status} {1.reason}".format( response.url_obj.human_repr(), response)) connector = aiohttp.TCPConnector(verify_ssl=(not insecure)) session = aiohttp.ClientSession(connector=connector) async with session: # Check that this server supports `authenticate-api`. async with session.get(url_versn) as response: check_response_is_okay(response) version_info = await response.json() if "authenticate-api" not in version_info["capabilities"]: raise LoginNotSupported( "Server does not support automated client log-in. " "Please obtain an API token via the MAAS UI.") # POST to the `authenticate` endpoint. data = { "username": username, "password": password, "consumer": "%s@%s" % (getuser(), gethostname()) } async with session.post(url_authn, data=data) as response: check_response_is_okay(response) token_info = await response.json() return Credentials( token_info["consumer_key"], token_info["token_key"], token_info["token_secret"], )
[ "async", "def", "authenticate", "(", "url", ",", "username", ",", "password", ",", "*", ",", "insecure", "=", "False", ")", ":", "url_versn", "=", "urljoin", "(", "url", ",", "\"version/\"", ")", "url_authn", "=", "urljoin", "(", "url", ",", "\"../../acc...
Obtain a new API key by logging into MAAS. :param url: URL for the MAAS API (i.e. ends with ``/api/x.y/``). :param insecure: If true, don't verify SSL/TLS certificates. :return: A `Credentials` instance. :raise RemoteError: An unexpected error from the remote system. :raise LoginNotSupported: Server does not support API client log-in.
[ "Obtain", "a", "new", "API", "key", "by", "logging", "into", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/bones/helpers.py#L248-L293
train
28,795
maas/python-libmaas
maas/client/viscera/pods.py
PodsType.create
async def create( cls, *, type: str, power_address: str, power_user: str = None, power_pass: str = None, name: str = None, zone: typing.Union[str, Zone] = None, tags: typing.Sequence[str] = None): """Create a `Pod` in MAAS. :param type: Type of pod to create (rsd, virsh) (required). :type name: `str` :param power_address: Address for power control of the pod (required). :type power_address: `str` :param power_user: User for power control of the pod (required for rsd). :type power_user: `str` :param power_pass: Password for power control of the pod (required for rsd). :type power_pass: `str` :param name: Name for the pod (optional). :type name: `str` :param zone: Name of the zone for the pod (optional). :type zone: `str` or `Zone` :param tags: A tag or tags (separated by comma) for the pod. :type tags: `str` :returns: The created Pod. :rtype: `Pod` """ params = remove_None({ 'type': type, 'power_address': power_address, 'power_user': power_user, 'power_pass': power_pass, 'name': name, 'tags': tags, }) if type == 'rsd' and power_user is None: message = "'power_user' is required for pod type `rsd`" raise OperationNotAllowed(message) if type == 'rsd' and power_pass is None: message = "'power_pass' is required for pod type `rsd`" raise OperationNotAllowed(message) if zone is not None: if isinstance(zone, Zone): params["zone"] = zone.name elif isinstance(zone, str): params["zone"] = zone else: raise TypeError( "zone must be a str or Zone, not %s" % type(zone).__name__) return cls._object(await cls._handler.create(**params))
python
async def create( cls, *, type: str, power_address: str, power_user: str = None, power_pass: str = None, name: str = None, zone: typing.Union[str, Zone] = None, tags: typing.Sequence[str] = None): """Create a `Pod` in MAAS. :param type: Type of pod to create (rsd, virsh) (required). :type name: `str` :param power_address: Address for power control of the pod (required). :type power_address: `str` :param power_user: User for power control of the pod (required for rsd). :type power_user: `str` :param power_pass: Password for power control of the pod (required for rsd). :type power_pass: `str` :param name: Name for the pod (optional). :type name: `str` :param zone: Name of the zone for the pod (optional). :type zone: `str` or `Zone` :param tags: A tag or tags (separated by comma) for the pod. :type tags: `str` :returns: The created Pod. :rtype: `Pod` """ params = remove_None({ 'type': type, 'power_address': power_address, 'power_user': power_user, 'power_pass': power_pass, 'name': name, 'tags': tags, }) if type == 'rsd' and power_user is None: message = "'power_user' is required for pod type `rsd`" raise OperationNotAllowed(message) if type == 'rsd' and power_pass is None: message = "'power_pass' is required for pod type `rsd`" raise OperationNotAllowed(message) if zone is not None: if isinstance(zone, Zone): params["zone"] = zone.name elif isinstance(zone, str): params["zone"] = zone else: raise TypeError( "zone must be a str or Zone, not %s" % type(zone).__name__) return cls._object(await cls._handler.create(**params))
[ "async", "def", "create", "(", "cls", ",", "*", ",", "type", ":", "str", ",", "power_address", ":", "str", ",", "power_user", ":", "str", "=", "None", ",", "power_pass", ":", "str", "=", "None", ",", "name", ":", "str", "=", "None", ",", "zone", ...
Create a `Pod` in MAAS. :param type: Type of pod to create (rsd, virsh) (required). :type name: `str` :param power_address: Address for power control of the pod (required). :type power_address: `str` :param power_user: User for power control of the pod (required for rsd). :type power_user: `str` :param power_pass: Password for power control of the pod (required for rsd). :type power_pass: `str` :param name: Name for the pod (optional). :type name: `str` :param zone: Name of the zone for the pod (optional). :type zone: `str` or `Zone` :param tags: A tag or tags (separated by comma) for the pod. :type tags: `str` :returns: The created Pod. :rtype: `Pod`
[ "Create", "a", "Pod", "in", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/pods.py#L29-L80
train
28,796
maas/python-libmaas
maas/client/viscera/pods.py
Pod.compose
async def compose( self, *, cores: int = None, memory: int = None, cpu_speed: int = None, architecture: str = None, storage: typing.Sequence[str] = None, hostname: str = None, domain: typing.Union[int, str] = None, zone: typing.Union[int, str, Zone] = None, interfaces: typing.Sequence[str] = None): """Compose a machine from `Pod`. All fields below are optional: :param cores: Minimum number of CPU cores. :type cores: `int` :param memory: Minimum amount of memory (MiB). :type memory: `int` :param cpu_speed: Minimum amount of CPU speed (MHz). :type cpu_speed: `int` :param architecture: Architecture for the machine. Must be an architecture that the pod supports. :type architecture: `str` :param storage: A list of storage constraint identifiers, in the form: <label>:<size>(<tag>[,<tag>[,...])][,<label>:...] :type storage: `str` :param hostname: Hostname for the newly composed machine. :type hostname: `str` :param domain: The domain ID for the machine (optional). :type domain: `int` or `str` :param zone: The zone ID for the machine (optional). :type zone: `int` or 'str' or `Zone` :param interfaces: A labeled constraint map associating constraint labels with interface properties that should be matched. Returned nodes must have one or more interface matching the specified constraints. The labeled constraint map must be in the format: ``<label>:<key>=<value>[,<key2>=<value2>[,...]]`` Each key can be one of the following: - id: Matches an interface with the specific id - fabric: Matches an interface attached to the specified fabric. - fabric_class: Matches an interface attached to a fabric with the specified class. - ip: Matches an interface with the specified IP address assigned to it. - mode: Matches an interface with the specified mode. (Currently, the only supported mode is "unconfigured".) - name: Matches an interface with the specified name. (For example, "eth0".) - hostname: Matches an interface attached to the node with the specified hostname. - subnet: Matches an interface attached to the specified subnet. - space: Matches an interface attached to the specified space. - subnet_cidr: Matches an interface attached to the specified subnet CIDR. (For example, "192.168.0.0/24".) - type: Matches an interface of the specified type. (Valid types: "physical", "vlan", "bond", "bridge", or "unknown".) - vlan: Matches an interface on the specified VLAN. - vid: Matches an interface on a VLAN with the specified VID. - tag: Matches an interface tagged with the specified tag. :type interfaces: `str` :returns: The created Machine :rtype: `Machine` """ params = remove_None({ 'cores': str(cores) if cores else None, 'memory': str(memory) if memory else None, 'cpu_speed': str(cpu_speed) if cpu_speed else None, 'architecture': architecture, 'storage': storage, 'hostname': hostname, 'domain': str(domain) if domain else None, 'interfaces': interfaces, }) if zone is not None: if isinstance(zone, Zone): params["zone"] = str(zone.id) elif isinstance(zone, int): params["zone"] = str(zone) elif isinstance(zone, str): params["zone"] = zone else: raise TypeError( "zone must be an int, str or Zone, not %s" % type(zone).__name__) return await self._handler.compose(**params, id=self.id)
python
async def compose( self, *, cores: int = None, memory: int = None, cpu_speed: int = None, architecture: str = None, storage: typing.Sequence[str] = None, hostname: str = None, domain: typing.Union[int, str] = None, zone: typing.Union[int, str, Zone] = None, interfaces: typing.Sequence[str] = None): """Compose a machine from `Pod`. All fields below are optional: :param cores: Minimum number of CPU cores. :type cores: `int` :param memory: Minimum amount of memory (MiB). :type memory: `int` :param cpu_speed: Minimum amount of CPU speed (MHz). :type cpu_speed: `int` :param architecture: Architecture for the machine. Must be an architecture that the pod supports. :type architecture: `str` :param storage: A list of storage constraint identifiers, in the form: <label>:<size>(<tag>[,<tag>[,...])][,<label>:...] :type storage: `str` :param hostname: Hostname for the newly composed machine. :type hostname: `str` :param domain: The domain ID for the machine (optional). :type domain: `int` or `str` :param zone: The zone ID for the machine (optional). :type zone: `int` or 'str' or `Zone` :param interfaces: A labeled constraint map associating constraint labels with interface properties that should be matched. Returned nodes must have one or more interface matching the specified constraints. The labeled constraint map must be in the format: ``<label>:<key>=<value>[,<key2>=<value2>[,...]]`` Each key can be one of the following: - id: Matches an interface with the specific id - fabric: Matches an interface attached to the specified fabric. - fabric_class: Matches an interface attached to a fabric with the specified class. - ip: Matches an interface with the specified IP address assigned to it. - mode: Matches an interface with the specified mode. (Currently, the only supported mode is "unconfigured".) - name: Matches an interface with the specified name. (For example, "eth0".) - hostname: Matches an interface attached to the node with the specified hostname. - subnet: Matches an interface attached to the specified subnet. - space: Matches an interface attached to the specified space. - subnet_cidr: Matches an interface attached to the specified subnet CIDR. (For example, "192.168.0.0/24".) - type: Matches an interface of the specified type. (Valid types: "physical", "vlan", "bond", "bridge", or "unknown".) - vlan: Matches an interface on the specified VLAN. - vid: Matches an interface on a VLAN with the specified VID. - tag: Matches an interface tagged with the specified tag. :type interfaces: `str` :returns: The created Machine :rtype: `Machine` """ params = remove_None({ 'cores': str(cores) if cores else None, 'memory': str(memory) if memory else None, 'cpu_speed': str(cpu_speed) if cpu_speed else None, 'architecture': architecture, 'storage': storage, 'hostname': hostname, 'domain': str(domain) if domain else None, 'interfaces': interfaces, }) if zone is not None: if isinstance(zone, Zone): params["zone"] = str(zone.id) elif isinstance(zone, int): params["zone"] = str(zone) elif isinstance(zone, str): params["zone"] = zone else: raise TypeError( "zone must be an int, str or Zone, not %s" % type(zone).__name__) return await self._handler.compose(**params, id=self.id)
[ "async", "def", "compose", "(", "self", ",", "*", ",", "cores", ":", "int", "=", "None", ",", "memory", ":", "int", "=", "None", ",", "cpu_speed", ":", "int", "=", "None", ",", "architecture", ":", "str", "=", "None", ",", "storage", ":", "typing",...
Compose a machine from `Pod`. All fields below are optional: :param cores: Minimum number of CPU cores. :type cores: `int` :param memory: Minimum amount of memory (MiB). :type memory: `int` :param cpu_speed: Minimum amount of CPU speed (MHz). :type cpu_speed: `int` :param architecture: Architecture for the machine. Must be an architecture that the pod supports. :type architecture: `str` :param storage: A list of storage constraint identifiers, in the form: <label>:<size>(<tag>[,<tag>[,...])][,<label>:...] :type storage: `str` :param hostname: Hostname for the newly composed machine. :type hostname: `str` :param domain: The domain ID for the machine (optional). :type domain: `int` or `str` :param zone: The zone ID for the machine (optional). :type zone: `int` or 'str' or `Zone` :param interfaces: A labeled constraint map associating constraint labels with interface properties that should be matched. Returned nodes must have one or more interface matching the specified constraints. The labeled constraint map must be in the format: ``<label>:<key>=<value>[,<key2>=<value2>[,...]]`` Each key can be one of the following: - id: Matches an interface with the specific id - fabric: Matches an interface attached to the specified fabric. - fabric_class: Matches an interface attached to a fabric with the specified class. - ip: Matches an interface with the specified IP address assigned to it. - mode: Matches an interface with the specified mode. (Currently, the only supported mode is "unconfigured".) - name: Matches an interface with the specified name. (For example, "eth0".) - hostname: Matches an interface attached to the node with the specified hostname. - subnet: Matches an interface attached to the specified subnet. - space: Matches an interface attached to the specified space. - subnet_cidr: Matches an interface attached to the specified subnet CIDR. (For example, "192.168.0.0/24".) - type: Matches an interface of the specified type. (Valid types: "physical", "vlan", "bond", "bridge", or "unknown".) - vlan: Matches an interface on the specified VLAN. - vid: Matches an interface on a VLAN with the specified VID. - tag: Matches an interface tagged with the specified tag. :type interfaces: `str` :returns: The created Machine :rtype: `Machine`
[ "Compose", "a", "machine", "from", "Pod", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/pods.py#L150-L233
train
28,797
maas/python-libmaas
maas/client/viscera/ipranges.py
IPRangesType.create
async def create( cls, start_ip: str, end_ip: str, *, type: IPRangeType = IPRangeType.RESERVED, comment: str = None, subnet: Union[Subnet, int] = None): """ Create a `IPRange` in MAAS. :param start_ip: First IP address in the range (required). :type start_ip: `str` :parma end_ip: Last IP address in the range (required). :type end_ip: `str` :param type: Type of IP address range (optional). :type type: `IPRangeType` :param comment: Reason for the IP address range (optional). :type comment: `str` :param subnet: Subnet the IP address range should be created on (optional). By default MAAS will calculate the correct subnet based on the `start_ip` and `end_ip`. :type subnet: `Subnet` or `int` :returns: The created IPRange :rtype: `IPRange` """ if not isinstance(type, IPRangeType): raise TypeError( "type must be an IPRangeType, not %s" % TYPE(type).__name__) params = { 'start_ip': start_ip, 'end_ip': end_ip, 'type': type.value, } if comment is not None: params["comment"] = comment if subnet is not None: if isinstance(subnet, Subnet): params["subnet"] = subnet.id elif isinstance(subnet, int): params["subnet"] = subnet else: raise TypeError( "subnet must be Subnet or int, not %s" % ( TYPE(subnet).__class__)) return cls._object(await cls._handler.create(**params))
python
async def create( cls, start_ip: str, end_ip: str, *, type: IPRangeType = IPRangeType.RESERVED, comment: str = None, subnet: Union[Subnet, int] = None): """ Create a `IPRange` in MAAS. :param start_ip: First IP address in the range (required). :type start_ip: `str` :parma end_ip: Last IP address in the range (required). :type end_ip: `str` :param type: Type of IP address range (optional). :type type: `IPRangeType` :param comment: Reason for the IP address range (optional). :type comment: `str` :param subnet: Subnet the IP address range should be created on (optional). By default MAAS will calculate the correct subnet based on the `start_ip` and `end_ip`. :type subnet: `Subnet` or `int` :returns: The created IPRange :rtype: `IPRange` """ if not isinstance(type, IPRangeType): raise TypeError( "type must be an IPRangeType, not %s" % TYPE(type).__name__) params = { 'start_ip': start_ip, 'end_ip': end_ip, 'type': type.value, } if comment is not None: params["comment"] = comment if subnet is not None: if isinstance(subnet, Subnet): params["subnet"] = subnet.id elif isinstance(subnet, int): params["subnet"] = subnet else: raise TypeError( "subnet must be Subnet or int, not %s" % ( TYPE(subnet).__class__)) return cls._object(await cls._handler.create(**params))
[ "async", "def", "create", "(", "cls", ",", "start_ip", ":", "str", ",", "end_ip", ":", "str", ",", "*", ",", "type", ":", "IPRangeType", "=", "IPRangeType", ".", "RESERVED", ",", "comment", ":", "str", "=", "None", ",", "subnet", ":", "Union", "[", ...
Create a `IPRange` in MAAS. :param start_ip: First IP address in the range (required). :type start_ip: `str` :parma end_ip: Last IP address in the range (required). :type end_ip: `str` :param type: Type of IP address range (optional). :type type: `IPRangeType` :param comment: Reason for the IP address range (optional). :type comment: `str` :param subnet: Subnet the IP address range should be created on (optional). By default MAAS will calculate the correct subnet based on the `start_ip` and `end_ip`. :type subnet: `Subnet` or `int` :returns: The created IPRange :rtype: `IPRange`
[ "Create", "a", "IPRange", "in", "MAAS", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/ipranges.py#L31-L74
train
28,798
maas/python-libmaas
maas/client/viscera/interfaces.py
gen_parents
def gen_parents(parents): """Generate the parents to send to the handler.""" for idx, parent in enumerate(parents): if isinstance(parent, Interface): parent = parent.id elif isinstance(parent, int): pass else: raise TypeError( 'parent[%d] must be an Interface or int, not %s' % ( idx, type(parent).__name__)) yield parent
python
def gen_parents(parents): """Generate the parents to send to the handler.""" for idx, parent in enumerate(parents): if isinstance(parent, Interface): parent = parent.id elif isinstance(parent, int): pass else: raise TypeError( 'parent[%d] must be an Interface or int, not %s' % ( idx, type(parent).__name__)) yield parent
[ "def", "gen_parents", "(", "parents", ")", ":", "for", "idx", ",", "parent", "in", "enumerate", "(", "parents", ")", ":", "if", "isinstance", "(", "parent", ",", "Interface", ")", ":", "parent", "=", "parent", ".", "id", "elif", "isinstance", "(", "par...
Generate the parents to send to the handler.
[ "Generate", "the", "parents", "to", "send", "to", "the", "handler", "." ]
4092c68ef7fb1753efc843569848e2bcc3415002
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/interfaces.py#L31-L42
train
28,799