VmCreateProvider.php 14 KB

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