Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[e2e] implement vm template related function and test case #1341

Merged
merged 4 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 11 additions & 101 deletions apiclient/harvester_api/managers/templates.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import json

from harvester_api.models.templates import TemplateSpec
from .base import DEFAULT_NAMESPACE, BaseManager


Expand All @@ -10,6 +9,8 @@ class TemplateManager(BaseManager):
_KIND = "VirtualMachineTemplate"
_VER_KIND = "VirtualMachineTemplateVersion"

Spec = TemplateSpec

def create_data(self, name, namespace, description):
data = {
"apiVersion": "{API_VERSION}",
Expand All @@ -24,101 +25,6 @@ def create_data(self, name, namespace, description):
}
return self._inject_data(data)

def create_version_data(self, name, namespace, cpu, mem, disk_name):
data = {
"apiVersion": "{API_VERSION}",
"kind": self._VER_KIND,
"metadata": {
"generateName": f"{name}-",
"labels": {
"template.harvesterhci.io/templateID": name
},
"namespace": namespace
},
"spec": {
"templateId": f"{namespace}/{name}",
"vm": {
"metadata": {
"annotations": {
"harvesterhci.io/volumeClaimTemplates": json.dumps([{
"metadata": {
"annotations": {"harvesterhci.io/imageId": ""},
"name": f"-{disk_name}"
},
"spec": {
"accessModes": ["ReadWriteMany"],
"resources": {"requests": {"storage": "10Gi"}},
"volumeMode": "Block"
}
}])
}
},
"spec": {
"runStrategy": "RerunOnFailure",
"template": {
"metadata": {
"annotations": {
"harvesterhci.io/sshNames": "[]"
}
},
"spec": {
"domain": {
"cpu": {
"cores": cpu,
"sockets": 1,
"threads": 1
},
"devices": {
"disks": [
{
"disk": {"bus": "virtio"},
"name": "disk-0"
}
],
"inputs": [
{
"bus": "usb",
"name": "tablet",
"type": "tablet"
}
],
"interfaces": [
{
"masquerade": {},
"model": "virtio",
"name": "default"
}
]
},
"features": {"acpi": {"enabled": True}},
"machine": {
"type": ""
},
"resources": {
"limits": dict(cpu=cpu, memory=mem)
}
},
"evictionStrategy": "LiveMigrate",
"networks": [
{
"name": "default",
"pod": {}
}
],
"volumes": [
{
"dataVolume": {"name": f"-{disk_name}"},
"name": "disk-0"
}
]
}
}
}
}
}
}
return self._inject_data(data)

def get(self, name="", namespace=DEFAULT_NAMESPACE, *, raw=False):
return self._get(self.PATH_fmt.format(uid=name, ns=namespace), raw=raw)

Expand All @@ -130,12 +36,16 @@ def create(self, name, namespace=DEFAULT_NAMESPACE, description="", *, raw=False
path = self.PATH_fmt.format(ns=namespace, uid="")
return self._create(path, json=data, raw=raw)

def update(self, name, namespace=DEFAULT_NAMESPACE, *, raw=False, **options):
cpu, memory = options.get('cpu', 1), options.get('memory', "1Gi")
disk_name = options.get("disk_name", "default")
data = self.create_version_data(name, namespace, cpu, memory, disk_name)
def create_version(self, name, template_spec, namespace=DEFAULT_NAMESPACE, *, raw=False):
if isinstance(template_spec, self.Spec):
template_spec = template_spec.to_dict(name, namespace)
template_spec.update(apiVersion="{API_VERSION}", kind=self._VER_KIND)
data = self._inject_data(template_spec)
path = self.VER_PATH_fmt.format(uid="", ns=namespace)
return self._create(path, json=data, raw=raw)

def delete(self, name, namespace=DEFAULT_NAMESPACE, *, raw=False):
return self._delete(self.PATH_fmt.format(uid=name, ns=namespace), raw=raw)

def delete_version(self, name, namespace=DEFAULT_NAMESPACE, *, raw=False):
return self._delete(self.VER_PATH_fmt.format(uid=name, ns=namespace), raw=raw)
13 changes: 11 additions & 2 deletions apiclient/harvester_api/managers/virtualmachines.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ def get_status(self, name="", namespace=DEFAULT_NAMESPACE, *, raw=False, **kwarg

def create(self, name, vm_spec, namespace=DEFAULT_NAMESPACE, *, raw=False):
if isinstance(vm_spec, self.Spec):
vm_spec = vm_spec.to_dict(name, namespace)
vm_spec = self.Spec.to_dict(vm_spec, name, namespace)
path = self.PATH_fmt.format(uid="", ns=namespace)
return self._create(path, json=vm_spec, raw=raw)

def update(self, name, vm_spec, namespace=DEFAULT_NAMESPACE, *,
raw=False, as_json=True, **kwargs):
if isinstance(vm_spec, self.Spec):
vm_spec = vm_spec.to_dict(name, namespace)
vm_spec = self.Spec.to_dict(vm_spec, name, namespace)
albinsun marked this conversation as resolved.
Show resolved Hide resolved
path = self.PATH_fmt.format(uid=f"/{name}", ns=namespace)
return self._update(path, vm_spec, raw=raw, as_json=as_json, **kwargs)

Expand Down Expand Up @@ -114,3 +114,12 @@ def remove_volume(self, name, disk_name, namespace=DEFAULT_NAMESPACE, *, raw=Fal
json = dict(diskName=disk_name)
params = dict(action="removeVolume")
return self._create(path, params=params, json=json, raw=raw)

def create_template(
self, name, template_name, keep_data=False, description="", namespace=DEFAULT_NAMESPACE,
*, raw=False
):
path = self.PATH_fmt.format(uid=f"/{name}", ns=namespace)
json = dict(description=description, name=template_name, withData=keep_data)
params = dict(action="createTemplate")
return self._create(path, params=params, json=json, raw=raw)
39 changes: 39 additions & 0 deletions apiclient/harvester_api/models/templates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from .virtualmachines import VMSpec


class TemplateSpec(VMSpec):
def to_dict(self, name, namespace, hostname=""):
vd = super().to_dict(name, namespace, "")
metadata = vd.pop('metadata')
spec = vd.pop('spec')

# we can't modify name/namespace/description in template
metadata.pop('namespace'), metadata.pop('name')
metadata['annotations'].pop('field.cattle.io/description')
# hostname are not injected in the time
spec['template']['spec'].pop('hostname')

return {
"metadata": {
"generateName": f"{name}-",
"labels": {
"template.harvesterhci.io/templateID": name
},
"namespace": namespace
},
"spec": {
"templateId": f"{namespace}/{name}",
"vm": dict(metadata=metadata, spec=spec)
}
}

@classmethod
def from_dict(cls, data):
if "VirtualMachineTemplateVersion" != data.get('kind'):
raise ValueError("Only support data comes from 'VirtualMachineTemplateVersion'")

vd = data['spec']['vm']

vd['type'] = "kubevirt.io.virtualmachine"
vd['spec']['template']['spec']['hostname'] = ""
return super().from_dict(vd)
14 changes: 10 additions & 4 deletions apiclient/harvester_api/models/virtualmachines.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from copy import deepcopy
from json import dumps
from json import dumps, loads

import yaml

Expand Down Expand Up @@ -329,6 +329,7 @@ def to_dict(self, name, namespace, hostname=""):
if self._data:
self._data['metadata'].update(data['metadata'])
self._data['spec'].update(data['spec'])
self._data['metadata'].pop('resourceVersion') # remove for create new ones
return deepcopy(self._data)

return deepcopy(data)
Expand All @@ -342,11 +343,12 @@ def from_dict(cls, data):
spec, metadata = data.get('spec', {}), data.get('metadata', {})
vm_spec = spec['template']['spec']

run_strategy = spec['runStrategy']
os_type = metadata.get('labels', {}).get("harvesterhci.io/os", "")
desc = metadata['annotations'].get("field.cattle.io/description", "")
reserved_mem = metadata['annotations'].get("harvesterhci.io/reservedMemory", "")
run_strategy = spec['runStrategy']
# ???: volume template claims not load
vol_claims = {v['metadata']['name']: VolumeSpec.from_dict(v) for v in loads(
metadata['annotations'].get("harvesterhci.io/volumeClaimTemplates", "[]"))}

hostname = vm_spec['hostname']
eviction_strategy = vm_spec['evictionStrategy']
Expand All @@ -369,8 +371,12 @@ def from_dict(cls, data):

obj._features = features
obj._firmwares = firmware
obj._cloudinit_vol = dict(disk=devices['disks'][-1], volume=volumes[-1])
obj.networks = [dict(iface=i, network=n) for i, n in zip(devices['interfaces'], networks)]
obj.volumes = [dict(disk=d, volume=v) for d, v in zip(devices['disks'][:-1], volumes[:-1])]
obj._cloudinit_vol = dict(disk=devices['disks'][-1], volume=volumes[-1])
for v in obj.volumes:
if "persistentVolumeClaim" in v['volume']:
v['claim'] = vol_claims[v['volume']['persistentVolumeClaim']['claimName']]

obj._data = data
return obj
8 changes: 3 additions & 5 deletions harvester_e2e_tests/apis/test_vm_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,9 @@ def test_get(self, api_client, unique_name):
assert unique_name == data['metadata']['name']

def test_update(self, api_client, unique_name):
config = {
"cpu": 1,
"memory": "2Gi",
}
code, data = api_client.templates.update(unique_name, **config)
spec = api_client.templates.Spec(1, 2)

code, data = api_client.templates.create_version(unique_name, spec)

assert 201 == code, (code, data)
assert data['metadata']['name'].startswith(unique_name), (code, data)
Expand Down
2 changes: 1 addition & 1 deletion harvester_e2e_tests/integrations/test_3_vm_functions.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from time import sleep
from datetime import datetime, timedelta
from contextlib import contextmanager

import json
import re

import pytest
import yaml
from paramiko.ssh_exception import ChannelException
Expand Down
Loading