api.ophanimmgr.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. <?php
  2. /**
  3. * Performs basic collector config and execution management
  4. */
  5. class OphanimMgr {
  6. /**
  7. * Contains alter config as key=>value
  8. *
  9. * @var array
  10. */
  11. protected $altCfg = array();
  12. /**
  13. * Contains tracked networks database abstraction layer
  14. *
  15. * @var object
  16. */
  17. protected $networksDb = '';
  18. /**
  19. * Contains system messages helper instance
  20. *
  21. * @var object
  22. */
  23. protected $messages = '';
  24. /**
  25. * Contains preloaded tracking networks list as id=>id/network
  26. *
  27. * @var array
  28. */
  29. protected $allNetworks = array();
  30. /**
  31. * Count of tracked networks
  32. *
  33. * @var int
  34. */
  35. protected $netsCount = 0;
  36. /**
  37. * Contains default sampling rate
  38. *
  39. * @var int
  40. */
  41. protected $samplingRate = 100;
  42. /**
  43. * Contains default collector port
  44. *
  45. * @var int
  46. */
  47. protected $port = 42112;
  48. /**
  49. * Contains networks table structure as field=>index
  50. *
  51. * @var array
  52. */
  53. protected $networksStruct = array();
  54. //some predefined stuff here
  55. const DB_PATCHES_PATH = 'dist/dumps/patches/';
  56. const DB_PATCHES_EXT = '.sql';
  57. const CONF_PATH = '/etc/of.conf';
  58. const PRETAG_PATH = '/etc/pretag.map';
  59. const TEMPLATE_PATH = 'dist/collector/of.template';
  60. const PID_PATH = '/var/run/nfacctd.pid';
  61. const NFT_PATH = '/etc/netflow_templates';
  62. const TABLE_NETWORKS = 'networks';
  63. //and some routes
  64. const URL_ME = '?module=settings';
  65. const PROUTE_NETW_CREATE = 'newnetwork';
  66. const PROUTE_NETW_DESC = 'newnetworkdescr';
  67. const ROUTE_NETW_DEL = 'deletenetwork';
  68. const ROUTE_START = 'startcollector';
  69. const ROUTE_STOP = 'stopcollector';
  70. const ROUTE_RECONF = 'rebuildconfig';
  71. public function __construct($checkDatabaseStruct = false) {
  72. $this->initMessages();
  73. $this->loadConfigs();
  74. $this->initNetsDb();
  75. if ($checkDatabaseStruct) {
  76. $this->loadNetStruct();
  77. }
  78. $this->loadNetworks();
  79. }
  80. /**
  81. * Inits networks database abstraction layer
  82. *
  83. * @return void
  84. */
  85. protected function initNetsDb() {
  86. $this->networksDb = new NyanORM(self::TABLE_NETWORKS);
  87. }
  88. /**
  89. * Inits system messages helper
  90. *
  91. * @return void
  92. */
  93. protected function initMessages() {
  94. $this->messages = new UbillingMessageHelper();
  95. }
  96. /**
  97. * Loads required configs and sets some properties
  98. *
  99. * @return void
  100. */
  101. protected function loadConfigs() {
  102. global $ubillingConfig;
  103. $this->altCfg = $ubillingConfig->getAlter();
  104. $this->port = $this->altCfg['COLLECTOR_PORT'];
  105. $this->samplingRate = $this->altCfg['SAMPLING_RATE'];
  106. }
  107. /**
  108. * Loads tracking networks data from database
  109. *
  110. * @return void
  111. */
  112. protected function loadNetworks() {
  113. $this->allNetworks = $this->networksDb->getAll('id');
  114. $this->netsCount = sizeof($this->allNetworks);
  115. }
  116. /**
  117. * Loads networks database struct and applies some patches if required
  118. *
  119. * @return void
  120. */
  121. protected function loadNetStruct() {
  122. $patchesApplied = false;
  123. $structTmp = $this->networksDb->getTableStructure(true);
  124. $structTmp = array_flip($structTmp);
  125. $this->networksStruct = $structTmp;
  126. //0.0.2 patch
  127. if (!isset($this->networksStruct['descr'])) {
  128. debarr($this->networksStruct);
  129. $this->applyDbPatch('0.0.2');
  130. $patchesApplied = true;
  131. }
  132. //viewport refresh
  133. if ($patchesApplied) {
  134. ubRouting::nav(self::URL_ME);
  135. }
  136. }
  137. /**
  138. * Apllies database patch by its name
  139. *
  140. * @param type $patchName
  141. *
  142. * @return void
  143. */
  144. protected function applyDbPatch($patchName) {
  145. if (!empty($patchName)) {
  146. $patchPath = self::DB_PATCHES_PATH . $patchName . self::DB_PATCHES_EXT;
  147. if (file_exists($patchPath)) {
  148. $patchContent = file_get_contents($patchPath);
  149. if (!empty($patchContent)) {
  150. $patchContent = explode(';', $patchContent);
  151. if (!empty($patchContent)) {
  152. foreach ($patchContent as $io => $eachQuery) {
  153. $eachQuery = trim($eachQuery);
  154. if (!empty($eachQuery)) {
  155. nr_query($eachQuery);
  156. show_success(__('DB patch') . $patchName . ': ' . $eachQuery);
  157. }
  158. }
  159. }
  160. }
  161. }
  162. }
  163. }
  164. /**
  165. * Renders available networks list
  166. *
  167. * @return string
  168. */
  169. public function renderNetworksList() {
  170. $result = '';
  171. if (!empty($this->allNetworks)) {
  172. $cells = wf_TableCell(__('Network'));
  173. if (isset($this->networksStruct['descr'])) {
  174. $cells .= wf_TableCell(__('Description'));
  175. }
  176. $cells .= wf_TableCell(__('Actions'));
  177. $rows = wf_TableRow($cells, 'table-light');
  178. foreach ($this->allNetworks as $io => $each) {
  179. $cells = wf_TableCell($each['network']);
  180. if (isset($this->networksStruct['descr'])) {
  181. $cells .= wf_TableCell($each['descr']);
  182. }
  183. $delUrl = self::URL_ME . '&' . self::ROUTE_NETW_DEL . '=' . $each['id'];
  184. $actLinks = wf_JSAlertStyled($delUrl, __('Delete'), __('Are you serious') . '?', 'btn cur-p btn-danger btn-color');
  185. $cells .= wf_TableCell($actLinks);
  186. $rows .= wf_TableRow($cells, '');
  187. }
  188. $result .= wf_TableBody($rows, '100%', 0, 'table');
  189. } else {
  190. $result .= $this->messages->getStyledMessage(__('Nothing to show'), 'warning');
  191. }
  192. return ($result);
  193. }
  194. /**
  195. * Renders new network creation form
  196. *
  197. * @return string
  198. */
  199. public function renderNetworkCreateForm() {
  200. $result = '';
  201. $inputs = wf_TextInput(self::PROUTE_NETW_CREATE, __('Network') . '/CIDR', '', false, '20', 'net-cidr') . ' ';
  202. $inputs .= wf_TextInput(self::PROUTE_NETW_DESC, __('Description'), '', false, '20', '') . ' ';
  203. $inputs .= wf_Submit(__('Create new'), '', 'class="btn btn-primary btn-color"');
  204. $result .= wf_delimiter();
  205. $result .= wf_Form('', 'POST', $inputs, 'glamour');
  206. return ($result);
  207. }
  208. /**
  209. * Checks is some network exists by its ID
  210. *
  211. * @param int $networkId
  212. *
  213. * @return bool
  214. */
  215. public function isNetworkIdExists($networkId) {
  216. $result = false;
  217. if (isset($this->allNetworks[$networkId])) {
  218. $result = true;
  219. }
  220. return ($result);
  221. }
  222. /**
  223. * Check is some network exists by its CIDR
  224. *
  225. * @param string $network
  226. *
  227. * @return bool
  228. */
  229. public function isNetworkExists($network) {
  230. $result = false;
  231. if (!empty($this->allNetworks)) {
  232. foreach ($this->allNetworks as $io => $each) {
  233. if ($each['network'] == $network) {
  234. $result = true;
  235. }
  236. }
  237. }
  238. return ($result);
  239. }
  240. /**
  241. * Creates new network database record
  242. *
  243. * @param string $network
  244. * @param string $descr
  245. *
  246. * @return void
  247. */
  248. public function createNetwork($network, $descr = '') {
  249. $netF = ubRouting::filters($network, 'mres');
  250. $descrF = ubRouting::filters($descr, 'mres');
  251. if (!$this->isNetworkExists($network)) {
  252. $this->networksDb->data('network', $netF);
  253. $this->networksDb->data('descr', $descrF);
  254. $this->networksDb->create();
  255. }
  256. }
  257. /**
  258. * Deletes some network from database
  259. *
  260. * @param int $networkId
  261. *
  262. * @return void
  263. */
  264. public function deleteNetwork($networkId) {
  265. $networkId = ubRouting::filters($networkId, 'int');
  266. if ($this->isNetworkIdExists($networkId)) {
  267. $this->networksDb->where('id', '=', $networkId);
  268. $this->networksDb->delete();
  269. }
  270. }
  271. /**
  272. * Returns pretag map for existing networks
  273. *
  274. * @return string
  275. */
  276. public function generatePretagMap() {
  277. $result = '';
  278. $vlansFlag = false;
  279. if (isset($this->altCfg['CONSIDER_VLANS'])) {
  280. if ($this->altCfg['CONSIDER_VLANS']) {
  281. $vlansFlag = true;
  282. }
  283. }
  284. if (!empty($this->allNetworks)) {
  285. $srcId = 1;
  286. foreach ($this->allNetworks as $io => $each) {
  287. $result .= "id=" . $srcId . " filter='src net " . $each['network'] . "'" . PHP_EOL;
  288. if ($vlansFlag) {
  289. $result .= "id=" . $srcId . " filter='vlan and src net " . $each['network'] . "'" . PHP_EOL;
  290. }
  291. $srcId++;
  292. }
  293. $dstId = $this->netsCount + 1;
  294. foreach ($this->allNetworks as $io => $each) {
  295. $result .= "id=" . $dstId . " filter='dst net " . $each['network'] . "'" . PHP_EOL;
  296. if ($vlansFlag) {
  297. $result .= "id=" . $dstId . " filter='vlan and dst net " . $each['network'] . "'" . PHP_EOL;
  298. }
  299. $dstId++;
  300. }
  301. }
  302. return ($result);
  303. }
  304. /**
  305. * Generates collector config
  306. *
  307. * @return string
  308. */
  309. public function generateConfig() {
  310. $result = '';
  311. if (!empty($this->allNetworks)) {
  312. $dbConfig = rcms_parse_ini_file('config/mysql.ini');
  313. $template = file_get_contents(self::TEMPLATE_PATH);
  314. $result = $template;
  315. if ($this->netsCount == 1) {
  316. $srcRange = 1;
  317. $dstRange = 2;
  318. } else {
  319. $srcLo = 1;
  320. $srcHi = $this->netsCount;
  321. $dstLo = $this->netsCount + 1;
  322. $dstHi = $this->netsCount + $this->netsCount;
  323. $srcRange = $srcLo . '-' . $srcHi;
  324. $dstRange = $dstLo . '-' . $dstHi;
  325. }
  326. $result = str_replace('{PORT}', $this->port, $result);
  327. $result = str_replace('{NETFLOW_TEMPLATES_PATH}', self::NFT_PATH, $result);
  328. $result = str_replace('{SAMPLING_RATE}', $this->samplingRate, $result);
  329. $result = str_replace('{PRETAG_PATH}', self::PRETAG_PATH, $result);
  330. $result = str_replace('{PID_PATH}', self::PID_PATH, $result);
  331. $result = str_replace('{SRC_RANGE}', $srcRange, $result);
  332. $result = str_replace('{DST_RANGE}', $dstRange, $result);
  333. $result = str_replace('{MYSQLUSER}', $dbConfig['username'], $result);
  334. $result = str_replace('{MYSQLPASSWORD}', $dbConfig['password'], $result);
  335. }
  336. return ($result);
  337. }
  338. /**
  339. * Checks for running collector process
  340. *
  341. * @return bool
  342. */
  343. public function isCollectorRunning() {
  344. $result = false;
  345. if (file_exists(self::PID_PATH)) {
  346. $result = true;
  347. }
  348. return ($result);
  349. }
  350. /**
  351. * Renders collector process conrols depends on it state
  352. *
  353. * @return string
  354. */
  355. public function renderCollectorControls() {
  356. $result = '';
  357. if ($this->isCollectorRunning()) {
  358. $collectorLabel = '';
  359. $collectorLabel .= __('Netflow collector is running at port') . ' ' . $this->port . ', ' . __('sampling rate') . ': ' . $this->samplingRate;
  360. $result .= $this->messages->getStyledMessage($collectorLabel, 'success');
  361. $result .= wf_delimiter();
  362. $result .= wf_Link(self::URL_ME . '&' . self::ROUTE_STOP . '=true', __('Stop collector'), false, 'btn cur-p btn-danger btn-color');
  363. } else {
  364. $result .= $this->messages->getStyledMessage(__('Netflow collector is stopped'), 'warning');
  365. $result .= wf_delimiter();
  366. if (!empty($this->allNetworks)) {
  367. $result .= wf_Link(self::URL_ME . '&' . self::ROUTE_RECONF . '=true', __('Rebuild configuration'), false, 'btn cur-p btn-dark btn-color') . ' ';
  368. $result .= wf_Link(self::URL_ME . '&' . self::ROUTE_START . '=true', __('Start collector'), false, 'btn cur-p btn-success btn-color');
  369. }
  370. }
  371. $result .= wf_delimiter();
  372. return ($result);
  373. }
  374. /**
  375. * Rebuilds pretag map and collector config
  376. *
  377. * @return void/string
  378. */
  379. public function rebuildConfigs() {
  380. $result = '';
  381. if (!$this->isCollectorRunning()) {
  382. if (file_exists(self::CONF_PATH) and file_exists(self::PRETAG_PATH)) {
  383. if (is_writable(self::CONF_PATH) and is_writable(self::PRETAG_PATH)) {
  384. if (!empty($this->allNetworks)) {
  385. $pretagMap = $this->generatePretagMap();
  386. $mainConf = $this->generateConfig();
  387. file_put_contents(self::PRETAG_PATH, $pretagMap);
  388. file_put_contents(self::CONF_PATH, $mainConf);
  389. } else {
  390. $result .= __('Networks list is empty');
  391. }
  392. } else {
  393. $result .= self::CONF_PATH . ' ' . __('or') . ' ' . self::PRETAG_PATH . ' ' . __('is not writable');
  394. }
  395. } else {
  396. $result .= self::CONF_PATH . ' ' . __('or') . ' ' . self::PRETAG_PATH . ' ' . __('config files not exists');
  397. }
  398. } else {
  399. $result .= __('Collector is running now');
  400. }
  401. return ($result);
  402. }
  403. /**
  404. * Starts new collector process
  405. *
  406. * @return void/string
  407. */
  408. public function startCollector() {
  409. $result = '';
  410. if (!$this->isCollectorRunning()) {
  411. $command = $this->altCfg['SUDO_PATH'] . ' ' . $this->altCfg['COLLECTOR_PATH'] . ' -f ' . self::CONF_PATH;
  412. shell_exec($command);
  413. sleep(3);
  414. if (!$this->isCollectorRunning()) {
  415. $result .= __('Collector startup failed by unknown reason');
  416. }
  417. } else {
  418. $result .= __('Collector is running now');
  419. }
  420. return ($result);
  421. }
  422. /**
  423. * Brutally kills collector process
  424. *
  425. * @return void
  426. */
  427. public function stopCollector() {
  428. if ($this->isCollectorRunning()) {
  429. //shittiest way ever
  430. $command = $this->altCfg['SUDO_PATH'] . ' ' . $this->altCfg['KILLALL_PATH'] . ' -9 nfacctd';
  431. shell_exec($command);
  432. $pidRemove = $this->altCfg['SUDO_PATH'] . ' ' . $this->altCfg['RM_PATH'] . ' -fr ' . self::PID_PATH;
  433. shell_exec($pidRemove);
  434. }
  435. }
  436. /**
  437. * Retrieves all networks as id=>networkData
  438. *
  439. * @return array
  440. */
  441. public function getAllNetworks() {
  442. return ($this->allNetworks);
  443. }
  444. }