GLPI-Zabbix 集成插件开发文档
1. 项目概述
1.1 系统架构
系统整体架构图展示了GLPI与Zabbix的集成关系:
- GLPI系统负责资产管理、工单处理和监控展示
- Zabbix系统负责数据采集、告警触发和API接口提供
- 两系统通过API进行数据同步和告警联动
1.2 功能模块
功能模块思维导图展示了插件的核心功能:
- 监控展示:提供实时监控数据和可视化图表
- 告警管理:实现告警规则配置和工单自动创建
- 资产集成:确保GLPI和Zabbix资产数据同步
- 单点登录:提供安全的跨系统认证机制
mindmap
root((GLPI-Zabbix<br/>集成))
监控展示
主机状态
性能指标
历史数据
图表展示
告警管理
告警规则
工单联动
自动处理
状态同步
资产集成
主机映射
资产同步
配置管理
单点登录
SSO认证
安全控制
会话管理
1.3 技术特点
-
双向数据同步
- GLPI资产自动同步到Zabbix监控
- Zabbix告警自动创建GLPI工单
- 支持增量同步和全量同步
-
高性能设计
- 采用多级缓存机制
- 异步任务处理
- 分布式部署支持
-
安全机制
- SSO安全认证
- API访问控制
- 数据加密传输
-
扩展性
- 插件化架构
- 自定义监控模板
- 灵活的告警规则
1.4 使用场景
-
IT基础设施监控
- 服务器性能监控
- 网络设备状态监控
- 数据库运行监控
-
业务系统监控
- 应用服务可用性监控
- 业务指标监控
- 接口调用监控
-
自动化运维
- 告警自动处理
- 工单自动分派
- 问题自动诊断
2. 技术架构
2.1 系统要求
2.1.1 GLPI 版本支持
- 完整支持: GLPI 10.0.x (最新版本 10.0.10)
- 兼容支持: GLPI 9.5.x (最低要求 9.5.7)
- 推荐版本: GLPI 10.0.10
- 特别说明:
- GLPI 10.0.x 引入新的插件架构
- 支持新版本的资产管理功能
- 提供更完善的API接口
2.1.2 Zabbix 版本支持
- 完整支持: Zabbix 6.4.x (最新版本 6.4.10)
- 兼容支持: Zabbix 6.0.x (最低要求 6.0.19)
- 推荐版本: Zabbix 6.4.10
- 特别说明:
- Zabbix 6.4.x 提供更强大的API功能
- 支持高级告警管理
- 优化的数据采集性能
2.1.3 其他环境要求
- PHP >= 8.1 (推荐 8.2)
- MySQL >= 8.0 / MariaDB >= 10.6
- Web Server: Apache 2.4+ / Nginx 1.18+
- 内存: 8GB及以上
- 存储: 50GB及以上(取决于监控规模)
2.1.4 版本兼容性说明
GLPI版本 | Zabbix版本 | 插件支持情况 |
---|---|---|
10.0.10 | 6.4.x | 完整支持 |
10.0.x | 6.4.x | 完整支持 |
10.0.x | 6.0.x | 基本支持 |
9.5.x | 6.0.x | 有限支持 |
2.2 项目结构
plugin-root/
├── front/
│ ├── config.form.php
│ ├── monitor.php
│ └── sso.php
├── inc/
│ ├── config.class.php
│ ├── monitor.class.php
│ ├── zabbix.class.php
│ └── ticket.class.php
├── ajax/
│ └── getmonitoring.php
├── setup.php
└── hook.php
2.3 部署架构
部署架构图说明了系统各层级的部署关系:
- 前端层:处理用户交互和SSO认证
- 应用层:运行GLPI和Zabbix核心服务
- 服务层:提供业务逻辑和数据处理
- 数据层:存储配置信息和监控数据
2.4 插件依赖
-
必需依赖
- PHP >= 7.4
- MySQL/MariaDB >= 5.7
- GLPI >= 10.0.0
- Zabbix >= 6.0
-
推荐依赖
- Redis >= 6.0 (缓存)
- RabbitMQ >= 3.8 (消息队列)
- Elasticsearch >= 7.0 (日志分析)
2.5 性能要求
-
硬件配置
- CPU: 4核心及以上
- 内存: 8GB及以上
- 存储: 50GB及以上
-
网络要求
- GLPI与Zabbix间带宽: >=100Mbps
- 网络延迟: <=100ms
3. 关键流程实现
3.1 数据交互流程
交互流程图展示了系统间的数据流转:
- 用户发起监控数据请求的处理流程
- 插件模块与Zabbix API的交互过程
- 告警触发后的工单创建流程
3.2 组件关系
组件类图展示了核心类的关系:
- PluginZabbixConfig负责配置管理
- PluginZabbixAPI处理与Zabbix的通信
- 两个组件之间的依赖关系
3.3 核心代码实现
3.3.1 Zabbix API 集成类
/**
- Zabbix API集成核心类
- 功能:
-
- 提供与Zabbix API的通信接口
-
- 处理监控数据获取
-
- 管理告警信息查询
- 实现要点:
-
- 支持API认证和会话管理
-
- 实现数据查询和转换
-
- 处理异常情况和错误重试
*/
- 处理异常情况和错误重试
// filepath: untitled://untitled/src/inc/zabbix.class.php
<?php
class PluginZabbixAPI {
private $api_url;
private $api_token;
public function __construct() {
$config = new PluginZabbixConfig();
$this->api_url = $config->getZabbixUrl();
$this->api_token = $config->getApiToken();
}
// 获取主机监控数据
public function getHostMetrics($hostid) {
$params = [
'output' => 'extend',
'hostids' => $hostid,
'selectItems' => ['key_', 'lastvalue', 'name']
];
return $this->apiRequest('host.get', $params);
}
// 获取告警信息
public function getAlerts($hostid) {
$params = [
'output' => 'extend',
'hostids' => $hostid,
'selectTriggers' => 'extend',
'filter' => ['status' => 1]
];
return $this->apiRequest('problem.get', $params);
}
// API请求方法
private function apiRequest($method, $params) {
$data = [
'jsonrpc' => '2.0',
'method' => $method,
'params' => $params,
'auth' => $this->api_token,
'id' => 1
];
$curl = curl_init($this->api_url);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response, true);
}
}
3.3.2 监控视图实现
// filepath: untitled://untitled/src/inc/monitor.class.php
<?php
class PluginZabbixMonitor extends CommonGLPI {
public static function showHostMonitoring($params) {
$hostid = $params['id'];
$api = new PluginZabbixAPI();
// 获取监控数据
$metrics = $api->getHostMetrics($hostid);
// 生成SSO链接
$ssoUrl = self::generateSSOUrl($hostid);
// 显示监控面板
echo "<div class='monitoring-panel'>";
echo "<div class='header'>";
echo "<h2>监控状态</h2>";
echo "<a href='{$ssoUrl}' class='button'>在Zabbix中查看</a>";
echo "</div>";
// 显示关键指标
foreach ($metrics['items'] as $item) {
echo "<div class='metric-item'>";
echo "<span class='name'>{$item['name']}</span>";
echo "<span class='value'>{$item['lastvalue']}</span>";
echo "</div>";
}
echo "</div>";
}
private static function generateSSOUrl($hostid) {
$config = new PluginZabbixConfig();
$timestamp = time();
$token = hash_hmac('sha256',
"hostid={$hostid}&time={$timestamp}",
$config->getSSOSecret()
);
return $config->getZabbixUrl() . "/sso.php?" .
"hostid={$hostid}&time={$timestamp}&token={$token}";
}
}
3.3.3 工单自动化处理
// filepath: untitled://untitled/src/inc/ticket.class.php
<?php
class PluginZabbixTicket {
public static function createFromAlert($alert) {
$ticket = new Ticket();
// 创建工单
$ticketId = $ticket->add([
'name' => "监控告警: " . $alert['description'],
'content' => self::formatAlertContent($alert),
'status' => Ticket::INCOMING,
'priority' => self::mapSeverityToPriority($alert['severity'])
]);
// 记录告警关联
self::linkAlertToTicket($alert['eventid'], $ticketId);
return $ticketId;
}
public static function checkAlertStatus($ticketId) {
$alert = self::getLinkedAlert($ticketId);
$api = new PluginZabbixAPI();
// 检查告警状态
$currentStatus = $api->getAlertStatus($alert['eventid']);
if ($currentStatus == 0) { // 告警已解决
$ticket = new Ticket();
$ticket->update([
'id' => $ticketId,
'status' => Ticket::SOLVED,
'closedate' => date('Y-m-d H:i:s')
]);
}
}
}
3.3.4 SSO实现
// filepath: untitled://untitled/src/front/sso.php
<?php
class PluginZabbixSSO {
public static function validateRequest() {
$config = new PluginZabbixConfig();
$hostid = $_GET['hostid'];
$timestamp = $_GET['time'];
$token = $_GET['token'];
// 验证时间戳
if (time() - $timestamp > $config->getSSOLifetime()) {
throw new Exception('Link expired');
}
// 验证Token
$expectedToken = hash_hmac('sha256',
"hostid={$hostid}&time={$timestamp}",
$config->getSSOSecret()
);
if (!hash_equals($expectedToken, $token)) {
throw new Exception('Invalid token');
}
return true;
}
public static void redirect($hostid) {
$config = new PluginZabbixConfig();
$zabbixUrl = $config->getZabbixUrl();
// 生成Zabbix会话
$sessionId = self::createZabbixSession();
// 重定向到Zabbix
header("Location: {$zabbixUrl}/hosts.php?hostid={$hostid}");
exit;
}
}
4. 数据模型设计
4.1 配置表
CREATE TABLE IF NOT EXISTS `glpi_plugin_zabbix_config` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`zabbix_url` varchar(255) NOT NULL,
`api_token` varchar(255) NOT NULL,
`sync_interval` int(11) DEFAULT 300,
`last_sync` datetime DEFAULT NULL,
`sso_secret` varchar(255) DEFAULT NULL,
`sso_lifetime` int(11) DEFAULT 3600,
`allowed_ips` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
5. 安全实现
本章节描述了插件的核心安全机制实现,包括SSO认证、API访问控制和数据安全保护等关键特性。
5.1 SSO认证流程
SSO认证机制实现了GLPI和Zabbix系统间的无缝切换:
- URL签名机制
- 时效性控制
- IP白名单
- HTTPS传输
5.2 API安全
API安全机制确保系统间的安全通信:
- 访问控制
- 频率限制
- 请求验证
- 数据传输安全
- HTTPS强制
- 加密传输
- 认证增强
- Token轮换
- 双因素认证
5.3 数据安全防护
6. 实现方法详解
6.1 监控数据采集
6.2 告警处理流程
6.3 工单生命周期
6.4 数据同步实现
// filepath: untitled://untitled/src/inc/sync.class.php
class PluginZabbixSync {
public function syncMonitoringData() {
$hosts = $this->getActiveHosts();
foreach ($hosts as $host) {
try {
$this->syncHostData($host);
$this->syncAlerts($host);
$this->updateStatus($host);
} catch (Exception $e) {
$this->logError($e);
}
}
}
private function syncHostData($host) {
$metrics = $this->api->getHostMetrics($host['id']);
$cache = new Cache();
$cache->set("host_metrics_{$host['id']}", $metrics, 300);
}
}
6.5 告警自动处理
// filepath: untitled://untitled/src/inc/alert_handler.class.php
class PluginZabbixAlertHandler {
public function processAlert($alert) {
// 告警去重和合并
if ($this->isDuplicate($alert)) {
return $this->updateExisting($alert);
}
// 创建工单
if ($this->needsTicket($alert)) {
$ticket = $this->createTicket($alert);
$this->notify($ticket);
}
// 更新统计
$this->updateStats($alert);
}
private function isDuplicate($alert) {
return $this->getRecentAlert($alert['host'], $alert['trigger']);
}
}
6.6 数据可视化
// filepath: untitled://untitled/js/charts.js
class ZabbixCharts {
constructor(containerId) {
this.container = document.getElementById(containerId);
this.chart = null;
}
drawMetrics(data) {
const options = {
chart: {
type: 'line',
height: 350
},
series: [{
name: 'CPU使用率',
data: data.cpu
}, {
name: '内存使用率',
data: data.memory
}],
xaxis: {
type: 'datetime'
}
};
this.chart = new ApexCharts(this.container, options);
this.chart.render();
}
}
6.7 模块交互图
6.8 配置管理实现
// filepath: untitled://untitled/src/inc/config_manager.class.php
class PluginZabbixConfigManager {
private $config;
public function __construct() {
$this->loadConfig();
}
public function updateSyncInterval($interval) {
$this->validateInterval($interval);
$this->config->sync_interval = $interval;
$this->saveConfig();
$this->updateCronJob();
}
private function validateInterval($interval) {
if ($interval < 60 || $interval > 3600) {
throw new Exception('同步间隔必须在1-60分钟之间');
}
}
}
7. 监控指标实现
7.1 基础监控指标
7.2 指标采集实现
// filepath: untitled://untitled/src/inc/metrics_collector.class.php
class PluginZabbixMetricsCollector {
public function collectMetrics($hostId) {
$metrics = [
'system' => $this->getSystemMetrics($hostId),
'service' => $this->getServiceStatus($hostId),
'hardware' => $this->getHardwareStatus($hostId),
'application' => $this->getApplicationMetrics($hostId)
];
// 数据处理和存储
$this->processMetrics($metrics);
return $metrics;
}
private function processMetrics($metrics) {
// 数据标准化处理
// 异常值检测
// 数据持久化
}
}
7.3 可视化面板实现
// filepath: untitled://untitled/js/dashboard.js
class MetricsDashboard {
constructor() {
this.charts = {};
this.initCharts();
}
initCharts() {
// CPU使用率图表
this.charts.cpu = new LineChart('#cpu-chart', {
title: 'CPU使用率趋势',
yAxis: { max: 100, unit: '%' }
});
// 内存使用率图表
this.charts.memory = new LineChart('#memory-chart', {
title: '内存使用率趋势',
yAxis: { max: 100, unit: '%' }
});
// 系统负载图表
this.charts.load = new LineChart('#load-chart', {
title: '系统负载趋势'
});
}
updateCharts(data) {
Object.keys(this.charts).forEach(key => {
this.charts[key].update(data[key]);
});
}
}
8. 告警处理增强
8.1 智能告警分类
8.2 告警关联分析
// filepath: untitled://untitled/src/inc/alert_analyzer.class.php
class PluginZabbixAlertAnalyzer {
public function analyzeAlerts($alerts) {
$groups = $this->groupRelatedAlerts($alerts);
foreach ($groups as $group) {
if ($this->isRootCause($group)) {
$this->createPriorityTicket($group);
} else {
$this->linkToExistingTicket($group);
}
}
}
private function groupRelatedAlerts($alerts) {
// 基于时间窗口和关联规则分组
// 识别告警之间的依赖关系
// 返回分组后的告警
}
}
9. 性能优化实现
9.1 缓存策略实现
// filepath: untitled://untitled/src/inc/cache_manager.class.php
class PluginZabbixCacheManager {
private $cache;
private $config;
public function __construct() {
$this->initCache();
$this->loadConfig();
}
public function get($key) {
$value = $this->cache->get($key);
if ($value === false) {
$value = $this->loadFromSource($key);
$this->cache->set($key, $value, $this->getTTL($key));
}
return $value;
}
private function getTTL($key) {
// 根据数据类型返回不同的缓存时间
$ttlMap = [
'host_metrics' => 300, // 5分钟
'alerts' => 60, // 1分钟
'host_status' => 180 // 3分钟
];
return $ttlMap[$key] ?? 300;
}
}
9.2 异步任务处理
// filepath: untitled://untitled/src/inc/task_queue.class.php
class PluginZabbixTaskQueue {
private $queue;
public function addTask($type, $data) {
$task = [
'id' => uniqid(),
'type' => $type,
'data' => $data,
'created_at' => time(),
'status' => 'pending'
];
$this->queue->push($task);
return $task['id'];
}
public function processTasks() {
while ($task = $this->queue->pop()) {
try {
$this->processTask($task);
$this->markCompleted($task['id']);
} catch (Exception $e) {
$this->handleError($task, $e);
}
}
}
}
10. 安全加固实现
10.1 API访问控制
// filepath: untitled://untitled/src/inc/api_security.class.php
class PluginZabbixAPISecurity {
private $rateLimit = [
'window' => 60, // 1分钟
'limit' => 100 // 最大请求数
];
public function checkAccess($request) {
$this->checkRateLimit($request);
$this->validateToken($request);
$this->checkIPWhitelist($request);
$this->logAccess($request);
}
private void checkRateLimit($request) {
$key = "rate_limit:" . $request->getClientIp();
$count = $this->cache->increment($key);
if ($count > $this->rateLimit['limit']) {
throw new Exception('Rate limit exceeded');
}
}
}
10.2 数据安全实现
// filepath: untitled://untitled/src/inc/data_security.class.php
class PluginZabbixDataSecurity {
public function encryptSensitiveData($data) {
$key = $this->getEncryptionKey();
return openssl_encrypt(
json_encode($data),
'AES-256-CBC',
$key,
0,
$this->getIV()
);
}
public function maskSensitiveData($data) {
$patterns = [
'password' => '/^.{2}(.+).{2}$/',
'token' => '/^.{4}(.+).{4}$/',
'ip' => '/\d{1,3}\.\d{1,3}\.(\d{1,3})\.\d{1,3}/'
];
foreach ($patterns as $field => $pattern) {
if (isset($data[$field])) {
$data[$field] = preg_replace($pattern, '***', $data[$field]);
}
}
return $data;
}
}
11. 系统集成增强
11.1 多Zabbix实例支持
// filepath: untitled://untitled/src/inc/multi_instance.class.php
class PluginZabbixMultiInstance {
private $instances = [];
public function addInstance($config) {
$instance = new ZabbixInstance($config);
$this->instances[$config['name']] = $instance;
}
public function aggregateMetrics($hostId) {
$metrics = [];
foreach ($this->instances as $instance) {
$metrics[] = $instance->getHostMetrics($hostId);
}
return $this->mergeMetrics($metrics);
}
}
11.2 数据聚合流程
12. 自动化运维
12.1 自动发现与注册
// filepath: untitled://untitled/src/inc/auto_discovery.class.php
class PluginZabbixAutoDiscovery {
public function discoverAssets() {
$assets = $this->scanNetwork();
foreach ($assets as $asset) {
if ($this->isNewAsset($asset)) {
$this->registerAsset($asset);
$this->configureMonitoring($asset);
}
}
}
private function configureMonitoring($asset) {
// 根据资产类型配置监控模板
$template = $this->selectTemplate($asset);
$this->applyTemplate($asset, $template);
}
}
12.2 自动化部署流程
13. 业务流程自动化
13.1 工单自动分派
// filepath: untitled://untitled/src/inc/ticket_dispatcher.class.php
class PluginZabbixTicketDispatcher {
public function dispatchTicket($ticket) {
$rules = $this->loadDispatchRules();
foreach ($rules as $rule) {
if ($this->matchRule($ticket, $rule)) {
return $this->assignTicket($ticket, $rule['assignee']);
}
}
return $this->assignToDefaultGroup($ticket);
}
private function matchRule($ticket, $rule) {
// 根据规则匹配工单
// 检查严重程度、资产类型、告警类型等
}
}
13.2 告警升级机制
// filepath: untitled://untitled/src/inc/alert_escalation.class.php
class PluginZabbixAlertEscalation {
public function checkEscalation($alert) {
$escalationLevels = [
1 => ['timeout' => 1800, 'action' => 'notify_team'],
2 => ['timeout' => 3600, 'action' => 'notify_manager'],
3 => ['timeout' => 7200, 'action' => 'notify_emergency']
];
$currentLevel = $this->getCurrentLevel($alert);
if ($this->needsEscalation($alert, $currentLevel)) {
$this->escalate($alert, $escalationLevels[$currentLevel]);
}
}
}
14. 报表与分析
14.1 报表生成器
// filepath: untitled://untitled/src/inc/report_generator.class.php
class PluginZabbixReportGenerator {
public function generateReport($type, $params) {
$data = $this->collectReportData($type, $params);
$template = $this->loadTemplate($type);
$report = [
'summary' => $this->generateSummary($data),
'details' => $this->generateDetails($data),
'charts' => $this->generateCharts($data),
'recommendations' => $this->generateRecommendations($data)
];
return $this->formatReport($report, $template);
}
}
14.2 趋势分析实现
// filepath: untitled://untitled/js/trend_analysis.js
class TrendAnalysis {
constructor(data) {
this.data = data;
this.threshold = this.calculateThreshold();
}
analyzePerformanceTrend() {
return {
trend: this.calculateTrend(),
forecast: this.predictFuture(),
anomalies: this.detectAnomalies(),
recommendations: this.generateRecommendations()
};
}
predictFuture() {
// 使用线性回归或其他算法预测未来趋势
return this.linearRegression(this.data);
}
}
14.3 可视化仪表板
// filepath: untitled://untitled/js/dashboard_advanced.js
class AdvancedDashboard extends MetricsDashboard {
constructor() {
super();
this.initAdvancedFeatures();
}
initAdvancedFeatures() {
// 添加高级图表
this.charts.sla = new GaugeChart('#sla-chart', {
title: 'SLA达成率',
thresholds: [
{ value: 95, color: 'green' },
{ value: 90, color: 'yellow' },
{ value: 0, color: 'red' }
]
});
// 添加预测分析图表
this.charts.forecast = new ForecastChart('#forecast-chart', {
title: '性能趋势预测',
forecastPeriod: 30 // 天
});
}
}
15. 系统优化建议
15.1 性能优化架构
性能优化架构图说明了系统优化策略:
- 应用层:实现负载均衡和多服务器部署
- 缓存层:采用本地缓存和Redis集群
- 数据层:配置主从复制和读写分离
15.2 系统监控体系
监控体系图展示了全面的监控策略:
- 性能监控:跟踪系统资源和响应能力
- 可用性监控:确保服务和数据同步正常
- 安全监控:保障访问控制和数据安全
16. 最佳实践指南
16.1 部署架构图
生产部署架构图说明了高可用部署方案:
- 生产环境:配置负载均衡和主从数据库
- 灾备环境:部署备用服务器和数据库
- 数据同步:确保生产和灾备数据一致
16.2 运维流程图
运维流程状态图展示了日常运维工作流:
- 从日常运维到问题处理的完整流程
- 重大问题的应急响应机制
- 问题解决后的复盘和文档更新
16.3 变更管理流程
变更管理流程图说明了系统变更的标准流程:
- 变更申请和风险评估
- 方案制定和预演验证
- 变更实施和结果验证
- 失败情况下的回滚机制
17. 故障处理指南
17.1 常见问题诊断
常见故障及其解决方案:
-
同步失败问题
- 检查网络连接
- 验证API权限
- 查看错误日志
-
性能问题
- 检查缓存状态
- 优化SQL查询
- 调整并发参数
-
认证问题
- 验证SSO配置
- 检查Token有效性
- 更新安全证书
21. 开发指南
21.1 开发环境配置
- 开发环境要求
- PHP 8.2 开发环境
- Composer 2.0+
- Visual Studio Code / PHPStorm
- Xdebug 3.0+
- Git 2.0+