VmUpdateProvider.php 16 KB

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