Rolled out new request mechanism, vm migration view added

This commit is contained in:
ahmadbilalkhalid 2019-08-11 22:01:27 +05:00
commit 080933b140
4 changed files with 137 additions and 37 deletions

View file

@ -1,10 +1,15 @@
import json
from common_fields import Field, VmUUIDField, SpecsField
from ucloud_common.host import HostPool, HostStatus
from ucloud_common.vm import VmPool, VMStatus
from helper import check_otp
from etcd3_wrapper import Etcd3Wrapper
from os.path import join
client = Etcd3Wrapper()
host_pool = HostPool(client, "/v1/host")
vm_pool = VmPool(client, "/v1/vm")
class BaseSchema(object):
@ -39,7 +44,7 @@ class BaseSchema(object):
return True
def get_errors(self):
return {"Message": self.__errors}
return {"message": self.__errors}
def add_field_errors(self, field: Field):
self.__errors += field.get_errors()
@ -125,19 +130,55 @@ class VmActionSchema(OTPSchema):
self.action.validation = self.action_validation
fields = [self.uuid, self.action]
super().__init__(data=data, fields=fields)
_fields = [self.uuid, self.action]
super().__init__(data=data, fields=_fields)
def action_validation(self):
allowed_actions = ["start", "shutdown", "suspend", "resume", "delete"]
allowed_actions = ["start", "stop", "delete"]
if self.action.value not in allowed_actions:
self.add_error(f"Invalid Action. Allowed Actions are {allowed_actions}")
def validation(self):
vm = client.get(f"/v1/vm/{self.uuid.value}", value_in_json=True)
if vm.value["owner"] != self.name:
vm = vm_pool.get(self.uuid.value)
if vm.value["owner"] != self.name.value:
self.add_error("Invalid User")
if self.action.value == "start" and vm.status == VMStatus.running and vm.hostname != "":
self.add_error("VM Already Running")
if self.action.value == "stop" and vm.status == VMStatus.stopped:
self.add_error("VM Already Stopped")
class VmMigrationSchema(OTPSchema):
def __init__(self, data):
self.uuid = VmUUIDField(data)
self.destination = Field("destination", str, data.get("destination", KeyError))
self.destination.validation = self.destination_validation
fields = [self.destination]
super().__init__(data=data, fields=fields)
def destination_validation(self):
host_key = self.destination.value
host = host_pool.get(host_key)
if not host:
self.add_error(f"No Such Host ({self.destination.value}) exists")
elif host.status != HostStatus.alive:
self.add_error("Destination Host is dead")
def validation(self):
vm = vm_pool.get(self.uuid.value)
if vm.owner != self.name.value:
self.add_error("Invalid User")
if vm.status != VMStatus.running:
self.add_error("Can't migrate non-running VM")
if vm.hostname == join("/v1/host", self.destination.value):
self.add_error("Destination host couldn't be same as Source Host")
class CreateHostSchema(OTPSchema):
def __init__(self, data):