L2Store.php 7.8 KB

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