L2Store.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php declare(strict_types = 0);
  2. /*
  3. ** L2 Topology - persistence & configuration layer.
  4. **
  5. ** Two tables are auto-created (portable: works on any Zabbix DB the web user
  6. ** can write to; the compose init sidecar also creates them as root):
  7. **
  8. ** l2_topology_history : one compressed snapshot per configured interval
  9. ** l2_topology_config : single row (id=1) holding every display/collection knob
  10. **
  11. ** Snapshots are gzip-compressed MEDIUMBLOBs. At the default 5-minute
  12. ** interval a full week is ~70-100 MB (measured ~33 KB per compressed
  13. ** snapshot), instead of >1 GB of raw JSON.
  14. */
  15. namespace Modules\WecomCenter\Lib;
  16. use DB;
  17. use Throwable;
  18. class L2Store {
  19. public const HISTORY_TABLE = 'l2_topology_history';
  20. public const CONFIG_TABLE = 'l2_topology_config';
  21. public const CONFIG_ID = 1;
  22. /** Full default configuration. Every key can be overridden from the UI. */
  23. public static function defaults(): array {
  24. return [
  25. // Display page ------------------------------------------------------
  26. 'refresh_seconds' => 300, // auto-refresh of the live view
  27. 'root_label' => 'COBCO', // outermost frame label
  28. // Physical networks. A switch belongs to the first network whose
  29. // keyword appears in its name or IP; adjacency is used as fallback.
  30. // key | label | keyword1,keyword2 | colour
  31. 'networks' => [
  32. ['key' => 'SURVE', 'label' => 'SURVE 监控网', 'keywords' => ['SURVE', '10.169.'], 'color' => '#2E75B6'],
  33. ['key' => 'OFFICE', 'label' => 'OFFICE 办公网', 'keywords' => ['OFFICE', '10.160.'], 'color' => '#548235']
  34. ],
  35. // Root/core switches. A network may have more than one core; every
  36. // match is drawn in the left-most core column. match = contains|regex.
  37. 'core_rules' => [
  38. ['net' => 'SURVE', 'match' => 'contains', 'pattern' => 'core surve'],
  39. ['net' => 'OFFICE', 'match' => 'contains', 'pattern' => 'core office']
  40. ],
  41. // Collection --------------------------------------------------------
  42. 'templates' => ['Huawei VRP by SNMP (walk)'],
  43. 'full_interval_min' => 5, // full topology/port collection
  44. 'alarm_interval_min'=> 1, // alarm-only refresh
  45. 'history_interval_min' => 5, // one DB snapshot per N minutes
  46. 'history_days' => 7, // retention window, hard-pruned
  47. // Link colours (bits per second bucket) -----------------------------
  48. 'colors' => [
  49. '100' => '#F39C12', // 100M 橙色
  50. '1000' => '#2ECC71', // 1G 绿色
  51. '10000' => '#3498DB', // 10G 蓝色
  52. '20000' => '#9B59B6', // 20G+ 紫色
  53. 'unknown' => '#E74C3C', // 未知 红色
  54. 'down' => '#C0392B' // 中断 红色
  55. ],
  56. // Latency thresholds (ms) applied to switch nodes (host->switch ping)
  57. 'latency_warn' => 1.0,
  58. 'latency_bad' => 5.0,
  59. // Grouping rules: first matching rule wins, else "Other".
  60. // match = contains | regex ; label may contain $1..$9 backrefs.
  61. 'group_rules' => [
  62. ['match' => 'contains', 'pattern' => 'DataCenter', 'label' => 'DataCenter', 'big' => true],
  63. ['match' => 'contains', 'pattern' => 'Core', 'label' => 'Core', 'big' => true],
  64. ['match' => 'regex', 'pattern' => 'COBCO-(\\d{4}[A-Za-z]?)', 'label' => '$1', 'big' => false],
  65. ['match' => 'regex', 'pattern' => '^(\\d{4}[A-Za-z]?)', 'label' => '$1', 'big' => false]
  66. ],
  67. 'other_label' => 'Other'
  68. ];
  69. }
  70. /** Create tables if absent. Safe to call on every request (idempotent). */
  71. public static function ensureSchema(): void {
  72. try {
  73. \DBexecute(
  74. 'CREATE TABLE IF NOT EXISTS '.self::HISTORY_TABLE.' ('.
  75. ' id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,'.
  76. ' ts BIGINT UNSIGNED NOT NULL,'.
  77. ' captured_at DATETIME NOT NULL,'.
  78. ' stats TEXT NOT NULL,'.
  79. ' snapshot MEDIUMBLOB NOT NULL,'.
  80. ' PRIMARY KEY (id),'.
  81. ' KEY idx_l2_ts (ts)'.
  82. ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin'
  83. );
  84. \DBexecute(
  85. 'CREATE TABLE IF NOT EXISTS '.self::CONFIG_TABLE.' ('.
  86. ' id TINYINT UNSIGNED NOT NULL,'.
  87. ' config LONGTEXT NOT NULL,'.
  88. ' updated DATETIME NOT NULL,'.
  89. ' PRIMARY KEY (id)'.
  90. ') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin'
  91. );
  92. }
  93. catch (Throwable $e) {
  94. // Table may already exist or the DB user may lack DDL rights; the
  95. // compose init sidecar / install doc handles that case. Never fail a page.
  96. }
  97. }
  98. public static function getConfig(): array {
  99. self::ensureSchema();
  100. $cfg = self::defaults();
  101. $mirror = dirname(__DIR__).'/assets/l2topology/config.json';
  102. try {
  103. // Module tables are not in Zabbix's table-schema cache, so use the
  104. // raw DBselect()/DBfetch() helpers rather than DB::select().
  105. $cursor = \DBselect('SELECT config FROM '.self::CONFIG_TABLE.' WHERE id='.self::CONFIG_ID);
  106. $row = \DBfetch($cursor);
  107. $rows = $row ? [$row] : [];
  108. if ($rows && isset($rows[0]['config'])) {
  109. $saved = json_decode((string) $rows[0]['config'], true);
  110. if (is_array($saved)) {
  111. $cfg = self::mergeDeep($cfg, $saved);
  112. }
  113. }
  114. else if (is_readable($mirror)) {
  115. // Keep working when the table could not be created yet but the
  116. // collector mirror was written by an earlier save.
  117. $saved = json_decode((string) @file_get_contents($mirror), true);
  118. if (is_array($saved)) {
  119. $cfg = self::mergeDeep($cfg, $saved);
  120. }
  121. }
  122. }
  123. catch (Throwable $e) {
  124. // fall back to defaults
  125. }
  126. // Make sure the out-of-process collectors can always read the config
  127. // (write it once if the mirror file is still missing).
  128. if (!is_file($mirror)) {
  129. self::writeMirror($cfg);
  130. }
  131. return $cfg;
  132. }
  133. public static function saveConfig(array $cfg): void {
  134. self::ensureSchema();
  135. $cfg = self::mergeDeep(self::defaults(), $cfg);
  136. $json = json_encode($cfg, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  137. try {
  138. \DBexecute(
  139. 'INSERT INTO '.self::CONFIG_TABLE.' (id, config, updated) VALUES ('.
  140. self::CONFIG_ID.', '.\zbx_dbstr($json).', UTC_TIMESTAMP())'.
  141. ' ON DUPLICATE KEY UPDATE config=VALUES(config), updated=VALUES(updated)'
  142. );
  143. }
  144. catch (Throwable $e) {
  145. error_log('L2Store::saveConfig failed: '.$e->getMessage());
  146. }
  147. self::writeMirror($cfg);
  148. }
  149. /** Mirror config to a JSON file so the out-of-process collectors can read it. */
  150. public static function writeMirror(array $cfg): void {
  151. $file = dirname(__DIR__).'/assets/l2topology/config.json';
  152. try {
  153. $tmp = $file.'.tmp';
  154. file_put_contents($tmp, json_encode($cfg, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  155. @chmod($tmp, 0644);
  156. @rename($tmp, $file);
  157. }
  158. catch (Throwable $e) {
  159. }
  160. }
  161. /** Newest-first list of stored snapshots (for the time selector). */
  162. public static function listHistory(int $limit = 500): array {
  163. $out = [];
  164. try {
  165. $cursor = \DBselect(
  166. 'SELECT ts, captured_at, stats FROM '.self::HISTORY_TABLE.
  167. ' ORDER BY ts DESC LIMIT '.max(1, $limit)
  168. );
  169. while ($r = \DBfetch($cursor)) {
  170. $out[] = [
  171. 'ts' => (int) $r['ts'],
  172. 'captured_at' => (string) $r['captured_at'],
  173. 'stats' => json_decode((string) $r['stats'], true)
  174. ];
  175. }
  176. }
  177. catch (Throwable $e) {
  178. // No history yet / table not ready: the selector simply stays empty.
  179. }
  180. return $out;
  181. }
  182. /**
  183. * Snapshot JSON at the exact recorded $ts. When $ts is null the newest
  184. * stored snapshot is used, falling back to the live snapshot.json file.
  185. */
  186. public static function snapshotAt(?int $ts): array {
  187. $json = null;
  188. $used = $ts;
  189. try {
  190. if ($ts === null) {
  191. $cursor = \DBselect(
  192. 'SELECT ts, snapshot FROM '.self::HISTORY_TABLE.' ORDER BY ts DESC LIMIT 1'
  193. );
  194. $row = \DBfetch($cursor);
  195. $rows = $row ? [$row] : [];
  196. }
  197. else {
  198. // The UI only offers exact recorded timestamps. Querying by
  199. // exact ts prevents an arbitrary URL from silently showing
  200. // the nearest (wrong) snapshot.
  201. $cursor = \DBselect(
  202. 'SELECT ts, snapshot FROM '.self::HISTORY_TABLE.
  203. ' WHERE ts='.(int) $ts.' LIMIT 1'
  204. );
  205. $row = \DBfetch($cursor);
  206. $rows = $row ? [$row] : [];
  207. }
  208. if ($rows) {
  209. $blob = $rows[0]['snapshot'];
  210. $raw = @gzdecode($blob);
  211. if ($raw !== false && $raw !== '') {
  212. $json = $raw;
  213. $used = (int) $rows[0]['ts'];
  214. }
  215. }
  216. }
  217. catch (Throwable $e) {
  218. }
  219. if ($json === null && $ts === null) {
  220. $file = dirname(__DIR__).'/assets/l2topology/snapshot.json';
  221. if (is_readable($file)) {
  222. $raw = file_get_contents($file);
  223. if ($raw !== false && $raw !== '') {
  224. $json = $raw;
  225. }
  226. }
  227. }
  228. return ['json' => $json, 'ts' => ($json !== null ? $used : null)];
  229. }
  230. private static function mergeDeep(array $base, array $over): array {
  231. foreach ($over as $k => $v) {
  232. if (is_array($v) && isset($base[$k]) && is_array($base[$k]) && self::isAssoc($base[$k])) {
  233. $base[$k] = self::mergeDeep($base[$k], $v);
  234. }
  235. else {
  236. $base[$k] = $v;
  237. }
  238. }
  239. return $base;
  240. }
  241. private static function isAssoc(array $a): bool {
  242. return array_keys($a) !== range(0, count($a) - 1);
  243. }
  244. }