libcloud.compute.drivers.kubevirt module

kubevirt driver with support for nodes (vms)

class libcloud.compute.drivers.kubevirt.KubeVirtNodeDriver(key=None, secret=None, secure=False, host='localhost', port=4243, key_file=None, cert_file=None, ca_cert=None, ex_token_bearer_auth=False)[source]

Bases: KubernetesDriverMixin, NodeDriver

Parameters:
  • key (str) – API key or username to be used (required)

  • secret (str) – Secret password to be used (required)

  • secure (bool) – Whether to use HTTPS or HTTP. Note: Some providers only support HTTPS, and it is on by default.

  • host (str) – Override hostname used for connections.

  • port (int) – Override port used for connections.

  • key_file (str) – Path to the key file used to authenticate (when using key file auth).

  • cert_file (str) – Path to the cert file used to authenticate (when using key file auth).

  • ex_token_bearer_auth (bool) – True to use token bearer auth.

Returns:

None

NODE_STATE_MAP: Dict[str, NodeState] = {'pending': NodeState.PENDING, 'running': NodeState.RUNNING, 'stopped': NodeState.STOPPED}
attach_volume(node, volume, device='disk', ex_bus='virtio', ex_name=None)[source]

params: bus, name , device (disk or lun)

connectionCls

alias of KubernetesBasicAuthConnection

create_node(name: str, size: NodeSize | None = None, image: NodeImage | str | None = None, location: NodeLocation | None = None, auth: NodeAuthSSHKey | NodeAuthPassword | None = None, ex_cpu: int | str | None = None, ex_memory: int | None = None, ex_disks: list | None = None, ex_network: dict | None = None, ex_termination_grace_period: int | None = 0, ex_ports: dict | None = None, ex_template: dict | None = None) Node[source]

Creating a VM with a containerDisk.

@inherits: NodeDriver.create_node

The size parameter should be a NodeSize object that defines the CPU and memory limits of the VM. The NodeSize object must have the following attributes:

  • ram: int (in MiB)

  • extra[“cpu”]: int (in cores)

An example NodeSize for a VM with 1 CPU and 2GiB of memory (attributes except for ram and extra["cpu"] are not supported atm, but they are required by the NodeSize object):

>>> size = NodeSize(
>>>     id='small',  # str: Size ID
>>>     name='small',  # str: Size name. Not used atm
>>>     ram=2048,  # int: Amount of memory (in MB)
>>>     disk=20,  # int: Amount of disk storage (in GB). Not used atm
>>>     bandwidth=0,  # int: Amount of bandwidth. Not used atm
>>>     price=0,  # float: Price (in US dollars) of running this node for an hour. Not used atm
>>>     driver=KubeVirtNodeDriver  # NodeDriver: Driver this size belongs to
>>>     extra={
>>>         'cpu': 1,  # int: Number of CPUs provided by this size.
>>>     },
>>> )

The KubeVirtNodeSize wrapper can be used to create the NodeSize object more easily:

>>> size = KubeVirtNodeSize(
>>>     cpu=1,  # int: Number of CPUs provided by this size.
>>>     ram=2048,  # int: Amount of memory (in MB)
>>> )

For legacy support, the ex_cpu and ex_memory parameters can be used instead of size:

  • ex_cpu: The number of CPU cores to allocate to the VM.

    ex_cpu must be a number (cores) or a string ending with ‘m’ (miliCPUs).

  • ex_memory: The amount of memory to allocate to the VM in MiB.

The image parameter can be either a NodeImage object with a name attribute that points to a containerDisk image, or a string representing the image URI.

In both cases, it must point to a Docker image with an embedded disk. May be a URI like kubevirt/cirros-registry-disk-demo, kubevirt will automatically pull it from https://hub.docker.com/u/URI.

For more info visit: https://kubevirt.io/user-guide/docs/latest/creating-virtual-machines/disks-and-volumes.html#containerdisk

An example NodeImage:

>>> image = NodeImage(
>>>     id="something_unique",
>>>     name="quay.io/containerdisks/ubuntu:22.04"
>>>     driver=KubeVirtNodeDriver,
>>> )

The KubeVirtNodeImage wrapper can be used to create the NodeImage object more easily:

>>> image = KubeVirtNodeImage(
>>>     name="quay.io/containerdisks/ubuntu:22.04"
>>> )

The location parameter is a NodeLocation object with the name being the kubernetes namespace where the VM will live. If not provided, the VM will be created in the default namespace. It can be created as the following:

>>> location = NodeLocation(
>>>     name='default',  # str: namespace
>>>     ... # Other attributes are ignored
>>> )

The auth parameter is the authentication method for the VM, either a NodeAuthSSHKey or a NodeAuthPassword:

  • NodeAuthSSHKey(pubkey='pubkey data here')

  • NodeAuthPassword(password='mysecretpassword')

If the auth parameter is provided, the VM will be created with a cloud-init volume that will inject the provided authentication into the VM. For details, see: https://kubevirt.io/user-guide/virtual_machines/startup_scripts/#injecting-ssh-keys-with-cloud-inits-cloud-config

The ex_disks parameter is a list of disk dictionaries that define the disks of the VM. Each dictionary should have specific keys for disk configuration.

The following are optional keys:

  • "bus": can be “virtio”, “sata”, or “scsi”

  • "device": can be “lun” or “disk”

The following are required keys:

  • "disk_type":

    One of the supported DISK_TYPES. Atm only “persistentVolumeClaim” and “containerDisk” are promised to work. Other types may work but are not tested.

  • "name":

    The name of the disk configuration

  • "voulme_spec":

    the dictionary that defines the volume of the disk. The content is depending on the disk_type:

    For containerDisk the dictionary should have a key image with the value being the image URI.

    For persistentVolumeClaim the dictionary should have a key claim_name with the value being the name of the claim. If you wish, a new Persistent Volume Claim can be created by providing the following:

    • required:
      • size: the desired size (implied in GB)

      • storage_class_name: the name of the storage class to # NOQA

        be used for the creation of the Persistent Volume Claim. Make sure it allows for dymamic provisioning.

    • optional:
      • access_mode: default is ReadWriteOnce

      • volume_mode: default is Filesystem, it can also be Block

    For other disk types, it will be translated to a KubeVirt volume object as is:

    {disk_type: <volume_spec>, "name": disk_name}
    

    This dict will be translated to KubeVirt API object:

    volumes:
      - name: <disk_name>
        <disk_type>:
          <voulme_spec>
    

Please refer to the KubeVirt API documentation for volume specifications:

https://kubevirt.io/user-guide/virtual_machines/disks_and_volumes

An example ex_disks list with a hostDisk that will create a new img file in the host machine:

>>> ex_disks = [
>>>     {
>>>         "bus": "virtio",
>>>         "device": "disk",
>>>         "disk_type": "hostDisk",
>>>         "name": "disk114514",
>>>         "volume_spec": {
>>>             "capacity": "10Gi",
>>>             "path": "/tmp/kubevirt/data/disk114514.img",
>>>             "type": "DiskOrCreate",
>>>         },
>>>     },
>>> ]

The ex_network parameter is a dictionary that defines the network of the VM. Only the pod type is supported, and in the configuration masquerade or bridge are the accepted values. The parameter must be a dict:

{
    "network_type": "pod",
    "interface": "masquerade | bridge",
    "name": "network_name"
}

For advanced configurations not covered by the other parameters, the ex_template parameter can be used to provide a dictionary of kubernetes object that defines the KubeVirt VM. Notice, If provided, ex_template will override all other parameters except for name and location.

The ex_template parameter is a dictionary of kubernetes object:

  • apiVersion: str

  • kind: str

  • metadata: dict

  • spec: dict
    • domain: dict

    • volumes: list

See also:

Parameters:
  • name (str) – A name to give the VM. The VM will be identified by this name and atm it cannot be changed after it is set.

  • size (NodeSize with) – The size of the VM in terms of CPU and memory. A NodeSize object with the attributes ram (int in MiB) and extra["cpu"] (int in cores).

  • image (str or NodeImage) – Either a libcloud NodeImage or a string. In both cases, it must a URL to the containerDisk image.

  • location (NodeLocation` in which the name is the namespace) – The namespace where the VM will live. (default is 'default')

  • auth (NodeAuthSSHKey or NodeAuthPassword.) – authentication to a node.

  • ex_cpu (int or str) – The number of CPU cores to allocate to the VM. (Legacy support, consider using size instead)

  • ex_memory (int) – The amount of memory to allocate to the VM in MiB. (Legacy support, consider using size instead)

  • ex_disks (list of dict with keys: bus: str, device: str, disk_type: str, name: str and voulme_spec: dict) – A list containing disk dictionaries. Each dictionary should have the following keys: bus: can be "virtio", "sata", or "scsi"; device: can be "lun" or "disk"; disk_type: One of the supported DISK_TYPES; name: The name of the disk configuration; voulme_spec: the dictionary that defines the volume of the disk.

  • ex_network (dict with keys: network_type: str, interface: str and name: str) – a dictionary that defines the network of the VM. The following keys are required: network_type: "pod"; interface: "masquerade" or "bridge"; name: "network_name".

  • ex_termination_grace_period (int) – The grace period in seconds before the VM is forcefully terminated. (default is 0)

  • ex_ports (dict with keys ports_tcp: list of int; ports_udp: list of int.) – A dictionary with keys: "ports_tcp" and "ports_udp" "ports_tcp" value is a list of ints that indicate the ports to be exposed with TCP protocol, and "ports_udp" is a list of ints that indicate the ports to be exposed with UDP protocol.

  • ex_template (dict with keys: apiVersion: str, kind: str, metadata: dict and spec: dict) – A dictionary of kubernetes object that defines the KubeVirt VM. This is for advanced vm specifications that are not covered by the other parameters. If provided, it will override all other parameters except for name and location.

create_volume(size, name, location=None, ex_storage_class_name='', ex_volume_mode='Filesystem', ex_access_mode='ReadWriteOnce', ex_dynamic=True, ex_reclaim_policy='Recycle', ex_volume_type=None, ex_volume_params=None)[source]
Parameters:
  • size (int) – The size in Gigabytes

  • volume_type (str) –

    This is the type of volume to be created that is dependent on the underlying cloud where Kubernetes is deployed. K8s is supporting the following types: -gcePersistentDisk -awsElasticBlockStore -azureFile -azureDisk -csi -fc (Fibre Channel) -flexVolume -flocker -nfs -iSCSI -rbd (Ceph Block Device) -cephFS -cinder (OpenStack block storage) -glusterfs -vsphereVolume -quobyte Volumes -hostPath (Single node testing only – local storage is not supported in any way and WILL NOT WORK in a multi-node cluster) # NOQA -portworx Volumes -scaleIO Volumes -storageOS This parameter is a dict in the form {type: {key1:value1, key2:value2,…}}, where type is one of the above and key1, key2… are type specific keys and their corresponding values. eg: {nsf: {server: “172.0.0.0”, path: “/tmp”}}

    {awsElasticBlockStore: {fsType: ‘ext4’, volumeID: “1234”}}

  • volume_params – A dict with the key:value that the volume_type needs. This parameter is a dict in the form {key1:value1, key2:value2,…}, where type is one of the above and key1, key2… are type specific keys and their corresponding values. eg: for nsf volume_type {server: “172.0.0.0”, path: “/tmp”} for awsElasticBlockStore volume_type {fsType: ‘ext4’, volumeID: “1234”}

destroy_node(node)[source]

Terminating a VMI and deleting the VM resource backing it.

Parameters:

node (Node) – The node to be destroyed.

Returns:

True if the destruction was successful, False otherwise.

Return type:

bool

destroy_volume(volume)[source]

Destroys a storage volume.

Parameters:

volume (StorageVolume) – Volume to be destroyed

Return type:

bool

detach_volume(volume, ex_node)[source]

Detaches a volume from a node but the node must be given since a PVC can have more than one VMI’s pointing to it

ex_create_service(node, ports, service_type='NodePort', cluster_ip=None, load_balancer_ip=None, override_existing_ports=False)[source]

Each node has a single service of one type on which the exposed ports are described. If a service exists then the port declared will be exposed alongside the existing ones, set override_existing_ports=True to delete existing exposed ports and expose just the ones in the port variable.

Parameters:
  • node (libcloud Node class) – the libcloud node for which the ports will be exposed

  • ports (list of dict where each dict has keys –> values: ‘port’ –> int; ‘target_port’ –> int; ‘protocol’ –> str; ‘name’ –> str;) –

    a list of dictionaries with keys –> values: ‘port’ –> port to be exposed on the service; ‘target_port’ –> port on the pod/node, optional

    if empty then it gets the same value as ‘port’ value;

    ’protocol’ —> either ‘UDP’ or ‘TCP’, defaults to TCP; ‘name’ –> A name for the service; If ports is an empty list and a service exists of this type then the service will be deleted.

  • service_type (str) – Valid types are ClusterIP, NodePort, LoadBalancer

  • cluster_ip (str) – This can be set with an IP string value if you want manually set the service’s internal IP. If the value is not correct the method will fail, this value can’t be updated.

  • override_existing_ports (boolean) – Set to True if you want to delete the existing ports exposed by the service and keep just the ones declared in the present ports argument. By default it is false and if the service already exists the ports will be added to the existing ones.

ex_delete_service(namespace, service_name)[source]
ex_list_persistent_volume_claims(namespace='default')[source]
ex_list_services(namespace='default', node_name=None, service_name=None)[source]

If node_name is given then the services returned will be those that concern the node.

ex_list_storage_classes()[source]
features: Dict[str, List[str]] = {'create_node': ['ssh_key', 'password']}
List of available features for a driver.
get_node(id=None, name=None)[source]

get a vm by name or id.

Parameters:
  • id (str) – id of the vm

  • name (str) – name of the vm

list_images(location=None)[source]

If location (namespace) is provided only the images in that location will be provided. Otherwise all of them.

list_locations()[source]

By locations here it is meant namespaces.

list_nodes(location=None)[source]

List all nodes.

Returns:

list of node objects

Return type:

list of Node

list_sizes(location=None)[source]

List sizes on a provider

Parameters:

location (NodeLocation) – The location at which to list sizes

Returns:

list of node size objects

Return type:

list of NodeSize

list_volumes()[source]

Location is a namespace of the cluster.

name: str = 'kubevirt'
reboot_node(node)[source]

Rebooting a node.

Parameters:

node (Node) – The node to be rebooted.

Returns:

True if the reboot was successful, False otherwise.

Return type:

bool

start_node(node)[source]

Starting a VM.

Parameters:

node (Node) – The node to be started.

Returns:

True if the start was successful, False otherwise.

Return type:

bool

stop_node(node)[source]

Stopping a VM.

Parameters:

node (Node) – The node to be stopped.

Returns:

True if the stop was successful, False otherwise.

Return type:

bool

type: Provider | str = 'kubevirt'
website: str = 'https://www.kubevirt.io'
libcloud.compute.drivers.kubevirt.KubeVirtNodeImage(name: str) NodeImage[source]

Create a NodeImage object for KubeVirt driver.

This function is just a shorthand for NodeImage(name=name).

Parameters:

name (str) – image source

Returns:

a NodeImage object with the name set to the source to a containerDisk image (e.g. "quay.io/containerdisks/ubuntu:22.04")

Return type:

NodeImage

libcloud.compute.drivers.kubevirt.KubeVirtNodeSize(cpu: int, ram: int, cpu_request: int | None = None, ram_request: int | None = None) NodeSize[source]

Create a NodeSize object for KubeVirt driver.

This function is just a shorthand for NodeSize(ram=ram, extra={"cpu": cpu}).

Parameters:
  • cpu (int) – number of virtual CPUs (max limit)

  • ram (int) – amount of RAM in MiB (max limit)

  • cpu_request (int) – number of virtual CPUs (min request)

  • ram_request (int) – amount of RAM in MiB (min request)

Returns:

a NodeSize object with ram and extra.cpu set

Return type:

NodeSize