dashboard/dash/utils.py

105 lines
3.1 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 django.conf import settings
from .models import Instance, InstanceConfiguration
@unique
class VmErrors(Enum):
NAME_EXISTS = "Instance name exists, please try again with a different name"
ILLEGAL_NAME = "Only alphanumeric characters are allowed in instance name"
NAME_TOO_LONG = "Instance name must be less than 20 characters"
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 __str__(self):
return self.error
def sanitize_vm_name(vm_name: str) -> str:
"""
Sanity checks and normalization of the vm name
"""
vm_name = vm_name.lower()
if len(vm_name) > 20:
raise VmException(code=VmErrors.NAME_TOO_LONG)
if not str.isalnum(vm_name):
raise VmException(code=VmErrors.ILLEGAL_NAME)
if Instance.objects.filter(name=vm_name).exists():
raise VmException(code=VmErrors.NAME_EXISTS)
return vm_name
def create_instance(vm_name: str, configuration_name: str, user: User) -> Instance:
"""
Create instance view
"""
vm_name = sanitize_vm_name(vm_name)
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
source_code = None
def footer_ctx():
global source_code
if source_code is None:
if "SOURCE_CODE" in settings.HOSTEA:
source_code = {
"text": "Source Code",
"link": settings.HOSTEA["SOURCE_CODE"],
}
else:
link = "https://forgejo.gna.org/Hostea/dashboard"
source_code = {"text": "Source Code", "link": link}
try:
r = Repo(".")
commit = r.head.commit.hexsha
source_code["text"] = f"v-{commit.hexsha[0:8]}"
except:
pass
return {
"source_code": source_code,
"admin_email": settings.HOSTEA["INSTANCE_MAINTAINER_CONTACT"],
}