dashboard/dash/utils.py

93 lines
2.9 KiB
Python
Raw Normal View History

2022-06-27 15:13:02 +00:00
# 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
2022-06-30 09:07:49 +00:00
from django.conf import settings
2022-06-27 15:13:02 +00:00
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"
2022-06-27 15:13:02 +00:00
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
2022-06-27 19:54:43 +00:00
def __str__(self):
return self.error
2022-06-27 15:13:02 +00:00
def create_instance(vm_name: str, configuration_name: str, user: User) -> Instance:
"""
Create instance view
"""
if len(vm_name) > 20:
raise VmException(code=VmErrors.NAME_TOO_LONG)
if not str.isalnum(vm_name):
raise VmException(code=VmErrors.ILLEGAL_NAME)
2022-06-27 15:13:02 +00:00
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
2022-06-30 09:07:49 +00:00
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://gitea.gna.org/Hostea/dashboard"
source_code = {"text": "Source Code", "link": link}
2022-06-30 09:07:49 +00:00
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"],
}