VmCreateProvider.php 14 KB

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