ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Telegraf cloud_pubsub 输出插件详解:将 Metrics 高效发布到 Google Cloud PubSub

Telegraf cloud_pubsub 输出插件详解:将 Metrics 高效发布到 Google Cloud PubSub Telegraf cloud_pubsub 输出插件详解将 Metrics 高效发布到 Google Cloud PubSub【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegraf本篇技术指南围绕 Telegraf 的cloud_pubsub输出插件展开讲解如何把 Telegraf 采集的指标序列化为任意支持的数据格式并发布到 Google Cloud PubSub 主题中。读完后你将掌握该插件的完整配置参数项目、主题、凭据、批量发布阈值、内容编码、消息属性等、底层序列化与发布流程的源码级原理以及测试用例中验证过的批处理行为能够独立完成插件接入与调优。插件定位cloud_pubsub是 Telegraf 的输出插件之一其职责是把 Telegraf 指标发布到 Google Cloud PubSub 主题中且消息载荷可以采用 Telegraf 支持的任意一种数据格式。根据插件 README 的标注该插件自 Telegraf v1.10.0 引入标签为 cloud、messaging支持全部平台all。插件的核心实现位于 cloud_pubsub.go配置样例位于 sample.conf此外 topic_gcp.go 定义了面向 PubSub 客户端的抽象接口cloud_pubsub_test.go 提供了覆盖各配置分支的单元测试。插件通过标准的outputs.Add注册机制挂入 Telegraf 输出体系见 cloud_pubsub.go 末尾的init()函数func init() { outputs.Add(cloud_pubsub, func() telegraf.Output { return PubSub{} }) }完整配置示例以下配置完整继承自插件 README 与 sample.conf可直接复制到 Telegraf 主配置文件使用# Publish Telegraf metrics to a Google Cloud PubSub topic [[outputs.cloud_pubsub]] ## Required. Name of Google Cloud Platform (GCP) Project that owns ## the given PubSub topic. project my-project ## Required. Name of PubSub topic to publish metrics to. topic my-topic ## Content encoding for message payloads, can be set to gzip or ## identity to apply no encoding. # content_encoding identity ## Required. Data format to consume. ## Each data format has its own unique set of configuration options. data_format influx ## Optional. Filepath for GCP credentials JSON file to authorize calls to ## PubSub APIs. If not set explicitly, Telegraf will attempt to use ## Application Default Credentials, which is preferred. # credentials_file path/to/my/creds.json ## Optional. If true, will send all metrics per write in one PubSub message. # send_batched true ## The following publish_* parameters specifically configures batching ## requests made to the GCP Cloud PubSub API via the PubSub Golang library. ## Optional. Send a request to PubSub (actually publish a batch) ## when it has this many PubSub messages. If send_batched is true, ## this is ignored and treated as if it were 1. # publish_count_threshold 1000 ## Optional. Send a request to PubSub (actually publish a batch) ## when it has this many PubSub messages. If send_batched is true, ## this is ignored and treated as if it were 1 # publish_byte_threshold 1000000 ## Optional. Specifically configures requests made to the PubSub API. # publish_num_go_routines 2 ## Optional. Specifies a timeout for requests to the PubSub API. # publish_timeout 30s ## Optional. If true, published PubSub message data will be base64-encoded. # base64_data false ## 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 ## Optional. PubSub attributes to add to metrics. # [outputs.cloud_pubsub.attributes] # my_attr tag_value与通用输出插件一样cloud_pubsub也支持 Telegraf 的全局与插件级配置选项如指标/标签/字段的过滤与改写、别名、插件排序等详见 CONFIGURATION.md。配置参数逐项解析结合 sample.conf 中的注释与 cloud_pubsub.go 中的PubSub结构体定义各参数说明如下参数必填默认值说明project是无拥有该 PubSub 主题的 GCP 项目名为空时Init()直接报错topic是无要发布指标的目标 PubSub 主题名为空时Init()直接报错data_format是无消息载荷的数据格式各格式有各自的配置项参考 DATA_FORMATS_OUTPUT.mdcredentials_file否空GCP 凭据 JSON 文件路径不设置时使用 Application Default CredentialsADC官方推荐方式content_encoding否identity消息载荷的内容编码gzip表示 gzip 压缩identity表示不做编码send_batched否false为true时每次Write的所有指标序列化为一条 PubSub 消息publish_count_threshold否0库默认PubSub 消息数达到该值时发送一次批量发布请求send_batched true时该值被忽略等价于 1publish_byte_threshold否0库默认消息字节数达到该值时发送一次批量发布请求send_batched true时同样等价于 1publish_num_go_routines否0库默认配置向 PubSub API 发起请求的 goroutine 数量publish_timeout否0库默认PubSub API 请求超时Go duration 字符串格式如30sbase64_data否false为true时对消息数据做 base64 编码attributes否空附加到每条 PubSub 消息上的属性键值对TOML 子表两点实现细节值得注意必填项校验。Init() 在启动阶段就检查topic与project任一为空立即返回错误避免运行到写入阶段才暴露配置缺失同时对content_encoding做白名单校验——只接受、identity、gzip其他取值会在启动时以invalid value %q for content_encoding报错。TOML 子表必须置于末尾。配置注释中专门强调由于 TOML 的解析方式[outputs.cloud_pubsub.attributes]这样的子表必须放在插件定义的末尾否则后面的配置项会被读入 attributes 表内。认证机制ADC 优先凭据文件兜底插件在Connect()阶段调用 initPubSubClient() 建立 PubSub 客户端认证逻辑如下若设置了credentials_file先通过 plugins/common/gcp/auth.go 的ParseCredentialType读取该 JSON 文件并解析其type字段确认凭据类型后用option.WithAuthCredentialsFile将其注入客户端若未设置则调用google.FindDefaultCredentials查找 GCP Application Default CredentialsADC查找失败会返回明确错误unable to find GCP Application Default Credentials: ... Either set ADC or provide CredentialsFile config客户端创建时统一附加pubsub.ScopeCloudPlatform权限范围并通过internal.ProductToken()设置 User-Agent 以便服务端识别 Telegraf 来源。因此生产环境推荐使用 ADC如 GCE 实例的服务账号、gcloud auth application-default login等使用服务账号密钥文件时type字段缺失或文件不可读都会在连接阶段快速失败。发布流程从 Write 到 PubSub API插件的核心写路径在 Write() 中可分为四步func (ps *PubSub) Write(metrics []telegraf.Metric) error { ps.refreshTopic() // Serialize metrics and package into appropriate PubSub messages msgs, err : ps.toMessages(metrics) if err ! nil { return err } cctx, cancel : context.WithCancel(context.Background()) // Publish all messages - each call to Publish returns a future. ps.publishResults make([]publishResult, 0, len(msgs)) for _, m : range msgs { ps.publishResults append(ps.publishResults, ps.t.Publish(cctx, m)) } // topic.Stop() forces all published messages to be sent, even // if PubSub batch limits have not been reached. go ps.t.Stop() return ps.waitForResults(cctx, cancel) }refreshTopic()每次写入都会刷新 topic 对象生产环境通过ps.c.Publisher(ps.Topic)获取*pubsub.Publisher并用 topicWrapper 包装随后调用SetPublishSettings(ps.publishSettings())把配置参数应用到发布器上。这里引入topic接口定义见 topic_gcp.go是关键设计——接口包含ID、Stop、Publish、PublishSettings、SetPublishSettings五个方法测试中用stubTopic替换真实客户端即可完整模拟 PubSub 客户端的 bundler 行为这正是 cloud_pubsub_test.go 能够离线验证批量阈值的原因。toMessages()将指标转换为 PubSub 消息下一节详述。异步发布Publish对每条消息返回一个 futurepublishResult不阻塞等待网络结果同时启动go ps.t.Stop()——PubSub 客户端库的Stop()会强制冲刷所有已入队消息即使未达到批量阈值也立即发送保证Write返回时所有消息都已提交给 PubSub。waitForResults()waitForResults() 为每个 future 起一个 goroutine 等待Get(ctx)结果用sync.Once记录第一个错误并取消 context从而让其余等待快速退出。任何一条消息发布失败Write都会返回该错误由 Telegraf 的输出缓冲/重试机制buffer 配置决定后续处理。消息打包send_batched 的两种模式toMessages() 根据send_batched分两条路径send_batched true调用serializer.SerializeBatch(metrics)把本次Write收到的全部指标序列化成单个字节流经 base64/压缩处理后打包成一条PubSub 消息。适合下游按批消费、或对单条消息完整性有要求的场景。send_batched false默认逐条调用serializer.Serialize(m)每个指标独立成为一条消息单条序列化失败只记录 Debug 日志并跳过该指标不中断整批。两条路径处理完载荷后都会附加attributes子表如果配置了的话到msg.Attributes。载荷处理管线序列化 → base64 → 内容编码每条消息的数据经历一个固定的后处理管线serializer → encodeB64Data → compressData。base64encodeB64Data() 仅在base64_data true时用标准 base64 编码整段数据适用于下游传输通道无法承载二进制/非文本字节的场景。内容编码compressData() 中identity直接原样返回gzip则调用 Telegraf 内部公共的 internal/content_coding.go 中的ContentEncoder。该编码器的 gzip 实现GzipEncoder.Encode见 content_coding.go还有一个性能优化数据超过 1MB 时切换到并行 gzippgzip小于 1MB 使用标准 gzip 实现兼顾大小载荷的压缩吞吐。顺序注意base64 发生在压缩之前即先 base64 再 gzip压缩针对的是 base64 之后的字节流。gzip 分支的测试TestPubSub_WriteGzipSingle用十六进制精确比对了压缩后的消息体TestPubSub_WriteGzipAndBase64Single则验证了 base64gzip 组合管线可作为消费端解码逻辑的对照依据。批量发布参数与 PublishSettings 的映射publish_*系列参数最终映射到 PubSub Go 客户端库的PublishSettings映射逻辑见 publishSettings()func (ps *PubSub) publishSettings() pubsub.PublishSettings { settings : pubsub.PublishSettings{} if ps.PublishNumGoroutines 0 { settings.NumGoroutines ps.PublishNumGoroutines } if time.Duration(ps.PublishTimeout) 0 { settings.CountThreshold 1 } if ps.SendBatched { settings.CountThreshold 1 } else if ps.PublishCountThreshold 0 { settings.CountThreshold ps.PublishCountThreshold } if ps.PublishByteThreshold 0 { settings.ByteThreshold ps.PublishByteThreshold } return settings }由此可以得到几条从源码确认的行为规则只有显式配置了正值的参数才会覆盖库的默认值未配置时完全走pubsub.DefaultPublishSettings配置了publish_timeout或开启send_batched时CountThreshold被强制置 1即不做客户端侧的消息数批量聚合send_batched与publish_count_threshold/publish_byte_threshold同时配置时批量阈值语义被send_batched覆盖视为 1与 README 注释一致。单元测试对批量行为做了量化验证TestPubSub_WriteOverCountThreshold4 条指标、publish_count_threshold 2断言实际发出 2 个 bundle与TestPubSub_WriteOverByteThreshold2 条指标、publish_byte_threshold 1断言 2 个 bundle分别证明消息数阈值与字节阈值都真实作用于客户端 bundler见 cloud_pubsub_test.go。错误处理与可观测性发布失败任一 future 返回错误时waitForResults通过sync.Once只保留第一个错误并取消 contextWrite整体返回错误TestPubSub_Errorcloud_pubsub_test.go模拟了某条消息发送失败并断言Write返回包含this is an error的错误。序列化失败非批量模式下单条指标序列化失败仅打 Debug 日志并跳过批量模式下SerializeBatch失败则整个Write失败。压缩失败批量模式下压缩失败会使整个Write失败unable to compress message with %s非批量模式下降级为该条指标记录 Error 日志并丢弃两种模式在可靠性语义上存在差异选型时值得留意。资源释放Close()会调用topic.Stop()释放发布器资源防止 Telegraf 退出时消息滞留。数据格式与生态位置data_format决定载荷的序列化方式可选格式及其配置项完整列表见 DATA_FORMATS_OUTPUT.md如influx、json等。测试用例中使用的 influx 行协议序列化后形如test,tag1value1 valuevalue_1 1257894000000000000见 cloud_pubsub_test.go 的期望值消费端可按对应格式直接解析。cloud_pubsub在 Telegraf 生态中属于“指标外发”型输出典型链路是各类 input 插件采集 → 可选 processors/aggregators 加工 →cloud_pubsub序列化并发布 → PubSub 订阅端流处理、存储、告警系统等按主题拉取。若下游是 GCP 内部组件attributes子表提供了轻量级的消息路由/打标能力若关注带宽成本可组合content_encoding gzip与send_batched true把每批指标压缩成单条大消息发送。小结cloud_pubsub插件的配置面虽不大但每个参数都有明确的源码级行为project/topic启动期强校验、ADC/凭据文件双通道认证、send_batched决定单条还是逐指标成消息、publish_*参数精确映射到 PubSub 客户端库的批量策略、base64 与 gzip 按固定顺序构成载荷管线且所有分支均由 cloud_pubsub_test.go 的 stub 化 topic 测试逐一锁定。基于 sample.conf 起步、按需叠加批量与编码参数即可把 Telegraf 指标稳定接入 Google Cloud PubSub 生态。【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegraf创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表