github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/aagent/watchers/nagioswatcher/builtin_goss_unix.go (about)

     1  // Copyright (c) 2021, R.I. Pienaar and the Choria Project contributors
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  //go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
     6  // +build darwin dragonfly freebsd linux netbsd openbsd solaris
     7  
     8  package nagioswatcher
     9  
    10  import (
    11  	"bytes"
    12  	"encoding/json"
    13  	"fmt"
    14  
    15  	"github.com/goss-org/goss"
    16  	"github.com/goss-org/goss/outputs"
    17  	gossutil "github.com/goss-org/goss/util"
    18  )
    19  
    20  func (w *Watcher) watchUsingGoss() (state State, output string, err error) {
    21  	var out bytes.Buffer
    22  
    23  	opts := []gossutil.ConfigOption{
    24  		gossutil.WithMaxConcurrency(1),
    25  		gossutil.WithResultWriter(&out),
    26  		gossutil.WithSpecFile(w.properties.Gossfile),
    27  	}
    28  
    29  	od, err := w.machine.OverrideData()
    30  	if err == nil && len(od) > 0 {
    31  		opts = append(opts, gossutil.WithVarsBytes(od))
    32  	}
    33  
    34  	cfg, err := gossutil.NewConfig(opts...)
    35  	if err != nil {
    36  		return UNKNOWN, fmt.Sprintf("UNKNOWN: goss configuration failed: %s", err), err
    37  	}
    38  
    39  	_, err = goss.Validate(cfg)
    40  	if err != nil {
    41  		return UNKNOWN, fmt.Sprintf("UNKNOWN: goss validate failed: %s", err), err
    42  	}
    43  
    44  	res := &outputs.StructuredOutput{}
    45  	err = json.Unmarshal(out.Bytes(), res)
    46  	if err != nil {
    47  		return UNKNOWN, fmt.Sprintf("UNKNOWN: goss output invalid: %s", err), err
    48  	}
    49  
    50  	pd := fmt.Sprintf("checks=%d;; failed=%d;; runtime=%fs", res.Summary.TestCount, res.Summary.Failed, res.Summary.TotalDuration.Seconds())
    51  
    52  	if res.Summary.Failed > 0 {
    53  		return CRITICAL, fmt.Sprintf("CRITICAL: %s|%s", res.SummaryLine, pd), nil
    54  	}
    55  
    56  	return OK, fmt.Sprintf("OK: %s|%s", res.SummaryLine, pd), nil
    57  }