VmCloneProvider.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. //virtual interfaces
  157. for($i=1; $i<=20; $i++){
  158. if(!$this->formData['virtualNetwork'.$i]){
  159. continue;
  160. }
  161. $ip = $this->formData['virtualNetwork'.$i]['ip'];
  162. $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
  163. //lock public ip
  164. if( $virtualNetworkId == 'public'){
  165. VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  166. ->ofIp($ip)
  167. ->update(['vm_id' => $this->vmModel->id ]);
  168. }
  169. $vi = new VirtualInterface();
  170. $vi->ip = $ip;
  171. $vi->ip_long = ip2long($ip);
  172. $vi->vm_id = $this->vmModel->id;
  173. $vi->vn_id = $virtualNetworkId=="public"? 0 : $virtualNetworkId;
  174. $vi->hosting_id = $this->getWhmcsParamByKey('serviceid');
  175. $vi->save();
  176. }
  177. logModuleCall(
  178. 'CloneVM',
  179. __FUNCTION__,
  180. $this->formData,
  181. 'Debug Ressource',
  182. $this->VmModel
  183. );
  184. $this->createJob();
  185. /**
  186. * @deprecated
  187. $networkService = new NetworkService();
  188. //ip validation
  189. $networkService->hasIp((int)$this->formData['ipv4'], (int)$this->formData['ipv6'], $this->vmModel->node);
  190. //assign IPs
  191. $networkService->addIp((int)$this->formData['ipv4'], (int)$this->formData['ipv6'], $this->vmModel->node);
  192. foreach ($this->formData['ip'] as $virtualNetworkId => $ip){
  193. if($ip == 0){
  194. continue;
  195. }
  196. //request validation
  197. if(!VirtualNetwork::where('id', $virtualNetworkId)
  198. ->ofHostingId($this->getWhmcsParamByKey('serviceid'))->count()){
  199. throw new \InvalidArgumentException(sprintf("Virtual Network %s cannot be found", $virtualNetworkId));
  200. }
  201. }
  202. */
  203. return (new HtmlDataJsonResponse())
  204. ->setMessageAndTranslate('The process of Virtual Machine creation is in progress')
  205. ->setCallBackFunction('pcVmCreatedAjaxDone')
  206. ->addData('redirectUrl' , (new UrlServiceHelper())->home());
  207. }
  208. private function getJobClass(){
  209. if($this->getFormDataValues()['osTemplate'] && $this->formData['osTemplate'] !='installationFromIso' && $this->configuration()->isQemu()){
  210. if($this->getFormDataValues()['start'] == 'off') {
  211. return CloneQemuJobNoStart::class;
  212. }
  213. else {
  214. return CloneQemuJob::class;
  215. }
  216. }elseif ( $this->configuration()->isQemu()){
  217. return CreateQemuJob::class;
  218. }else{
  219. return CreateLxcJob::class;
  220. }
  221. }
  222. protected function getJobArguments(){
  223. $arguments = $this->formData;
  224. $arguments['hostingId'] =$this->getWhmcsParamByKey('serviceid');
  225. return $arguments;
  226. }
  227. private function createJob(){
  228. $jobClass = $this->getJobClass();
  229. if($jobClass == CloneQemuJob::class && $this->getFormDataValues()['cloudInitScript']){
  230. $parent = queue(
  231. CreateSnippet::class,
  232. $this->getJobArguments(),
  233. null,
  234. "hosting",
  235. $this->getWhmcsParamByKey("serviceid"),
  236. $this->vmModel->id
  237. );
  238. } elseif ($jobClass == CloneQemuJobNoStart::class && $this->getFormDataValues()['cloudInitScript']){
  239. $parent = queue(
  240. CreateSnippet::class,
  241. $this->getJobArguments(),
  242. null,
  243. "hosting",
  244. $this->getWhmcsParamByKey("serviceid"),
  245. $this->vmModel->id
  246. );
  247. }
  248. return queue(
  249. $this->getJobClass(),
  250. $this->getJobArguments(),
  251. $parent->id,
  252. "hosting",
  253. $this->getWhmcsParamByKey("serviceid"),
  254. $this->vmModel->id
  255. );
  256. }
  257. /**
  258. * @deprecated
  259. */
  260. protected function requestValidation(){
  261. //load form data
  262. $this->getFormDataValues();
  263. //ipv4
  264. if(!$this->configuration()->isPermissionIpv4()){
  265. $this->formData['ipv4'] = $this->configuration()->serverIpv4->min;
  266. }
  267. //ipv6
  268. if(!$this->configuration()->isPermissionIpv6){
  269. $this->formData['ipv6'] = $this->configuration()->serverIpv6->min;
  270. }
  271. }
  272. private function isDiskSizeValid(){
  273. list($node, $vmid) = explode("/", $this->formData['osTemplate']);
  274. $this->vmTemplate = new Kvm($node, $vmid);
  275. $this->vmTemplate->setApi($this->api());
  276. $diskSizeBytes = $this->formData['disk'];
  277. Utility::unitFormat($diskSizeBytes,'gb','bytes');
  278. $this->templateDiskSizeBytes = $this->vmTemplate->getMasterHardDisk()->getBytes();
  279. return $diskSizeBytes >= $this->templateDiskSizeBytes;
  280. }
  281. protected function fillVmModel(){
  282. $this->vmModel->fill($this->getFormDataValues());
  283. //sockets
  284. if( !$this->configuration()->isPermissionSockets() && !$this->configuration()->isCalculateSocketsAndCores()){
  285. $this->vmModel->sockets = $this->configuration()->serverSockets->min;
  286. }
  287. //cores
  288. if( !$this->configuration()->isPermissionCores() && !$this->configuration()->isCalculateSocketsAndCores() ){
  289. $this->vmModel->cores = $this->configuration()->serverCores->min;
  290. }
  291. //vcpus
  292. if( !$this->configuration()->isPermissionVcpus() ){
  293. $this->vmModel->vcpus = $this->configuration()->serverVcpus->min;
  294. }
  295. if($this->configuration()->isCalculateSocketsAndCores()){
  296. }
  297. //cpulimit
  298. if( !$this->configuration()->isPermissionCpuLimit() && !$this->formData['cpuPriority']){
  299. // $this->vmModel->cpulimit = $this->configuration()->serverCpulimit->min;
  300. $this->vmModel->cpulimit = $this->formData['vcpu'] * 0.8;
  301. }
  302. //cpuunits
  303. if( !$this->configuration()->isPermissionCpuunits() && !$this->formData['cpuPriority']){
  304. $this->vmModel->cpuunits = $this->configuration()->serverCpuunit->min;
  305. }
  306. //swap
  307. if( !$this->configuration()->isPermissionSwap() ){
  308. $this->vmModel->swap = $this->configuration()->serverSwap->min;
  309. }
  310. //disks
  311. $disks = (int) $this->getAdditionalDiskTotalSize();
  312. if($disks || $this->configuration()->isDetailsCombinedView()){
  313. $this->vmModel->disks = $disks;
  314. }
  315. //cpu prioryty
  316. if($this->formData['cpuPriority']){
  317. $this->vmModel->cpulimit = $this->configuration()->get('cpulimitPriority'.$this->formData['cpuPriority']);
  318. $this->vmModel->cpuunits = $this->configuration()->get('cpuunitsPriority'.$this->formData['cpuPriority']);
  319. }
  320. }
  321. private function getAdditionalDiskTotalSize()
  322. {
  323. $size = 0;
  324. for ($i = 1; $i <= 10; $i++) {
  325. $size += (int)$this->formData['additionalDiskSize' . $i];
  326. }
  327. return $size;
  328. }
  329. protected function calculateSocketsAndCores()
  330. {
  331. $cores =1;
  332. $socket = 1;
  333. $cpus = $this->configuration()->serverCores->max;
  334. while($cpus > 0)
  335. {
  336. if($this->vmModel->vcpus % $cpus === 0 && $this->vmModel->vcpus / $cpus <= $this->configuration()->serverSockets->max)
  337. {
  338. $cores = $cpus;
  339. $socket = $this->vmModel->vcpus / $cpus;
  340. }
  341. $cpus--;
  342. }
  343. $this->vmModel->cores = $cores;
  344. $this->vmModel->sockets = $socket;
  345. }
  346. public function countPublicIpv4(){
  347. $total=0;
  348. for($i=1; $i<=20; $i++){
  349. if(!$this->formData['virtualNetwork'.$i]){
  350. continue;
  351. }
  352. $ip = $this->formData['virtualNetwork'.$i]['ip'];
  353. $virtualNetworkId = $this->formData['virtualNetwork'.$i]['id'];
  354. //lock public ip
  355. if($ip && !preg_match("/\:/", $ip) && $virtualNetworkId == 'public'){
  356. $total++;
  357. }
  358. }
  359. return $total;
  360. }
  361. }