VmUpdateProvider.php 15 KB

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