如何在telegraf中排除此错误?

2024-06-11 04:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个自定义python插件,用于将数据拉入Telegraf。它按预期打印出线路协议输出

在我的Ubuntu 18.04环境中,当运行此插件时,我会在日志中看到一行:

2020-12-28T21:55:00Z E! [inputs.exec] Error in plugin: exec: exit status 1 for command '/my_company/plugins-enabled/plugin-mysystem/poll_mysystem.py': Traceback (most recent call last):...

就是这样。我不知道怎样才能得到真正的回溯

如果我运行sudo -u telegraf /usr/bin/telegraf -config /etc/telegraf/telegraf.conf,插件将按预期工作。它完全按照应该的方式轮询和加载数据

当telegraf自己执行插件时,我不知道如何解决这个错误

我已经重新启动了telegraf服务。我已经验证了权限(我认为上面的执行表明它应该可以工作)

根据收到的评论和答复,还有一些其他细节:

  • 插件位于一个目录中,整个结构归telegraf:telegraf所有。这个错误似乎并不表示它看不到正在执行的文件,而是表示当Telegraf执行插件时,文件中的某些东西出现了故障
  • 插件的代码如下所示

插件代码(/my_company/plugins-enabled/plugin-mysystem/poll_mysystem.py):

from google.auth.transport.requests import Request
from google.oauth2 import id_token
import requests
import os

RUNTIME_URL = INTERNAL_URL
MEASUREMENT = "MY_MEASUREMENT"
CREDENTIALS = "GOOGLE_SERVICE_FILE.json"
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = CREDENTIALS  # ENV VAR REQUIRED BY GOOGLE CODE BELOW
CLIENT_ID = VALUE_FROM_GOOGLE

exclude_fields = ["name", "version"] # Don't try to put these into influxdb from json response

def make_iap_request(url, client_id, method="GET", **kwargs):
    # Code provided by Google docs
    # Set the default timeout, if missing
    if "timeout" not in kwargs:
        kwargs["timeout"] = 90

    # Obtain an OpenID Connect (OIDC) token from metadata server or using service
    # account.
    open_id_connect_token = id_token.fetch_id_token(Request(), client_id)

    # Fetch the Identity-Aware Proxy-protected URL, including an
    # Authorization header containing "Bearer " followed by a
    # Google-issued OpenID Connect token for the service account.
    resp = requests.request(method, url, headers={"Authorization": "Bearer {}".format(open_id_connect_token)}, **kwargs)
    if resp.status_code == 403:
        raise Exception("Service account does not have permission to " "access the IAP-protected application.")
    elif resp.status_code != 200:
        raise Exception(
            "Bad response from application: {!r} / {!r} / {!r}".format(resp.status_code, resp.headers, resp.text)
        )
    else:
        return resp.json()


def print_results(results):
    """
    Take the results of a Dolores call and print influx line protocol results
    """
    for item in results["workflow"]:
        line_protocol_line_base = f"{MEASUREMENT},name={item['name']}"
        values = ""
        for key, value in item.items():
            if key not in exclude_fields:
                values = values + f",{key}={value}"
        values = values[1:]
        line_protocol_line = f"{line_protocol_line_base} {values}"
        print(line_protocol_line)


def main():
    current_runtime = make_iap_request(URL, CLIENT_ID, timeout=30)
    print_results(current_runtime)


if __name__== "__main__":
    main()

telegraf.conf文件的相关部分:

[[inputs.exec]]
  ## Commands array
  commands = [
    "/my_company/plugins-enabled/plugin-*/poll_*.py",
  ]

配置文件的代理部分

[agent]
  interval = "60s"
  round_interval = true
  metric_batch_size = 1000
  metric_buffer_limit = 10000
  collection_jitter = "0s"
  flush_interval = "10s"
  flush_jitter = "0s"
  precision = ""
  debug = false
  quiet = false
  logfile = "/var/log/telegraf/telegraf.log"
  hostname = ""
  omit_hostname = true

我下一步做什么


Tags: theinfrom插件tokenidifstatus
2条回答

请检查权限。 这似乎是一个权限错误。因为telegraf拥有运行sudo -u telegraf工作的必要权限。但是您尝试使用的user没有访问/my_company/plugins-enabled/中文件所需的权限

因此,我建议查看它们并将权限更改为Other can access and write或您试图使用telegraf的用户名

要解决此问题,请运行命令转到目录:

cd /my_company/plugins-enabled/

然后,要将所有权更改为您且仅更改为您:

sudo chown -R $(whoami)

然后,要更改所有文件和文件夹的读/写权限,请执行以下操作:

sudo chmod -R u+w

如果您希望所有人,系统上的所有人都可以对这些文件和文件夹进行读/写操作,并且只想将所有权限授予所有人:

sudo chmod -R 777

exec插件正在换行时截断您的异常消息。如果您将对make_iap_request的调用包装在try/except块中,然后print(e, file=sys.stderr)而不是让异常一直冒泡,这应该告诉您更多

def main():
    """
    Query URL and print line protocol
    """
    try:
        current_runtime = make_iap_request(URL, CLIENT_ID, timeout=30)
        print_results(current_runtime)
    except Exception as e:
        print(e, file=sys.stderr)

或者,您的脚本可以将错误消息记录到自己的日志文件中,而不是将它们传递回Telegraf。这将使您能够更好地控制记录的内容

我怀疑您遇到了一个环境问题,您运行它的方式有所不同。如果不是权限,则可能是环境变量差异

相关问题 更多 >