VmUpdateProvider.php 15 KB

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