diff --git a/manager/models.py b/manager/models.py index 2f883f2..932041d 100644 --- a/manager/models.py +++ b/manager/models.py @@ -19,6 +19,7 @@ from lib.db import ( ) from lib.proxmox import Proxmox from mikrotik.models import DNSStatic, IPAddress, IPDHCPLease +from proxmox.models import Lxc class MinValueValidatorExtended(MinValueValidator): @@ -87,6 +88,11 @@ class CloneContainer(CloneAbstract): super().__init__(*args, **kwargs) self._old_active = self.is_active + def get_clone_machine_status(self): + self.vm.sync_from_proxmox() + return self.vm.status + + def execute(self, task_uuid_override=None, *args, **kwargs): from proxmox.models import Lxc from tasklogger.models import TaskFactory @@ -99,6 +105,12 @@ class CloneContainer(CloneAbstract): try: data = self.proxmox_data + old_status = None + if self.vm: + old_status = self.get_clone_machine_status() + if old_status == 'running': + task.add_entry(f"Stopping container '{self.vm.name}'") + self.vm.stop() pm = Proxmox() route = data.pop('route') vmdata = data.pop('vm') @@ -128,6 +140,7 @@ class CloneContainer(CloneAbstract): } task.add_entry(f"Cloning container {self.vm.vmid}") + success = False lxc = None lease = None @@ -141,9 +154,13 @@ class CloneContainer(CloneAbstract): def _lxc_post(): return pm.lxc_post(route, **vmparams) + def _restart_cloned(): + return self.vm.start() # Wrap the proxmox function - this handles UPID monitoring synchronously task.wrap_proxmox_function(_lxc_post) + if old_status == 'running': + task.wrap_proxmox_function(_restart_cloned) task.add_entry("Container creation completed") success = True diff --git a/proxmox/models.py b/proxmox/models.py index 9deccd1..3e657af 100644 --- a/proxmox/models.py +++ b/proxmox/models.py @@ -58,9 +58,10 @@ class ProxmoxAbstractModel(BaseModel, TaskAwareModelMixin): def int_fields(self): return [] - def from_proxmox(self, **kwargs): + def from_proxmox(self, write_to_db=True, **kwargs): """Sets the values in DB Extracts csv Values into self, if given""" + logging.debug(f"Got {kwargs} from proxmox") kwkeys = list(kwargs.keys()) params = {} @@ -92,7 +93,10 @@ class ProxmoxAbstractModel(BaseModel, TaskAwareModelMixin): v = no_int_re.sub('', _v) or 0 params[k] = v logging.debug(f"No CSValues for {self}") - return self.write(**params) + if write_to_db: + return self.write(**params) + else: + return params class Lxc(ProxmoxAbstractModel): @@ -205,8 +209,9 @@ class Lxc(ProxmoxAbstractModel): if not data: logging.warning(f'Could not find {self.vmid} in proxmox - deleting from local database!') return self.delete() - self.from_proxmox(**data) - super().save() + statusdata = pm.lxc_get(f'{self.vmid}/status/current') + data |= statusdata + self.from_proxmox(write_to_db=True, **data) except Exception as e: logging.error(f"Could not get config for {self.vmid} - {e}") return self