api.switchsonic.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. <?php
  2. /**
  3. * Live switch/routers SNMP bandwidth monitoring implementation
  4. */
  5. class SwitchSonic {
  6. /**
  7. * Contains remote device IP address
  8. *
  9. * @var string
  10. */
  11. protected $ip = '';
  12. /**
  13. * Contains remote device SNMP read community
  14. *
  15. * @var string
  16. */
  17. protected $community = '';
  18. /**
  19. * SNMP helper object placeholder
  20. *
  21. * @var object
  22. */
  23. protected $snmp = '';
  24. /**
  25. * Caching engine object placeholder
  26. *
  27. * @var object
  28. */
  29. protected $cache = '';
  30. /**
  31. * Default caching timeout to store switch/auth data in seconds
  32. *
  33. * @var int
  34. */
  35. protected $cachingTimeout = 120;
  36. /**
  37. * Time window to display on charts in seconds
  38. *
  39. * @var int
  40. */
  41. protected $timeWindow = 300;
  42. /**
  43. * Contains default kilo-multiplier to convert bits in Kilo
  44. *
  45. * @var int
  46. */
  47. protected $offsetKilo = 1024;
  48. /**
  49. * Contains default kilo-multiplier to convert bits in Mega
  50. *
  51. * @var int
  52. */
  53. protected $offsetMega = 1024000;
  54. /**
  55. * Contains default kilo-multiplier to convert bits in Giga
  56. *
  57. * @var int
  58. */
  59. protected $offsetGiga = 1024000000;
  60. //some predefined stuff
  61. const CACHE_KEY = 'SWITCHSONICDATA';
  62. const AUTH_KEY = 'SWITCHSONICAUTH';
  63. const OID_CHECK = '.1.3.6.1.2.1.1.1.0';
  64. const OID_IFINDEX = '.1.3.6.1.2.1.2.2.1.1';
  65. const OID_IFDESCR = '.1.3.6.1.2.1.31.1.1.1.18';
  66. const OID_OCTIN = '.1.3.6.1.2.1.31.1.1.1.6';
  67. const OID_OCTOUT = '.1.3.6.1.2.1.31.1.1.1.10';
  68. const OID_STATE = '.1.3.6.1.2.1.2.2.1.8';
  69. /**
  70. * Cretes new Sonic instance
  71. *
  72. * @param string $ip
  73. * @param string $community
  74. */
  75. public function __construct($ip, $community) {
  76. $this->setOptions($ip, $community);
  77. $this->initCache();
  78. $this->initSnmp();
  79. // ___------__
  80. // |\__-- /\ _-
  81. // |/ __ -
  82. // //\ / \ /__
  83. // | o| 0|__ --_
  84. // \\____-- __ \ ___-
  85. // (@@ __/ / /_
  86. // -_____--- --_
  87. // // \ \\ ___-
  88. // //|\__/ \\ \
  89. // \_-\_____/ \-\
  90. // // \\--\|
  91. // ____// ||_
  92. // /_____\ /___\
  93. }
  94. /**
  95. * Sets IP/community to current instance
  96. *
  97. * @param string $ip
  98. * @param string $community
  99. *
  100. * @return void
  101. */
  102. protected function setOptions($ip, $community) {
  103. if (!empty($ip)) {
  104. if (filter_var($ip, FILTER_VALIDATE_IP)) {
  105. if (!empty($community)) {
  106. $this->ip = $ip;
  107. $this->community = $community;
  108. } else {
  109. throw new Exception('EX_EMPTY_SNMPCOMMUNITY');
  110. }
  111. } else {
  112. throw new Exception('EX_WRONG_IP');
  113. }
  114. } else {
  115. throw new Exception('EX_EMPTY_IP');
  116. }
  117. }
  118. /**
  119. * Inits system caching engine
  120. *
  121. * @return void
  122. */
  123. protected function initCache() {
  124. $this->cache = new UbillingCache();
  125. }
  126. /**
  127. * Inits SNMP helper instance for further usage
  128. *
  129. * @return void
  130. */
  131. protected function initSnmp() {
  132. $this->snmp = new SNMPHelper();
  133. $this->snmp->setMode('system');
  134. }
  135. /**
  136. * Returns array of available interfaces on device as port=>iface
  137. *
  138. * @return array
  139. */
  140. protected function getIfaces() {
  141. return($this->receiveOidData(self::OID_IFINDEX));
  142. }
  143. /**
  144. * Returns available ports description as port=>desc
  145. *
  146. * @return array
  147. */
  148. protected function getIfDescr() {
  149. return($this->receiveOidData(self::OID_IFDESCR));
  150. }
  151. /**
  152. * Returns array of interfaces octets in as port=>octets
  153. *
  154. * @return array
  155. */
  156. protected function getOctIn() {
  157. return($this->receiveOidData(self::OID_OCTIN));
  158. }
  159. /**
  160. * Returns array of interfaces octets out as port=>octets
  161. *
  162. * @return array
  163. */
  164. protected function getOctOut() {
  165. return($this->receiveOidData(self::OID_OCTOUT));
  166. }
  167. /**
  168. * Returns array of interface activity states as port=>state up/down
  169. *
  170. * @return array
  171. */
  172. protected function getLinks() {
  173. return($this->receiveOidData(self::OID_STATE));
  174. }
  175. /**
  176. * Checks can we auth on device and receive some data or not?
  177. *
  178. * @return bool
  179. */
  180. public function checkAuth() {
  181. $result = false;
  182. $rawCache = $this->cache->get(self::AUTH_KEY, $this->cachingTimeout);
  183. if (empty($rawCache)) {
  184. $rawCache = array();
  185. }
  186. if (isset($rawCache[$this->ip])) {
  187. $result = true;
  188. } else {
  189. $checkResult = $this->snmp->walk($this->ip, $this->community, self::OID_CHECK, false);
  190. if (!empty($checkResult)) {
  191. $rawCache[$this->ip] = 1;
  192. $this->cache->set(self::AUTH_KEY, $rawCache, $this->cachingTimeout);
  193. $result = true;
  194. }
  195. }
  196. return($result);
  197. }
  198. /**
  199. * Returns port/interface ID extracted from left part of OID
  200. *
  201. * @param string $rawSnmpData
  202. * @param string $oid
  203. *
  204. * @return string
  205. */
  206. protected function extractPortNum($rawSnmpData, $oid) {
  207. $result = '';
  208. $removeMask = $oid . '.';
  209. if (!empty($rawSnmpData)) {
  210. $result = explode('=', $rawSnmpData);
  211. $result = trim($result[0]);
  212. $result = str_replace($removeMask, '', $result);
  213. }
  214. return($result);
  215. }
  216. /**
  217. * Returns preprocessed data extracted from OID as port=>value
  218. *
  219. * @param string $oid
  220. *
  221. * @return array
  222. */
  223. protected function receiveOidData($oid) {
  224. $result = array();
  225. $raw = $this->snmp->walk($this->ip, $this->community, $oid, false);
  226. if (!empty($raw)) {
  227. $raw = explodeRows($raw);
  228. if (!empty($raw)) {
  229. foreach ($raw as $io => $each) {
  230. if (!empty($each)) {
  231. $portNum = $this->extractPortNum($each, $oid);
  232. if (!empty($portNum)) {
  233. $result[$portNum] = zb_SanitizeSNMPValue($each);
  234. }
  235. }
  236. }
  237. }
  238. }
  239. return($result);
  240. }
  241. /**
  242. * Rturns array of preprocessed device stats
  243. *
  244. * @return array
  245. */
  246. public function getStats() {
  247. $devStats = array();
  248. $cachedStats = $this->cache->get(self::CACHE_KEY, $this->cachingTimeout);
  249. if (empty($cachedStats)) {
  250. $cachedStats = array();
  251. }
  252. //initial filling
  253. if (!isset($cachedStats[$this->ip])) {
  254. $devIfindex = $this->getIfaces();
  255. //interfaces index received?
  256. if (!empty($devIfindex)) {
  257. $devPortDesc = $this->getIfDescr();
  258. $devInOcts = $this->getOctIn();
  259. $devOutOcts = $this->getOctOut();
  260. $devLinks = $this->getLinks();
  261. $pollTime = time();
  262. $devStats['lasttime'] = $pollTime;
  263. $devStats['ifaces'] = $devIfindex;
  264. $devStats['portdescr'] = $devPortDesc;
  265. $devStats['previn'] = $devInOcts;
  266. $devStats['prevout'] = $devOutOcts;
  267. $devStats['links'] = $devLinks;
  268. foreach ($devOutOcts as $eachOutPort => $eachOutOct) {
  269. $devStats['speedin'][$eachOutPort] = 0;
  270. $devStats['speedout'][$eachOutPort] = 0;
  271. }
  272. $devStats['speedline'] = array();
  273. }
  274. } else {
  275. $devTmp = $cachedStats[$this->ip];
  276. $newOctIn = $this->getOctIn();
  277. $newOctOut = $this->getOctOut();
  278. $newLinks = $this->getLinks();
  279. $pollTime = time();
  280. $timePast = $pollTime - $devTmp['lasttime'];
  281. $timePast = ($timePast != 0) ? $timePast : 1; //prevent div by zero
  282. foreach ($newOctIn as $io => $eachIn) {
  283. $speedIn = ($eachIn - $devTmp['previn'][$io]) / $timePast;
  284. $rawSpeed = round($speedIn);
  285. $devTmp['speedin'][$io] = $rawSpeed;
  286. $devTmp['speedline'][$io]['in'][$pollTime] = $rawSpeed;
  287. }
  288. foreach ($newOctOut as $io => $eachOut) {
  289. $speedOut = ($eachOut - $devTmp['prevout'][$io]) / $timePast;
  290. $rawSpeed = round($speedOut);
  291. $devTmp['speedout'][$io] = $rawSpeed;
  292. $devTmp['speedline'][$io]['out'][$pollTime] = $rawSpeed;
  293. }
  294. $devStats['lasttime'] = $pollTime;
  295. $devStats['ifaces'] = $devTmp['ifaces'];
  296. $devStats['portdescr'] = $devTmp['portdescr'];
  297. $devStats['previn'] = $newOctIn;
  298. $devStats['prevout'] = $newOctOut;
  299. $devStats['speedin'] = $devTmp['speedin'];
  300. $devStats['speedout'] = $devTmp['speedout'];
  301. $devStats['links'] = $newLinks;
  302. $devStats['speedline'] = $devTmp['speedline'];
  303. }
  304. //cache update
  305. $cachedStats[$this->ip] = $devStats;
  306. $this->cache->set(self::CACHE_KEY, $cachedStats, $this->cachingTimeout);
  307. return($devStats);
  308. }
  309. /**
  310. * Converts actual octet counters into human-readable speed value
  311. *
  312. * @param int $octets
  313. *
  314. * @return string
  315. */
  316. protected function convertSpeed($octets) {
  317. $result = '';
  318. $bits = $octets * 8;
  319. $result = $bits;
  320. if ($bits > $this->offsetKilo) {
  321. $result = round($bits / $this->offsetKilo) . ' ' . __('Kbit/s');
  322. }
  323. if ($bits > $this->offsetMega) {
  324. $result = round($bits / $this->offsetMega, 1) . ' ' . __('Mbit/s');
  325. }
  326. if ($bits > $this->offsetGiga) {
  327. $result = round($bits / $this->offsetGiga, 1) . ' ' . __('Gbit/s');
  328. }
  329. return($result);
  330. }
  331. /**
  332. * Converts octet speed values into Mbit/s
  333. *
  334. * @param int $octetSpeed
  335. *
  336. * @return float
  337. */
  338. protected function speedForCharts($octetSpeed) {
  339. $result = 0;
  340. $bits = $octetSpeed * 8;
  341. $result = $bits / $this->offsetMega;
  342. $result = round($result, 1);
  343. return($result);
  344. }
  345. /**
  346. * Converts basic port infor into link state led
  347. *
  348. * @param string $linkState
  349. * @param int $speedIn
  350. * @param int $speedOut
  351. *
  352. * @return string
  353. */
  354. protected function convertLinkState($linkState, $speedIn = 0, $speedOut = 0) {
  355. $result = '';
  356. $result = (ispos($linkState, 'up')) ? web_green_led() : web_red_led();
  357. if (ispos($linkState, 'up')) {
  358. //ok, interface is up
  359. if ($speedIn OR $speedOut) {
  360. $result = web_green_led('Active');
  361. } else {
  362. $result = web_yellow_led('Link up');
  363. }
  364. } else {
  365. //port is offline at all
  366. $result = web_red_led('Offline');
  367. }
  368. return($result);
  369. }
  370. /**
  371. * Renders device stats
  372. *
  373. * @return string
  374. */
  375. public function renderSpeeds() {
  376. $result = '';
  377. $devStats = $this->getStats();
  378. if (!empty($devStats)) {
  379. $ifaces = $devStats['ifaces'];
  380. $ifdescr = $devStats['portdescr'];
  381. $prevOut = $devStats['prevout'];
  382. $cells = wf_tableCell(__('Interface'), '5%');
  383. $cells .= wf_tableCell(__('Status'), '5%');
  384. $cells .= wf_tableCell(__('Description'));
  385. $cells .= wf_tableCell(__('Speed') . ' ' . __('TX'));
  386. $cells .= wf_tableCell(__('Speed') . ' ' . __('RX'));
  387. $cells .= wf_tableCell(__('Bytes TX'));
  388. $cells .= wf_tableCell(__('Bytes RX'));
  389. $rows = wf_tableRow($cells, 'row1');
  390. foreach ($prevOut as $portNum => $eachPrevOut) {
  391. $speedIn = $devStats['speedin'][$portNum];
  392. $speedOut = $devStats['speedout'][$portNum];
  393. $cells = wf_tableCell($ifaces[$portNum]);
  394. $cells .= wf_tableCell($this->convertLinkState($devStats['links'][$portNum], $speedIn, $speedOut));
  395. $descrLabel = (isset($ifdescr[$portNum])) ? $ifdescr[$portNum] : '';
  396. $cells .= wf_tableCell($descrLabel);
  397. $cells .= wf_tableCell($this->convertSpeed($speedIn));
  398. $cells .= wf_tableCell($this->convertSpeed($speedOut));
  399. $cells .= wf_tableCell(stg_convert_size($devStats['previn'][$portNum]));
  400. $cells .= wf_tableCell(stg_convert_size($devStats['prevout'][$portNum]));
  401. $rows .= wf_tableRow($cells, 'row5');
  402. }
  403. $result .= wf_tableBody($rows, '100%');
  404. } else {
  405. $messages = new UbillingMessageHelper();
  406. $result .= $messages->getStyledMessage(__('Nothing to show'), 'warning');
  407. }
  408. return($result);
  409. }
  410. /**
  411. * Renders charts based on speedline of some ports
  412. *
  413. * @return string
  414. */
  415. public function renderCharts() {
  416. $result = '';
  417. $devStats = $this->getStats();
  418. if (!empty($devStats)) {
  419. $ifaces = $devStats['ifaces'];
  420. $ifdescr = $devStats['portdescr'];
  421. $prevOut = $devStats['prevout'];
  422. $speedLine = $devStats['speedline'];
  423. $options = '';
  424. if (!empty($speedLine)) {
  425. foreach ($speedLine as $portNum => $speedData) {
  426. $csvData = '';
  427. $portLabel = __('Interface') . ' ' . $portNum;
  428. if (isset($ifdescr[$portNum])) {
  429. $portDescr = $ifdescr[$portNum];
  430. if (!empty($portDescr)) {
  431. $portLabel .= ' - ' . $portDescr;
  432. }
  433. foreach ($speedData['in'] as $timeIn => $speedIn) {
  434. $timeLabel = date("Y-m-d H:i:s", $timeIn);
  435. $speedOut = $speedData['out'][$timeIn];
  436. if ($speedIn OR $speedOut) {
  437. $curTime = time();
  438. if (($timeIn) > ($curTime - $this->timeWindow)) {
  439. $inLabel = $this->speedForCharts($speedIn);
  440. $outLabel = $this->speedForCharts($speedOut);
  441. $csvData .= $timeLabel . ',' . $inLabel . ',' . $outLabel . PHP_EOL;
  442. }
  443. }
  444. }
  445. }
  446. if (!empty($csvData)) {
  447. $result .= wf_Graph($csvData, '100%', '200px;', false, $portLabel, __('Time'), __('Mbit/s'), false);
  448. }
  449. }
  450. } else {
  451. $messages = new UbillingMessageHelper();
  452. $result .= $messages->getStyledMessage(__('Nothing to show') . '. ' . __('Collecting data') . '...', 'warning');
  453. }
  454. }
  455. return($result);
  456. }
  457. }