Bladeren bron

mergekonflikte beseitigt

andre 4 jaren geleden
bovenliggende
commit
cb2785a735

+ 3 - 0
app/Config/events.php

@@ -16,6 +16,9 @@ return [
     \ModulesGarden\ProxmoxAddon\App\Events\Cloud\VmCreatedEvent::class     => [
         \ModulesGarden\ProxmoxAddon\App\Listeners\Cloud\VmCreatedListener::class
     ],
+    \ModulesGarden\ProxmoxAddon\App\Events\Cloud\VmClonedEvent::class     => [
+        \ModulesGarden\ProxmoxAddon\App\Listeners\Cloud\VmClonedListener::class
+    ],
     \ModulesGarden\ProxmoxAddon\App\Events\Cloud\VmReinstalledEvent::class => [
         \ModulesGarden\ProxmoxAddon\App\Listeners\Cloud\VmReinstalledListener::class
     ],

+ 183 - 0
app/Jobs/Cloud/CloneQemuJobNoStart.php

@@ -0,0 +1,183 @@
+<?php
+
+namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud;
+
+use Illuminate\Database\Capsule\Manager as DB;
+use MGProvision\Proxmox\v2\Api;
+use MGProvision\Proxmox\v2\models\Kvm;
+use MGProvision\Proxmox\v2\models\Lxc;
+use MGProvision\Proxmox\v2\ProxmoxApiException;
+use ModulesGarden\ProxmoxAddon\App\Events\Cloud\QemuUpdateEvent;
+use ModulesGarden\ProxmoxAddon\App\Events\Cloud\VmClonedEvent;
+use ModulesGarden\ProxmoxAddon\App\Jobs\BaseJob;
+use ModulesGarden\ProxmoxAddon\App\Models\TaskHistory;
+use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
+use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AdditionalDiskService;
+use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AgentService;
+use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ContainerService;
+use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
+use ModulesGarden\ProxmoxAddon\App\Services\Cloud\UserService;
+use ModulesGarden\ProxmoxAddon\App\Services\EmailService;
+use function ModulesGarden\ProxmoxAddon\Core\Helper\fire;
+use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;
+
+class CloneQemuJobNoStart extends BaseJob
+{
+
+    use ProductService;
+    use UserService;
+    /**
+     * @var \ModulesGarden\ProxmoxAddon\App\Services\Cloud\ContainerService
+     */
+    protected $containerService;
+
+    /**
+     * @var Kvm|Lxc
+     */
+    protected $vm;
+    /**
+     * @var AdditionalDiskService
+     */
+    protected $additionalDiskService;
+    protected function initServices()
+    {
+        $this->emailService     = new EmailService();
+        $this->containerService = new ContainerService();
+        $this->agentService = new AgentService();
+        $this->additionalDiskService = new AdditionalDiskService();
+
+    }
+    public function handle()
+    {
+        $this->initParams();
+        $this->initServices();
+        //create task validation
+        if ($this->isDone())
+        {
+            $this->initVm();
+            if(!sl('Vm')->getVm()->isRunning()){
+                $this->deleteNetwork();
+            }
+            if($this->getModelData()['additionalDiskSize1'] && !$this->additionalDiskService->hasDisk()){
+                $this->additionalDiskService->create($this->getModelData());
+            }
+            fire(new QemuUpdateEvent($this->getVmModel(), $this->getModelData()));
+            try{
+
+                if($this->agentService->isEnabled()){
+                    if(!sl('Vm')->getVm()->isRunning()){
+                        $this->log->info(sprintf("VM %s - Start", sl('Vm')->getVm()->getVmid()));
+                        sl('Vm')->getVm()->start();
+                        $this->sleep(5);
+                        return false;
+                    }
+                    sl('Vm')->getVm()->agent()->ping();
+                    $this->agentService ->passwordUpdate();
+                    $this->agentService ->configureNetwork();
+                }
+            }catch (ProxmoxApiException $ex){
+                if(preg_match("/not running/", $ex->getMessage())){
+                    $this->log->info($ex->getMessage());
+                }else{
+                    $this->log->error($ex->getMessage());
+                }
+                //sleep
+                $this->sleep(5);
+                return false;
+            }
+            fire(new VmClonedEvent($this->getVmModel()));
+            return true;
+        }
+        elseif ($this->isTaskRunning())
+        {
+            //sleep
+            $this->sleep(5);
+            return false;
+        }
+        try
+        {
+            Api::beginTransaction();
+            DB::beginTransaction();
+            $osTemplate = $this->getModelData()['osTemplate'];
+            //Support for configurable options i.e vmname|OS Name
+            if (preg_match('/\//', $osTemplate))
+            {
+                list($templateNode, $templateVmid) = explode("/", $osTemplate);
+            }
+            //vmid
+            $vmid = $this->nextVmid();
+            $this->getVmModel();
+            $this->vmModel->vmid = $vmid;
+            $this->vmModel->save();
+            //init container
+            $container = [
+                "newid"  => $vmid,
+                "full"   => $this->configuration()->getCloneMode(),
+                "target" => $this->vmModel->node
+            ];
+            //description
+            $container['description'] = $this->getModelData()['description'];
+            //hostname
+            $container['name'] = $this->getModelData()['name'];
+            //Storage
+            if (!$this->configuration()->isCloneOnTheSameStorage() && $this->configuration()->getDiskStorage() && $this->configuration()->getCloneMode() == "1")
+            {
+                $container['storage'] = $this->configuration()->getDiskStorage();
+            }
+            //pool
+            if ($this->configuration()->getPool())
+            {
+                $container['pool'] = $this->configuration()->getPool();
+            }
+            //bwlimit
+            if($this->configuration()->getBwLimit()){
+                $container['bwlimit'] = $this->configuration()->getBwLimit();
+            }
+            //Create
+            $template = new Kvm($templateNode, $templateVmid);
+            $template->setApi($this->api());
+            $taskId = $template->cloneVm($container);
+            DB::commit();
+        }
+        catch (\Exception $ex)
+        {
+            DB::rollBack();
+            Api::commit();
+            $this->failed($ex->getMessage());
+            throw $ex;
+        }
+        //task history
+        $task = new TaskHistory();
+        $task->fill([
+            'hosting_id' => $this->getWhmcsParamByKey("serviceid"),
+            'upid'       => $taskId,
+            'name'       => sprintf("VM %s - %s", $vmid, "Clone"),
+            'vmid'       => $template->getVmid(),
+            'node'       => $template->getNode(),
+            'status'     => 0
+        ])->save();
+        //save task id
+        $this->putModelDataAndSave(["taskId" => $taskId, "node" => $template->getNode(), "templateNode" => $templateNode]);
+        //sleep
+        $this->sleep();
+        return false;
+    }
+
+    private function  deleteNetwork(){
+
+        $deleteNetwork = [];
+        foreach (sl('Vm')->getVm()->getNetworkDevices() as $networkDevice){
+            if(VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
+                           ->ofNet($networkDevice->getId())
+                          ->ofVmId(sl('Vm')->getVmModel()->id)
+                          ->count()){
+                continue;
+            }
+            $deleteNetwork[]=$networkDevice->getId();
+        }
+        if(!empty($deleteNetwork)){
+            sl('Vm')->getVm()->deleteConfig(implode(",",$deleteNetwork));
+        }
+    }
+
+}

+ 49 - 24
app/Jobs/Cloud/SnapshotVmJob.php

@@ -1,6 +1,4 @@
 <?php
-
-
 namespace ModulesGarden\ProxmoxAddon\App\Jobs\Cloud;
 
 
@@ -13,8 +11,8 @@ use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
 use ModulesGarden\ProxmoxAddon\App\Enum\Cloud\ConfigurableOption;
 use function ModulesGarden\ProxmoxAddon\Core\Helper\sl;
 
-class SnapshotVmJob extends BaseJob
-{
+
+class SnapshotVmJob extends BaseJob {
 
     use ProductService;
 
@@ -23,40 +21,44 @@ class SnapshotVmJob extends BaseJob
      */
     private  $snapshotJob;
 
-    public function handle($text = null)
-    {
+    public function handle($text = null)  {
+        openlog("ProxmoxSnapshot", LOG_PID, LOG_SYSLOG);
+
         $this->initParams();
         $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
         $this->initVm();
-        if ($this->isDone())
-        {
+        if ($this->isDone()) {
             return true;
-        }
-        elseif ($this->isTaskRunning())
-        {
+        } elseif ($this->isTaskRunning()) {
             //sleep
             $this->sleep(5);
             return false;
         }
-        $this->clean();
         $snapshot = new Snapshot();
         $snapshot->setApi($this->api());
         $snapshot->setPath(sl('Vm')->getVm()->getPath() . "/snapshot");
         $snapshot->setAttributes([
-            "name"        => $this->getSnapshotJob()->name."_".$this->model->id,
+            // Changed by Roland at 2021-08-28 because duplicate snappshot names which causes the error: TASK ERROR: snapshot name 'Secure_280' already used
+            // Added ' "_" . date("m") . "_" . date("d") . "_" . date("H"),' to make the snapshot-name more unique
+            "name"        => $this->getSnapshotJob()->name . "_" . $this->model->id . "_" . date("m") . "_" . date("d") . "_" . date("H"),
             "description" => $this->snapshotJob->description,
         ]);
-        if (!is_null($this->snapshotJob->vmstate ) && sl('Vm')->getVm() instanceof  Kvm)
-        {
+        
+        syslog(LOG_NOTICE,"Creating Snapshot for " . $this->getSnapshotJob()->name . "_" . $this->model->id . date("d") . "_" . date("H"));
+        if (!is_null($this->snapshotJob->vmstate ) && sl('Vm')->getVm() instanceof  Kvm) {
             $snapshot->setVmstate($this->snapshotJob->vmstate );
         }
         $taskId =  $snapshot->create();
         //save task id
         $this->putModelDataAndSave(["taskId" => $taskId, "node" => sl('Vm')->getVm()->getNode()]);
+        
         //sleep
         $this->sleep(5);
+        $this->clean();
+        $this->sleep(25);
         return false;
     }
+    
 
     /**
      * @return SnapshotJob
@@ -66,28 +68,51 @@ class SnapshotVmJob extends BaseJob
     }
 
     private function clean(){
+        syslog(LOG_NOTICE,"Snapshot Clean for " . $this->model->id );
         $limit = $this->getWhmcsConfigOption(ConfigurableOption::SNAPSHOTS, $this->configuration()->getSnapshotMaxFiles());
-        if($limit=="-1"){
+        if($limit=="-1") {
             return;
         }
-        if(!$limit || !is_numeric($limit)){
+        syslog(LOG_NOTICE,"   Checking Snapshot Limit (" . $limit . ") for " . $this->model->id );
+        if(!$limit || !is_numeric($limit)) {
             throw new \InvalidArgumentException("Snapshot limit cannot be empty");
         }
         $snapshotRepository = new SnapshotRepository();
         $snapshotRepository->setApi($this->api());
         $snapshotRepository->findByVm(sl('Vm')->getVm());
         $snapshotRepository->ignoreCurrent(true);
-        if($snapshotRepository->count() < $limit){
+        if($snapshotRepository->count() < $limit) {
             return;
         }
         $toDelete = (int) $snapshotRepository->count() - $limit;
-        foreach ($snapshotRepository->sortBySnaptime()->fetch() as $entity)
-        {
-            if($toDelete <=0){
-                break;
+        syslog(LOG_NOTICE,"   Snapshots: Existing: " . $snapshotRepository->count() . "   Limit: " . $limit );
+        syslog(LOG_NOTICE,"   Number of Snapshots to delete: " . $toDelete );
+        foreach ($snapshotRepository->sortBySnaptime()->fetch() as $entity) {
+            syslog(LOG_NOTICE,"   Checking Snapshot: " . $entity->getName() . " (" . $entity->getPath() . ")" );
+            if($toDelete <=0) {
+            	    break;
+    	    }
+            $errorCount = 0;
+            $errorMessage = "NOT EMPTY";
+            while(!empty($errorMessage) && $errorCount < 18) {
+                syslog(LOG_NOTICE,"   ->Delete Snapshot: " . $entity->getName() );
+                while(!empty($errorMessage) && $errorCount < 18) {
+                try {
+                    $result = $entity->delete();
+                    //syslog(LOG_NOTICE,"   ->RESULT " . print_r($result,true) );
+
+                    $errorMessage = "";
+                    syslog(LOG_NOTICE,"   ->SUCCESS " . $result );
+                    sleep(55);
+                } catch(\Exception $ex) {
+                    $errorMessage = $ex->getMessage();
+                    syslog(LOG_NOTICE,"   ->ERROR " . $errorCount . ": " . $errorMessage );
+                    $errorCount ++;
+                    sleep(55);
+                }
             }
-            $entity->delete();
             $toDelete --;
         }
     }
-}
+    syslog(LOG_NOTICE,"Snapshot Clean DONE" );
+}

+ 24 - 50
app/Jobs/Vps/BaseJob.php

@@ -63,8 +63,7 @@ class BaseJob extends Job
      */
     protected $additionalMountPointService;
 
-    protected function initServices()
-    {
+    protected function initServices()  {
         $this->emailService     = new EmailService();
         $this->containerService = new ContainerService();
         $this->agentService = new AgentService();
@@ -73,8 +72,7 @@ class BaseJob extends Job
 
     }
 
-    public function initParams()
-    {
+    public function initParams()  {
         if (!$this->model->rel_id)
         {
             new \InvalidArgumentException(sprintf("Job model: #%s rel_id cannot be empty", $this->model->id));
@@ -90,15 +88,13 @@ class BaseJob extends Job
         return $this;
     }
 
-    protected function sleep($seconds = 60)
-    {
+    protected function sleep($seconds = 60)  {
         $this->model->setWaiting();
         $this->model->setRetryAfter(date("Y-m-d H:i:s", strtotime("+{$seconds} seconds")));
         $this->model->increaseRetryCount();
     }
 
-    protected function vmidExistInWhmcs($vmid)
-    {
+    protected function vmidExistInWhmcs($vmid)  {
         //vps
         $cfv   = 'tblcustomfieldsvalues';
         $cfn   = 'tblcustomfields';
@@ -109,8 +105,7 @@ class BaseJob extends Job
             ->where("{$cfn}.fieldname", "like", "vmid%")
             ->where("{$cfv}.value", $vmid)
             ->whereIn("{$h}.domainstatus", ['Active', "Suspended"]);
-        if ($query->count())
-        {
+        if ($query->count())  {
             return true;
         }
         //cloud
@@ -125,41 +120,31 @@ class BaseJob extends Job
         return false;
     }
 
-    protected function findFreeVmid($vmid)
-    {
-        for ($i = $vmid; $i <= 1000000; $i++)
-        {
-            if ($this->vmidExistInWhmcs($i))
-            {
+    protected function findFreeVmid($vmid)  {
+        for ($i = $vmid; $i <= 1000000; $i++) {
+            if ($this->vmidExistInWhmcs($i)) {
                 continue;
             }
-            try
-            {
+            try  {
                 $res = $this->api()->get("/cluster/nextid", ['vmid' => $i]);
-            }
-            catch (\Exception $ex)
-            {
+            } catch (\Exception $ex) {
                 continue;
             }
-            if ($res == $i)
-            {
+            if ($res == $i) {
                 return $i;
             }
         }
         throw new \Exception("Unable to obtain vmid");
     }
 
-    protected function isVmRange()
-    {
-        if (RangeVm::ofServerId($this->getWhmcsParamByKey("serverid"))->count())
-        {
+    protected function isVmRange(){
+        if (RangeVm::ofServerId($this->getWhmcsParamByKey("serverid"))->count()) {
             return true;
         }
         return Configuration::where("setting", "proxmoxVPSMinimumVMID")->count() > 0;
     }
 
-    protected function nextVmid()
-    {
+    protected function nextVmid() {
         $data = $this->api()->get("/cluster/nextid", []);
         $vmid = (int)$data ? (int)$data : 100;
         $vmid = $this->findFreeVmid($vmid);
@@ -172,9 +157,7 @@ class BaseJob extends Job
             if (!$rageVm->has() && !$rageVm->getMin())
             {
                 return $vmid;
-            }
-            else
-            {
+            } else  {
                 if (!$rageVm->getMax() && $rageVm->getMin())
                 {
                     $from = (int)$rageVm->getMin();
@@ -308,23 +291,18 @@ class BaseJob extends Job
         return $task->getExitstatus() && $task->getExitstatus() != "OK";
     }
 
-    protected function failed($error)
-    {
+    protected function failed($error) {
 
-        if ((int)$this->model->retry_count != 21)
-        {
+        if ((int)$this->model->retry_count != 21) {
             return;
         }
-        if (!preg_match("/Create/", $this->model->job) || preg_match("/Clone/", $this->model->job))
-        {
+        if (!preg_match("/Create/", $this->model->job) || preg_match("/Clone/", $this->model->job)) {
             return;
         }
         //create new entery on to do list
-        if ($this->configuration()->isToDoList())
-        {
+        if ($this->configuration()->isToDoList())  {
             $title = sprintf('Creation Failed - Service ID: %s', $this->getWhmcsParamByKey('serviceid'));
-            if (ToDoList::ofTitle($title)->pending()->count())
-            {
+            if (ToDoList::ofTitle($title)->pending()->count())  {
                 return;
             }
             $entity = new ToDoList();
@@ -372,21 +350,17 @@ class BaseJob extends Job
     /**
      * @return \ModulesGarden\ProxmoxAddon\App\Models\Job:
      */
-    protected function getParentModel()
-    {
-        if (is_null($this->model->parent_id))
-        {
+    protected function getParentModel() {
+        if (is_null($this->model->parent_id)) {
             throw new \InvalidArgumentException("The Parent Id is not valid");
         }
-        if ($this->parent)
-        {
+        if ($this->parent) {
             return $this->parent;
         }
         return $this->parent = \ModulesGarden\ProxmoxAddon\App\Models\Job::ofId($this->model->parent_id)->firstOrFail();
     }
 
-    protected function getParentModelData()
-    {
+    protected function getParentModelData() {
         return unserialize($this->getParentModel()->data);
     }
 

+ 57 - 24
app/Jobs/Vps/SnapshotVmJob.php

@@ -1,9 +1,6 @@
 <?php
-
-
 namespace ModulesGarden\ProxmoxAddon\App\Jobs\Vps;
 
-
 use MGProvision\Proxmox\v2\models\Kvm;
 use MGProvision\Proxmox\v2\models\Snapshot;
 use MGProvision\Proxmox\v2\repository\SnapshotRepository;
@@ -11,8 +8,7 @@ use ModulesGarden\ProxmoxAddon\App\Models\SnapshotJob;
 use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
 use ModulesGarden\ProxmoxAddon\App\Enum\Vps\ConfigurableOption;
 
-class SnapshotVmJob extends BaseJob
-{
+class SnapshotVmJob extends BaseJob {
 
     use ProductService;
 
@@ -21,40 +17,54 @@ class SnapshotVmJob extends BaseJob
      */
     private  $snapshotJob;
 
-    public function handle($text = null)
-    {
+    public function handle($text = null)  {
+        openlog("ProxmoxSnapshot", LOG_PID,LOG_SYSLOG);
         $this->initParams();
         $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
-        if ($this->isDone())
-        {
+        if ($this->isDone()) {
             return true;
-        }
-        elseif ($this->isTaskRunning())
-        {
+        } elseif ($this->isTaskRunning())  {
             //sleep
-            $this->sleep(5);
+            $this->sleep(25);
             return false;
         }
-        $this->clean();
+        
+        syslog(LOG_NOTICE,"Snapshot Create for " . $this->model->id );
         $snapshot = new Snapshot();
         $snapshot->setApi($this->api());
         $snapshot->setPath($this->vm()->getPath() . "/snapshot");
         $snapshot->setAttributes([
-            "name"        => $this->getSnapshotJob()->name."_".$this->model->id,
+    	    // Changed by Roland at 2021-08-28 because duplicate snappshot names which causes the error: TASK ERROR: snapshot name 'Secure_280' already used
+    	    // Added ' "_" . date("m") . "_" . date("d") . "_" . date("H") . "_" . date("i"),' to make the snapshot-name more unique
+            "name"        => $this->getSnapshotJob()->name . "_" . date("m") . "_" . date("d") . "_" . date("H") . "_" . date("i"),
             "description" => $this->snapshotJob->description,
         ]);
-        if (!is_null($this->snapshotJob->vmstate ) && $this->vm() instanceof  Kvm)
-        {
+        syslog(LOG_NOTICE,"   Creating Snapshot for " . $this->getSnapshotJob()->name . "_" . $this->model->id . "_" . date("m") . "_" . date("d") . "_" . date("H"));
+        if (!is_null($this->snapshotJob->vmstate ) && $this->vm() instanceof  Kvm) {
             $snapshot->setVmstate($this->snapshotJob->vmstate );
         }
-        $taskId =  $snapshot->create();
+        
+        try {
+    	    $taskId =  $snapshot->create();
+        } catch(\Exception $ex) {
+    	    $message = $ex->getMessage();
+    	    syslog(LOG_NOTICE,"!!Snapshot throw Exception: " . $message );
+	    if (strpos($message,"snapshot") === false && strpos($message,"already") === false && strpos($message,"used") === false ) {
+    	        throw $ex;
+    	    }
+        }
+        sleep(25);
+        $this->clean();
+	$this->sleep(5);
+	
         //save task id
         $this->putModelDataAndSave(["taskId" => $taskId, "node" => $this->vm()->getNode()]);
-        //sleep
-        $this->sleep(5);
+        
+        syslog(LOG_NOTICE,"Snapshot Processing DONE" );
         return false;
     }
 
+
     /**
      * @return SnapshotJob
      */
@@ -62,8 +72,10 @@ class SnapshotVmJob extends BaseJob
         return $this->snapshotJob = SnapshotJob::findOrFail($this->getModelData()['snapshotJobId']);
     }
 
-    private function clean(){
+    private function clean() {
+        syslog(LOG_NOTICE,"Snapshot Clean for " . $this->model->id );
         $limit = $this->getWhmcsConfigOption(ConfigurableOption::SNAPSHOTS, $this->configuration()->getSnapshotMaxFiles());
+        syslog(LOG_NOTICE,"   Checking Snapshot Limit (" . $limit . ") for " . $this->model->id );
         if($limit=="-1"){
             return;
         }
@@ -78,13 +90,34 @@ class SnapshotVmJob extends BaseJob
             return;
         }
         $toDelete = (int) $snapshotRepository->count() - $limit;
-        foreach ($snapshotRepository->sortBySnaptime()->fetch() as $entity)
-        {
+        syslog(LOG_NOTICE,"   Snapshots: Existing: " . $snapshotRepository->count() . "   Limit: " . $limit );
+        syslog(LOG_NOTICE,"   Number of Snapshots to delete: " . $toDelete );
+        
+        foreach ($snapshotRepository->sortBySnaptime()->fetch() as $entity) {
+    	    syslog(LOG_NOTICE,"   Checking Snapshot: " . $entity->getName() . " (" . $entity->getPath() . ")" );
             if($toDelete <=0){
                 break;
             }
-            $entity->delete();
+            $errorCount = 0;
+            $errorMessage = "NOT EMPTY";
+            while(!empty($errorMessage) && $errorCount < 18) { 
+        	syslog(LOG_NOTICE,"   ->Delete Snapshot: " . $entity->getName() );
+                try {
+	            $result = $entity->delete();
+	            //syslog(LOG_NOTICE,"   ->RESULT " . print_r($result,true) );
+
+	            $errorMessage = "";
+	            syslog(LOG_NOTICE,"   ->SUCCESS " . $result );
+	            sleep(45);
+        	} catch(\Exception $ex) {
+    		    $errorMessage = $ex->getMessage();
+    	    	    syslog(LOG_NOTICE,"   ->ERROR " . $errorCount . ": " . $errorMessage );
+    	    	    $errorCount ++;
+    	    	    sleep(45);
+		}
+            }
             $toDelete --;
         }
+        syslog(LOG_NOTICE,"Snapshot Clean DONE" );
     }
 }

+ 30 - 0
app/Listeners/Cloud/VmClonedListener.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace ModulesGarden\ProxmoxAddon\App\Listeners\Cloud;
+
+use ModulesGarden\ProxmoxAddon\App\Events\Cloud\VmClonedEvent;
+
+class VmClonedListener extends VmListener
+{
+
+    public function handle(VmClonedEvent $event)
+    {
+        $this->event    = $event;
+        $this->api();
+        $this->initVmAnVmModel();
+        //update user permission
+        $this->userUpdatePermission([$this->event->getVmModel()->vmid]);
+        //Update firewal Options
+        $this->firewallOptionService->update();
+        //IP Set
+        if ($this->configuration()->isIpsetIpFilter())
+        {
+            $this->ipSetFilterService->create();
+        }
+        //HA
+        if ($this->highAvailabilityClusterService->isConfigured() && !$this->highAvailabilityClusterService->exist())
+        {
+            $this->highAvailabilityClusterService->create();
+        }
+    }
+}

+ 2 - 4
app/Models/Job.php

@@ -23,10 +23,8 @@ class Job extends \ModulesGarden\ProxmoxAddon\Core\Queue\Models\Job
         return $query->where("job", $job . '@handle');
     }
 
-    public function scopeOfJobs($query, $jobs)
-    {
-        foreach ($jobs as &$job)
-        {
+    public function scopeOfJobs($query, $jobs)  {
+        foreach ($jobs as &$job) {
             $job .= '@handle';
         }
         return $query->whereIn("job", $jobs);

+ 2 - 4
app/Models/SnapshotJob.php

@@ -21,8 +21,7 @@ use ModulesGarden\ProxmoxAddon\Core\Models\ExtendedEloquentModel;
  * @property string $created_at
  * @method static $this ofHostingId($hostingId)
  */
-class SnapshotJob extends ExtendedEloquentModel
-{
+class SnapshotJob extends ExtendedEloquentModel {
 
     /** @var string */
     protected $table = 'SnapshotJob';
@@ -37,8 +36,7 @@ class SnapshotJob extends ExtendedEloquentModel
         'days' => 'array',
     ];
 
-    public function scopeOfHostingId($query, $hostingId)
-    {
+    public function scopeOfHostingId($query, $hostingId) {
         return $query->where("hosting_id", $hostingId);
     }
 

+ 4 - 1
app/Services/Cloud/ClientAreaSidebarService.php

@@ -154,6 +154,9 @@ class ClientAreaSidebarService
              * @var VmModel $vmModel
              */
             foreach (VmModel::ofHostingId( $this->getHostingId())->notVmid(0)->notTemplate()->get() as $vmModel){
+            	if($sidebar->getName()=='Virtual Datacenter'){
+		    continue;
+	        }
                 $childOrder++;
                 $newItem = [
                     'label'   => $vmModel->name,
@@ -167,4 +170,4 @@ class ClientAreaSidebarService
 
         }
     }
-}
+}

+ 1 - 2
app/Services/Vm.php

@@ -8,8 +8,7 @@ use MGProvision\Proxmox\v2\models\Kvm;
 use MGProvision\Proxmox\v2\models\Lxc;
 use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
 
-class Vm
-{
+class Vm {
     /**
      * @var Kvm|Lxc
      */

+ 0 - 1
core/CommandLine/Application.php

@@ -52,7 +52,6 @@ class Application extends \Symfony\Component\Console\Application
         foreach ($commands as $command)
         {
             $class = ModuleConstants::getRootNamespace() . '\App\\' . $this->dir . '\\' . $command;
-
             $this->add(new $class);
         }
     }

+ 1 - 2
core/CommandLine/CronManager.php

@@ -2,7 +2,6 @@
 
 namespace ModulesGarden\ProxmoxAddon\Core\CommandLine;
 
-class CronManager extends Application
-{
+class CronManager extends Application {
     protected $dir = 'Cron';
 }

+ 19 - 27
core/Queue/Manager.php

@@ -5,8 +5,7 @@ namespace ModulesGarden\ProxmoxAddon\Core\Queue;
 use ModulesGarden\ProxmoxAddon\Core\DependencyInjection\DependencyInjection;
 use ModulesGarden\ProxmoxAddon\Core\Queue\Services\Log;
 
-class Manager
-{
+class Manager {
     /**
      * @var Models\Job
      */
@@ -21,46 +20,41 @@ class Manager
      * Manager constructor.
      * @param Models\Job $job
      */
-    public function __construct(\ModulesGarden\ProxmoxAddon\Core\Queue\Models\Job $job)
-    {
+    public function __construct(\ModulesGarden\ProxmoxAddon\Core\Queue\Models\Job $job) {
         $this->job  = $job;
         $this->log  = new Log($this->job);
     }
 
     /**
-     *
+     *  snapshot name 'Snapshot_320_08_30_02' already used
      */
-    public function fire()
-    {
-        try
-        {
+    public function fire(){
+        try {
             $this->job->setRunning();
 
             $ret    = $this->resolveAndFire($this->job->job, $this->job->data);
-            if($ret !== false)
-            {
+            if($ret !== false) {
                 $this->job->setFinished();
-            }
-        }
-        catch(\Exception $ex)
-        {
-            //Set error in job
+            } 
+        } catch(\Exception $ex) {
+    	    //Set error in job
             $this->job->setError();
-            $this->job->setRetryAfter(date('Y-m-d H:i:s', strtotime('+ 60 seconds')));
-            $this->job->increaseRetryCount();
+	    $this->job->setRetryAfter(date('Y-m-d H:i:s', strtotime('+ 60 seconds')));
+    	    $this->job->increaseRetryCount();
 
-            //add log message
-            $this->log->error($ex->getMessage(), debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
-        }
+    	    //add log message
+    	    $this->log->error($ex->getMessage(), debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
+    	}
     }
 
+
+
     /**
      * @param $job
      * @param $data
      * @return mixed
      */
-    protected function resolveAndFire($job, $data)
-    {
+    protected function resolveAndFire($job, $data)  {
         list($class, $method)   = $this->parseJob($job);
         $instance               = $this->resolve($class);
 
@@ -71,8 +65,7 @@ class Manager
      * @param $class
      * @return mixed
      */
-    protected function resolve($class)
-    {
+    protected function resolve($class) {
         return new $class($this->job, $this->log);
     }
 
@@ -82,8 +75,7 @@ class Manager
      * @param  string  $job
      * @return array
      */
-    protected function parseJob($job)
-    {
+    protected function parseJob($job)  {
         $segments = explode('@', $job);
         return count($segments) > 1 ? $segments : array($segments[0], 'fire');
     }

+ 1 - 2
cron/cron.php

@@ -11,8 +11,7 @@ require_once $modulePath . DS . 'core' . DS . 'Bootstrap.php';
 ini_set('max_execution_time', 0);
 
 $argList = $argv ? $argv : $_SERVER['argv'];
-if (count($argList) === 0)
-{
+if (count($argList) === 0) {
     $argList = [__FILE__];
 }
 

+ 1 - 0
langs/english.php

@@ -525,6 +525,7 @@ $_LANG['addonAA']['jobs']['ModulesGarden\ProxmoxAddon\App\Jobs\Vps\RebootVmJob@h
 $_LANG['addonAA']['jobs']['ModulesGarden\ProxmoxAddon\App\Jobs\Vps\MigrateVmJob@handle'] = 'Migrate VM';
 //cloud
 $_LANG['addonAA']['jobs']['ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CloneQemuJob@handle'] = 'Clone KVM';
+$_LANG['addonAA']['jobs']['ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CloneQemuJobNoStart@handle'] = 'Clone KVM (no start)';
 $_LANG['addonAA']['jobs']['ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateLxcJob@handle'] = 'Create LXC';
 $_LANG['addonAA']['jobs']['ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateQemuJob@handle'] = 'Create KVM';
 $_LANG['addonAA']['jobs']['ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\RebootVmJob@handle'] = 'Reboot VM ';