github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/aagent/util/nagios.go (about) 1 // Copyright (c) 2021, R.I. Pienaar and the Choria Project contributors 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 5 package util 6 7 import ( 8 "regexp" 9 "strconv" 10 "strings" 11 ) 12 13 // PerfData represents a single item of Nagios performance data 14 type PerfData struct { 15 Unit string `json:"unit"` 16 Label string `json:"label"` 17 Value float64 `json:"value"` 18 } 19 20 var valParse = regexp.MustCompile(`^([-*\d+\.]+)(us|ms|s|%|B|KB|MB|TB|c)*`) 21 22 // ParsePerfData parses Nagios format performance data from an output string 23 // https://stackoverflow.com/questions/46886118/what-is-the-nagios-performance-data-format 24 func ParsePerfData(pd string) (perf []PerfData) { 25 parts := strings.Split(pd, "|") 26 if len(parts) != 2 { 27 return perf 28 } 29 30 rawMetrics := strings.Split(strings.TrimSpace(parts[1]), " ") 31 for _, rawMetric := range rawMetrics { 32 metric := strings.TrimSpace(rawMetric) 33 metric = strings.TrimPrefix(metric, "'") 34 metric = strings.TrimSuffix(metric, "'") 35 36 if len(metric) == 0 { 37 continue 38 } 39 40 // throwing away thresholds for now 41 mparts := strings.Split(metric, ";") 42 mparts = strings.Split(mparts[0], "=") 43 if len(mparts) != 2 { 44 continue 45 } 46 47 label := strings.Replace(mparts[0], " ", "_", -1) 48 valParts := valParse.FindStringSubmatch(mparts[1]) 49 rawValue := valParts[1] 50 value, err := strconv.ParseFloat(rawValue, 64) 51 if err != nil { 52 continue 53 } 54 55 pdi := PerfData{ 56 Label: label, 57 Value: value, 58 } 59 if len(valParts) == 3 { 60 pdi.Unit = valParts[2] 61 } 62 63 perf = append(perf, pdi) 64 } 65 66 return perf 67 }