VmCreateProvider.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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($this->vmTemplate->getSlaveHddsSize()) {
  100. $additonalDiskSize += $this->vmTemplate->getSlaveHddsSize();
  101. }
  102. if($additonalDiskSize && $additonalDiskSize > $diskResource->freeTotal() ){
  103. sl("lang")->addReplacementConstant("additional_disks_size", $additonalDiskSize);
  104. sl("lang")->addReplacementConstant("size", $diskResource->freeTotal());
  105. return (new HtmlDataJsonResponse())
  106. ->setStatusError()
  107. ->setMessageAndTranslate('You are not able to set :additional_disks_size: GB of the additional disks size. The available size is: :size: GB');
  108. }
  109. //ipv4
  110. if($this->configuration()->isOrderPublicIp() && $this->configuration()->serverIpv4->min && $this->configuration()->serverIpv4->min > $this->countPublicIpv4() ){
  111. return (new HtmlDataJsonResponse())
  112. ->setStatusError()
  113. ->setMessageAndTranslate('Select the Virtual Network with IPv4 address');
  114. }
  115. //serverVirtualInterfaces
  116. if($this->configuration()->isPermissionVirtualNetwork() && $this->configuration()->serverVirtualInterfaces->min && $this->configuration()->serverVirtualInterfaces->min > $this->countVirtualIntefaces() ){
  117. return (new HtmlDataJsonResponse())
  118. ->setStatusError()
  119. ->setMessageAndTranslate('Select the Virtual Network');
  120. }
  121. if($this->configuration()->isPermissionVirtualNetwork() && $this->configuration()->serverVirtualInterfaces->max && $this->configuration()->serverVirtualInterfaces->max < $vi =$this->countVirtualIntefaces() ){
  122. sl("lang")->addReplacementConstant("virtual_interfaces", (string)$vi);
  123. sl("lang")->addReplacementConstant("max",$this->configuration()->serverVirtualInterfaces->max);
  124. return (new HtmlDataJsonResponse())
  125. ->setStatusError()
  126. ->setMessageAndTranslate('You are not able to set :virtual_interfaces: of the virtual inferfaces. The available virtual interfec is: :max:');
  127. }
  128. if($this->configuration()->isPermissionVirtualNetwork() && $this->configuration()->serverVirtualInterfaces->min && $this->configuration()->serverVirtualInterfaces->min > $this->countVirtualIntefaces() ){
  129. return (new HtmlDataJsonResponse())
  130. ->setStatusError()
  131. ->setMessageAndTranslate('Select the Virtual Network');
  132. }
  133. $this->vmModel = new VmModel();
  134. $this->fillVmModel();
  135. if($this->vmTemplate instanceof Kvm){
  136. $this->vmModel->data = ['osTemplate'=> $this->vmTemplate->status()['name']];
  137. }else{
  138. $this->vmModel->data = ['osTemplate'=> $this->formData['osTemplate']];
  139. }
  140. $this->vmModel->setPassword($this->formData['password']);
  141. $this->vmModel->hosting_id = $this->getWhmcsParamByKey('serviceid');
  142. unset($this->formData['password']);
  143. $this->vmModel->virtualization = $this->configuration()->getVirtualization();
  144. if($this->formData['location'] && in_array($this->formData['location'], $this->configuration()->getLocations())){
  145. $this->vmModel->node = $this->formData['location'];
  146. }else{
  147. $this->vmModel->node = $this->getNode()->getNode();
  148. }
  149. if($this->configuration()->isCalculateSocketsAndCores()){
  150. $this->calculateSocketsAndCores();
  151. };
  152. $networkService = new NetworkService();
  153. $bridge = $this->configuration()->getBridge();
  154. if(!$this->configuration()->isOrderPublicIp()){
  155. //ip validation
  156. $networkService->hasIp((int)$this->formData['ipv4'], (int)$this->formData['ipv6'], $this->vmModel->node, $bridge );
  157. }
  158. //init vm
  159. $this->vmModel->save();
  160. \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->setVmModel($this->vmModel);
  161. //assign IPs
  162. if(!$this->configuration()->isOrderPublicIp()){
  163. $networkService->addIp((int)$this->formData['ipv4'], (int)$this->formData['ipv6'], $this->vmModel->node,$bridge);
  164. foreach (VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  165. ->ofVmId($this->vmModel->id)->get() as $vmIp){
  166. $vi = new VirtualInterface();
  167. $vi->ip = $vmIp->ip;
  168. $vi->ip_long = ip2long($vmIp->ip);
  169. $vi->vm_id = $this->vmModel->id;
  170. $vi->vn_id = 0;
  171. $vi->hosting_id = $this->getWhmcsParamByKey('serviceid');
  172. $vi->save();
  173. }
  174. }
  175. $this->createJob();
  176. //virtual interfaces
  177. for($i=1; $i<=20; $i++){
  178. if(!$this->formData['virtualNetwork'.$i]){
  179. continue;
  180. }
  181. $ip = $this->formData['virtualNetwork'.$i]['ip'];
  182. $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
  183. //lock public ip
  184. if( $virtualNetworkId == 'public'){
  185. VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  186. ->ofIp($ip)
  187. ->update(['vm_id' => $this->vmModel->id ]);
  188. }
  189. $vi = new VirtualInterface();
  190. $vi->ip = $ip;
  191. $vi->ip_long = ip2long($ip);
  192. $vi->vm_id = $this->vmModel->id;
  193. $vi->vn_id = $virtualNetworkId=="public"? 0 : $virtualNetworkId;
  194. $vi->hosting_id = $this->getWhmcsParamByKey('serviceid');
  195. $vi->save();
  196. }
  197. return (new HtmlDataJsonResponse())
  198. ->setMessageAndTranslate('The process of Virtual Machine creation is in progress')
  199. ->setCallBackFunction('pcVmCreatedAjaxDone')
  200. ->addData('redirectUrl' , (new UrlServiceHelper())->home());
  201. }
  202. private function getJobClass(){
  203. if($this->getFormDataValues()['osTemplate'] && !in_array($this->formData['osTemplate'] ,['installationFromIso','installationFromArchive']) && $this->configuration()->isQemu()){
  204. return CloneQemuJob::class;
  205. }elseif ( $this->configuration()->isQemu() && $this->formData['osTemplate'] == "installationFromArchive"){
  206. return RestoreArchiveJob::class;
  207. }elseif ( $this->configuration()->isQemu()){
  208. return CreateQemuJob::class;
  209. }else{
  210. return CreateLxcJob::class;
  211. }
  212. }
  213. protected function getJobArguments(){
  214. $arguments = $this->formData;
  215. $arguments['hostingId'] =$this->getWhmcsParamByKey('serviceid');
  216. return $arguments;
  217. }
  218. private function createJob(){
  219. $jobClass = $this->getJobClass();
  220. //snippet
  221. if($jobClass == CloneQemuJob::class && $this->getFormDataValues()['cloudInitScript']){
  222. $parent = queue(
  223. CreateSnippet::class,
  224. $this->getJobArguments(),
  225. null,
  226. "hosting",
  227. $this->getWhmcsParamByKey("serviceid"),
  228. $this->vmModel->id
  229. );
  230. }
  231. $parent = queue(
  232. $this->getJobClass(),
  233. $this->getJobArguments(),
  234. $parent->id,
  235. "hosting",
  236. $this->getWhmcsParamByKey("serviceid"),
  237. $this->vmModel->id
  238. );
  239. //archive
  240. if($this->formData['archive'] && $this->formData['osTemplate'] == "installationFromArchive" ){
  241. list($backupNode, $volid) = explode(":", $this->formData['archive'], 2);
  242. if($this->vmModel->node != $backupNode){
  243. $attributes = [
  244. "targetNode" => $this->vmModel->node,
  245. "online" => 1,
  246. 'with-local-disks' => 1,
  247. 'restart' => 1
  248. ];
  249. queue(
  250. MigrateVmJob::class,
  251. $attributes,
  252. $parent->id,
  253. "hosting",
  254. $this->getWhmcsParamByKey("serviceid"),
  255. $this->vmModel->id
  256. );
  257. }
  258. }
  259. }
  260. /**
  261. * @deprecated
  262. */
  263. protected function requestValidation(){
  264. //load form data
  265. $this->getFormDataValues();
  266. //ipv4
  267. if(!$this->configuration()->isPermissionIpv4()){
  268. $this->formData['ipv4'] = $this->configuration()->serverIpv4->min;
  269. }
  270. //ipv6
  271. if(!$this->configuration()->isPermissionIpv6){
  272. $this->formData['ipv6'] = $this->configuration()->serverIpv6->min;
  273. }
  274. }
  275. private function isDiskSizeValid(){
  276. list($node, $vmid) = explode("/", $this->formData['osTemplate']);
  277. $this->vmTemplate = new Kvm($node, $vmid);
  278. $this->vmTemplate->setApi($this->api());
  279. $diskSizeBytes = $this->formData['disk'];
  280. Utility::unitFormat($diskSizeBytes,'gb','bytes');
  281. $this->templateDiskSizeBytes = $this->vmTemplate->getMasterHardDisk()->getBytes();
  282. return $diskSizeBytes >= $this->templateDiskSizeBytes;
  283. }
  284. protected function fillVmModel(){
  285. $this->vmModel->fill($this->getFormDataValues());
  286. //sockets
  287. if( !$this->configuration()->isPermissionSockets() && !$this->configuration()->isCalculateSocketsAndCores()){
  288. $this->vmModel->sockets = $this->configuration()->serverSockets->min;
  289. }
  290. //cores
  291. if( !$this->configuration()->isPermissionCores() && !$this->configuration()->isCalculateSocketsAndCores() ){
  292. $this->vmModel->cores = $this->configuration()->serverCores->min;
  293. }
  294. //vcpus
  295. if( !$this->configuration()->isPermissionVcpus() ){
  296. $this->vmModel->vcpus = $this->configuration()->serverVcpus->min;
  297. }
  298. if($this->configuration()->isCalculateSocketsAndCores()){
  299. }
  300. //cpulimit
  301. if( !$this->configuration()->isPermissionCpuLimit() && !$this->formData['cpuPriority']){
  302. // $this->vmModel->cpulimit = $this->configuration()->serverCpulimit->min;
  303. $this->vmModel->cpulimit = $this->formData['vcpu'] * 0.8;
  304. }
  305. //cpuunits
  306. if( !$this->configuration()->isPermissionCpuunits() && !$this->formData['cpuPriority']){
  307. $this->vmModel->cpuunits = $this->configuration()->serverCpuunit->min;
  308. }
  309. //swap
  310. if( !$this->configuration()->isPermissionSwap() ){
  311. $this->vmModel->swap = $this->configuration()->serverSwap->min;
  312. }
  313. //disks
  314. $disks = (int) $this->getAdditionalDiskTotalSize();
  315. if($disks || $this->configuration()->isDetailsCombinedView()){
  316. $this->vmModel->disks = $disks;
  317. }
  318. //cpu prioryty
  319. if($this->formData['cpuPriority']){
  320. $this->vmModel->cpulimit = $this->configuration()->get('cpulimitPriority'.$this->formData['cpuPriority']);
  321. $this->vmModel->cpuunits = $this->configuration()->get('cpuunitsPriority'.$this->formData['cpuPriority']);
  322. }
  323. }
  324. private function getAdditionalDiskTotalSize()
  325. {
  326. $size = 0;
  327. for ($i = 1; $i <= 10; $i++) {
  328. $size += (int)$this->formData['additionalDiskSize' . $i];
  329. }
  330. return $size;
  331. }
  332. protected function calculateSocketsAndCores()
  333. {
  334. $cores =1;
  335. $socket = 1;
  336. $cpus = $this->configuration()->serverCores->max;
  337. while($cpus > 0)
  338. {
  339. if($this->vmModel->vcpus % $cpus === 0 && $this->vmModel->vcpus / $cpus <= $this->configuration()->serverSockets->max)
  340. {
  341. $cores = $cpus;
  342. $socket = $this->vmModel->vcpus / $cpus;
  343. }
  344. $cpus--;
  345. }
  346. $this->vmModel->cores = $cores;
  347. $this->vmModel->sockets = $socket;
  348. }
  349. public function countPublicIpv4(){
  350. $total=0;
  351. for($i=1; $i<=20; $i++){
  352. if(!$this->formData['virtualNetwork'.$i]){
  353. continue;
  354. }
  355. $ip = $this->formData['virtualNetwork'.$i]['ip'];
  356. $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
  357. //lock public ip
  358. if($ip && !preg_match("/\:/", $ip) && $virtualNetworkId == 'public'){
  359. $total++;
  360. }
  361. }
  362. return $total;
  363. }
  364. public function countVirtualIntefaces(){
  365. $total=0;
  366. for($i=1; $i<=20; $i++){
  367. if(!$this->formData['virtualNetwork'.$i]){
  368. continue;
  369. }
  370. $ip = $this->formData['virtualNetwork'.$i]['ip'];
  371. $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
  372. //lock public ip
  373. if($ip && !preg_match("/\:/", $ip) && $virtualNetworkId != 'public'){
  374. $total++;
  375. }
  376. }
  377. return $total;
  378. }
  379. }