VmCreateProvider.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. namespace ModulesGarden\Servers\ProxmoxCloudVps\App\UI\VmCreate\Providers;
  3. use MGProvision\Proxmox\v2\models\Kvm;
  4. use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CloneQemuJob;
  5. use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateLxcJob;
  6. use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateQemuJob;
  7. use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\CreateSnippet;
  8. use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\MigrateVmJob;
  9. use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\RestoreArchiveJob;
  10. use ModulesGarden\ProxmoxAddon\App\Libs\Format;
  11. use ModulesGarden\ProxmoxAddon\App\Models\CloudInitScript;
  12. use ModulesGarden\ProxmoxAddon\App\Models\VirtualInterface;
  13. use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
  14. use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
  15. use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
  16. use ModulesGarden\ProxmoxAddon\App\Services\Cloud\NetworkService;
  17. use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
  18. use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ResourceManager;
  19. use ModulesGarden\ProxmoxAddon\App\Services\Utility;
  20. use ModulesGarden\Servers\ProxmoxCloudVps\App\Helpers\UrlServiceHelper;
  21. use ModulesGarden\Servers\ProxmoxCloudVps\Core\FileReader\Reader\Json;
  22. use ModulesGarden\Servers\ProxmoxCloudVps\Core\ModuleConstants;
  23. use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Interfaces\ClientArea;
  24. use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
  25. use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Widget\Forms\DataProviders\BaseModelDataProvider;
  26. use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\queue;
  27. use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;
  28. class VmCreateProvider extends BaseModelDataProvider implements ClientArea
  29. {
  30. use ApiService;
  31. use ProductService;
  32. /**
  33. * @var VmModel
  34. */
  35. protected $vmModel;
  36. protected $vmTemplate;
  37. /**
  38. * VmUpdateProvider constructor.
  39. */
  40. public function __construct()
  41. {
  42. $this->model = VmModel::class;
  43. }
  44. public function read()
  45. {
  46. parent::read();
  47. /**
  48. * virtual network ip addresses
  49. * @deprecated
  50. foreach (VirtualNetwork::ofHostingId($this->getWhmcsParamByKey('serviceid'))->get() as $vn){
  51. $ipRange = new Ipv4Range($vn->pool, $vn->cidr);
  52. $ipRange->setLimit(10);
  53. $ipRange->disableIpAddresses( $vn->virtualInterfaces->pluck('ip')->toArray());
  54. $this->availableValues[sprintf("ip[%s]", $vn->id)] [0] = sl('lang')->abtr('None');
  55. foreach ( $ipRange->get() as $ip ){
  56. $this->availableValues[sprintf("ip[%s]", $vn->id)] [$ip] = $ip;
  57. }
  58. }
  59. */
  60. //location
  61. foreach ($this->configuration()->getLocations() as $location){
  62. $this->availableValues['location'] [$location] = sl('lang')->abtr('location', $location);
  63. }
  64. //ostype
  65. $osTypes = $this->configuration()->getPermissionOstype();
  66. if($osTypes){
  67. $ostype = new Json('ostype.json', ModuleConstants::getFullPathWhmcs('modules', 'addons', 'proxmoxAddon', 'storage', 'app'));
  68. foreach ($ostype->get() as $k => $ostype)
  69. {
  70. if(!in_array($k, $osTypes)){
  71. continue;
  72. }
  73. $this->availableValues["ostype"][$k] = sl('lang')->abtr('ostype',$ostype);
  74. }
  75. }
  76. //cloudInitScript
  77. if($this->configuration()->getCloudInitScript()){
  78. $this->availableValues["cloudInitScript"] = CloudInitScript::ofIds($this->configuration()->getCloudInitScript())
  79. ->orderBy('name','asc')
  80. ->pluck('name','id')
  81. ->prepend(sl('lang')->abtr('None'),0)
  82. ->toArray();
  83. }
  84. }
  85. public function create()
  86. {
  87. //Clone KVM check disk size
  88. if($this->getJobClass() == CloneQemuJob::class && !$this->isDiskSizeValid()){
  89. sl("lang")->addReplacementConstant("size", Format::convertBytes($this->vmTemplate->getMasterHardDisk()->getBytes()));
  90. return (new HtmlDataJsonResponse())
  91. ->setStatusError()
  92. ->setMessageAndTranslate('OS Template require disk size :size:');
  93. }
  94. $resurceManager = new ResourceManager();
  95. //disk size validation
  96. $diskResource = $resurceManager ->disk();
  97. $diskResource->setTotal($diskResource ->getTotal() - $this->formData['disk']);
  98. $additonalDiskSize = $this->getAdditionalDiskTotalSize();
  99. if($additonalDiskSize && $additonalDiskSize > $diskResource->freeTotal() ){
  100. sl("lang")->addReplacementConstant("additional_disks_size", $additonalDiskSize);
  101. sl("lang")->addReplacementConstant("size", $diskResource->freeTotal());
  102. return (new HtmlDataJsonResponse())
  103. ->setStatusError()
  104. ->setMessageAndTranslate('You are not able to set :additional_disks_size: GB of the additional disks size. The available size is: :size: GB');
  105. }
  106. //ipv4
  107. if($this->configuration()->isOrderPublicIp() && $this->configuration()->serverIpv4->min && $this->configuration()->serverIpv4->min > $this->countPublicIpv4() ){
  108. return (new HtmlDataJsonResponse())
  109. ->setStatusError()
  110. ->setMessageAndTranslate('Select the Virtual Network with IPv4 address');
  111. }
  112. //serverVirtualInterfaces
  113. if($this->configuration()->isPermissionVirtualNetwork() && $this->configuration()->serverVirtualInterfaces->min && $this->configuration()->serverVirtualInterfaces->min > $this->countVirtualIntefaces() ){
  114. return (new HtmlDataJsonResponse())
  115. ->setStatusError()
  116. ->setMessageAndTranslate('Select the Virtual Network');
  117. }
  118. if($this->configuration()->isPermissionVirtualNetwork() && $this->configuration()->serverVirtualInterfaces->max && $this->configuration()->serverVirtualInterfaces->max < $vi =$this->countVirtualIntefaces() ){
  119. sl("lang")->addReplacementConstant("virtual_interfaces", (string)$vi);
  120. sl("lang")->addReplacementConstant("max",$this->configuration()->serverVirtualInterfaces->max);
  121. return (new HtmlDataJsonResponse())
  122. ->setStatusError()
  123. ->setMessageAndTranslate('You are not able to set :virtual_interfaces: of the virtual inferfaces. The available virtual interfec is: :max:');
  124. }
  125. if($this->configuration()->isPermissionVirtualNetwork() && $this->configuration()->serverVirtualInterfaces->min && $this->configuration()->serverVirtualInterfaces->min > $this->countVirtualIntefaces() ){
  126. return (new HtmlDataJsonResponse())
  127. ->setStatusError()
  128. ->setMessageAndTranslate('Select the Virtual Network');
  129. }
  130. $this->vmModel = new VmModel();
  131. $this->fillVmModel();
  132. if($this->vmTemplate instanceof Kvm){
  133. $this->vmModel->data = ['osTemplate'=> $this->vmTemplate->status()['name']];
  134. }else{
  135. $this->vmModel->data = ['osTemplate'=> $this->formData['osTemplate']];
  136. }
  137. $this->vmModel->setPassword($this->formData['password']);
  138. $this->vmModel->hosting_id = $this->getWhmcsParamByKey('serviceid');
  139. unset($this->formData['password']);
  140. $this->vmModel->virtualization = $this->configuration()->getVirtualization();
  141. if($this->formData['location'] && in_array($this->formData['location'], $this->configuration()->getLocations())){
  142. $this->vmModel->node = $this->formData['location'];
  143. }else{
  144. $this->vmModel->node = $this->getNode()->getNode();
  145. }
  146. if($this->configuration()->isCalculateSocketsAndCores()){
  147. $this->calculateSocketsAndCores();
  148. };
  149. $networkService = new NetworkService();
  150. $bridge = $this->configuration()->getBridge();
  151. if(!$this->configuration()->isOrderPublicIp()){
  152. //ip validation
  153. $networkService->hasIp((int)$this->formData['ipv4'], (int)$this->formData['ipv6'], $this->vmModel->node, $bridge );
  154. }
  155. //init vm
  156. $this->vmModel->save();
  157. \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->setVmModel($this->vmModel);
  158. //assign IPs
  159. if(!$this->configuration()->isOrderPublicIp()){
  160. $networkService->addIp((int)$this->formData['ipv4'], (int)$this->formData['ipv6'], $this->vmModel->node,$bridge);
  161. foreach (VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  162. ->ofVmId($this->vmModel->id)->get() as $vmIp){
  163. $vi = new VirtualInterface();
  164. $vi->ip = $vmIp->ip;
  165. $vi->ip_long = ip2long($vmIp->ip);
  166. $vi->vm_id = $this->vmModel->id;
  167. $vi->vn_id = 0;
  168. $vi->hosting_id = $this->getWhmcsParamByKey('serviceid');
  169. $vi->save();
  170. }
  171. }
  172. $this->createJob();
  173. //virtual interfaces
  174. for($i=1; $i<=20; $i++){
  175. if(!$this->formData['virtualNetwork'.$i]){
  176. continue;
  177. }
  178. $ip = $this->formData['virtualNetwork'.$i]['ip'];
  179. $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
  180. //lock public ip
  181. if( $virtualNetworkId == 'public'){
  182. VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  183. ->ofIp($ip)
  184. ->update(['vm_id' => $this->vmModel->id ]);
  185. }
  186. $vi = new VirtualInterface();
  187. $vi->ip = $ip;
  188. $vi->ip_long = ip2long($ip);
  189. $vi->vm_id = $this->vmModel->id;
  190. $vi->vn_id = $virtualNetworkId=="public"? 0 : $virtualNetworkId;
  191. $vi->hosting_id = $this->getWhmcsParamByKey('serviceid');
  192. $vi->save();
  193. }
  194. return (new HtmlDataJsonResponse())
  195. ->setMessageAndTranslate('The process of Virtual Machine creation is in progress')
  196. ->setCallBackFunction('pcVmCreatedAjaxDone')
  197. ->addData('redirectUrl' , (new UrlServiceHelper())->home());
  198. }
  199. private function getJobClass(){
  200. if($this->getFormDataValues()['osTemplate'] && !in_array($this->formData['osTemplate'] ,['installationFromIso','installationFromArchive']) && $this->configuration()->isQemu()){
  201. return CloneQemuJob::class;
  202. }elseif ( $this->configuration()->isQemu() && $this->formData['osTemplate'] == "installationFromArchive"){
  203. return RestoreArchiveJob::class;
  204. }elseif ( $this->configuration()->isQemu()){
  205. return CreateQemuJob::class;
  206. }else{
  207. return CreateLxcJob::class;
  208. }
  209. }
  210. protected function getJobArguments(){
  211. $arguments = $this->formData;
  212. $arguments['hostingId'] =$this->getWhmcsParamByKey('serviceid');
  213. return $arguments;
  214. }
  215. private function createJob(){
  216. $jobClass = $this->getJobClass();
  217. //snippet
  218. if($jobClass == CloneQemuJob::class && $this->getFormDataValues()['cloudInitScript']){
  219. $parent = queue(
  220. CreateSnippet::class,
  221. $this->getJobArguments(),
  222. null,
  223. "hosting",
  224. $this->getWhmcsParamByKey("serviceid"),
  225. $this->vmModel->id
  226. );
  227. }
  228. $parent = queue(
  229. $this->getJobClass(),
  230. $this->getJobArguments(),
  231. $parent->id,
  232. "hosting",
  233. $this->getWhmcsParamByKey("serviceid"),
  234. $this->vmModel->id
  235. );
  236. //archive
  237. if($this->formData['archive'] && $this->formData['osTemplate'] == "installationFromArchive" ){
  238. list($backupNode, $volid) = explode(":", $this->formData['archive'], 2);
  239. if($this->vmModel->node != $backupNode){
  240. $attributes = [
  241. "targetNode" => $this->vmModel->node,
  242. "online" => 1,
  243. 'with-local-disks' => 1,
  244. 'restart' => 1
  245. ];
  246. queue(
  247. MigrateVmJob::class,
  248. $attributes,
  249. $parent->id,
  250. "hosting",
  251. $this->getWhmcsParamByKey("serviceid"),
  252. $this->vmModel->id
  253. );
  254. }
  255. }
  256. }
  257. /**
  258. * @deprecated
  259. */
  260. protected function requestValidation(){
  261. //load form data
  262. $this->getFormDataValues();
  263. //ipv4
  264. if(!$this->configuration()->isPermissionIpv4()){
  265. $this->formData['ipv4'] = $this->configuration()->serverIpv4->min;
  266. }
  267. //ipv6
  268. if(!$this->configuration()->isPermissionIpv6){
  269. $this->formData['ipv6'] = $this->configuration()->serverIpv6->min;
  270. }
  271. }
  272. private function isDiskSizeValid(){
  273. list($node, $vmid) = explode("/", $this->formData['osTemplate']);
  274. $this->vmTemplate = new Kvm($node, $vmid);
  275. $this->vmTemplate->setApi($this->api());
  276. $diskSizeBytes = $this->formData['disk'];
  277. Utility::unitFormat($diskSizeBytes,'gb','bytes');
  278. $this->templateDiskSizeBytes = $this->vmTemplate->getMasterHardDisk()->getBytes();
  279. return $diskSizeBytes >= $this->templateDiskSizeBytes;
  280. }
  281. protected function fillVmModel(){
  282. $this->vmModel->fill($this->getFormDataValues());
  283. //sockets
  284. if( !$this->configuration()->isPermissionSockets() && !$this->configuration()->isCalculateSocketsAndCores()){
  285. $this->vmModel->sockets = $this->configuration()->serverSockets->min;
  286. }
  287. //cores
  288. if( !$this->configuration()->isPermissionCores() && !$this->configuration()->isCalculateSocketsAndCores() ){
  289. $this->vmModel->cores = $this->configuration()->serverCores->min;
  290. }
  291. //vcpus
  292. if( !$this->configuration()->isPermissionVcpus() ){
  293. $this->vmModel->vcpus = $this->configuration()->serverVcpus->min;
  294. }
  295. if($this->configuration()->isCalculateSocketsAndCores()){
  296. }
  297. //cpulimit
  298. if( !$this->configuration()->isPermissionCpuLimit() && !$this->formData['cpuPriority']){
  299. $this->vmModel->cpulimit = $this->configuration()->serverCpulimit->min;
  300. }
  301. //cpuunits
  302. if( !$this->configuration()->isPermissionCpuunits() && !$this->formData['cpuPriority']){
  303. $this->vmModel->cpuunits = $this->configuration()->serverCpuunit->min;
  304. }
  305. //swap
  306. if( !$this->configuration()->isPermissionSwap() ){
  307. $this->vmModel->swap = $this->configuration()->serverSwap->min;
  308. }
  309. //disks
  310. $disks = (int) $this->getAdditionalDiskTotalSize();
  311. if($disks || $this->configuration()->isDetailsCombinedView()){
  312. $this->vmModel->disks = $disks;
  313. }
  314. //cpu prioryty
  315. if($this->formData['cpuPriority']){
  316. $this->vmModel->cpulimit = $this->configuration()->get('cpulimitPriority'.$this->formData['cpuPriority']);
  317. $this->vmModel->cpuunits = $this->configuration()->get('cpuunitsPriority'.$this->formData['cpuPriority']);
  318. }
  319. }
  320. private function getAdditionalDiskTotalSize()
  321. {
  322. $size = 0;
  323. for ($i = 1; $i <= 10; $i++) {
  324. $size += (int)$this->formData['additionalDiskSize' . $i];
  325. }
  326. return $size;
  327. }
  328. protected function calculateSocketsAndCores()
  329. {
  330. $cores =1;
  331. $socket = 1;
  332. $cpus = $this->configuration()->serverCores->max;
  333. while($cpus > 0)
  334. {
  335. if($this->vmModel->vcpus % $cpus === 0 && $this->vmModel->vcpus / $cpus <= $this->configuration()->serverSockets->max)
  336. {
  337. $cores = $cpus;
  338. $socket = $this->vmModel->vcpus / $cpus;
  339. }
  340. $cpus--;
  341. }
  342. $this->vmModel->cores = $cores;
  343. $this->vmModel->sockets = $socket;
  344. }
  345. public function countPublicIpv4(){
  346. $total=0;
  347. for($i=1; $i<=20; $i++){
  348. if(!$this->formData['virtualNetwork'.$i]){
  349. continue;
  350. }
  351. $ip = $this->formData['virtualNetwork'.$i]['ip'];
  352. $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
  353. //lock public ip
  354. if($ip && !preg_match("/\:/", $ip) && $virtualNetworkId == 'public'){
  355. $total++;
  356. }
  357. }
  358. return $total;
  359. }
  360. public function countVirtualIntefaces(){
  361. $total=0;
  362. for($i=1; $i<=20; $i++){
  363. if(!$this->formData['virtualNetwork'.$i]){
  364. continue;
  365. }
  366. $ip = $this->formData['virtualNetwork'.$i]['ip'];
  367. $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
  368. //lock public ip
  369. if($ip && !preg_match("/\:/", $ip) && $virtualNetworkId != 'public'){
  370. $total++;
  371. }
  372. }
  373. return $total;
  374. }
  375. }