import logging import uuid import os import sys import gitlab from jinja2 import Environment, FileSystemLoader 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 # Initialize logger. logger = logging.getLogger(__name__) class VMInstance(models.Model): owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, editable=True) vm_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=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): # Read the deployment yaml file and render the template # Then save it as new yaml file and push it to github repo if 'test' in sys.argv: return super().save(*args, **kwargs) template_dir = os.path.join(os.path.dirname(__file__), 'yaml') env = Environment(loader = FileSystemLoader(template_dir),autoescape = True) tmpl = env.get_template('deployment.yaml.tmpl') result = tmpl.render( name=self.vm_id ) 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'{self.vm_id}.yaml', 'branch': 'master', 'content': result, 'author_email': settings.GITLAB_AUTHOR_EMAIL, 'author_name': settings.GITLAB_AUTHOR_NAME, 'commit_message': f'Add New Deployment for {self.vm_id}'}) 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'{self.vm_id}.yaml' file = project.files.get(file_path=f_path, ref='master') if file: project.files.delete(file_path=f_path, commit_message=f'Delete {self.vm_id}', 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}" def delete_for_bill(self, bill): #TODO delete related instances return True