atc0005 / go-nagios

Shared Golang package for Nagios plugins
MIT License
8 stars 3 forks source link

Add constructor to initialize plugin start time, provide `time` Performance Data metric "automatically" #102

Closed atc0005 closed 1 year ago

atc0005 commented 2 years ago

Example code snippet from the atc0005/check-vmware project:

func main() {

    // Start the timer. We'll use this to emit the plugin runtime as a
    // performance data metric.
    pluginStart := time.Now()

    // Set initial "state" as valid, adjust as we go.
    var nagiosExitState = nagios.ExitState{
        LastError:      nil,
        ExitStatusCode: nagios.StateOKExitCode,
    }

    // defer this from the start so it is the last deferred function to run
    defer nagiosExitState.ReturnCheckResults()

    // Collect last minute details just before ending plugin execution.
    defer func(exitState *nagios.ExitState, start time.Time) {

        // Record plugin runtime, emit this metric regardless of exit
        // point/cause.
        runtimeMetric := nagios.PerformanceData{
            Label: "time",
            Value: fmt.Sprintf("%dms", time.Since(start).Milliseconds()),
        }
        if err := exitState.AddPerfData(false, runtimeMetric); err != nil {
            zlog.Error().
                Err(err).
                Msg("failed to add time (runtime) performance data metric")
        }

        // Annotate errors (if applicable) with additional context to aid in
        // troubleshooting.
        nagiosExitState.LastError = vsphere.AnnotateError(nagiosExitState.LastError)
    }(&nagiosExitState, pluginStart)

Some thoughts come to mind:

The initialization logic for plugins in the atc0005/check-vmware project would be greatly simplified, and presumably other projects would benefit from these changes.

One "gotcha" that I'd need to guard against would be if client code opts to not use the constructor: the ReturnCheckResults() method would need to assert that the runtime field is not its zero value before generating a performance data metric.

atc0005 commented 1 year ago

Implemented via GH-167.