import logging import uuid import os import json import sys import gitlab import yaml from django.db import models from django.conf import settings from django.contrib.auth import get_user_model from django.template.loader import render_to_string from uncloud_pay.models import Order, BillRecord # Initialize logger. logger = logging.getLogger(__name__) class VMInstance(models.Model): owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, editable=True) vm_name = models.CharField(max_length=253, editable=False, unique=True) homeserver_domain = models.CharField(max_length=253, unique=True, blank=True) webclient_domain = models.CharField(max_length=253, unique=True, blank=True) config = models.JSONField(null=False, blank=False) order = models.OneToOneField(Order, on_delete=models.CASCADE, related_name='instance_id') creation_date = models.DateTimeField(auto_now_add=True) termination_date = models.DateTimeField(blank=True, null=True) def save(self, *args, **kwargs): # Save it as new yaml file and push it to github repo if 'test' in sys.argv: return super().save(*args, **kwargs) result = yaml.dump(self.config) gl = gitlab.Gitlab(settings.GITLAB_SERVER, oauth_token=settings.GITLAB_OAUTH_TOKEN) project = gl.projects.get(settings.GITLAB_PROJECT_ID) project.files.create({'file_path': settings.GITLAB_YAML_DIR + f'matrix-{self.vm_name}.yaml', 'branch': 'master', 'content': result, 'author_email': settings.GITLAB_AUTHOR_EMAIL, 'author_name': settings.GITLAB_AUTHOR_NAME, 'commit_message': f'Add New Deployment for matrix-{self.vm_name}'}) super().save(*args, **kwargs) def delete(self, *args, **kwargs): # Delete the deployment yaml file first then # Then delete it if 'test' in sys.argv: return super().delete(*args, **kwargs) gl = gitlab.Gitlab(settings.GITLAB_SERVER, oauth_token=settings.GITLAB_OAUTH_TOKEN) project = gl.projects.get(settings.GITLAB_PROJECT_ID) f_path = settings.GITLAB_YAML_DIR + f'matrix-{self.vm_name}.yaml' file = project.files.get(file_path=f_path, ref='master') if file: project.files.delete(file_path=f_path, commit_message=f'Delete matrix-{self.vm_name}', branch='master', author_email=settings.GITLAB_AUTHOR_EMAIL, author_name=settings.GITLAB_AUTHOR_NAME) super().delete(*args, **kwargs) def __str__(self): return f"{self.id}-{self.order}" @classmethod def delete_for_bill(cls, bill): bill_records = BillRecord.objects.filter(bill=bill) for record in bill_records: instances = VMInstance.objects.filter(order=record.order) for instance in instances: instance.delete() return True @classmethod def create_instance(cls, order): machine = cls.objects.filter(order=order).first() if not machine: order_config = json.loads(order.config) isOpenRegistration = order_config.get('is_open_registration', False) instance_config = {'cpuCores': order_config['cores'], 'ram': order_config['memory'], 'storage': order_config['storage'], 'matrixDomain': order_config['matrix_domain'], 'homeserverDomain': order_config['homeserver_domain'], 'webClientDomain': order_config['webclient_domain'], 'isOpenRegistration': isOpenRegistration} cls.objects.create(owner=order.owner, order=order, vm_name=order_config['homeserver_domain'], homeserver_domain=order_config['homeserver_domain'],webclient_domain=order_config['webclient_domain'], config=instance_config)