Skip to content

Commit

Permalink
Add support for embedded/encoded payloads
Browse files Browse the repository at this point in the history
OVERVIEW

Add support for embedding an encoded payload within and later
extracting the payload from plugin output.

The current Nagios plugin API permits returning human readable
information to Nagios for display in a web UI or notifications and
metrics for calculations & other data manipulation purposes. As far as
I know, Nagios does not permit passing something like a JSON payload
directly between the plugin and the monitoring system.

This new (optional) support provides a way for plugins to safely &
reliably embed content (e.g., JSON data) within the generated output
which can later be extracted by other tools.

Due to current Nagios plugin output length restrictions (8192 bytes),
the use of encoded payloads should be used sparingly.

CHANGES

- add standalone functions for encoding/decoding payload content
- add new `Plugin` methods for adding (append or overwrite behavior)
  content to be encoded and embedded as a payload
- add new `Plugin` methods to override behavior
  - opt out of using delimiters (NOT RECOMMENDED)
  - use custom delimiters
  - set custom payload section label
- minor README updates
  - note new functionality
  - refresh overview & status sections
- add test coverage for new functionality
- add numerous testdata input files
- add basic examples
  - extract and decode an embedded payload from (previous) plugin
    output
  - add encoded payload

CREDIT

I consulted ChatGPT when planning the implementation. While later
iterations of the code differed significantly, ChatGPT provided
code samples that acted as a starting point for the initial
encoding/decoding functionality.

Discussions with ChatGPT proved very helpful when deciding between
using the base64 encoding format (more common, but less efficient) and
the base85 (aka, "Ascii85") encoding format (more efficient). Those
discussions also covered concerns such as adhering to the default
`illegal_macro_output_chars` requirements that Nagios imposes for
plugin output.

REFERENCES

- refs #251
- refs atc0005/check-cert#960
  • Loading branch information
atc0005 committed Oct 15, 2024
1 parent 6243506 commit f64b513
Show file tree
Hide file tree
Showing 38 changed files with 2,904 additions and 161 deletions.
35 changes: 21 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,37 +12,38 @@ Shared Golang package for Nagios plugins
<!-- omit in toc -->
## Table of contents

- [Status](#status)
- [Overview](#overview)
- [Status](#status)
- [Features](#features)
- [Changelog](#changelog)
- [Examples](#examples)
- [License](#license)
- [Used by](#used-by)
- [References](#references)

## Status

Alpha quality.
## Overview

This codebase is subject to change without notice and may break client code
that depends on it. You are encouraged to [vendor](#references) this package
if you find it useful until such time that the API is considered stable.
This package provides support and functionality common to monitoring plugins.
While Nagios (Core and XI) are primary monitoring platform targets, the intent
is to support (where feasible) all monitoring platforms compatible with Nagios
plugins.

## Overview
## Status

This package contains common types and package-level variables used when
developing Nagios plugins. The intent is to reduce code duplication between
various plugins and help reduce typos associated with literal strings.
While attempts are made to provide stability, this codebase is subject to
change without notice and may break client code that depends on it. You are
encouraged to [vendor](#references) this package if you find it useful until
such time that the API is considered stable.

## Features

- Nagios state constants
- state labels (e.g., `StateOKLabel`)
- state exit codes (e.g., `StateOKExitCode`)
- Nagios `CheckOutputEOL` constant
- provides a consistent newline format for both Nagios Core and Nagios XI
(and presumably other similar monitoring systems)
- provides a common newline format shown to produce consistent results for
both Nagios Core and Nagios XI (and presumably other similar monitoring
systems)
- Nagios `ServiceState` type
- simple label and exit code "wrapper"
- useful in client code as a way to map internal check results to a Nagios
Expand All @@ -58,7 +59,7 @@ various plugins and help reduce typos associated with literal strings.
the service or host state to be an issue
- Panics from client code are captured and reported
- panics are surfaced as `CRITICAL` state
- service output and error details are overridden to panic prominent
- service output and error details are overridden to make panics prominent
- Optional support for emitting performance data generated by plugins
- if not overridden by client code *and* if using the provided
`nagios.NewPlugin()` constructor, a default `time` performance data metric
Expand All @@ -73,6 +74,12 @@ various plugins and help reduce typos associated with literal strings.
- Automatically omit `LongServiceOutput` section if not specified by client
code
- Support for overriding text used for section headers/labels
- Support for adding/embedding an encoded payload (Ascii85) in plugin output
- Support for decoding (Ascii85) encoded input (payload)
- Support for extracting an (Ascii85) encoded payload from captured plugin
output
- Support for extracting and decoding an (Ascii85) encoded payload (into the
original non-encoded form) from captured plugin output

## Changelog

Expand Down
70 changes: 70 additions & 0 deletions example_add_encoded_payload_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Copyright 2020 Adam Chalkley
//
// https://github.com/atc0005/go-nagios
//
// Licensed under the MIT License. See LICENSE file in the project root for
// full license information.

package nagios_test

import (
"log"

"github.com/atc0005/go-nagios"
)

// Ignore this. This is just to satisfy the "whole file" example requirements
// per https://go.dev/blog/examples.
var _ = "https://github.com/atc0005/go-nagios"

// Example_addEncodedPayload demonstrates adding an encoded payload to plugin
// output (e.g., for potential later retrieval via the monitor systems' API).
func Example_addEncodedPayload() {
// First, create an instance of the Plugin type. By default this value is
// configured to indicate a successful execution. This should be
// overridden by client code to indicate the final plugin state to Nagios
// when the plugin exits.
var plugin = nagios.NewPlugin()

// Second, immediately defer ReturnCheckResults() so that it runs as the
// last step in your client code. If you do not defer ReturnCheckResults()
// immediately any other deferred functions in your client code will not
// run.
//
// Avoid calling os.Exit() directly from your code. If you do, this
// library is unable to function properly; this library expects that it
// will handle calling os.Exit() with the required exit code (and
// specifically formatted output).
//
// For handling error cases, the approach is roughly the same, only you
// call return explicitly to end execution of the client code and allow
// deferred functions to run.
defer plugin.ReturnCheckResults()

// more stuff here involving performing the actual service check

// This simple JSON structure represents a more detailed blob of data that
// might need post-processing once retrieved from the monitoring system's
// API, etc.
//
// Imagine this is something like a full certificate chain or a system's
// state and not easily represented by performance data metrics (e.g.,
// best represented in a structured format once later extracted and
// decoded).
sampleComplexData := `{"Age":17,"Interests":["books","games", "Crystal Stix"]}`

if _, err := plugin.AddPayloadString(sampleComplexData); err != nil {
log.Printf("failed to add encoded payload: %v", err)
plugin.Errors = append(plugin.Errors, err)

return
}

//nolint:goconst
plugin.ServiceOutput = "one-line summary of plugin results "

//nolint:goconst
plugin.LongServiceOutput = "more detailed output from plugin here"

// more stuff here involving wrapping up the service check
}
80 changes: 80 additions & 0 deletions example_extract_payload_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright 2020 Adam Chalkley
//
// https://github.com/atc0005/go-nagios
//
// Licensed under the MIT License. See LICENSE file in the project root for
// full license information.

package nagios_test

import (
"fmt"
"log"
"os"

"github.com/atc0005/go-nagios"
)

// Ignore this. This is just to satisfy the "whole file" example requirements
// per https://go.dev/blog/examples.
var _ = "https://github.com/atc0005/go-nagios"

// Example_extractEncodedPayload represents a sample client application that
// extracts a previously encoded payload from plugin output (e.g., retrieved
// via the monitoring system's API or a log file).
func Example_extractEncodedPayload() {
// This represents the data before it was encoded and added to the plugin
// output.
origData := `{"Age":17,"Interests":["books","games", "Crystal Stix"]}`

// This represents the encoded data that was previously added to the
// plugin output.
encodedData := `<~HQkagAKj/i2_6.EDKKH1ATMs7,!&pP@W-1#F!<.ZB45XgF!<.X,"$BrF*(i,+B*ArGTpFA~>`

sampleServiceOutput := "one-line summary of plugin results "
sampleLongServiceOutput := "detailed text line1\ndetailed text line2\ndetailed text line3"
sampleMetricsOutput := `| 'time'=874ms;;;;`

// This represents the original plugin output captured by the monitoring
// system which we retrieved via the monitoring system's API, a log file,
// etc.
originalPluginOutput := fmt.Sprintf(
"%s%s%s%s%s%s%s",
sampleServiceOutput,
sampleLongServiceOutput,
nagios.CheckOutputEOL,
encodedData,
nagios.CheckOutputEOL,
sampleMetricsOutput,
nagios.CheckOutputEOL,
)

decodedPayload, err := nagios.ExtractAndDecodeASCII85Payload(
originalPluginOutput,
"",
nagios.DefaultASCII85EncodingDelimiterLeft,
nagios.DefaultASCII85EncodingDelimiterRight,
)

if err != nil {
log.Println("Failed to extract and decode payload from original plugin output", err)

os.Exit(1)
}

// We compare here for illustration purposes, but in many cases you may
// not have access to the data in its original form as collected by the
// monitoring plugin (e.g., it was generated dynamically or retrieved from
// a remote system's state and not stored long-term).
if decodedPayload != origData {
log.Println("Extracted & decoded payload data does not match original data")

os.Exit(1)
}

fmt.Println("Original data:", decodedPayload)

// Output:
//
// Original data: {"Age":17,"Interests":["books","games", "Crystal Stix"]}
}
Loading

0 comments on commit f64b513

Please sign in to comment.