Debian Codegraph @

circonus-gometrics.go

raw symbols SCIP
1 // Copyright 2016 Circonus, Inc. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package circonusgometrics provides instrumentation for your applications in the form
6 // of counters, gauges and histograms and allows you to publish them to
7 // Circonus
8 //
9 // Counters
10 //
11 // A counter is a monotonically-increasing, unsigned, 64-bit integer used to
12 // represent the number of times an event has occurred. By tracking the deltas
13 // between measurements of a counter over intervals of time, an aggregation
14 // layer can derive rates, acceleration, etc.
15 //
16 // Gauges
17 //
18 // A gauge returns instantaneous measurements of something using signed, 64-bit
19 // integers. This value does not need to be monotonic.
20 //
21 // Histograms
22 //
23 // A histogram tracks the distribution of a stream of values (e.g. the number of
24 // seconds it takes to handle requests). Circonus can calculate complex
25 // analytics on these.
26 //
27 // Reporting
28 //
29 // A period push to a Circonus httptrap is confgurable.
30 package circonusgometrics
31
32 import (
33 "bufio"
34 "bytes"
35 "fmt"
36 "io/ioutil"
37 "log"
38 "os"
39 "strconv"
40 "strings"
41 "sync"
42 "time"
43
44 "github.com/circonus-labs/circonus-gometrics/api"
45 "github.com/circonus-labs/circonus-gometrics/checkmgr"
46 "github.com/pkg/errors"
47 )
48
49 const (
50 defaultFlushInterval = "10s" // 10 * time.Second
51 )
52
53 // Metric defines an individual metric
54 type Metric struct {
55 Type string `json:"_type"`
56 Value interface{} `json:"_value"`
57 }
58
59 // Metrics holds host metrics
60 type Metrics map[string]Metric
61
62 // Config options for circonus-gometrics
63 type Config struct {
64 Log *log.Logger
65 Debug bool
66 ResetCounters string // reset/delete counters on flush (default true)
67 ResetGauges string // reset/delete gauges on flush (default true)
68 ResetHistograms string // reset/delete histograms on flush (default true)
69 ResetText string // reset/delete text on flush (default true)
70
71 // API, Check and Broker configuration options
72 CheckManager checkmgr.Config
73
74 // how frequenly to submit metrics to Circonus, default 10 seconds.
75 // Set to 0 to disable automatic flushes and call Flush manually.
76 Interval string
77 }
78
79 type prevMetrics struct {
80 metrics *Metrics
81 metricsmu sync.Mutex
82 ts time.Time
83 }
84
85 // CirconusMetrics state
86 type CirconusMetrics struct {
87 Log *log.Logger
88 Debug bool
89
90 resetCounters bool
91 resetGauges bool
92 resetHistograms bool
93 resetText bool
94 flushInterval time.Duration
95 flushing bool
96 flushmu sync.Mutex
97 packagingmu sync.Mutex
98 check *checkmgr.CheckManager
99 lastMetrics *prevMetrics
100
101 counters map[string]uint64
102 cm sync.Mutex
103
104 counterFuncs map[string]func() uint64
105 cfm sync.Mutex
106
107 gauges map[string]interface{}
108 gm sync.Mutex
109
110 gaugeFuncs map[string]func() int64
111 gfm sync.Mutex
112
113 histograms map[string]*Histogram
114 hm sync.Mutex
115
116 text map[string]string
117 tm sync.Mutex
118
119 textFuncs map[string]func() string
120 tfm sync.Mutex
121 }
122
123 // NewCirconusMetrics returns a CirconusMetrics instance
124 func NewCirconusMetrics(cfg *Config) (*CirconusMetrics, error) {
125 return New(cfg)
126 }
127
128 // New returns a CirconusMetrics instance
129 func New(cfg *Config) (*CirconusMetrics, error) {
130
131 if cfg == nil {
132 return nil, errors.New("invalid configuration (nil)")
133 }
134
135 cm := &CirconusMetrics{
136 counters: make(map[string]uint64),
137 counterFuncs: make(map[string]func() uint64),
138 gauges: make(map[string]interface{}),
139 gaugeFuncs: make(map[string]func() int64),
140 histograms: make(map[string]*Histogram),
141 text: make(map[string]string),
142 textFuncs: make(map[string]func() string),
143 lastMetrics: &prevMetrics{},
144 }
145
146 // Logging
147 {
148 cm.Debug = cfg.Debug
149 cm.Log = cfg.Log
150
151 if cm.Debug && cm.Log == nil {
152 cm.Log = log.New(os.Stderr, "", log.LstdFlags)
153 }
154 if cm.Log == nil {
155 cm.Log = log.New(ioutil.Discard, "", log.LstdFlags)
156 }
157 }
158
159 // Flush Interval
160 {
161 fi := defaultFlushInterval
162 if cfg.Interval != "" {
163 fi = cfg.Interval
164 }
165
166 dur, err := time.ParseDuration(fi)
167 if err != nil {
168 return nil, errors.Wrap(err, "parsing flush interval")
169 }
170 cm.flushInterval = dur
171 }
172
173 // metric resets
174
175 cm.resetCounters = true
176 if cfg.ResetCounters != "" {
177 setting, err := strconv.ParseBool(cfg.ResetCounters)
178 if err != nil {
179 return nil, errors.Wrap(err, "parsing reset counters")
180 }
181 cm.resetCounters = setting
182 }
183
184 cm.resetGauges = true
185 if cfg.ResetGauges != "" {
186 setting, err := strconv.ParseBool(cfg.ResetGauges)
187 if err != nil {
188 return nil, errors.Wrap(err, "parsing reset gauges")
189 }
190 cm.resetGauges = setting
191 }
192
193 cm.resetHistograms = true
194 if cfg.ResetHistograms != "" {
195 setting, err := strconv.ParseBool(cfg.ResetHistograms)
196 if err != nil {
197 return nil, errors.Wrap(err, "parsing reset histograms")
198 }
199 cm.resetHistograms = setting
200 }
201
202 cm.resetText = true
203 if cfg.ResetText != "" {
204 setting, err := strconv.ParseBool(cfg.ResetText)
205 if err != nil {
206 return nil, errors.Wrap(err, "parsing reset text")
207 }
208 cm.resetText = setting
209 }
210
211 // check manager
212 {
213 cfg.CheckManager.Debug = cm.Debug
214 cfg.CheckManager.Log = cm.Log
215
216 check, err := checkmgr.New(&cfg.CheckManager)
217 if err != nil {
218 return nil, errors.Wrap(err, "creating new check manager")
219 }
220 cm.check = check
221 }
222
223 // start background initialization
224 cm.check.Initialize()
225
226 // if automatic flush is enabled, start it.
227 // NOTE: submit will jettison metrics until initialization has completed.
228 if cm.flushInterval > time.Duration(0) {
229 go func() {
230 for range time.NewTicker(cm.flushInterval).C {
231 cm.Flush()
232 }
233 }()
234 }
235
236 return cm, nil
237 }
238
239 // Start deprecated NOP, automatic flush is started in New if flush interval > 0.
240 func (m *CirconusMetrics) Start() {
241 // nop
242 }
243
244 // Ready returns true or false indicating if the check is ready to accept metrics
245 func (m *CirconusMetrics) Ready() bool {
246 return m.check.IsReady()
247 }
248
249 func (m *CirconusMetrics) packageMetrics() (map[string]*api.CheckBundleMetric, Metrics) {
250
251 m.packagingmu.Lock()
252 defer m.packagingmu.Unlock()
253
254 if m.Debug {
255 m.Log.Println("[DEBUG] Packaging metrics")
256 }
257
258 counters, gauges, histograms, text := m.snapshot()
259 newMetrics := make(map[string]*api.CheckBundleMetric)
260 output := make(Metrics, len(counters)+len(gauges)+len(histograms)+len(text))
261 for name, value := range counters {
262 send := m.check.IsMetricActive(name)
263 if !send && m.check.ActivateMetric(name) {
264 send = true
265 newMetrics[name] = &api.CheckBundleMetric{
266 Name: name,
267 Type: "numeric",
268 Status: "active",
269 }
270 }
271 if send {
272 output[name] = Metric{Type: "L", Value: value}
273 }
274 }
275
276 for name, value := range gauges {
277 send := m.check.IsMetricActive(name)
278 if !send && m.check.ActivateMetric(name) {
279 send = true
280 newMetrics[name] = &api.CheckBundleMetric{
281 Name: name,
282 Type: "numeric",
283 Status: "active",
284 }
285 }
286 if send {
287 output[name] = Metric{Type: m.getGaugeType(value), Value: value}
288 }
289 }
290
291 for name, value := range histograms {
292 send := m.check.IsMetricActive(name)
293 if !send && m.check.ActivateMetric(name) {
294 send = true
295 newMetrics[name] = &api.CheckBundleMetric{
296 Name: name,
297 Type: "histogram",
298 Status: "active",
299 }
300 }
301 if send {
302 output[name] = Metric{Type: "n", Value: value.DecStrings()}
303 }
304 }
305
306 for name, value := range text {
307 send := m.check.IsMetricActive(name)
308 if !send && m.check.ActivateMetric(name) {
309 send = true
310 newMetrics[name] = &api.CheckBundleMetric{
311 Name: name,
312 Type: "text",
313 Status: "active",
314 }
315 }
316 if send {
317 output[name] = Metric{Type: "s", Value: value}
318 }
319 }
320
321 m.lastMetrics.metricsmu.Lock()
322 defer m.lastMetrics.metricsmu.Unlock()
323 m.lastMetrics.metrics = &output
324 m.lastMetrics.ts = time.Now()
325
326 return newMetrics, output
327 }
328
329 // PromOutput returns lines of metrics in prom format
330 func (m *CirconusMetrics) PromOutput() (*bytes.Buffer, error) {
331 m.lastMetrics.metricsmu.Lock()
332 defer m.lastMetrics.metricsmu.Unlock()
333
334 if m.lastMetrics.metrics == nil {
335 return nil, errors.New("no metrics available")
336 }
337
338 var b bytes.Buffer
339 w := bufio.NewWriter(&b)
340
341 ts := m.lastMetrics.ts.UnixNano() / int64(time.Millisecond)
342
343 for name, metric := range *m.lastMetrics.metrics {
344 switch metric.Type {
345 case "n":
346 if strings.HasPrefix(fmt.Sprintf("%v", metric.Value), "[H[") {
347 continue // circonus histogram != prom "histogram" (aka percentile)
348 }
349 case "s":
350 continue // text metrics unsupported
351 }
352 fmt.Fprintf(w, "%s %v %d\n", name, metric.Value, ts)
353 }
354
355 err := w.Flush()
356 if err != nil {
357 return nil, errors.Wrap(err, "flushing metric buffer")
358 }
359
360 return &b, err
361 }
362
363 // FlushMetrics flushes current metrics to a structure and returns it (does NOT send to Circonus)
364 func (m *CirconusMetrics) FlushMetrics() *Metrics {
365 m.flushmu.Lock()
366 if m.flushing {
367 m.flushmu.Unlock()
368 return &Metrics{}
369 }
370
371 m.flushing = true
372 m.flushmu.Unlock()
373
374 _, output := m.packageMetrics()
375
376 m.flushmu.Lock()
377 m.flushing = false
378 m.flushmu.Unlock()
379
380 return &output
381 }
382
383 // Flush metrics kicks off the process of sending metrics to Circonus
384 func (m *CirconusMetrics) Flush() {
385 m.flushmu.Lock()
386 if m.flushing {
387 m.flushmu.Unlock()
388 return
389 }
390
391 m.flushing = true
392 m.flushmu.Unlock()
393
394 newMetrics, output := m.packageMetrics()
395
396 if len(output) > 0 {
397 m.submit(output, newMetrics)
398 } else {
399 if m.Debug {
400 m.Log.Println("[DEBUG] No metrics to send, skipping")
401 }
402 }
403
404 m.flushmu.Lock()
405 m.flushing = false
406 m.flushmu.Unlock()
407 }