在监控和性能分析的场景中,探测远程服务的可达性和安全性是至关重要的。blackbox_exporter
是 Prometheus 项目的一部分,它能够帮助我们在不同协议层(HTTP、HTTPS、TCP、DNS 等)上进行服务监控。本文将详细解读 blackbox_exporter
中的 ProbeTCP
函数,分析如何使用 Go 实现对 TCP 连接的探测、SSL/TLS 协议的支持,以及如何在探测过程中获取并处理 SSL 证书和响应信息。
1. 函数定义
func ProbeTCP(ctx context.Context, target string, module config.Module, registry *prometheus.Registry, logger *slog.Logger) bool {
ProbeTCP
函数的目的是对指定目标(target
)进行 TCP 连接探测。它会根据配置(module
)发送查询请求,读取响应数据,并在需要时升级到 TLS 连接。
参数说明:
- ctx:上下文,用于控制超时、取消等操作。
- target:目标地址,通常是一个 IP 或域名。
- module:配置模块,包含了与 TCP 连接相关的配置(如查询、响应、TLS 设置等)。
- registry:Prometheus 注册表,用于注册和暴露监控指标。
- logger:日志记录器,用于记录操作信息和错误。
2. 创建 Prometheus 指标
probeSSLEarliestCertExpiry := prometheus.NewGauge(sslEarliestCertExpiryGaugeOpts)
probeSSLLastChainExpiryTimestampSeconds := prometheus.NewGauge(sslChainExpiryInTimeStampGaugeOpts)
probeSSLLastInformation := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "probe_ssl_last_chain_info",
Help: "Contains SSL leaf certificate information",
},
[]string{
"fingerprint_sha256", "subject", "issuer", "subjectalternative"},
)
probeTLSVersion := prometheus.NewGaugeVec(
probeTLSInfoGaugeOpts,
[]string{
"version"},
)
probeFailedDueToRegex := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_failed_due_to_regex",
Help: "Indicates if probe failed due to regex",
})
registry.MustRegister(probeFailedDueToRegex)
这些代码片段创建了多个 Prometheus 指标,用于收集与 SSL/TLS 相关的数据。具体包括:
- SSL证书到期时间(
probeSSLEarliestCertEx