VmUpdateProvider.php 15 KB

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