| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407 |
- <?php
- namespace ModulesGarden\Servers\ProxmoxCloudVps\App\UI\VmCreate\Providers;
- use MGProvision\Proxmox\v2\models\Kvm;
- use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CloneQemuJob;
- use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateLxcJob;
- use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateQemuJob;
- use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateSnippet;
- use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\MigrateVmJob;
- use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\RestoreArchiveJob;
- use ModulesGarden\ProxmoxAddon\App\Libs\Format;
- use ModulesGarden\ProxmoxAddon\App\Models\CloudInitScript;
- use ModulesGarden\ProxmoxAddon\App\Models\VirtualInterface;
- use ModulesGarden\ProxmoxAddon\App\Models\VirtualNetwork;
- use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
- use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
- use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
- use ModulesGarden\ProxmoxAddon\App\Services\Cloud\NetworkService;
- use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
- use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ResourceManager;
- use ModulesGarden\ProxmoxAddon\App\Services\Ip\Ipv4Range;
- use ModulesGarden\ProxmoxAddon\App\Services\Utility;
- use ModulesGarden\Servers\ProxmoxCloudVps\App\Helpers\BuildUrl;
- use ModulesGarden\Servers\ProxmoxCloudVps\App\Helpers\UrlServiceHelper;
- use ModulesGarden\Servers\ProxmoxCloudVps\Core\FileReader\Reader\Json;
- use ModulesGarden\Servers\ProxmoxCloudVps\Core\ModuleConstants;
- use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\ClientArea;
- use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
- use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\DataProviders\BaseModelDataProvider;
- use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\queue;
- use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;
- class VmCreateProvider extends BaseModelDataProvider implements ClientArea
- {
- use ApiService;
- use ProductService;
- /**
- * @var VmModel
- */
- protected $vmModel;
- protected $vmTemplate;
- /**
- * VmUpdateProvider constructor.
- */
- public function __construct()
- {
- $this->model = VmModel::class;
- }
- public function read()
- {
- parent::read();
- /**
- * virtual network ip addresses
- * @deprecated
- foreach (VirtualNetwork::ofHostingId($this->getWhmcsParamByKey('serviceid'))->get() as $vn){
- $ipRange = new Ipv4Range($vn->pool, $vn->cidr);
- $ipRange->setLimit(10);
- $ipRange->disableIpAddresses( $vn->virtualInterfaces->pluck('ip')->toArray());
- $this->availableValues[sprintf("ip[%s]", $vn->id)] [0] = sl('lang')->abtr('None');
- foreach ( $ipRange->get() as $ip ){
- $this->availableValues[sprintf("ip[%s]", $vn->id)] [$ip] = $ip;
- }
- }
- */
- //location
- foreach ($this->configuration()->getLocations() as $location){
- $this->availableValues['location'] [$location] = sl('lang')->abtr('location', $location);
- }
- //ostype
- $osTypes = $this->configuration()->getPermissionOstype();
- if($osTypes){
- $ostype = new Json('ostype.json', ModuleConstants::getFullPathWhmcs('modules', 'addons', 'proxmoxAddon', 'storage', 'app'));
- foreach ($ostype->get() as $k => $ostype)
- {
- if(!in_array($k, $osTypes)){
- continue;
- }
- $this->availableValues["ostype"][$k] = sl('lang')->abtr('ostype',$ostype);
- }
- }
- //cloudInitScript
- if($this->configuration()->getCloudInitScript()){
- $this->availableValues["cloudInitScript"] = CloudInitScript::ofIds($this->configuration()->getCloudInitScript())
- ->orderBy('name','asc')
- ->pluck('name','id')
- ->prepend(sl('lang')->abtr('None'),0)
- ->toArray();
- }
- }
- public function create()
- {
- //Clone KVM check disk size
- if($this->getJobClass() == CloneQemuJob::class && !$this->isDiskSizeValid()){
- sl("lang")->addReplacementConstant("size", Format::convertBytes($this->vmTemplate->getMasterHardDisk()->getBytes()));
- return (new HtmlDataJsonResponse())
- ->setStatusError()
- ->setMessageAndTranslate('OS Template require disk size :size:');
- }
- $resurceManager = new ResourceManager();
- //disk size validation
- $diskResource = $resurceManager ->disk();
- $diskResource->setTotal($diskResource ->getTotal() - $this->formData['disk']);
- $additonalDiskSize = $this->getAdditionalDiskTotalSize();
- if($this->vmTemplate->getSlaveHddsSize()) {
- $additonalDiskSize += $this->vmTemplate->getSlaveHddsSize();
- }
- if($additonalDiskSize && $additonalDiskSize > $diskResource->freeTotal() ){
- sl("lang")->addReplacementConstant("additional_disks_size", $additonalDiskSize);
- sl("lang")->addReplacementConstant("size", $diskResource->freeTotal());
- return (new HtmlDataJsonResponse())
- ->setStatusError()
- ->setMessageAndTranslate('You are not able to set :additional_disks_size: GB of the additional disks size. The available size is: :size: GB');
- }
- //ipv4
- if($this->configuration()->isOrderPublicIp() && $this->configuration()->serverIpv4->min && $this->configuration()->serverIpv4->min > $this->countPublicIpv4() ){
- return (new HtmlDataJsonResponse())
- ->setStatusError()
- ->setMessageAndTranslate('Select the Virtual Network with IPv4 address');
- }
- //serverVirtualInterfaces
- if($this->configuration()->isPermissionVirtualNetwork() && $this->configuration()->serverVirtualInterfaces->min && $this->configuration()->serverVirtualInterfaces->min > $this->countVirtualIntefaces() ){
- return (new HtmlDataJsonResponse())
- ->setStatusError()
- ->setMessageAndTranslate('Select the Virtual Network');
- }
- if($this->configuration()->isPermissionVirtualNetwork() && $this->configuration()->serverVirtualInterfaces->max && $this->configuration()->serverVirtualInterfaces->max < $vi =$this->countVirtualIntefaces() ){
- sl("lang")->addReplacementConstant("virtual_interfaces", (string)$vi);
- sl("lang")->addReplacementConstant("max",$this->configuration()->serverVirtualInterfaces->max);
- return (new HtmlDataJsonResponse())
- ->setStatusError()
- ->setMessageAndTranslate('You are not able to set :virtual_interfaces: of the virtual inferfaces. The available virtual interfec is: :max:');
- }
- if($this->configuration()->isPermissionVirtualNetwork() && $this->configuration()->serverVirtualInterfaces->min && $this->configuration()->serverVirtualInterfaces->min > $this->countVirtualIntefaces() ){
- return (new HtmlDataJsonResponse())
- ->setStatusError()
- ->setMessageAndTranslate('Select the Virtual Network');
- }
- $this->vmModel = new VmModel();
- $this->fillVmModel();
- if($this->vmTemplate instanceof Kvm){
- $this->vmModel->data = ['osTemplate'=> $this->vmTemplate->status()['name']];
- }else{
- $this->vmModel->data = ['osTemplate'=> $this->formData['osTemplate']];
- }
- $this->vmModel->setPassword($this->formData['password']);
- $this->vmModel->hosting_id = $this->getWhmcsParamByKey('serviceid');
- unset($this->formData['password']);
- $this->vmModel->virtualization = $this->configuration()->getVirtualization();
- if($this->formData['location'] && in_array($this->formData['location'], $this->configuration()->getLocations())){
- $this->vmModel->node = $this->formData['location'];
- }else{
- $this->vmModel->node = $this->getNode()->getNode();
- }
- if($this->configuration()->isCalculateSocketsAndCores()){
- $this->calculateSocketsAndCores();
- };
- $networkService = new NetworkService();
- $bridge = $this->configuration()->getBridge();
- if(!$this->configuration()->isOrderPublicIp()){
- //ip validation
- $networkService->hasIp((int)$this->formData['ipv4'], (int)$this->formData['ipv6'], $this->vmModel->node, $bridge );
- }
- //init vm
- $this->vmModel->save();
- \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->setVmModel($this->vmModel);
- //assign IPs
- if(!$this->configuration()->isOrderPublicIp()){
- $networkService->addIp((int)$this->formData['ipv4'], (int)$this->formData['ipv6'], $this->vmModel->node,$bridge);
- foreach (VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
- ->ofVmId($this->vmModel->id)->get() as $vmIp){
- $vi = new VirtualInterface();
- $vi->ip = $vmIp->ip;
- $vi->ip_long = ip2long($vmIp->ip);
- $vi->vm_id = $this->vmModel->id;
- $vi->vn_id = 0;
- $vi->hosting_id = $this->getWhmcsParamByKey('serviceid');
- $vi->save();
- }
- }
- $this->createJob();
- //virtual interfaces
- for($i=1; $i<=20; $i++){
- if(!$this->formData['virtualNetwork'.$i]){
- continue;
- }
- $ip = $this->formData['virtualNetwork'.$i]['ip'];
- $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
- //lock public ip
- if( $virtualNetworkId == 'public'){
- VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
- ->ofIp($ip)
- ->update(['vm_id' => $this->vmModel->id ]);
- }
- $vi = new VirtualInterface();
- $vi->ip = $ip;
- $vi->ip_long = ip2long($ip);
- $vi->vm_id = $this->vmModel->id;
- $vi->vn_id = $virtualNetworkId=="public"? 0 : $virtualNetworkId;
- $vi->hosting_id = $this->getWhmcsParamByKey('serviceid');
- $vi->save();
- }
- return (new HtmlDataJsonResponse())
- ->setMessageAndTranslate('The process of Virtual Machine creation is in progress')
- ->setCallBackFunction('pcVmCreatedAjaxDone')
- ->addData('redirectUrl' , (new UrlServiceHelper())->home());
- }
- private function getJobClass(){
- if($this->getFormDataValues()['osTemplate'] && !in_array($this->formData['osTemplate'] ,['installationFromIso','installationFromArchive']) && $this->configuration()->isQemu()){
- return CloneQemuJob::class;
- }elseif ( $this->configuration()->isQemu() && $this->formData['osTemplate'] == "installationFromArchive"){
- return RestoreArchiveJob::class;
- }elseif ( $this->configuration()->isQemu()){
- return CreateQemuJob::class;
- }else{
- return CreateLxcJob::class;
- }
- }
- protected function getJobArguments(){
- $arguments = $this->formData;
- $arguments['hostingId'] =$this->getWhmcsParamByKey('serviceid');
- return $arguments;
- }
- private function createJob(){
- $jobClass = $this->getJobClass();
- //snippet
- if($jobClass == CloneQemuJob::class && $this->getFormDataValues()['cloudInitScript']){
- $parent = queue(
- CreateSnippet::class,
- $this->getJobArguments(),
- null,
- "hosting",
- $this->getWhmcsParamByKey("serviceid"),
- $this->vmModel->id
- );
- }
- $parent = queue(
- $this->getJobClass(),
- $this->getJobArguments(),
- $parent->id,
- "hosting",
- $this->getWhmcsParamByKey("serviceid"),
- $this->vmModel->id
- );
- //archive
- if($this->formData['archive'] && $this->formData['osTemplate'] == "installationFromArchive" ){
- list($backupNode, $volid) = explode(":", $this->formData['archive'], 2);
- if($this->vmModel->node != $backupNode){
- $attributes = [
- "targetNode" => $this->vmModel->node,
- "online" => 1,
- 'with-local-disks' => 1,
- 'restart' => 1
- ];
- queue(
- MigrateVmJob::class,
- $attributes,
- $parent->id,
- "hosting",
- $this->getWhmcsParamByKey("serviceid"),
- $this->vmModel->id
- );
- }
- }
- }
- /**
- * @deprecated
- */
- protected function requestValidation(){
- //load form data
- $this->getFormDataValues();
- //ipv4
- if(!$this->configuration()->isPermissionIpv4()){
- $this->formData['ipv4'] = $this->configuration()->serverIpv4->min;
- }
- //ipv6
- if(!$this->configuration()->isPermissionIpv6){
- $this->formData['ipv6'] = $this->configuration()->serverIpv6->min;
- }
- }
- private function isDiskSizeValid(){
- list($node, $vmid) = explode("/", $this->formData['osTemplate']);
- $this->vmTemplate = new Kvm($node, $vmid);
- $this->vmTemplate->setApi($this->api());
- $diskSizeBytes = $this->formData['disk'];
- Utility::unitFormat($diskSizeBytes,'gb','bytes');
- $this->templateDiskSizeBytes = $this->vmTemplate->getMasterHardDisk()->getBytes();
- return $diskSizeBytes >= $this->templateDiskSizeBytes;
- }
- protected function fillVmModel(){
- $this->vmModel->fill($this->getFormDataValues());
- //sockets
- if( !$this->configuration()->isPermissionSockets() && !$this->configuration()->isCalculateSocketsAndCores()){
- $this->vmModel->sockets = $this->configuration()->serverSockets->min;
- }
- //cores
- if( !$this->configuration()->isPermissionCores() && !$this->configuration()->isCalculateSocketsAndCores() ){
- $this->vmModel->cores = $this->configuration()->serverCores->min;
- }
- //vcpus
- if( !$this->configuration()->isPermissionVcpus() ){
- $this->vmModel->vcpus = $this->configuration()->serverVcpus->min;
- }
- if($this->configuration()->isCalculateSocketsAndCores()){
- }
- //cpulimit
- if( !$this->configuration()->isPermissionCpuLimit() && !$this->formData['cpuPriority']){
- $this->vmModel->cpulimit = $this->formData['vcpu'] * 0.8;
- }
- //cpuunits
- if( !$this->configuration()->isPermissionCpuunits() && !$this->formData['cpuPriority']){
- $this->vmModel->cpuunits = $this->configuration()->serverCpuunit->min;
- }
- //swap
- if( !$this->configuration()->isPermissionSwap() ){
- $this->vmModel->swap = $this->configuration()->serverSwap->min;
- }
- //disks
- $disks = (int) $this->getAdditionalDiskTotalSize();
- if($disks || $this->configuration()->isDetailsCombinedView()){
- $this->vmModel->disks = $disks;
- }
- //cpu prioryty
- if($this->formData['cpuPriority']){
- $this->vmModel->cpulimit = $this->configuration()->get('cpulimitPriority'.$this->formData['cpuPriority']);
- $this->vmModel->cpuunits = $this->configuration()->get('cpuunitsPriority'.$this->formData['cpuPriority']);
- }
- }
- private function getAdditionalDiskTotalSize()
- {
- $size = 0;
- for ($i = 1; $i <= 10; $i++) {
- $size += (int)$this->formData['additionalDiskSize' . $i];
- }
- return $size;
- }
- protected function calculateSocketsAndCores()
- {
- $cores =1;
- $socket = 1;
- $cpus = $this->configuration()->serverCores->max;
- while($cpus > 0)
- {
- if($this->vmModel->vcpus % $cpus === 0 && $this->vmModel->vcpus / $cpus <= $this->configuration()->serverSockets->max)
- {
- $cores = $cpus;
- $socket = $this->vmModel->vcpus / $cpus;
- }
- $cpus--;
- }
- $this->vmModel->cores = $cores;
- $this->vmModel->sockets = $socket;
- }
- public function countPublicIpv4(){
- $total=0;
- for($i=1; $i<=20; $i++){
- if(!$this->formData['virtualNetwork'.$i]){
- continue;
- }
- $ip = $this->formData['virtualNetwork'.$i]['ip'];
- $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
- //lock public ip
- if($ip && !preg_match("/\:/", $ip) && $virtualNetworkId == 'public'){
- $total++;
- }
- }
- return $total;
- }
- public function countVirtualIntefaces(){
- $total=0;
- for($i=1; $i<=20; $i++){
- if(!$this->formData['virtualNetwork'.$i]){
- continue;
- }
- $ip = $this->formData['virtualNetwork'.$i]['ip'];
- $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
- //lock public ip
- if($ip && !preg_match("/\:/", $ip) && $virtualNetworkId != 'public'){
- $total++;
- }
- }
- return $total;
- }
- }
|