NetworkService.php 30 KB

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