Search code examples
prometheusgrafanapromql

Prometheus and Grafana - Is there a way to get users on a machine?


I have been working with Prometheus and Grafana to get status and statistics on a couple computer labs. Is there a way that I can get users that have logged onto a computer through Prometheus and get that put onto Grafana?


Solution

  • I will list 2 options. First using Pushgateway with Prometheus and the second using only Prometheus.

    1 - Using Pushgateway with Prometheus

    One solution that you can use is with Pushgateway. You push the logged and not logged users to Pushgateway and Prometheus scrapes it to collect the values. This is fast because you don't have to configure your application to let Prometheus scrape data from it. First configure PushGateway on your prometheus.yml config file:

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

    Then use this script to collect all users and split them into logged and not logged users:

    #!/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
    

    Once you Pushgateway is up and running at http://127.0.0.1:9091/ you run the script in a corn job and it will push the values to Pushgateway. enter image description here

    2 - Using only Prometheus

    If you don't want to use Pushgateway you can configure your application to collect the users logged in your machine and use a Prometheus client library which fits your app programming language and expose the metric end-point and let Prometheus pull data from it. Here is one example using Spring Boot with micrometer in Java.