Telegraf 的 Sensu Go 输出插件:通过 HTTP Events API 上报指标的完整指南
2026/9/14 9:36:40 网站建设 项目流程

Telegraf 的 Sensu Go 输出插件:通过 HTTP Events API 上报指标的完整指南

【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegraf

Telegraf 的outputs.sensu插件负责将采集、处理、聚合后的指标通过 Sensu Go 的 HTTP Events API 写入 Sensu 监控平台,使 Sensu 能够基于这些指标数据执行告警、事件处理与指标存储。阅读本文后,你将掌握该插件的双 API 模式(Backend API 与 Agent API)、完整的 TOML 配置方法、API Key 的签发流程,以及插件底层的事件结构与写入流程,从而在生产环境中正确接入 Sensu Go。

插件概览与适用场景

outputs.sensu是 Telegraf 官方输出插件之一,通过 Sensu Go 的 HTTP Events API 将指标作为Sensu Event(事件)写入目标后端。根据 plugins/outputs/sensu/README.md 的标注:

  • 引入版本:Telegraf v1.18.0 起提供;
  • 插件类别:applications(面向应用类监控场景);
  • 支持平台:all(全平台,无操作系统限制)。

插件在源码中通过outputs.Add("sensu", ...)完成注册(见 plugins/outputs/sensu/sensu.go 的init()函数),并在 plugins/outputs/all/sensu.go 中以import _ "github.com/influxdata/telegraf/plugins/outputs/sensu"的形式被默认构建引入。也就是说,使用默认方式编译的 Telegraf 二进制已经内置该插件,只需要在配置文件中声明[[outputs.sensu]]即可启用。

典型的应用场景是:你在 Sensu Go 中统一管理告警与事件流,希望把 Telegraf 采集到的系统/应用指标(例如 CPU、内存、业务自定义指标)一并送入 Sensu,由 Sensu 的 handler(如 InfluxDB、Elasticsearch)负责存储或进一步处理。该插件正是连接 Telegraf 数据管道与 Sensu Go 事件模型的桥梁。

工作原理:Backend API 与 Agent API 双模式

Sensu Go 提供了两条可接收指标事件的 HTTP 通道,该插件均支持:

模式配置项自动拼接的 API 路径用途
Backend APIbackend_api_url/api/core/v2/namespaces/:entity_namespace/events直接写入 Sensu Backend,需要 API Key 认证
Agent APIagent_api_url/events写入本机 Sensu Agent,由 Agent 转发到 Backend

从源码 sensu.go 的setEndpointURL()方法可以看到端点的解析优先级与完整逻辑:

  1. 若配置了backend_api_url,则使用该地址并拼接/api/core/v2/namespaces/<namespace>/events,其中 namespace 取entity.namespace的值,未配置时默认为default
  2. 否则若配置了agent_api_url,则使用该地址并拼接/events
  3. 若两者都未提供(或值解析后为空),插件会回退到默认的 Agent API 地址http://127.0.0.1:3031,路径同样为/events

关于优先级,README 中有明确说明:backend_api_urlagent_api_urlapi_key同时设置时,插件始终优先使用backend_api_url。这一行为同样体现在setEndpointURL()中——BackendAPIURL的判断先于AgentAPIURL

对应的单元测试位于 sensu_test.go 的TestResolveEventEndpointUrl,覆盖了四种组合:

  • 仅配置agent_api_urlhttp://127.0.0.1:3031/events
  • 同时配置 Agent 与 Backend → 使用 Backend 且 namespace 为默认值default
  • 配置 Backend 且显式声明entity.namespace = "test-namespace"/api/core/v2/namespaces/test-namespace/events
  • agent_api_url为空字符串 → 回退到默认地址。

完整配置示例

以下是插件完整可用的配置(与 plugins/outputs/sensu/sample.conf 及 README 中的示例保持一致):

# Send aggregate metrics to Sensu Monitor [[outputs.sensu]] ## BACKEND API URL is the Sensu Backend API root URL to send metrics to ## (protocol, host, and port only). The output plugin will automatically ## append the corresponding backend API path ## /api/core/v2/namespaces/:entity_namespace/events/:entity_name/:check_name). ## ## Backend Events API reference: ## https://docs.sensu.io/sensu-go/latest/api/events/ ## ## AGENT API URL is the Sensu Agent API root URL to send metrics to ## (protocol, host, and port only). The output plugin will automatically ## append the correspeonding agent API path (/events). ## ## Agent API Events API reference: ## https://docs.sensu.io/sensu-go/latest/api/events/ ## ## NOTE: if backend_api_url and agent_api_url and api_key are set, the output ## plugin will use backend_api_url. If backend_api_url and agent_api_url are ## not provided, the output plugin will default to use an agent_api_url of ## http://127.0.0.1:3031 ## # backend_api_url = "http://127.0.0.1:8080" # agent_api_url = "http://127.0.0.1:3031" ## API KEY is the Sensu Backend API token ## Generate a new API token via: ## ## $ sensuctl cluster-role create telegraf --verb create --resource events,entities ## $ sensuctl cluster-role-binding create telegraf --cluster-role telegraf --group telegraf ## $ sensuctl user create telegraf --group telegraf --password REDACTED ## $ sensuctl api-key grant telegraf ## ## For more information on Sensu RBAC profiles & API tokens, please visit: ## - https://docs.sensu.io/sensu-go/latest/reference/rbac/ ## - https://docs.sensu.io/sensu-go/latest/reference/apikeys/ ## # api_key = "${SENSU_API_KEY}" ## Optional TLS Config # tls_ca = "/etc/telegraf/ca.pem" # tls_cert = "/etc/telegraf/cert.pem" # tls_key = "/etc/telegraf/key.pem" ## Use TLS but skip chain & host verification # insecure_skip_verify = false ## Timeout for HTTP message # timeout = "5s" ## HTTP Content-Encoding for write request body, can be set to "gzip" to ## compress body or "identity" to apply no encoding. # content_encoding = "identity" ## NOTE: Due to the way TOML is parsed, tables must be at the END of the ## plugin definition, otherwise additional config options are read as part of ## the table ## Sensu Event details ## ## Below are the event details to be sent to Sensu. The main portions of the ## event are the check, entity, and metrics specifications. For more information ## on Sensu events and its components, please visit: ## - Events - https://docs.sensu.io/sensu-go/latest/reference/events ## - Checks - https://docs.sensu.io/sensu-go/latest/reference/checks ## - Entities - https://docs.sensu.io/sensu-go/latest/reference/entities ## - Metrics - https://docs.sensu.io/sensu-go/latest/reference/events#metrics ## ## Check specification ## The check name is the name to give the Sensu check associated with the event ## created. This maps to check.metadata.name in the event. [outputs.sensu.check] name = "telegraf" ## Entity specification ## Configure the entity name and namespace, if necessary. This will be part of ## the entity.metadata in the event. ## ## NOTE: if the output plugin is configured to send events to a ## backend_api_url and entity_name is not set, the value returned by ## os.Hostname() will be used; if the output plugin is configured to send ## events to an agent_api_url, entity_name and entity_namespace are not used. # [outputs.sensu.entity] # name = "server-01" # namespace = "default" ## Metrics specification ## Configure the tags for the metrics that are sent as part of the Sensu event # [outputs.sensu.tags] # source = "telegraf" ## Configure the handler(s) for processing the provided metrics # [outputs.sensu.metrics] # handlers = ["influxdb","elasticsearch"]

核心参数详解

1. 端点地址:backend_api_urlagent_api_url

  • backend_api_url:Sensu Backend API 的根地址,仅需协议、主机与端口三部分(例如http://127.0.0.1:8080),插件会自动拼接/api/core/v2/namespaces/<namespace>/events。该模式下写入的是 Backend 的 core/v2 Events API。
  • agent_api_url:Sensu Agent API 的根地址,插件自动拼接/events。Agent 默认监听3031端口,因此该模式无需暴露 Backend 端口,更贴近"本机 Agent 上报"的部署形态。
  • 两者都未配置时,插件默认使用http://127.0.0.1:3031(对应源码中的defaultURL常量,见 sensu.go)。
  • 注意:agent_api_url模式不使用实体名与命名空间(详见下文 entity 小节)。

2. API Key:api_key

当使用 Backend API 时,必须提供api_key。这一点在源码Init()中有强校验:如果配置了backend_api_url但没有api_key,插件会直接返回错误backend_api_url [...] specified, but no API Key provided,导致插件初始化失败。

README 给出了通过sensuctl签发 API Key 的完整流程(四步):

# 1. 创建 cluster-role,授予对 events 与 entities 资源的 create 权限 $ sensuctl cluster-role create telegraf --verb create --resource events,entities # 2. 创建 cluster-role-binding,将 telegraf 角色绑定到 telegraf 组 $ sensuctl cluster-role-binding create telegraf --cluster-role telegraf --group telegraf # 3. 创建用户并加入 telegraf 组 $ sensuctl user create telegraf --group telegraf --password REDACTED # 4. 为该用户签发 API Key $ sensuctl api-key grant telegraf

签名完成后将得到的 Key 填入api_key。示例配置使用${SENSU_API_KEY}环境变量引用,即通过 Telegraf 的环境变量替换机制(详见 docs/CONFIGURATION.md 中关于环境变量的说明)避免明文落盘。HTTP 请求发出时,插件会将该 Key 放入Authorization请求头,格式为Key <api_key>

3. TLS 配置

插件内嵌 Telegraf 通用的 TLSClientConfig(源码中tls.ClientConfig匿名内嵌),支持以下选项:

配置项默认值说明
tls_caCA 证书路径,用于校验服务端证书链
tls_cert客户端证书路径(mTLS 双向认证时使用)
tls_key客户端私钥路径
insecure_skip_verifyfalse设为true时跳过证书链与主机名校验(仅建议在测试环境使用)

Connect()阶段,插件通过s.ClientConfig.TLSConfig()构建*http.TransportTLSClientConfig,并连同超时配置一起组装成http.Client(见 sensu.go 的createClient())。

4. 请求超时:timeout

HTTP 请求超时时间,默认5s(源码中的defaultClientTimeout)。若 Sensu 后端处理较慢或网络链路较长,可适当调大,例如timeout = "10s"

5. 内容编码:content_encoding

请求体的 HTTP Content-Encoding,可选identity(不压缩)或gzip(gzip 压缩),默认identity。源码Init()会对该值做白名单校验,传入其他值会报错unsupported content_encoding [...] specified。当指标量很大时,开启gzip可显著降低网络传输开销;写入时插件会将请求头Content-Encoding设置为gzip,并借助internal.CompressWithGzip(internal/internal.go)对流式数据进行压缩。

6. 关于 TOML 表顺序的注意事项

README 特别提醒:由于 TOML 的解析方式,[outputs.sensu.check][outputs.sensu.entity]等子表必须放在整个插件定义的最后,否则后续的配置项会被错误地解析为子表的一部分。实际使用中应保持示例配置的书写顺序。

事件结构:check / entity / tags / metrics

插件将 Telegraf 指标封装为一个 Sensu Event,事件体包含entitycheckmetricstimestamp四个主要部分(对应源码中的outputEvent结构体)。事件体以 JSON 序列化后通过 HTTP POST 发送。

Check(检查)规格

[outputs.sensu.check] name = "telegraf"

check.name映射到事件的check.metadata.name,即与该事件关联的 Sensu Check 名称。源码getCheck()中该字段是必填项——若未配置,插件会返回missing check name错误并拒绝写入。此外插件会为 Check 自动填充:

  • status: 0(始终标记为 OK,因为 Telegraf 上报的是指标数据而非告警状态);
  • output: "Telegraf agent processed N metrics"(N 为本次写入的指标点数);
  • issued:Unix 时间戳;
  • output_metric_handlers:与 metrics 部分的 handlers 相同。

Entity(实体)规格

[outputs.sensu.entity] name = "server-01" namespace = "default"

entity.nameentity.namespace会进入事件的entity.metadata。行为规则如下:

  • 使用Backend API时:若未显式配置name,插件会调用os.Hostname()取本机主机名作为实体名(见 sensu.go 的setEntity());
  • 使用Agent API时:entity.nameentity.namespace均不会被使用(由 Agent 侧负责实体归属),此时插件只发送空的 entity 对象。

Tags(标签)规格

[outputs.sensu.tags] source = "telegraf"

tags是一个自由键值映射,会被附加到每一个发送的指标点上,用于标注数据来源等公共维度。结合源码看,插件在组装指标点时,会先追加配置的 tags,再追加指标自身的 tags。

Metrics(指标)规格与 Handlers

[outputs.sensu.metrics] handlers = ["influxdb", "elasticsearch"]

metrics.handlers指定处理这些指标数据的 Sensu handler 列表(例如持久化到 InfluxDB、Elasticsearch 的 handler 名称),对应事件metrics.handlers字段。未配置时 handlers 为空数组,指标仍会随事件上报,只是没有显式指定处理者。

指标写入流程(源码级剖析)

从 sensu.go 的Write()方法可以还原完整的写入流水线:

  1. 遍历指标构建点集:对每个 Telegraf 指标,将其全部 tags 与配置 tags 合并为outputTag列表;然后遍历FieldList(),把每个数值字段转换成一个outputMetric点。
  2. 字段值转 float64getFloat()支持float64/float32/int64/int32/int/uint64/uint32/uint共 8 种数值类型到float64的转换;遇到其他类型(如字符串、布尔值)返回math.NaN()
  3. 特殊值处理:由于 JSON 不支持InfNaN
    • 正无穷 → 替换为math.MaxFloat64
    • 负无穷 → 替换为-math.MaxFloat64
    • NaN→ 直接跳过该点(不写入)。
    • 以上情况均输出 Debug 级别日志便于排查。
  4. 指标点命名:点的名称采用metric.Name() + "." + fieldKey的拼接形式,例如指标cpu的字段value会生成名为cpu.value的点;时间戳取指标时间的Unix()秒值。
  5. 封装事件encodeToJSON()组装outputEvent,其中metrics.points为全部指标点、metrics.handlers来自配置、事件级timestamp取当前时间。
  6. 发送请求writeMetrics()使用 HTTP POST,请求头包括:
    • Content-Type: application/json; charset=utf-8(源码常量defaultContentType);
    • User-Agent:由internal.ProductToken()(见 internal/internal.go)生成,格式类似Telegraf/<version> Go/<go-version>
    • 配置了 API Key 时附带Authorization: Key <api_key>
    • 开启 gzip 时附带Content-Encoding: gzip
  7. 响应处理:成功以 HTTP201 Created为准(Sensu 创建事件的语义);非 2xx 时:
    • 若状态码为 4xx(客户端错误),记录 Debug 日志但不返回错误(避免因后端拒绝数据导致 Telegraf 输出端不断重试);
    • 若为其他状态码(如 5xx 服务端错误),返回包含状态码的错误,触发 Telegraf 的重试机制。

测试验证与质量保障

仓库为插件提供了较完整的单元测试(plugins/outputs/sensu/sensu_test.go),主要覆盖:

  • 端点解析TestResolveEventEndpointUrl):验证 Agent/Backend 模式下的路径拼接、namespace 默认值与自定义、空 URL 回退逻辑;
  • 连接与写入TestConnectAndWrite):使用httptest启动模拟服务端,校验请求 URL、Authorization头格式(Key a0b1c2d3-...)、事件体中 check 名、entity 名、metrics 非空、handlers 包含配置值,以及指标点名称/值与配置 tags 是否正确落位;
  • 数值转换TestGetFloat):逐一验证 8 种数值类型的转换结果以及非数值类型的NaN返回值。

这些测试不仅验证了配置到行为的映射关系,也为二次开发或排查接入问题提供了可参考的行为基准。

与其他配置体系的衔接

和所有 Telegraf 插件一样,outputs.sensu同样支持全局/插件级配置能力,例如利用namepassnamedroptagpass等过滤指标,使用alias重命名插件实例,以及通过处理器顺序控制数据流。具体说明见 docs/CONFIGURATION.md。

小结

outputs.sensu插件以简洁的配置在 Telegraf 与 Sensu Go 之间建立了标准化的指标通道:通过 Backend/Agent 双 API 适配不同部署拓扑,通过事件模型(entity/check/metrics)与 Sensu 的 RBAC、handlers 机制无缝集成,并在源码层面妥善处理了端点解析、TLS、压缩、特殊浮点值等工程细节。接入时只需重点确认三点:选用哪种 API 模式、是否已为 Backend 模式签发 API Key、事件结构中的 check 名是否按需配置,即可稳定运行。

【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegraf

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询