Debian Codegraph @

performance_data.go

raw
1 package monitoringplugin
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "github.com/pkg/errors"
8 "math/big"
9 "regexp"
10 "strconv"
11 )
12
13 type performanceDataPointKey struct {
14 Metric string `json:"metric"`
15 Label string `json:"label,omitempty"`
16 }
17
18 // performanceData is a map where all performanceDataPoints are stored.
19 // It assigns labels (string) to performanceDataPoints.
20 type performanceData map[performanceDataPointKey]PerformanceDataPoint
21
22 /*
23 add adds a PerformanceDataPoint to the performanceData Map.
24 The function checks if a PerformanceDataPoint is valid and if there is already another PerformanceDataPoint with the
25 same metric in the performanceData map.
26 Usage:
27 err := performanceData.add(NewPerformanceDataPoint("temperature", 32, "°C").SetWarn(35).SetCrit(40))
28 if err != nil {
29 ...
30 }
31 */
32 func (p *performanceData) add(point *PerformanceDataPoint) error {
33 if err := point.Validate(); err != nil {
34 return errors.Wrap(err, "given performance data point is not valid")
35 }
36 key := performanceDataPointKey{point.Metric, point.Label}
37 if _, ok := (*p)[key]; ok {
38 return fmt.Errorf("a performance data point with the metric '%s' does already exist", func(key performanceDataPointKey) string {
39 res := key.Metric
40 if key.Label != "" {
41 res += " and label " + key.Label
42 }
43 return res
44 }(key))
45 }
46 (*p)[key] = *point
47 return nil
48 }
49
50 // getInfo returns all information for performance data.
51 func (p performanceData) getInfo() []PerformanceDataPoint {
52 var info []PerformanceDataPoint
53 for _, pd := range p {
54 info = append(info, pd)
55 }
56 return info
57 }
58
59 // PerformanceDataPoint contains all information of one PerformanceDataPoint.
60 type PerformanceDataPoint struct {
61 Metric string `json:"metric" xml:"metric"`
62 Label string `json:"label" xml:"label"`
63 Value interface{} `json:"value" xml:"value"`
64 Unit string `json:"unit" xml:"unit"`
65 Thresholds Thresholds `json:"thresholds" xml:"thresholds"`
66 Min interface{} `json:"min" xml:"min"`
67 Max interface{} `json:"max" xml:"max"`
68 }
69
70 /*
71 Validate validates a PerformanceDataPoint.
72 This function is used to check if a PerformanceDataPoint is compatible with the documentation from
73 'http://nagios-plugins.org/doc/guidelines.html'(valid name and unit, value is inside the range of min and max etc.)
74 */
75 func (p *PerformanceDataPoint) Validate() error {
76 if p.Metric == "" {
77 return errors.New("data point metric cannot be an empty string")
78 }
79
80 match, err := regexp.MatchString("([='])", p.Metric)
81 if err != nil {
82 return errors.Wrap(err, "error during regex match")
83 }
84 if match {
85 return errors.New("metric contains invalid character")
86 }
87
88 match, err = regexp.MatchString("([='])", p.Label)
89 if err != nil {
90 return errors.Wrap(err, "error during regex match")
91 }
92 if match {
93 return errors.New("metric contains invalid character")
94 }
95
96 match, err = regexp.MatchString("([0-9;'\"])", p.Unit)
97 if err != nil {
98 return errors.Wrap(err, "error during regex match")
99 }
100 if match {
101 return errors.New("unit can not contain numbers, semicolon or quotes")
102 }
103
104 var min, max, value big.Float
105 _, _, err = value.Parse(fmt.Sprint(p.Value), 10)
106 if err != nil {
107 return errors.Wrap(err, "can't parse value")
108 }
109
110 if p.Min != nil {
111 _, _, err = min.Parse(fmt.Sprint(p.Min), 10)
112 if err != nil {
113 return errors.Wrap(err, "can't parse min")
114 }
115 switch min.Cmp(&value) {
116 case 1:
117 return errors.New("value cannot be smaller than min")
118 default:
119 }
120 }
121 if p.Max != nil {
122 _, _, err = max.Parse(fmt.Sprint(p.Max), 10)
123 if err != nil {
124 return errors.Wrap(err, "can't parse max")
125 }
126 switch max.Cmp(&value) {
127 case -1:
128 return errors.New("value cannot be larger than max")
129 default:
130 }
131 }
132 if p.Min != nil && p.Max != nil {
133 switch min.Cmp(&max) {
134 case 1:
135 return errors.New("min cannot be larger than max")
136 default:
137 }
138 }
139
140 if !p.Thresholds.IsEmpty() {
141 err = p.Thresholds.Validate()
142 if err != nil {
143 return errors.Wrap(err, "thresholds are invalid")
144 }
145 }
146
147 return nil
148 }
149
150 /*
151 NewPerformanceDataPoint creates a new PerformanceDataPoint. Metric and value are mandatory but are not checked at this
152 point, the performanceDatePoint's validation is checked later when it is added to the performanceData list in the
153 function performanceData.add(*PerformanceDataPoint).
154 It is possible to directly add thresholds, min and max values with the functions SetThresholds(Thresholds),
155 SetMin(int) and SetMax(int).
156 Usage:
157 PerformanceDataPoint := NewPerformanceDataPoint("memory_usage", 55).SetUnit("%")
158 */
159 func NewPerformanceDataPoint(metric string, value interface{}) *PerformanceDataPoint {
160 return &PerformanceDataPoint{
161 Metric: metric,
162 Value: value,
163 }
164 }
165
166 // SetUnit sets the unit of the performance data point
167 func (p *PerformanceDataPoint) SetUnit(unit string) *PerformanceDataPoint {
168 p.Unit = unit
169 return p
170 }
171
172 // SetMin sets minimum value.
173 func (p *PerformanceDataPoint) SetMin(min interface{}) *PerformanceDataPoint {
174 p.Min = min
175 return p
176 }
177
178 // SetMax sets maximum value.
179 func (p *PerformanceDataPoint) SetMax(max interface{}) *PerformanceDataPoint {
180 p.Max = max
181 return p
182 }
183
184 // SetLabel adds a tag to the performance data point
185 // If one tag is added more than once, the value before will be overwritten
186 func (p *PerformanceDataPoint) SetLabel(label string) *PerformanceDataPoint {
187 p.Label = label
188 return p
189 }
190
191 // SetThresholds sets the thresholds for the performance data point
192 func (p *PerformanceDataPoint) SetThresholds(thresholds Thresholds) *PerformanceDataPoint {
193 p.Thresholds = thresholds
194 return p
195 }
196
197 // This function returns the PerformanceDataPoint in the specified format that will be returned by the check plugin.
198 func (p *PerformanceDataPoint) output(jsonLabel bool) []byte {
199 var buffer bytes.Buffer
200 if jsonLabel {
201 buffer.WriteByte('\'')
202 key := performanceDataPointKey{
203 Metric: p.Metric,
204 Label: p.Label,
205 }
206 jsonKey, _ := json.Marshal(key)
207 buffer.Write(jsonKey)
208 buffer.WriteByte('\'')
209 } else {
210 buffer.WriteByte('\'')
211 buffer.WriteString(p.Metric)
212 if p.Label != "" {
213 buffer.WriteByte('_')
214 buffer.WriteString(p.Label)
215 }
216 buffer.WriteByte('\'')
217 }
218 buffer.WriteByte('=')
219
220 switch p.Value.(type) {
221 case float64:
222 buffer.WriteString(strconv.FormatFloat(p.Value.(float64), 'f', -1, 64))
223 default:
224 buffer.WriteString(fmt.Sprint(p.Value))
225 }
226
227 buffer.WriteString(p.Unit)
228
229 if !p.Thresholds.IsEmpty() || p.Max != nil || p.Min != nil {
230 buffer.WriteByte(';')
231 if p.Thresholds.HasWarning() {
232 buffer.WriteString(p.Thresholds.getWarning())
233 }
234 buffer.WriteByte(';')
235 if p.Thresholds.HasCritical() {
236 buffer.WriteString(p.Thresholds.getCritical())
237 }
238 buffer.WriteByte(';')
239 if p.Min != nil {
240 switch min := p.Min.(type) {
241 case float64:
242 buffer.WriteString(strconv.FormatFloat(min, 'f', -1, 64))
243 default:
244 buffer.WriteString(fmt.Sprint(min))
245 }
246 }
247 buffer.WriteByte(';')
248 if p.Max != nil {
249 switch max := p.Max.(type) {
250 case float64:
251 buffer.WriteString(strconv.FormatFloat(max, 'f', -1, 64))
252 default:
253 buffer.WriteString(fmt.Sprint(max))
254 }
255 }
256 }
257
258 return buffer.Bytes()
259 }