Skip to content
Snippets Groups Projects
node_context_switches.py 1.2 KiB
Newer Older
#!/usr/bin/env python3

# Script expects that Prometheus node_exporter is running on the local host
# https://github.com/prometheus/node_exporter
#
# The script queries node_exporter returns the total number of context
# switches as an integer, ex: 240080031436
#
# node_eporter field: node_context_switches_total
import requests

url = "http://localhost:9100/metrics"

# Send GET request to the URL
response = requests.get(url)

# Check if the request was successful (status code 200)

if response.status_code == 200:
    # Filter lines containing "node_context_switches_total" and ignore lines
    # starting with "#"
    filtered_lines = [line for line in response.text.split(
        "\n") if "node_context_switches_total" in line and not line.startswith("#")]

    # Parse the second column of the filtered lines
    for line in filtered_lines:
        columns = line.split()
        if len(columns) >= 2:
            metric_name = columns[0]
            metric_value = int(float(columns[1]))
#            print(f"Metric: {metric_name}")
#            print(f"Value: {metric_value}")
            print(metric_value)
else:
    print(
        f"Error: Failed to retrieve data from {url}. Status code: {response.status_code}")