【问题标题】:Prometheus and Grafana - Is there a way to get users on a machine?Prometheus 和 Grafana - 有没有办法让用户使用机器?
【发布时间】:2021-05-26 15:04:35
【问题描述】:

我一直在与 Prometheus 和 Grafana 合作,以获取几个计算机实验室的状态和统计数据。有没有办法让通过 Prometheus 登录计算机的用户将其放到 Grafana 上?

【问题讨论】:

    标签: prometheus grafana promql


    【解决方案1】:

    我将列出 2 个选项。第一次使用带有 Prometheus 的 Pushgateway,第二次只使用 Prometheus。

    1 - 将 Pushgateway 与 Prometheus 一起使用

    您可以使用的一种解决方案是使用Pushgateway。您将已登录和未登录的用户推送到 PushgatewayPrometheus 抓取它以收集值。这很快,因为您无需配置应用程序即可让 Prometheus 从中抓取数据。首先在 prometheus.yml 配置文件中配置 PushGateway:

    ....
    scrape_configs:
      - job_name: 'pushgateway'
        scrape_interval: 10s
        honor_labels: true # disable auto discover labels
        static_configs:
          - targets: ['pushgateway:9091']
    

    然后使用此脚本收集所有用户并将其拆分为已登录和未登录的用户:

    #!/bin/bash
    
    users=`cat /etc/passwd | cut -d: -f1`
    users_logged=`who | cut -d' ' -f1 | sort | uniq`
    
    for u in $users; do
      cmd="curl --data-binary @- http://admin:admin@localhost:9091/metrics/job/$u"
      if [[ "$users_logged" == *"$u"* ]]; then
        # echo "some_metric 3.14" | curl --data-binary @- http://admin:admin@localhost:9091/metrics/job/some_job
        echo "linux_user 1" | `echo $cmd`
      else
        echo "linux_user 0" | `echo $cmd`
      fi
    done
    

    Pushgateway 在http://127.0.0.1:9091/ 启动并运行后,您将在玉米作业中运行脚本,它将值推送到 Pushgateway。

    2 - 仅使用 Prometheus

    如果您不想使用 Pushgateway,您可以配置您的应用程序以收集登录您机器的用户并使用适合您的应用程序编程语言的 Prometheus client library 并公开指标端点并让 Prometheus 从它。这是一个使用Spring Boot with micrometer in Java 的示例。

    【讨论】:

    • 我最终使用了 Pushgateway,感谢您的好评!
    【解决方案2】:

    prometheus node_exporter 有一个 logind collector 默认禁用。

    您只需在启动时启用此收集器即可获取您需要的有关当前登录用户的指标。要启用导出器,您需要在启动时提供此标志:

    --collector.logind
    

    【讨论】: