dashboard/dash/utils.py

55 lines
1.8 KiB
Python

# Copyright © 2022 Aravinth Manivannan <realaravinth@batsense.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from enum import Enum, unique
from django.contrib.auth.models import User
from .models import Instance, InstanceConfiguration
@unique
class VmErrors(Enum):
NAME_EXISTS = "Instance name exists, please try again with a different name"
NO_CONFIG = "Configuration doesn't exist, please try again."
def __str__(self) -> str:
return self.name
class VmException(Exception):
error: str
code: VmErrors
def __init__(self, code: VmErrors):
self.error = str(code)
self.code = code
def create_instance(vm_name: str, configuration_name: str, user: User) -> Instance:
"""
Create instance view
"""
if Instance.objects.filter(name=vm_name).exists():
raise VmException(code=VmErrors.NAME_EXISTS)
if not InstanceConfiguration.objects.filter(name=configuration_name).exists():
raise VmException(code=VmErrors.NO_CONFIG)
configuration = InstanceConfiguration.objects.get(name=configuration_name)
instance = Instance(name=vm_name, configuration_id=configuration, owned_by=user)
instance.save()
return instance