VmCloneProvider.php 16 KB

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