Telegraf HTTP Response 输入插件详解:基于状态码、响应体与网络错误的多维度 HTTP 探活与监控
Telegraf HTTP Response 输入插件详解基于状态码、响应体与网络错误的多维度 HTTP 探活与监控【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegrafTelegraf 的http_response输入插件用于对指定的 HTTP/HTTPS 地址发起真实请求采集响应状态码、响应耗时、响应体长度等指标并通过内置的result标签与result_code字段将连接建立、超时、DNS 解析、响应体匹配等结果统一编码是构建服务可用性监控探活/拨测最直接的基础设施。读完本文你将掌握该插件的全部配置项、指标与错误码语义并能基于源码与测试用例理解其内部判定逻辑从而组合出适合自身业务的可观测性方案。该插件自 Telegraf v0.12.1 引入定位于 server 探活场景支持所有操作系统核心实现位于 plugins/inputs/http_response/http_response.go可直接运行的样例配置见 plugins/inputs/http_response/sample.conf。插件能力总览http_response插件会针对urls列表中的每一个地址发起 HTTP/HTTPS 请求每次轮询周期输出一条名为http_response的指标包含如下维度信息响应状态码与状态码是否与期望值匹配响应耗时秒、响应体长度响应体内容是否命中指定的子串或正则表达式将响应体按需写入指定字段网络层故障的精确分类连接失败、超时、DNS 错误等支持代理、TLS、Basic Auth、Bearer Token、Cookie 认证、自定义 Header、指定出口网卡等复杂请求场景。插件在启动时通过Init()完成地址校验、正则编译与默认值填充在每次采集时通过Gather()遍历所有已创建的 HTTP 客户端并汇聚指标见 http_response.go 中的Init与Gather实现。快速开始在 Telegraf 配置文件中加入以下最小配置即可开始采集[[inputs.http_response]] urls [http://localhost, https://example.com] response_timeout 5s采集结果示例如下来自 plugins/inputs/http_response/README.md 的 Example Outputhttp_response,methodGET,resultsuccess,serverhttp://github.com,status_code200 content_length87878i,http_response_code200i,response_time0.937655534,result_code0i,result_typesuccess 1565839598000000000其中server为被探测的目标 URLmethod为请求方法status_code与http_response_code分别为响应状态码字符串 tag 与整型 fieldresult/result_code为本次探测的综合结论。完整配置项详解以下为插件完整的 TOML 配置模板与 sample.conf 及 README 中的sample.conf块一致逐项说明见后文# HTTP/HTTPS request given an address a method and a timeout [[inputs.http_response]] ## List of urls to query. # urls [http://localhost] ## Set http_proxy. ## Telegraf uses the system wide proxy settings if its is not set. # http_proxy http://localhost:8888 ## Set response_timeout (default 5 seconds) # response_timeout 5s ## HTTP Request Method # method GET ## Whether to follow redirects from the server (defaults to false) # follow_redirects false ## Bearer token for authentication, accepting secret-store references ## This option cannot be used in combination with bearer_token. # token my-token ## Optional HTTP Basic Auth Credentials # username username # password pa$$word ## Optional HTTP Request Body # body # {fake:data} # ## Optional HTTP Request Body Form ## Key value pairs to encode and set at URL form. Can be used with the POST ## method application/x-www-form-urlencoded content type to replicate the ## POSTFORM method. # body_form { key: value } ## Optional name of the field that will contain the body of the response. ## By default it is set to an empty String indicating that the bodys ## content wont be added # response_body_field ## Maximum allowed HTTP response body size in bytes. ## 0 means to use the default of 32MiB. ## If the response body size exceeds this limit a body_read_error will ## be raised. # response_body_max_size 32MiB ## Optional substring or regex match in body of the response (case sensitive) # response_string_match \service_status\: \up\ # response_string_match ok # response_string_match \.*_status\.?:.?\up\ ## Expected response status code. ## The status code of the response is compared to this value. If they match, ## the field response_status_code_match will be 1, otherwise it will be 0. ## If the expected status code is 0, the check is disabled and the field ## wont be added. # response_status_code 0 ## 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 ## Use the given name as the SNI server name on each URL # tls_server_name ## TLS renegotiation method, choose from never, once, freely # tls_renegotiation_method never ## HTTP Request Headers (all values must be strings) # [inputs.http_response.headers] # Host github.com ## Optional setting to map response http headers into tags ## If the http header is not present on the request, no corresponding tag will ## be added. If multiple instances of the http header are present, only the ## first value will be used. # http_header_tags {HTTP_HEADER TAG_NAME} ## Interface to use when dialing an address # interface eth0 ## Optional Cookie authentication # cookie_auth_url https://localhost/authMe # cookie_auth_method POST # cookie_auth_username username # cookie_auth_password pa$$word # cookie_auth_body {username: user, password: pa$$word, authenticate: me} ## cookie_auth_renewal not set or set to 0 will auth once and never renew the cookie # cookie_auth_renewal 5m请求目标与基础行为urls要探测的地址列表支持同时配置多个插件会为每个 URL 单独创建 HTTP 客户端并逐条输出指标。仅支持http与https两种 scheme其余 scheme 会在Init()阶段直接报错http_response.go。methodHTTP 请求方法默认GET。测试用例TestMethod验证了 POST 以及小写方法名如head均能正常工作http_response_test.go。response_timeout请求超时时间默认 5 秒。源码中当配置值小于 1 秒时会被重置为默认 5 秒http_response.go。follow_redirects是否跟随服务端重定向默认false。默认情况下客户端通过CheckRedirect返回http.ErrUseLastResponse来直接返回 3xx 响应本身便于直接观测重定向状态码http_response.go。测试TestRedirect验证了不跟随重定向时 301 响应及其响应体可被正常读取与匹配http_response_test.go。http_proxy显式指定代理地址留空时使用系统环境代理http.ProxyFromEnvironment。源码getProxyFunc明确体现了配置的代理覆盖系统代理这一优先级规则http_response.go。interface指定发起连接所使用的本地网卡。源码通过net.InterfaceByName找到网卡并依据目标地址是 IPv4 还是 IPv6 自动选择同格式的本地地址IPv6 时还会带上 zone端口由内核自行分配http_response.go。对应的 IPv6 判定函数由Test_isURLInIPv6、Test_isIPNetInIPv6覆盖http_response_test.go。请求内容构造body原始请求体以字符串形式发送。测试TestBody验证了携带 body 与空 body 两种情况下服务端的接收差异http_response_test.go。body_form键值对形式的请求体会被url.Values.Encode()编码为keyvalue...格式。常用于 POST application/x-www-form-urlencoded场景可复刻传统表单提交。测试TestResponseBodyFormField验证了多值参数如同一 key 的foobar、fizbuzz也能正确编码http_response_test.go。注意body与body_form同时配置时body优先http_response.go。headers自定义请求头所有值必须是字符串。若未显式设置User-Agent插件会自动填充 Telegraf 的产品标识internal.ProductToken()Host头会被特殊处理为请求的Host字段http_response.go。TestHeaders对这三个行为均有断言http_response_test.go。认证方式tokenBearer Token值为字符串同时支持 secret-store 引用详见 docs/CONFIGURATION.md 中 Secret Store Secrets 一节。它会以Authorization: Bearer token头发送。与旧选项bearer_token从文件读取 token 的路径互斥二者同时配置会在Init()报错 either use bearer_token or token not bothhttp_response.go。bearer_token已在 1.39.0 标记弃用计划 1.45.0 移除请使用token替代。TestTokenAuth与TestTokenConflictsWithBearerTokenFile分别验证了 Token 发送与互斥校验http_response_test.go。username / passwordHTTP Basic Auth 凭据同样支持 secret-store 引用通过request.SetBasicAuth注入。源码在获取 secret 后会立即Destroy()以清理内存中的敏感数据http_response.go。TestBasicAuth验证了生成的Authorization: Basic ...头http_response_test.go。TLS 配置tls_ca/tls_cert/tls_key用于指定 CA、客户端证书与私钥insecure_skip_verify可跳过证书链与主机名校验tls_server_name用于指定 SNI 服务器名tls_renegotiation_method支持never、once、freely三档。TLS 配置经由tls.ClientConfig.TLSConfig()生成并注入到 HTTP Transporthttp_response.go。TestSNI验证了自定义 SNI 名称会被服务端正确收到http_response_test.go。响应内容处理response_body_field若设置则响应体内容会作为字符串写入该字段默认留空表示不采集响应体。注意只有响应体为合法 UTF-8 时才会写入否则触发body_read_error见 http_response.go。TestResponseBodyField同时覆盖了正常写入与非法 UTF-8 两种路径http_response_test.go。response_body_max_size响应体最大允许字节数默认 32 MiB32 * 1024 * 1024见 http_response.go。读取时使用io.LimitReader限制读取量一旦超限即设置body_read_error结果http_response.go。TestResponseBodyMaxSize以 5 字节上限验证了超限判定http_response_test.go。response_string_match响应体匹配模式可以是普通子串也可以是正则表达式大小写敏感。插件在Init()阶段通过regexp.Compile预编译编译失败会直接报错http_response.go。命中时response_string_match字段为 1未命中为 0。TestStringMatch、TestStringMatchJson、TestStringMatchFail、TestBadRegex分别覆盖了普通匹配、JSON 风格匹配、匹配失败与非法正则四种场景http_response_test.go。response_status_code期望的响应状态码。比较规则相等则response_status_code_match 1否则为 0默认 0 表示禁用该检查此时不会输出该字段。TestStatusCodeMatch、TestStatusCodeMatchFail以及将状态码与字符串匹配组合使用的TestStatusCodeAndStringMatch/TestStatusCodeAndStringMatchFail均验证了相关行为http_response_test.go。http_header_tags将响应头映射为指标标签映射关系为{HTTP响应头名 标签名}。若响应中不存在该头则不加标签存在多个同名响应头时只取第一个值。TestHTTPHeaderTags验证了映射成功与响应头缺失两种情况http_response_test.go。Cookie 认证针对不提供 OAuth 或 Basic Auth 的服务的可选认证方式插件会先从授权端点获取 Cookie再在后续探测请求中携带。配置项包括cookie_auth_url获取 Cookie 的授权端点cookie_auth_method授权请求方法留空默认POSTcookie_auth_username / cookie_auth_password授权请求的 Basic Auth 凭据cookie_auth_body授权请求体例如特斯拉 Powerwall API 场景下以 JSON 请求体换取授权 Cookiecookie_auth_renewalCookie 续期间隔例如5m。不设置或设为0表示只认证一次、不续期。其底层实现位于公共模块 plugins/common/cookie/cookie.go认证时每次都会新建 Cookie Jar 以免旧 Cookie 参与再认证若设置了Renewal会启动一个后台 goroutine 按 ticker 周期调用auth()续期续期失败会输出日志授权端点返回非 2xx 状态码时返回cookie auth renewal received status code: ...错误cookie.go。Start方法在插件创建 HTTP 客户端时被调用http_response.go。指标与标签每次探测输出一条http_response指标tagsserver目标 URLmethod请求方法status_code响应状态码字符串result探测结果取值见下文表格。fieldsresponse_time响应耗时float单位秒content_length响应体长度intresponse_string_match响应体匹配结果int0 不匹配或读取失败1 匹配response_status_code_match状态码匹配结果int0 不匹配1 匹配http_response_code响应状态码intresult_type字符串形式的结果在 1.6 中已弃用请改用result标签与result_code字段result_code结果数值编码int。result标签与result_code字段语义result标签用于暴露网络层与插件自身错误是判断一次探测是否真正成功的关键。需要特别强调的是HTTP 错误状态码如 4xx/5xx在 net/http 中并不产生错误因此只要连接建立成功就视为successHTTP 层的不健康需要通过response_status_code或response_string_match来判定。完整取值表如下见 plugins/inputs/http_response/README.md 的 result 一节且与源码setResult中硬编码的映射一致http_response.goresult 标签值对应 result_code说明success0HTTP 请求完成即使状态码代表错误4xx/5xx也算成功response_string_mismatch1配置了response_string_match且响应体未命中带响应体的 HTTP 错误如 4xx/5xx也会触发body_read_error2配置了response_string_match但无法读取响应体如 3xx、HEAD 等空响应体或配置了response_body_field但响应体非合法 UTF-8或响应体超过response_body_max_sizeconnection_failed3插件未专门处理的网络错误兜底分类timeout4等待 HTTP 连接完成时超时dns_error5连接主机时发生 DNS 错误response_status_code_mismatch6配置了response_status_code且响应状态码不匹配值得说明的是源码setError在对错误分类时使用errors.As逐层剥离net.Error、url.Error、net.OpError从而区分超时、DNS 错误与地址解析错误address_error见 http_response.go其余未识别错误统一归类为connection_failed。测试TestNetworkErrors通过伪造错误链验证了 DNS 错误与连接失败的分支TestTimeout以 1 秒超时探测一个休眠 2 秒的端点验证了超时分支http_response_test.go。典型实战场景场景一HTTP 状态码健康检查只关心服务是否返回 200[[inputs.http_response]] urls [https://api.example.com/health] response_timeout 10s response_status_code 200 follow_redirects false此时若返回 200resultsuccess、result_code0、response_status_code_match1若返回 503resultresponse_status_code_mismatch、result_code6、response_status_code_match0但连接本身仍算成功。场景二响应体关键字/正则匹配探测内容层面的健康状态例如 JSON 接口中的服务状态字段[[inputs.http_response]] urls [https://api.example.com/status] response_string_match \service_status\: \up\ response_status_code 200未命中时resultresponse_string_mismatch、result_code1、response_string_match0。注意response_string_match区分大小写。场景三POST 表单提交探测以application/x-www-form-urlencoded模拟登录或提交接口[[inputs.http_response]] urls [https://example.com/api/submit] method POST body_form { user monitor, token abc123 } headers { Content-Type application/x-www-form-urlencoded } response_string_match ok场景四结合 InfluxDB 告警通过查询result_code ! 0即可发现所有网络层故障而 HTTP 层异常4xx/5xx单独用http_response_code监控例如SELECT last(result_code) FROM http_response WHERE result timeout GROUP BY server与全局配置的配合作为标准 Telegraf 输入插件http_response同样支持所有插件通用配置能力包括指标/标签/字段的修改重命名、裁剪等为插件配置alias别名插件执行顺序控制。详细说明见 docs/CONFIGURATION.md 的 Plugins 一节。此外插件的username、password、token三个选项支持 secret-store 引用可避免在配置文件中明文写入凭据使用方式见同一文档中的 Secret Store Secrets 一节。插件的注册与构建从源码结构看http_response通过 plugins/inputs/http_response/http_response.go 末尾的init()函数调用inputs.Add(http_response, ...)完成注册并在 plugins/inputs/all/http_response.go 中以空导入方式纳入默认构建对应 build taginputs.http_response。这意味着在不启用自定义构建custom时插件默认随 Telegraf 一起编译并可直接在配置文件中使用。小结http_response插件的核心设计在于用统一的result/result_code编码将连接是否建立与内容/状态码是否符合预期两类问题彻底分开。前者交给网络层分类timeout、dns_error、connection_failed等后者交给response_string_match与response_status_code两个检查项。理解这套语义你就能准确设计告警规则避免服务明明返回 500 却显示 success之类的误判。配合 Token/Basic/Cookie 多种认证与代理、TLS、指定网卡等能力该插件可以覆盖绝大多数 HTTP 服务拨测场景。【免费下载链接】telegrafAgent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.项目地址: https://gitcode.com/GitHub_Trending/te/telegraf创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考