dashboard/dash/models.py

95 lines
3.0 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 django.db import models
from django.contrib.auth.models import User
from django.utils.http import urlencode
from django.db.utils import IntegrityError
from django.urls import reverse
class InstanceConfiguration(models.Model):
ID = models.AutoField(primary_key=True)
name = models.CharField(
"Name of this configuration",
unique=True,
max_length=32,
)
rent = models.FloatField("Monthly rent of instance in Euros", null=False)
ram = models.FloatField(
"The amount of RAM an instance will have",
null=False,
)
cpu = models.IntegerField(
"The amount of CPU an instance will have",
null=False,
)
storage = models.FloatField(
"The amount of storage an instance will have",
null=False,
)
created_at = models.DateTimeField(auto_now_add=True, blank=True)
@classmethod
def create_default_configs(cls: "InstanceConfiguration"):
configs = [
cls(name="s1-2", rent=10, ram=2, cpu=1, storage=10),
cls(name="s1-4", rent=20, ram=4, cpu=1, storage=20),
cls(name="s1-8", rent=40, ram=8, cpu=2, storage=40),
]
for config in configs:
print(f"[*] Saving configuration {config.name}")
try:
config.save()
except IntegrityError as db_error:
print(f"[!] Configuration {config.name} exists")
continue
except Exception as e:
print(f"[ERROR] {e}")
raise e
def __str__(self):
return f"{self.name}"
class Meta:
constraints = [
models.UniqueConstraint(
fields=["ram", "cpu", "storage"], name="no_repeat_config"
)
]
class Instance(models.Model):
"""
Hostea instances
"""
owned_by = models.OneToOneField(User, on_delete=models.CASCADE)
ID = models.AutoField(primary_key=True)
name = models.CharField(
"Name of this Instance. Also Serves as subdomain",
unique=True,
max_length=200,
)
configuration_id = models.ForeignKey(
InstanceConfiguration, on_delete=models.PROTECT
)
created_at = models.DateTimeField(auto_now_add=True, blank=True)
def __str__(self):
return f"{self.owned_by}'s instance '{self.name}'"