NetworkService.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. <?php
  2. namespace ModulesGarden\ProxmoxAddon\App\Services\Vps;
  3. use Illuminate\Database\Capsule\Manager as DB;
  4. use MGProvision\Proxmox\v2\Api;
  5. use MGProvision\Proxmox\v2\models\Config;
  6. use MGProvision\Proxmox\v2\models\IpConfig;
  7. use MGProvision\Proxmox\v2\models\Kvm;
  8. use MGProvision\Proxmox\v2\models\NetworkDeviceKvm;
  9. use MGProvision\Proxmox\v2\models\NetworkDeviceLxc;
  10. use ModulesGarden\ProxmoxAddon\App\Models\IpAddress;
  11. use ModulesGarden\ProxmoxAddon\App\Models\VmIpAddress;
  12. use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
  13. use ModulesGarden\ProxmoxAddon\App\Services\Utility;
  14. use ModulesGarden\ProxmoxAddon\App\Enum\Vps\ConfigurableOption;
  15. use ModulesGarden\ProxmoxAddon\App\Enum\Vps\CustomField;
  16. use ModulesGarden\ProxmoxAddon\Core\UI\Traits\WhmcsParams;
  17. class NetworkService
  18. {
  19. use WhmcsParams;
  20. use HostingService;
  21. use ApiService;
  22. use ProductService;
  23. protected $deletePrivateNetwork = false;
  24. /**
  25. * @param VmIpAddress[] $enteries
  26. */
  27. public function create(array $enteries)
  28. {
  29. //to do acl
  30. $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
  31. DB::beginTransaction();
  32. try
  33. {
  34. foreach ($enteries as &$ip)
  35. {
  36. //insert to data base
  37. $ip->save();
  38. $this->hosting()->ipAdd($ip->ip);
  39. //lock ip in proxmox addon
  40. if (!Utility::isIpManagerProxmoxVPSIntegration())
  41. {
  42. IpAddress::where('ip', $ip->ip)
  43. ->update(["hosting_id" => $ip->hosting_id]);
  44. }
  45. }
  46. //update hosting
  47. $this->hosting()->save();
  48. DB::commit();
  49. }
  50. catch (\Exception $ex)
  51. {
  52. DB::rollBack();
  53. throw $ex;
  54. }
  55. }
  56. /**
  57. * @param VmIpAddress[] $enteries
  58. */
  59. public function addPrivate(array $enteries)
  60. {
  61. $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
  62. $container = [];
  63. $rate = null;
  64. $tag = $this->makeTag();
  65. if ($this->isWhmcsConfigOption(ConfigurableOption::NETWORK_RATE) && $this->getWhmcsConfigOption(ConfigurableOption::NETWORK_RATE) != "-1")
  66. {
  67. $rate = $this->getWhmcsConfigOption(ConfigurableOption::NETWORK_RATE);
  68. }
  69. else
  70. {
  71. if ($this->configuration()->getRate())
  72. {
  73. $rate = $this->configuration()->getRate();
  74. }
  75. }
  76. //cloud init
  77. $isCloudInit = $this->configuration()->isQemu() && $this->configuration()->isCloudInit();
  78. try
  79. {
  80. DB::beginTransaction();
  81. Api::beginTransaction();
  82. foreach ($enteries as &$ip)
  83. {
  84. //insert to data base
  85. $ip->save();
  86. $this->hosting()->ipAdd($ip->ip);
  87. //lock ip in proxmox addon
  88. IpAddress::where('ip', $ip->ip)
  89. ->update(["hosting_id" => $ip->hosting_id]);
  90. $networkId = $this->vm()->findFreeNetworDeviceId();
  91. if ($this->configuration()->isLxc())
  92. {
  93. $networkDevice = new NetworkDeviceLxc('net' . $networkId);
  94. $networkDevice->setName('eth' . $networkId)
  95. ->setBridge($this->configuration()->getPrivateBridge())
  96. ->setFirewall($this->configuration()->isNetworkFirewall() ? 1 : 0);
  97. if ($ip->mac_address && $ip->mac_address != "auto")
  98. {
  99. $networkDevice->setHwaddr($ip->mac_address);
  100. }
  101. $networkDevice->setIp($ip->ip)
  102. ->setCidr($ip->cidr)
  103. ->setGw($ip->gateway)
  104. ->setTag($tag)
  105. ->setRate($rate)
  106. ->setTrunks($ip->trunks);
  107. $container[$networkDevice->getId()] = $networkDevice->asConfig();
  108. }
  109. else
  110. {
  111. if ($this->configuration()->isQemu())
  112. {
  113. $networkDevice = new NetworkDeviceKvm('net' . $networkId);
  114. $networkDevice->setBridge($this->configuration()->getPrivateBridge())
  115. ->setModel($this->configuration()->getNetworkPrivateModel())
  116. ->setRate($rate)
  117. ->setTag($tag)
  118. ->setTrunks($ip->trunks)
  119. ->setFirewall($this->configuration()->isNetworkFirewall() ? 1 : 0);
  120. if ($ip->mac_address && $ip->mac_address != "auto")
  121. {
  122. $networkDevice->setMacAddress($ip->mac_address);
  123. }
  124. $container[$networkDevice->getId()] = $networkDevice->asConfig();
  125. if ($isCloudInit)
  126. {
  127. $ipConfig = new IpConfig('ipconfig' . $networkId);
  128. $ipConfig->setIp(trim($ip->ip))
  129. ->setCidr(trim($ip->cidr))
  130. ->setGw(trim($ip->gateway));
  131. $container[$ipConfig->getId()] = $ipConfig->asConfig();
  132. }
  133. }
  134. }
  135. $ip->net = $networkDevice->getId();
  136. $ip->tag = $tag;
  137. $ip->save();
  138. }
  139. //update hosting
  140. $this->hosting()->save();
  141. $this->vm()->updateConfig($container);
  142. DB::commit();
  143. }
  144. catch (\Exception $ex)
  145. {
  146. DB::rollBack();
  147. Api::commit();
  148. throw $ex;
  149. }
  150. }
  151. protected function makeTag()
  152. {
  153. if (is_numeric($this->getWhmcsCustomField(CustomField::TAG)))
  154. {
  155. return $this->getWhmcsCustomField(CustomField::TAG);
  156. }
  157. if (!$this->configuration()->getTagFrom() && !$this->configuration()->getTagTo())
  158. {
  159. return null;
  160. }
  161. $tag = $this->nextTag();
  162. if (!$tag)
  163. {
  164. throw new \Exception("Max VLAN tag have been reached, Please Configure product (Max VLAN tag)");
  165. }
  166. $this->customFieldUpdate("VLAN Tag", $tag);
  167. return $tag;
  168. }
  169. public function nextTag()
  170. {
  171. $cf = "tblcustomfields";
  172. $cv = "tblcustomfieldsvalues";
  173. for ($i = $this->configuration()->getTagFrom(); $i <= $this->configuration()->getTagTo(); $i++)
  174. {
  175. $query = DB::table($cf)
  176. ->select("{$cv}.value")
  177. ->leftJoin($cv, "{$cv}.fieldid", "=", "{$cf}.id")
  178. ->where("{$cf}.type", "product")
  179. ->where("{$cf}.relid", $this->getWhmcsParamByKey("packageid"))
  180. ->where("{$cf}.fieldname", 'like', "VLAN Tag%")
  181. ->where("{$cv}.relid", '!=', $this->getWhmcsParamByKey("serviceid"))
  182. ->where("{$cv}.value", $i);
  183. if ($query->count())
  184. {
  185. continue;
  186. }
  187. return $i;
  188. }
  189. return false;
  190. }
  191. /**
  192. * @return VmIpAddress
  193. */
  194. public function getPrivateIpAddress()
  195. {
  196. $ip = IpAddress::where('private', 1)
  197. ->where('type', 'IPv4')
  198. ->whereIn("sid", [$this->getWhmcsParamByKey('serverid'), "0"])
  199. ->where('hosting_id', '0')
  200. ->firstOrFail();
  201. $newIp = new VmIpAddress();
  202. $newIp->fill($ip->toArray());
  203. $newIp->hosting_id = $this->getWhmcsParamByKey("serviceid");
  204. $newIp->server_id = $this->getWhmcsParamByKey("serverid");
  205. return $newIp;
  206. }
  207. public function hasPrivateIpAddress()
  208. {
  209. $query = IpAddress::where('private', 1)
  210. ->where('type', 'IPv4')
  211. ->whereIn("sid", [$this->getWhmcsParamByKey('serverid'), "0"])
  212. ->where('hosting_id', '0');
  213. return $query->count();
  214. }
  215. public function deleteByNetworkId(array $networkIds)
  216. {
  217. if (is_null($networkIds))
  218. {
  219. throw new \InvalidArgumentException('The network ids cannot be empty');
  220. }
  221. $ipAddresses = VmIpAddress::whereIn("net", $networkIds)->get()->all();
  222. return $this->deleteByIpAddresses($ipAddresses);
  223. }
  224. public function deleteByIpAddresses(array $ipAddresses)
  225. {
  226. if (is_null($ipAddresses))
  227. {
  228. throw new \InvalidArgumentException('The IP Addresses cannot be empty');
  229. }
  230. $devices = $this->vm()->getNetworkDevices();
  231. if($this->configuration()->getPrivateBridge()){
  232. $privateDevices = $this->vm()->getNetworkDevices($this->configuration()->getPrivateBridge());
  233. }
  234. $configDelete = [];
  235. $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
  236. DB::beginTransaction();
  237. Api::beginTransaction();
  238. try
  239. {
  240. foreach ($ipAddresses as &$ip)
  241. {
  242. if (is_numeric($ip))
  243. {
  244. $ip = VmIpAddress::where("id", $ip)->firstOrFail();
  245. }
  246. if (!$ip instanceof VmIpAddress)
  247. {
  248. throw new \InvalidArgumentException(sprintf('The following class are not supported "%s"', get_class($ip)));
  249. };
  250. //private ip
  251. if(!$this->deletePrivateNetwork && isset($privateDevices[0]) && $privateDevices[0] && $privateDevices[0]->getId() == $ip->net){
  252. continue;
  253. }
  254. $ip->delete();
  255. $this->hosting()->ipDelete($ip->ip);
  256. //Unlock ip in Proxmox Addon
  257. IpAddress::where('ip', $ip->ip)
  258. ->where('hosting_id', $ip->hosting_id)
  259. ->update(["hosting_id" => "0", 'last_check' => Utility::timeStamp()]);
  260. foreach ($devices as $deviceIndex => $device)
  261. {
  262. if ($this->configuration()->isOneNetworkDevice() && $device->getId() == "net0")
  263. {
  264. continue;
  265. }
  266. if($device instanceof NetworkDeviceLxc)
  267. {
  268. if ($ip->ip == $device->getIp())
  269. {
  270. $device->setIp(null);
  271. }
  272. if ($ip->ip == $device->getIp6())
  273. {
  274. $device->setIp6(null);
  275. }
  276. if(empty($device->getIp6()) && empty($device->getIp()))
  277. {
  278. unset($devices[$deviceIndex]);
  279. $configDelete[] = $device->getId();
  280. }
  281. }
  282. elseif($device instanceof NetworkDeviceKvm && $ip->net && $ip->net == $device->getId())
  283. {
  284. $configDelete[] = $device->getId();
  285. unset($devices[$deviceIndex]);
  286. }
  287. }
  288. //cloud init
  289. if ($this->vm() instanceof Kvm)
  290. {
  291. foreach ($this->vm()->getIpConfig()->fetch() as $ipConfig)
  292. {
  293. if ($ipConfig->getIp() == $ip->ip || $ipConfig->getIp6() == $ip->ip)
  294. {
  295. $configDelete[] = $ipConfig->getId();
  296. }
  297. }
  298. }
  299. }
  300. $this->hosting()->save();
  301. /**
  302. * Update current config. We need that only if we remove only one IP and other IP is still on the same interface
  303. */
  304. $config = new Config();
  305. $config->setNet($devices);
  306. $config = $config->toArray();
  307. if($config)
  308. {
  309. $this->vm()->updateConfig($config);
  310. }
  311. /**
  312. * Delete config. We need that when there is no more network interface
  313. */
  314. if (!empty($configDelete))
  315. {
  316. $this->vm()->deleteConfig(implode(",", $configDelete));
  317. }
  318. DB::commit();
  319. }
  320. catch (\Exception $ex)
  321. {
  322. DB::rollBack();
  323. Api::commit();
  324. throw $ex;
  325. }
  326. }
  327. public function hasIp($totalIpv4, $totalIpv6, $nodeName)
  328. {
  329. $virtualization = $this->configuration()->isQemu() ? "KVM" : "LXC";
  330. if ((int)$totalIpv4 > 0)
  331. {
  332. /**
  333. * @var $ipCollections IpAddress
  334. */
  335. $ipCollections = IpAddress::where('hosting_id', '0')
  336. ->where('private', '0')
  337. ->where('type', 'IPv4')
  338. ->whereIn('sid', [$this->getWhmcsParamByKey('serverid'), '0'])
  339. ->whereIn('visualization', [$virtualization, 'Auto'])
  340. ->whereIn('node', [$nodeName, '0', ""]);
  341. if ($this->configuration()->getTags())
  342. {
  343. $ipCollections->ofTags($this->configuration()->getTags());
  344. }
  345. $count = $ipCollections->count();
  346. if ((int)$count < $totalIpv4)
  347. {
  348. $errorMessage = sprintf("Unable to get %s of IPv4. IP Addresses available: %s", $totalIpv4, $count);
  349. if($nodeName){
  350. $errorMessage = sprintf("Unable to get %s of IPv4, on node: %s. IP Addresses available: %s", $totalIpv4, $nodeName, $count);
  351. }
  352. throw new \Exception($errorMessage);
  353. }
  354. }
  355. if ((int)$totalIpv6 > 0)
  356. {
  357. $ipCollections = IpAddress::where('hosting_id', '0')
  358. ->where('private', '0')
  359. ->where('type', 'IPv6')
  360. ->whereIn('sid', [$this->getWhmcsParamByKey('serverid'), '0'])
  361. ->whereIn('visualization', [$virtualization, 'Auto'])
  362. ->whereIn('node', [$nodeName, '0', ""]);
  363. if ($this->configuration()->getTags())
  364. {
  365. $ipCollections->ofTags($this->configuration()->getTags());
  366. }
  367. $count = $ipCollections->count();
  368. if ((int)$count < $totalIpv6)
  369. {
  370. $errorMessage = sprintf("Unable to get %s of IPv6. IP Addresses available: %s", $totalIpv6, $count);
  371. if($nodeName){
  372. $errorMessage = sprintf("Unable to get %s of IPv6, on node: %s. IP Addresses available: %s", $totalIpv6, $nodeName, $count);
  373. }
  374. throw new \Exception($errorMessage);
  375. }
  376. }
  377. return $this;
  378. }
  379. public function addIp($totalIpv4, $totalIpv6, $nodeName)
  380. {
  381. try {
  382. DB::beginTransaction();
  383. $virtualization = $this->configuration()->isQemu() ? "KVM" : "LXC";
  384. $this->setHostingId($this->getWhmcsParamByKey('serviceid'));
  385. if ((int)$totalIpv4 > 0) {
  386. $query = IpAddress::where('hosting_id', '0')
  387. ->where('private', '0')
  388. ->where('type', 'IPv4')
  389. ->whereIn('sid', [$this->getWhmcsParamByKey('serverid'), '0'])
  390. ->whereIn('visualization', [$virtualization, 'Auto'])
  391. ->whereIn('node', [$nodeName, '0', ""]);
  392. if ($this->configuration()->getTags()) {
  393. $query->ofTags($this->configuration()->getTags());
  394. }
  395. $count = $query->limit($totalIpv4)
  396. ->orderBy('last_check', 'asc')
  397. ->update(["hosting_id" => $this->getWhmcsParamByKey('serviceid'), 'last_check' => Utility::timeStamp()]);
  398. if ((int)$count < $totalIpv4) {
  399. throw new \Exception(sprintf("Unable to get %s of IPv4. IP Addresses available: %s", $totalIpv4, $count));
  400. }
  401. }
  402. if ((int)$totalIpv6 > 0) {
  403. $query = IpAddress::where('hosting_id', '0')
  404. ->where('private', '0')
  405. ->where('type', 'IPv6')
  406. ->whereIn('sid', [$this->getWhmcsParamByKey('serverid'), '0'])
  407. ->whereIn('visualization', [$virtualization, 'Auto'])
  408. ->whereIn('node', [$nodeName, '0', ""]);
  409. if ($this->configuration()->getTags()) {
  410. $query->ofTags($this->configuration()->getTags());
  411. }
  412. $count = $query->limit($totalIpv6)
  413. ->orderBy('last_check', 'asc')
  414. ->update(["hosting_id" => $this->getWhmcsParamByKey('serviceid'), 'last_check' => Utility::timeStamp()]);
  415. if ((int)$count < $totalIpv6) {
  416. throw new \Exception(sprintf("Unable to get %s of IPv6. IP Addresses available: %s", $totalIpv6, $count));
  417. }
  418. }
  419. $vmIp = (new VmIpAddress())->getTable();
  420. $collection = IpAddress::where('hosting_id', $this->getWhmcsParamByKey('serviceid'))
  421. ->orderBy("ip", "desc")
  422. ->whereNotIn('ip', function ($query) use ($vmIp) {
  423. $query->select('ip')->from($vmIp);
  424. });
  425. foreach ($collection->get()->sortBy("type")->all() as $ip) {
  426. /*@var $ip IpAddress */
  427. $newIp = new VmIpAddress();
  428. $ipData = $ip->toArray();
  429. unset($ipData['id']);
  430. $ipData['hosting_id'] = $this->getWhmcsParamByKey('serviceid');
  431. $ipData['server_id'] = $this->getWhmcsParamByKey('serverid');
  432. $newIp->fill($ipData)->save();
  433. $this->hosting()->ipAdd($ip->ip);
  434. }
  435. $this->hosting()->save();
  436. DB::commit();
  437. } catch (\Exception $ex) {
  438. DB::rollBack();
  439. throw $ex;
  440. }
  441. }
  442. public function deleteIpAddresses()
  443. {
  444. VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))->delete();
  445. //Unlock ip in Proxmox Addon
  446. IpAddress::where('hosting_id', $this->getWhmcsParamByKey('serviceid'))
  447. ->update(["hosting_id" => "0", 'last_check' => Utility::timeStamp()]);
  448. $this->setHostingId($this->getWhmcsParamByKey('serviceid'));
  449. $this->hosting()->dedicatedip = "";
  450. $this->hosting()->assignedips = "";
  451. $this->hosting()->save();
  452. return $this;
  453. }
  454. public function buildLxc()
  455. {
  456. $container = [];
  457. /**
  458. * @var VmIpAddress[] $ipv4
  459. */
  460. $ipv4 = VmIpAddress::ofHostingId($this->getWhmcsParamByKey("serviceid"))
  461. ->ofIp4()
  462. ->ofNetNull()
  463. ->get();
  464. //ip6
  465. $ipv6 = VmIpAddress::ofHostingId($this->getWhmcsParamByKey("serviceid"))
  466. ->ofIp6()
  467. ->ofNetNull()
  468. ->get();
  469. //Network
  470. $bridge = $this->configuration()->getBridge();
  471. $firewall = $this->configuration()->isNetworkFirewall() ? 1 : 0;
  472. $ip4Mode = $this->configuration()->getIpv4NetworkMode();
  473. $ip6Mode = $this->configuration()->getIpv6NetworkMode();
  474. $rate = null;
  475. if ($this->getWhmcsConfigOption(ConfigurableOption::NETWORK_RATE, $this->configuration()->getRate()) && $this->getWhmcsConfigOption(ConfigurableOption::NETWORK_RATE, $this->configuration()->getRate()) != "-1")
  476. {
  477. $rate = $this->getWhmcsConfigOption(ConfigurableOption::NETWORK_RATE, $this->configuration()->getRate());
  478. }
  479. $networkId = 0;
  480. if ($this->hasVm())
  481. {
  482. $networkId = $this->vm()->findFreeNetworDeviceId();
  483. }
  484. for ($i = 0; $i <= 9; $i++)
  485. {
  486. //Empty IP Addresses
  487. if (!$ipv4->get($i) && !$ipv6->get($i))
  488. {
  489. break;
  490. }
  491. if ($networkId > 9)
  492. {
  493. break;
  494. }
  495. $mac = null;
  496. //Name
  497. $interface = new NetworkDeviceLxc('net' . $networkId);
  498. $interface->setName('eth' . $networkId)
  499. ->setBridge($bridge)
  500. ->setFirewall($firewall);
  501. //IP 4
  502. if ($ipv4->get($i))
  503. {
  504. if ($ipv4->get($i)->mac_address)
  505. {
  506. $mac = $ipv4->get($i)->mac_address;
  507. }
  508. if ($ipv4->get($i)->tag)
  509. {
  510. $interface->setTag($ipv4->get($i)->tag);
  511. }
  512. $interface->setTrunks($ipv4->get($i)->trunks);
  513. if ($ip4Mode == 'static')
  514. { //IP & CIRD
  515. $interface->setIp($ipv4->get($i)->ip);
  516. $interface->setCidr($ipv4->get($i)->cidr);
  517. //Gateway
  518. $interface->setGw($ipv4->get($i)->gateway);
  519. }
  520. $ipv4->get($i)->net = $interface->getId();
  521. $ipv4->get($i)->save();
  522. }
  523. if ($ip4Mode == "dhcp")
  524. {
  525. $interface->setIp("dhcp");
  526. }
  527. //IP 6
  528. if ($ip6Mode == "dhcp")
  529. {
  530. $interface->setIp6("dhcp");
  531. }
  532. else
  533. {
  534. if ($ip6Mode == "slaac")
  535. {
  536. $interface->setIp6("auto");
  537. }
  538. }
  539. if ($ipv6->get($i))
  540. { //IP & CIRD
  541. if ($ip6Mode == "static")
  542. {
  543. $interface->setIp6($ipv6->get($i)->ip);
  544. $interface->setCidr6($ipv6->get($i)->cidr);
  545. //Gateway
  546. $interface->setGw6($ipv6->get($i)->gateway);
  547. }
  548. if ($ipv6->get($i)->tag)
  549. {
  550. $interface->setTag($ipv6->get($i)->tag);
  551. }
  552. if ($ipv6->get($i)->trunks)
  553. {
  554. $interface->setTrunks($ipv6->get($i)->trunks);
  555. }
  556. if ($mac == null && $ipv6->get($i)->mac_address)
  557. {
  558. $mac = $ipv6->get($i)->mac_address;
  559. }
  560. $ipv6->get($i)->net = $interface->getId();
  561. $ipv6->get($i)->save();
  562. }
  563. if ($rate)
  564. {
  565. $interface->setRate($rate);
  566. }
  567. $interface->setHwaddr($mac);
  568. $container['net' . $networkId] = $interface->asConfig();
  569. $networkId++;
  570. }
  571. return $container;
  572. }
  573. public function buildQemu()
  574. {
  575. $container = [];
  576. /**
  577. * @var VmIpAddress[] $ipv4
  578. */
  579. $ipv4 = VmIpAddress::ofHostingId($this->getWhmcsParamByKey("serviceid"))
  580. ->ofIp4()
  581. ->ofNetNull()
  582. ->get();
  583. //ip6
  584. $ipv6 = VmIpAddress::ofHostingId($this->getWhmcsParamByKey("serviceid"))
  585. ->ofIp6()
  586. ->ofNetNull()
  587. ->get();
  588. //Network
  589. $model = $this->configuration()->getNetworkModel();
  590. $bridge = $this->configuration()->getBridge();
  591. $firewall = $this->configuration()->isNetworkFirewall() ? 1 : 0;
  592. $rate = null;
  593. if ($this->getWhmcsConfigOption(ConfigurableOption::NETWORK_RATE, $this->configuration()->getRate()) && $this->getWhmcsConfigOption(ConfigurableOption::NETWORK_RATE, $this->configuration()->getRate()) != "-1")
  594. {
  595. $rate = $this->getWhmcsConfigOption(ConfigurableOption::NETWORK_RATE, $this->configuration()->getRate());
  596. }
  597. $networkId = 0;
  598. $vmNetworkDevices = [];
  599. if ($this->hasVm())
  600. {
  601. $networkId = $this->vm()->findFreeNetworDeviceId();
  602. $vmNetworkDevices = $this->vm()->getNetworkDevices();
  603. }
  604. $i4 = 0;
  605. $i6 = 0;
  606. $isApi52 = version_compare($this->api()->getVersion(), "5.2", '>=');
  607. for ($i = 0; $i <= 31; $i++)
  608. {
  609. //Empty IP Addresses
  610. if (!$ipv4->get($i4) && !$ipv6->get($i6))
  611. {
  612. break;
  613. }
  614. if ($networkId > 31)
  615. {
  616. break;
  617. }
  618. if ($this->configuration()->isOneNetworkDevice() && ($i > 0 || count($vmNetworkDevices)))
  619. {
  620. VmIpAddress::ofHostingId($this->getWhmcsParamByKey("serviceid"))
  621. ->ofNetNull()
  622. ->update(["net" => 'net0']);
  623. break;
  624. }
  625. $mac = null;
  626. $isIp4 = false;
  627. //Name
  628. $interface = new NetworkDeviceKvm('net' . $networkId);
  629. $interface->setModel($model)
  630. ->setBridge($bridge)
  631. ->setFirewall($firewall);
  632. $ipConfig = new IpConfig('ipconfig' . $networkId);
  633. //IP 4
  634. if ($ipv4->get($i4))
  635. {
  636. $isIp4 = true;
  637. if (trim($ipv4->get($i4)->mac_address))
  638. {
  639. $mac = $ipv4->get($i4)->mac_address;
  640. }
  641. if ($ipv4->get($i4)->tag)
  642. {
  643. $interface->setTag(trim($ipv4->get($i4)->tag));
  644. }
  645. $interface->setTrunks(trim($ipv4->get($i4)->trunks));
  646. //private ip
  647. if($this->configuration()->getPrivateBridge() && IpAddress::ofHostingId($this->getWhmcsParamByKey("serviceid"))->ofIp($ipv4->get($i4)->ip)->private()->count()){
  648. $interface->setBridge($this->configuration()->getPrivateBridge());
  649. }
  650. $ipConfig->setIp(trim($ipv4->get($i4)->ip));
  651. $ipConfig->setCidr(trim($ipv4->get($i4)->cidr));
  652. //Gateway
  653. $ipConfig->setGw(trim($ipv4->get($i4)->gateway));
  654. $ipv4->get($i4)->net = $interface->getId();
  655. $ipv4->get($i4)->save();
  656. $i4++;
  657. }
  658. //ipv6
  659. if ($ipv6->get($i6) && (!$isIp4 || $interface->getTag() == $ipv6->get($i6)->tag))
  660. { //IP & CIRD
  661. $ipConfig->setIp6(trim($ipv6->get($i6)->ip));
  662. $ipConfig->setCidr6(trim($ipv6->get($i6)->cidr));
  663. //Gateway
  664. $ipConfig->setGw6(trim($ipv6->get($i6)->gateway));
  665. if ($ipv6->get($i6)->tag)
  666. {
  667. $tag = $ipv6->get($i6)->tag;
  668. $interface->setTag(trim($ipv6->get($i6)->tag));
  669. }
  670. if ($ipv6->get($i6)->trunks)
  671. {
  672. $interface->setTrunks(trim($ipv6->get($i6)->trunks));
  673. }
  674. if ($mac == null && $ipv6->get($i6)->mac_address)
  675. {
  676. $mac = $ipv6->get($i6)->mac_address;
  677. }
  678. $ipv6->get($i6)->net = $interface->getId();
  679. $ipv6->get($i6)->save();
  680. $i6++;
  681. }
  682. $interface->setRate(trim($rate));
  683. $interface->setMacAddress(trim($mac));
  684. $interface->setQueues(trim($this->configuration()->getQueues()));
  685. $container[$interface->getId()] = $interface->asConfig();
  686. if ($isApi52 && ($ipConfig->getIp() || $ipConfig->getIp6()))
  687. {
  688. $container[$ipConfig->getId()] = $ipConfig->asConfig();
  689. }
  690. $networkId++;
  691. }
  692. return $container;
  693. }
  694. public function unassignIpAddressesAndDeleteNetwork()
  695. {
  696. list($requestIPv4, $requestIPv6) = $this->getIpAddressesRequest();
  697. $ip4 = [];
  698. $ip6 = [];
  699. if ($requestIPv4 < 0)
  700. {
  701. $ip4 = VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  702. ->ofIp4()
  703. ->ofNetNotNull()
  704. ->limit(abs($requestIPv4))
  705. ->orderByIdDesc()
  706. ->get()
  707. ->all();
  708. }
  709. if ($requestIPv6 < 0)
  710. {
  711. $ip6 = VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  712. ->ofIp6()
  713. ->ofNetNotNull()
  714. ->limit(abs($requestIPv6))
  715. ->orderByIdDesc()
  716. ->get()
  717. ->all();
  718. }
  719. $ipAddresses = array_merge($ip4, $ip6);
  720. if (!empty($ipAddresses))
  721. {
  722. $this->deleteByIpAddresses($ipAddresses);
  723. }
  724. }
  725. public function getIpAddressesRequest()
  726. {
  727. $ipv4Used = (int)VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  728. ->ofIp4()
  729. ->count();
  730. $ipv6Used = (int)VmIpAddress::ofHostingId($this->getWhmcsParamByKey('serviceid'))
  731. ->ofIp6()
  732. ->count();
  733. $requestIPv4 = (int)$this->configuration()->getIpv4();
  734. $requestIPv6 = (int)$this->configuration()->getIpv6();
  735. if ($this->isWhmcsConfigOption(ConfigurableOption::IPV4))
  736. {
  737. $requestIPv4 = (int)$this->getWhmcsConfigOption(ConfigurableOption::IPV4);
  738. }
  739. if ($this->isWhmcsConfigOption(ConfigurableOption::IPV6))
  740. {
  741. $requestIPv6 = (int)$this->getWhmcsConfigOption(ConfigurableOption::IPV6);
  742. }
  743. return [(int)$requestIPv4 -= $ipv4Used, (int)$requestIPv6 -= $ipv6Used];
  744. }
  745. /**
  746. * @param bool $deletePrivateNetwork
  747. * @return NetworkService
  748. */
  749. public function setDeletePrivateNetwork(bool $deletePrivateNetwork): NetworkService
  750. {
  751. $this->deletePrivateNetwork = $deletePrivateNetwork;
  752. return $this;
  753. }
  754. }