L2Store.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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' => 3.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. DB::execute(
  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. DB::execute(
  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. try {
  102. $rows = DB::select('SELECT config FROM '.self::CONFIG_TABLE.' WHERE id='.self::CONFIG_ID);
  103. if ($rows && isset($rows[0]['config'])) {
  104. $saved = json_decode((string) $rows[0]['config'], true);
  105. if (is_array($saved)) {
  106. $cfg = self::mergeDeep($cfg, $saved);
  107. }
  108. }
  109. }
  110. catch (Throwable $e) {
  111. // fall back to defaults
  112. }
  113. // Make sure the out-of-process collectors can always read the config
  114. // (write it once if the mirror file is still missing).
  115. $mirror = dirname(__DIR__).'/assets/l2topology/config.json';
  116. if (!is_file($mirror)) {
  117. self::writeMirror($cfg);
  118. }
  119. return $cfg;
  120. }
  121. public static function saveConfig(array $cfg): void {
  122. self::ensureSchema();
  123. $cfg = self::mergeDeep(self::defaults(), $cfg);
  124. $json = json_encode($cfg, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  125. try {
  126. DB::execute(
  127. 'INSERT INTO '.self::CONFIG_TABLE.' (id, config, updated) VALUES ('.self::CONFIG_ID.', ?, UTC_TIMESTAMP())'.
  128. ' ON DUPLICATE KEY UPDATE config=VALUES(config), updated=VALUES(updated)',
  129. [$json]
  130. );
  131. }
  132. catch (Throwable $e) {
  133. }
  134. self::writeMirror($cfg);
  135. }
  136. /** Mirror config to a JSON file so the out-of-process collectors can read it. */
  137. public static function writeMirror(array $cfg): void {
  138. $file = dirname(__DIR__).'/assets/l2topology/config.json';
  139. try {
  140. $tmp = $file.'.tmp';
  141. file_put_contents($tmp, json_encode($cfg, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  142. @chmod($tmp, 0644);
  143. @rename($tmp, $file);
  144. }
  145. catch (Throwable $e) {
  146. }
  147. }
  148. /** Newest-first list of stored snapshots (for the time selector). */
  149. public static function listHistory(int $limit = 500): array {
  150. $out = [];
  151. try {
  152. $rows = DB::select(
  153. 'SELECT ts, captured_at, stats FROM '.self::HISTORY_TABLE.' ORDER BY ts DESC LIMIT '.max(1, $limit)
  154. );
  155. foreach ($rows as $r) {
  156. $out[] = [
  157. 'ts' => (int) $r['ts'],
  158. 'captured_at' => (string) $r['captured_at'],
  159. 'stats' => json_decode((string) $r['stats'], true)
  160. ];
  161. }
  162. }
  163. catch (Throwable $e) {
  164. }
  165. return $out;
  166. }
  167. /**
  168. * Snapshot JSON at (or just before) $ts. When $ts is null the newest stored
  169. * snapshot is used, falling back to the live snapshot.json file.
  170. */
  171. public static function snapshotAt(?int $ts): array {
  172. $json = null;
  173. $used = $ts;
  174. try {
  175. if ($ts === null) {
  176. $rows = DB::select('SELECT ts, snapshot FROM '.self::HISTORY_TABLE.' ORDER BY ts DESC LIMIT 1');
  177. }
  178. else {
  179. $rows = DB::select(
  180. 'SELECT ts, snapshot FROM '.self::HISTORY_TABLE.' WHERE ts<=? ORDER BY ts DESC LIMIT 1',
  181. [$ts]
  182. );
  183. }
  184. if ($rows) {
  185. $blob = $rows[0]['snapshot'];
  186. $raw = @gzdecode($blob);
  187. if ($raw !== false && $raw !== '') {
  188. $json = $raw;
  189. $used = (int) $rows[0]['ts'];
  190. }
  191. }
  192. }
  193. catch (Throwable $e) {
  194. }
  195. if ($json === null && $ts === null) {
  196. $file = dirname(__DIR__).'/assets/l2topology/snapshot.json';
  197. if (is_readable($file)) {
  198. $raw = file_get_contents($file);
  199. if ($raw !== false && $raw !== '') {
  200. $json = $raw;
  201. }
  202. }
  203. }
  204. return ['json' => $json, 'ts' => ($json !== null ? $used : null)];
  205. }
  206. private static function mergeDeep(array $base, array $over): array {
  207. foreach ($over as $k => $v) {
  208. if (is_array($v) && isset($base[$k]) && is_array($base[$k]) && self::isAssoc($base[$k])) {
  209. $base[$k] = self::mergeDeep($base[$k], $v);
  210. }
  211. else {
  212. $base[$k] = $v;
  213. }
  214. }
  215. return $base;
  216. }
  217. private static function isAssoc(array $a): bool {
  218. return array_keys($a) !== range(0, count($a) - 1);
  219. }
  220. }