Zabbix模板資料儲存在哪裡?

潇湘隐者發表於2024-10-18

Zabbix的模板資料儲存在資料庫的哪一個表裡面?以MySQL資料庫為例,在資料庫zabbix中,其實模板資料儲存在hosts這個表裡面,而不是存在hosts_templates表裡面。很多人一看到templates關鍵字,容易先入為主的以為這個表會儲存模板的相關資料。但是實際上,hosts_templates表用於儲存主機和模板之間的關係。這個表允許一個主機與多個模板關聯,對應實際情況中的主機配置多個模板,從而實現監控項、觸發器和圖形的繼承。以下是hosts_templates表的一些重要欄位及其描述:

mysql> desc hosts_templates;
+----------------+-----------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-----------------+------+-----+---------+-------+
| hosttemplateid | bigint unsigned | NO | PRI | NULL | |
| hostid | bigint unsigned | NO | MUL | NULL | |
| templateid | bigint unsigned | NO | MUL | NULL | |
| link_type | int | NO | | 0 | |
+----------------+-----------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql>
mysql> show create table hosts_templates\G
*************************** 1. row ***************************
Table: hosts_templates
Create Table: CREATE TABLE `hosts_templates` (
`hosttemplateid` bigint unsigned NOT NULL,
`hostid` bigint unsigned NOT NULL,
`templateid` bigint unsigned NOT NULL,
`link_type` int NOT NULL DEFAULT '0',
PRIMARY KEY (`hosttemplateid`),
UNIQUE KEY `hosts_templates_1` (`hostid`,`templateid`),
KEY `hosts_templates_2` (`templateid`),
CONSTRAINT `c_hosts_templates_1` FOREIGN KEY (`hostid`) REFERENCES `hosts` (`hostid`) ON DELETE CASCADE,
CONSTRAINT `c_hosts_templates_2` FOREIGN KEY (`templateid`) REFERENCES `hosts` (`hostid`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
1 row in set (0.00 sec)

mysql>

由於模板和主機都儲存在hosts表中,hosts_templates表可以透過hostid或templateid與hosts表進行關聯。這種設計允許靈活地管理主機和模板之間的關係,包括建立層次化的模板結構,其中父模板的設定可以被子模板繼承。

下面我們來看一個簡單的例子,伺服器mysqlu01對映了兩個模板,如下所示:

mysql> select hostid from hosts where name='mysqlu01';
+--------+
| hostid |
+--------+
| 10556 |
+--------+
1 row in set (0.00 sec)

mysql> select * from hosts_templates where hostid=10556;
+----------------+--------+------------+-----------+
| hosttemplateid | hostid | templateid | link_type |
+----------------+--------+------------+-----------+
| 460 | 10556 | 10001 | 0 |
| 461 | 10556 | 10316 | 0 |
+----------------+--------+------------+-----------+
2 rows in set (0.00 sec)

mysql> select name,host from hosts where hostid in(10001,10316);
+-----------------------+-----------------------+
| name | host |
+-----------------------+-----------------------+
| Linux by Zabbix agent | Linux by Zabbix agent |
| MySQL by Zabbix agent | MySQL by Zabbix agent |
+-----------------------+-----------------------+
2 rows in set (0.00 sec)

mysql>

上面例子可以很清楚的展示了模板與主機的關聯關係。這裡就不做過多闡述了。

另外一個問題,既然hosts中儲存了主機和模板的資料,那麼它透過哪一個欄位來表示區分資料是模板資料還是主機資料呢? 其實它是透過hosts中的欄位status來區分的。其中status 代表主機的狀態:它有三個值,0 表示正常監控,1表示未被監控(disable狀態), 3表示該主機是模板。

備註:不清楚是否有狀態為2的記錄。

我們可以驗證一下,例如,在Zabbix的主頁,它提示模板數量有315個,如下所示,那麼

mysql>  select count(*) from hosts where status=3;
+----------+
| count(*) |
+----------+
| 315 |
+----------+
1 row in set (0.00 sec)

mysql>

相關文章