graph templates does not match my plugin script

This support forum board is for support questions relating to Nagios XI, our flagship commercial network monitoring solution.
sirine707
Posts: 7
Joined: Mon Mar 03, 2025 2:31 am

graph templates does not match my plugin script

Post by sirine707 »

Hello ,

I wrote a custom plugin script in order to retrieve with API , Moving average values as a line chart each at "start_date" key from json output
and "Alert" when the value is different of 0 at "start_date" as vertical line .
My question is how to modify the graph template in order for nagiosxi to parse my plugin output .
here is the output of the API i called in the plugin script :

Code: Select all

[
    {
        "date": "25/02/2025",
        "time_blocks": [
            {
                "alert": 4,
                "logs": [
                    {
                        "positive": false,
                        "reason": "",
                        "value": "hi"
                    },
                    {
                        "positive": false,
                        "reason": "",
                        "value": "hi"
                    },
                    {
                        "positive": false,
                        "reason": "",
                        "value": "hi"
                    },
                    {
                        "positive": false,
                        "reason": "",
                        "value": "hi"
                    },
                    {
                        "positive": false,
                        "reason": "",
                        "value": "hi"
                    }
                ],
                "moyenne_mobile": 0,
                "retries": 4,
                "start_time": "05:49:57"
            },
            {
                "alert": 0,
                "logs": [
                    {
                        "positive": false,
                        "reason": "",
                        "value": "hi"
                    }
                ],
                "moyenne_mobile": 0,
                "retries": 1,
                "start_time": "06:39:57"
            },
            {
                "alert": 0,
                "logs": [
                    {
                        "positive": false,
                        "reason": "",
                        "value": "hi"
                    },
                    {
                        "positive": false,
                        "reason": "",
                        "value": "hi"
                    },
                    {
                        "positive": false,
                        "reason": "",
                        "value": "hi"
                    }
                ],
                "moyenne_mobile": 0,
                "retries": 3,
                "start_time": "07:49:57"
            },
            {
                "alert": 0,
                "logs": [
                    {
                        "positive": false,
                        "reason": "",
                        "value": "hi"
                    }
                ],
                "moyenne_mobile": 0,
                "retries": 1,
                "start_time": "09:49:57"
            },
            {
                "alert": 0,
                "logs": [
                    {
                        "positive": false,
                        "reason": "apple",
                        "value": "est ce que Apple a sorti des nouvelels distributions"
                    }
                ],
                "moyenne_mobile": 4.0,
                "retries": 1,
                "start_time": "10:44:57"
            }
        ],
        "validator": "Competitor Check"
    },
            {
                "alert": 4,
                "logs": [
                    {
                        "positive": false,
                        "reason": "samsung",
                        "value": "did samsung partenred with Nvidia"
                    },
                    {
                        "positive": false,
                        "reason": "samsung",
                        "value": "did samsung release samsung pro max"
                    },
                    {
                        "positive": false,
                        "reason": "samsung",
                        "value": "did samsung release samsung pro max"
                    }
                ],
                "moyenne_mobile": 0,
                "retries": 4,
                "start_time": "16:44:57"
            }
        ],
        "validator": "Competitor Check"
    }
]
here is my plugin script logic that i want to visualize :

Code: Select all

#!/usr/bin/env python3

import requests
import sys
import json

# Nagios status codes
OK = 0
WARNING = 1
CRITICAL = 2
UNKNOWN = 3

API_URL = "http://XXX.XXX.XX.XXX:YYYY/api/comp_check"

def main():
   try:
       response = requests.get(API_URL, timeout=30)
       response.raise_for_status()
       data = response.json()
   except requests.RequestException as e:
       print(f"CRITICAL - API call failed: {e}")
       sys.exit(CRITICAL)
   except ValueError:
       print("CRITICAL - API response is not valid JSON")
       sys.exit(CRITICAL)

   perf_data_points = []

   # Process data
   for entry in data:
       date = entry.get("date", "")
       for tb in entry.get("time_blocks", []):
           start_time = tb.get("start_time", "")
           ma_value = tb.get("moyenne_mobile", 0)
           alert_value = tb.get("alert", 0)
           retries = tb.get("retries", 0)

           timestamp = f"{date} {start_time}"
           perf_data_points.append({
               "timestamp": timestamp,
               "ma_value": ma_value,
               "alert_value": alert_value,
               "retries": retries
           })

   # Determine Nagios status
   nagios_status = OK
   if any(tb["alert_value"] > 0 for tb in perf_data_points):
       nagios_status = WARNING

   if nagios_status == OK:
       status_text = f"OK - Moving Average: {ma_value}"
   else:
       status_text = f"WARNING - Alerts detected, Moving Average: {ma_value}"

   # Format performance data for graphing
   perf_data = " ".join([
       f"'{point['timestamp']}'={point['ma_value']};1;2;0;5 'Alert'={point['alert_value']};0;0;0;10"
       for point in perf_data_points
   ])

   print(f"Competitor Check - {status_text} | {perf_data}")
   sys.exit(nagios_status)

if __name__ == "__main__":
   main()
this is the grap output :
https://drive.google.com/file/d/14Rp9U2 ... sp=sharing

this is what iam expecting to visualize :
orange vertical lines are Alerts when Alert!=0
https://drive.google.com/file/d/1zzS5nv ... sp=sharing


I appreciate ur feedback :)
DoubleDoubleA
Posts: 199
Joined: Thu Feb 09, 2017 5:07 pm

Re: graph templates does not match my plugin script

Post by DoubleDoubleA »

Hi @sirine707,

I don't fully understand what you are trying to do here. Can you explain more simply and fully what you are doing and hoping to accomplish?

Aaron
sirine707
Posts: 7
Joined: Mon Mar 03, 2025 2:31 am

Re: graph templates does not match my plugin script

Post by sirine707 »

Hello ,

So iam working to visualize Moving average (theses values is calculated when a certain number of retries is exceeded) which triggers alerts( the value of alert key is 0 or 1).
both MA and alerts are retrieved from an API call , I attached above the output , i know it is not the main purpose of nagiosxi but thats what i must do .

now i solved the graph template issue by unticking the highchart box , but i noticed that older values of MA and alerts are not visualized at their "start_time" but instead visualized from the time the service started , is there a file I change manually ?

thank you for the feedback .
jsimon
Posts: 317
Joined: Wed Aug 23, 2023 11:27 am

Re: graph templates does not match my plugin script

Post by jsimon »

Hi @sirine707,

What kind of graph are you looking to generate based on this data? I understand you're trying to get a graph generated based on a custom plugin, are you trying to get a Performance Data graph for this? If so, your plugin would need to be generating an RRD file for the graph template to use. If this is correct, I believe what you need is a custom graph template that will look for the values you're putting into the perfdata field in your plugin output. Let me know if I've misunderstood your goals here, or if you have any questions about this.
sirine707
Posts: 7
Joined: Mon Mar 03, 2025 2:31 am

Re: graph templates does not match my plugin script

Post by sirine707 »

I am looking to visualize a line chart wich represents the moving average values with vertical lines when an alert is detected at 'start_time' retrieved from the api ,
I attached the desired output

my issue is the script of my custom plugin retrieves correctly the 'start_dates' (old dates from a week ago ) but they are not visualized correctly .instead the graph is visualizing with random dates starting from the time i launched the service .

can you please share ur feedback abt how can i possibly fix the issue

Thank you !
You do not have the required permissions to view the files attached to this post.
sirine707
Posts: 7
Joined: Mon Mar 03, 2025 2:31 am

Re: graph templates does not match my plugin script

Post by sirine707 »

this is my output of my custom plugin :
WARNING - Moving Average: 1.0 - Alerts detected! | moving_average=0;1;2;0;5 moving_average=0;1;2;0;5 alert=4;;;; moving_average=0;1;2;0;5 moving_average=0;1;2;0;5 moving_average=1.0;1;2;0;5 moving_average=0.5;1;2;0;5 moving_average=0;1;2;0;5 moving_average=0;1;2;0;5 alert=4;;;; moving_average=0;1;2;0;5 moving_average=0;1;2;0;5 alert=4;;;; moving_average=0;1;2;0;5 alert=4;;;; moving_average=1.0;1;2;0;5 alert=4;;;; moving_average=0.5;1;2;0;5 moving_average=0.3333333333333333;1;2;0;5 moving_average=0.25;1;2;0;5 moving_average=0;1;2;0;5 moving_average=0;1;2;0;5 moving_average=0;1;2;0;5 moving_average=0;1;2;0;5 moving_average=0;1;2;0;5 moving_average=0;1;2;0;5 moving_average=1.0;1;2;0;5 moving_average=0.5;1;2;0;5 moving_average=0;1;2;0;5 moving_average=0;1;2;0;5 moving_average=0;1;2;0;5 moving_average=0;1;2;0;5

in a perfect world, these should be my data entries , but instead this plugin generated about 21 Data source but i only have 2 metrics moving average and alert how to fix this please ?
jsimon
Posts: 317
Joined: Wed Aug 23, 2023 11:27 am

Re: graph templates does not match my plugin script

Post by jsimon »

I wouldn't say the graph you're getting has "random" dates, as look to be the same date if I'm reading the chart correctly. Looking at the output of the plugin you posted, I actually don't see dates in here at all, so I believe the first thing you need to fix is getting the date values you're looking into your plugin output. Once you do that, you'll need to make sure the field name you're using for your date and your "alert" values match what the graph Template you're using is looking for. Once you get those two pieces working I believe you'll have the graph you're looking for, or at least be further on the right track here.

It might be helpful as well to know which graph Template you're using.
sirine707
Posts: 7
Joined: Mon Mar 03, 2025 2:31 am

Re: graph templates does not match my plugin script

Post by sirine707 »

Hey ..
for this plugin output : /usr/local/nagios/libexec/sql_injection_plugin.py
WARNING - Moving Average: 1.0 - Alerts detected! | MA_1740128848=0;1;2;0;5 MA_1740215248=0;1;2;0;5 MA_1740474448=0;1;2;0;5 MA_1740478348=0;1;2;0;5 MA_1740481648=0;1;2;0;5 MA_1740485548=0;1;2;0;5 MA_1740490648=1.0;1;2;0;5 MA_1740550348=0;1;2;0;5 MA_1740553648=0;1;2;0;5 MA_1740651748=0;1;2;0;5 ALERT_1740651748=4;;;;

how can i visualize MA as line chart at the historic time retrieved from the api invoked in my custom plugin and same for alerts ?
here is the graph template script :

Code: Select all

<?php
#
# Template PNP4Nagios for "check_competitor"
# - Plots the moving average (MA) as a blue line
# - Marks alerts (ALERT) as vertical orange ticks
#

// Custom colors
define("_MA_COLOR", "#0000FF");    // Blue for moving average
define("_ALERT_COLOR", "#FFA500"); // Orange for alerts

// Create a single graph (index [1])
$opt[1] = '--vertical-label "Value" '
        . '--title "' . $hostname . ' / ' . $servicedesc . '" '
        . '--slope-mode';

$def[1] = '';

// Loop through each Data Source (DS)
foreach ($DS as $i => $ds_name) {
    $metric_name = $NAME[$i];

    // Extract metric type and timestamp
    preg_match('/^(MA|ALERT)_(\d+)$/', $metric_name, $matches);
    if (count($matches) == 3) {
        $metric_type = $matches[1];
        $timestamp = $matches[2];

        // Case: Moving Average (MA)
        if ($metric_type == "MA") {
            // Define series (DEF) and plot it as a blue line
            $def[1] .= "DEF:ma$i=$rrdfile:$ds_name:AVERAGE ";
            $def[1] .= "LINE2:ma$i"._MA_COLOR.":\"Moving Average ($timestamp)\" ";
            $def[1] .= "GPRINT:ma$i:LAST:\"LAST %3.2lf \" ";
            $def[1] .= "GPRINT:ma$i:MAX:\"MAX %3.2lf \" ";
            $def[1] .= "GPRINT:ma$i:AVERAGE:\"AVG %3.2lf\\n\" ";

        // Case: Alerts (ALERT)
        } elseif ($metric_type == "ALERT") {
            // Define series
            $def[1] .= "DEF:alert$i=$rrdfile:$ds_name:AVERAGE ";
            // TICK draws a vertical bar (1.0 height) for each alert > 0
            $def[1] .= "TICK:alert$i"._ALERT_COLOR.":1:\"Alert ($timestamp)\" ";
        }
    }
}
?>
can u please share with your feedback ?
jsimon
Posts: 317
Joined: Wed Aug 23, 2023 11:27 am

Re: graph templates does not match my plugin script

Post by jsimon »

So, there are several issues I see here. It looks like you're building labels out of timestamps here, and I think that's part of the issue you're running into. Labels for RRDs need to be the same for every instance of data occurring as they function like column names in a table. In theory you could map the timestamps from your plugin output by building output that is formatted like:

Code: Select all

time=timestamp, MA=0;1;2;0;5
However, it seems like the data you're trying to graph may not align with what the graph tool you're trying to use is made to do. The x axis on the graph you're using is not meant to be based on data from the check, but rather is a timestamp based on when the check was run. The idea is to set this custom plugin to be run at a set interval, and map the data from the response specifically when the check was run. You wouldn't be able to set the X axis of the graph to the timestamp data from the plugin results. You could graph that value as a separate line, but I don't see how the lines would correlate based on this.

Let us know if you have questions about this, or if I've misunderstood the nuance of your project.
sirine707
Posts: 7
Joined: Mon Mar 03, 2025 2:31 am

Re: graph templates does not match my plugin script

Post by sirine707 »

Hello ,

The reason why i set the x-axis as timestamps , because I have historical data retrieved from a custom log API , otherwise it will be automatically managed based on when the data is inserted which's not the correct timestamp.