VmUpdateProvider.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. <?php
  2. namespace ModulesGarden\Servers\ProxmoxCloudVps\App\UI\VmUpdate\Providers;
  3. use Illuminate\Database\Capsule\Manager as DB;
  4. use MGProvision\Proxmox\v2\Api;
  5. use MGProvision\Proxmox\v2\models\Kvm;
  6. use MGProvision\Proxmox\v2\models\MountPoint;
  7. use MGProvision\Proxmox\v2\models\NetworkDeviceKvm;
  8. use MGProvision\Proxmox\v2\repository\FileRepository;
  9. use MGProvision\Proxmox\v2\repository\StorageRepository;
  10. use ModulesGarden\ProxmoxAddon\App\Events\Cloud\LxcUpdateEvent;
  11. use ModulesGarden\ProxmoxAddon\App\Events\Cloud\QemuUpdateEvent;
  12. use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\Agent\ChangePasswordJob;
  13. use ModulesGarden\ProxmoxAddon\App\Jobs\Cloud\Agent\ConfigureNetworkJob;
  14. use ModulesGarden\ProxmoxAddon\App\Models\VirtualInterface;
  15. use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
  16. use ModulesGarden\ProxmoxAddon\App\Models\VmModel;
  17. use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
  18. use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AdditionalDiskService;
  19. use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AdditionalMountPointService;
  20. use ModulesGarden\ProxmoxAddon\App\Services\Cloud\AgentService;
  21. use ModulesGarden\ProxmoxAddon\App\Services\Cloud\IpSetIpFilterService;
  22. use ModulesGarden\ProxmoxAddon\App\Services\Cloud\NetworkService;
  23. use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
  24. use ModulesGarden\ProxmoxAddon\App\Services\Cloud\VirtualInterfaceConverter;
  25. use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\VmCreate\Providers\VmCreateProvider;
  26. use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
  27. use function ModulesGarden\ProxmoxAddon\Core\Helper\fire;
  28. use function ModulesGarden\ProxmoxAddon\Core\Helper\queue;
  29. use function ModulesGarden\Servers\ProxmoxCloudVps\Core\Helper\sl;
  30. class VmUpdateProvider extends VmCreateProvider
  31. {
  32. use ApiService;
  33. use ProductService;
  34. /**
  35. * VmUpdateProvider constructor.
  36. */
  37. public function __construct()
  38. {
  39. $this->model = VmModel::class;
  40. }
  41. public function read()
  42. {
  43. $this->vmModel = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel();
  44. $this->data = $this->vmModel->toArray();
  45. $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
  46. $config = $vm->config();
  47. $this->data['password'] = $this->vmModel->getPassword();
  48. $this->data['ciuser'] = $config['ciuser'];
  49. $this->data['cipassword'] = $config['cipassword'];
  50. $this->data['description'] = html_entity_decode($config['description']);
  51. $this->data['searchdomain'] = $config['searchdomain'];
  52. $ns = explode(" ",$config['nameserver']);
  53. $this->data['nameserver[0]'] = $ns[0];
  54. $this->data['nameserver[1]'] = $ns[1];
  55. if(!$this->configuration()->isOrderPublicIp()){
  56. $this->data['ipv4'] = $this->vmModel->ipv4Addresses->count();
  57. $this->data['ipv6'] = $this->vmModel->ipv6Addresses->count();
  58. }
  59. //Boot order
  60. if($vm instanceof Kvm){
  61. $bootOrder = $vm->getBootOrder();
  62. $this->data['bootOrder0'] = $bootOrder[0];
  63. $this->data['bootOrder1'] = $bootOrder[1];
  64. $this->data['bootOrder2'] = $bootOrder[2];
  65. $options = [
  66. 0 => sl("lang")->tr("None"),
  67. "c" => sl("lang")->tr("Disk"),
  68. "d" => sl("lang")->tr("CD-ROM"),
  69. "n" => sl("lang")->tr("Network"),
  70. ];
  71. if(version_compare($this->api()->getVersion(), "6.3", '>=')
  72. && !in_array("c", (array) $bootOrder )){
  73. $cdrom = $vm->cdrom();
  74. $nd = $vm->getNetworkDevices();
  75. $options = [
  76. 0 => sl("lang")->tr("None"),
  77. $vm->getMasterHardDisk()->getId() => sl("lang")->tr("Disk"),
  78. ];
  79. if($cdrom['bus']){
  80. $options[$cdrom['bus']] = sl("lang")->tr("CD-ROM");
  81. }
  82. if($nd[0] instanceof NetworkDeviceKvm){
  83. $options[$nd[0]->getId()] = sl("lang")->tr("Network");
  84. }
  85. }
  86. $this->availableValues['bootOrder0'] = $options;
  87. $this->availableValues['bootOrder1'] = $options;
  88. $this->availableValues['bootOrder2'] = $options;
  89. }
  90. //sshkeys
  91. $this->data['sshkeys'] = rawurldecode($vm->config()['sshkeys']);
  92. //cpu Priority
  93. if($this->configuration()->hasCpuPriority()){
  94. for($i=1; $i<=5; $i++){
  95. $cpuunits = $this->configuration()->get('cpuunitsPriority'.$i);
  96. $cpulimit = $this->configuration()->get('cpulimitPriority'.$i);
  97. if($this->vmModel->cpulimit >= $cpulimit){
  98. $this->data['cpuPriority'] = $i;
  99. }
  100. if($this->vmModel->cpuunits >= $cpuunits){
  101. $this->data['cpuPriority'] = $i;
  102. }
  103. }
  104. }
  105. //iso
  106. if ($this->configuration()->isQemu() && $this->configuration()->isPermissionIsoImage()) {
  107. $this->availableValues['iso'] = ["none" => sl('lang')->abtr("None")];
  108. $storageRepository = new StorageRepository();
  109. $storageRepository->findByNodes([$vm->getNode()])
  110. ->findEnabed();
  111. $storages = $storageRepository->fetchAsArray();
  112. $isoRepository = new FileRepository();
  113. $isoRepository->findByNodes([$vm->getNode()])
  114. ->findByStorages($storages);
  115. $isoRepository->findIso();
  116. foreach ($isoRepository->fetch() as $entity) {
  117. if ($this->configuration()->isPermissionIsoImages() && !in_array($entity->getVolid(), $this->configuration()->getPermissionIsoImages())) {
  118. continue;
  119. }
  120. $this->availableValues['iso'][$entity->getVolid()] = $entity->getFriendlyName();
  121. }
  122. if( $vm->getCdRomRepository()->first()){
  123. $this->data['iso']= $vm->getCdRomRepository()->first()->getLocation();
  124. }
  125. }
  126. }
  127. public function update()
  128. {
  129. $this->vmModel = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel();
  130. $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
  131. $this->networkService = new NetworkService();
  132. if(!$this->configuration()->isOrderPublicIp()){
  133. $ipv4 = (int) $this->getFormDataValues()['ipv4'] - (int) $this->vmModel->ipv4Addresses->count();
  134. $ipv6 = (int)$this->getFormDataValues()['ipv6'] - (int) $this->vmModel->ipv6Addresses->count();
  135. $this->networkService->hasIp($ipv4, $ipv6, $this->vmModel->node, $this->configuration()->getBridge());
  136. $this->networkService->addIp($ipv4, $ipv6, $this->vmModel->node, $this->configuration()->getBridge());
  137. $this->networkService->unassignIpAddressesAndDeleteNetwork($ipv4, $ipv6);
  138. foreach (VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  139. ->ofVmId($this->vmModel->id)->ofNetNull()->get() as $vmIp){
  140. $vi = new VirtualInterface();
  141. $vi->ip = $vmIp->ip;
  142. $vi->ip_long = ip2long($vmIp->ip);
  143. $vi->vm_id = $this->vmModel->id;
  144. $vi->vn_id = 0;
  145. $vi->hosting_id = $this->getWhmcsParamByKey('serviceid');
  146. $vi->save();
  147. }
  148. }
  149. //load data
  150. $this->getFormDataValues();
  151. if ($vm instanceof Kvm)
  152. {
  153. //iso
  154. if ($vm->cdrom())
  155. {
  156. $vm->updateCdrom($this->formData['iso']);
  157. }
  158. //Boot order
  159. $bootOrder = null;
  160. $order = [];
  161. for ($i = 0; $i <= 2; $i++)
  162. {
  163. if ($this->formData['bootOrder' . $i])
  164. {
  165. $bootOrder .= $this->formData['bootOrder' . $i];
  166. if(!in_array($this->formData['bootOrder' . $i],["c","d","n"])){
  167. $order[] = $this->formData['bootOrder' . $i];
  168. }
  169. }
  170. }
  171. if(version_compare($this->api()->getVersion(), "6.3", '>=') && !empty($order)){
  172. //order=scsi0;ide0;ide1;net0
  173. $vm->updateConfig(['boot' => "order=".implode(";", $order)]);
  174. }else{
  175. $vm->changeBootOrder($bootOrder);
  176. }
  177. //sshkeys
  178. if($this->configuration()->isPermissionSshkeys()){
  179. if ($this->formData['sshkeys'])
  180. {
  181. $vm->updateConfig(["sshkeys" => rawurlencode($this->formData['sshkeys'])]);
  182. } else if($vm->config()['sshkeys'])
  183. {
  184. $vm->deleteConfig('sshkeys');
  185. }
  186. }
  187. }
  188. try{
  189. Api::beginTransaction();
  190. DB::beginTransaction();
  191. $this->fillVmModel();
  192. if($this->getFormDataValues()['password']){
  193. $this->vmModel->setPassword($this->getFormDataValues()['password']);
  194. }
  195. if($this->getFormDataValues()['ciuser']){
  196. $vm->updateConfig(["ciuser" => $this->formData['ciuser']]);
  197. }
  198. if($this->getFormDataValues()['cipassword']){
  199. $vm->updateConfig(["cipassword" => $this->formData['cipassword']]);
  200. }
  201. if($this->configuration()->isCalculateSocketsAndCores()){
  202. $this->calculateSocketsAndCores();
  203. }
  204. $this->vmModel->save();
  205. if($this->configuration()->isQemu()){
  206. fire(new QemuUpdateEvent($this->vmModel, $this->formData));
  207. }
  208. if($this->configuration()->isLxc()){
  209. fire(new LxcUpdateEvent($this->vmModel, $this->formData));
  210. }
  211. if ($this->configuration()->isDetailsCombinedView()) {
  212. //virtual interfaces
  213. $this->virtualNetworkUpdate();
  214. //IP Set
  215. if ($this->configuration()->isIpsetIpFilter()){
  216. $ipSetFilterService = new IpSetIpFilterService();
  217. $ipSetFilterService->create();
  218. }
  219. //disks
  220. $this->disksUpdate();
  221. }
  222. $agentEnabled = (new AgentService())->isEnabled();
  223. if($agentEnabled && $this->configuration()->isAgentConfigureNetwork()){
  224. queue(ConfigureNetworkJob::class,
  225. ['hostingId' => $this->getWhmcsParamByKey('serviceid')],
  226. null,
  227. "hosting",
  228. $this->getWhmcsParamByKey("serviceid"),
  229. $this->vmModel->id
  230. );
  231. }
  232. if($agentEnabled && $this->configuration()->isAgentPassword()){
  233. queue(ChangePasswordJob::class,
  234. ['hostingId' => $this->getWhmcsParamByKey('serviceid')],
  235. null,
  236. "hosting",
  237. $this->getWhmcsParamByKey("serviceid"),
  238. $this->vmModel->id
  239. );
  240. }
  241. DB::commit();
  242. return (new HtmlDataJsonResponse())
  243. ->setMessageAndTranslate('Server has been updated')
  244. ->setCallBackFunction('pcVmUpdatedAjaxDone')
  245. ->addRefreshTargetId('serviceInformationDataTable')
  246. ->setCallBackFunction('mgLocationReload');
  247. }catch (\Exception $ex){
  248. DB::rollBack();
  249. Api::commit();
  250. return (new HtmlDataJsonResponse())
  251. ->setStatusError()
  252. ->setMessageAndTranslate($ex->getMessage());
  253. }
  254. }
  255. private function virtualNetworkUpdate()
  256. {
  257. try {
  258. $viIds = [];
  259. //delete
  260. for ($i = 0; $i <= 20; $i++) {
  261. if ($this->formData['virtualInterface' . $i]) {
  262. $viIds[] = $this->formData['virtualInterface' . $i]['id'];
  263. }
  264. }
  265. $virtualInterfaces = VirtualInterface::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  266. ->ofVmId($this->vmModel->id);
  267. if ($viIds) {
  268. $virtualInterfaces->notId($viIds);
  269. }
  270. $this->networkService->deleteByIpAddresses($virtualInterfaces->get());
  271. DB::commit();
  272. DB::beginTransaction();
  273. //create
  274. $newVi = [];
  275. for ($i = 1; $i <= 20; $i++) {
  276. if (!$this->formData['virtualNetwork' . $i]) {
  277. continue;
  278. }
  279. $ip = $this->formData['virtualNetwork' . $i]['ip'];
  280. $virtualNetworkId = $this->formData['virtualNetwork' . $i]['id'];
  281. //lock public ip
  282. if ($virtualNetworkId == 'public') {
  283. VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  284. ->ofIp($ip)
  285. ->update(['vm_id' => $this->vmModel->id]);
  286. }
  287. $vi = new VirtualInterface();
  288. $vi->ip = $ip;
  289. $vi->ip_long = ip2long($ip);
  290. $vi->vm_id = $this->vmModel->id;
  291. $vi->vn_id = $virtualNetworkId == "public" ? 0 : $virtualNetworkId;
  292. $vi->hosting_id = $this->getWhmcsParamByKey('serviceid');
  293. $vi->save();
  294. $newVi[] = $vi;
  295. $viIds[] = $vi->id;
  296. }
  297. if ($newVi) {
  298. $config = (new VirtualInterfaceConverter($newVi, \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm()))->asConfig();
  299. if(!empty($config)){
  300. \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm()->updateConfig($config);
  301. }
  302. }
  303. DB::commit();
  304. } catch (\Exception $ex) {
  305. DB::rollBack();
  306. Api::commit();
  307. throw $ex;
  308. }
  309. }
  310. private function disksUpdate()
  311. {
  312. $vm = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVm();
  313. $vmModel = \ModulesGarden\ProxmoxAddon\Core\Helper\sl('Vm')->getVmModel();
  314. $additonalDiskService = $this->configuration()->isQemu() ? new AdditionalDiskService() : new AdditionalMountPointService();
  315. //Update
  316. $diskIds=[];
  317. $resizeTask = null;
  318. for ($i = 0; $i <= 20; $i++) {
  319. if ($this->formData['disks' . $i]) {
  320. $id = $this->formData['disks' . $i]['id'];
  321. $size = $this->formData['disks' . $i]['size'];
  322. $backup = $this->formData['disks' . $i]['backup'] == "on" ? null : 0;
  323. $mp = $this->formData['disks' . $i]['mp'];
  324. $hdd = $vm->getHardDiskRepostiory()->findById($id);
  325. if($resizeTask && $this->configuration()->isLxc()){
  326. for($i=0; $i<=15; $i++){
  327. if($vm->node()->task($resizeTask)->isDone()){
  328. $resizeTask = null;
  329. break;
  330. }
  331. sleep(1);
  332. }
  333. }
  334. //Backup
  335. $hdd->setBackup($backup);
  336. //mp
  337. if($hdd instanceof MountPoint){
  338. $hdd->setBackup($this->formData['disks' . $i]['backup'] == "on" ? 1 : null);
  339. $hdd->setMp($mp);
  340. }
  341. $hdd->update();
  342. //resize
  343. if ((int)$hdd->getGb() < (int)$size)
  344. {
  345. $size = "+" . abs((int)$size - (int)$hdd->getGb()) . "G";
  346. $resizeTask = $hdd->resize($size);
  347. }
  348. $diskIds[] = $id;
  349. }
  350. }
  351. //delete
  352. foreach ($vm->getHardDiskRepostiory()->fetch() as $disk){
  353. if(!$disk->isMaster() && !in_array($disk->getId() ,$diskIds)){
  354. $disk->delete();
  355. }
  356. }
  357. $vm->getHardDiskRepostiory()->deleteUnused();
  358. //Create
  359. $additonalDiskService->create($this->formData);
  360. //Update disk size
  361. $vmModel->disks = $vm->getHardDiskRepostiory()->reset()->additionalSize();
  362. $vmModel->save();
  363. }
  364. }