VmCreateProvider.php 17 KB

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