VmCreateProvider.php 14 KB

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