This repository has been archived by the owner on Feb 15, 2024. It is now read-only.
/
metric_writer.go
97 lines (78 loc) · 2.31 KB
/
metric_writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package instrumentation
import (
"github.com/Azure/ASC-go-libs/pkg/common"
"os"
"path/filepath"
"sync"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
)
const (
_reportingInterval = 1 * time.Minute
)
// MetricWriter - interface for sending metrics
type MetricWriter interface {
// Write - send metric by name with provided dimensions
Write(metric *rawMetric)
}
// MetricWriterImpl implements MetricWriter interface
var _ MetricWriter = (*MetricWriterImpl)(nil)
// MetricWriterImpl a metric sender object - can be used to send metrics easily
type MetricWriterImpl struct {
tracer *log.Entry
fileWriter common.FileWriter
lock sync.RWMutex
values map[uint32]*rawMetric
}
// newAggregatedMetricWriter creates a new metric writer aggregator
func newAggregatedMetricWriter(tracer *log.Entry, componentName string, dirPath string) (MetricWriter, error) {
if err := os.MkdirAll(dirPath, os.ModePerm); err != nil {
return nil, err
}
filePath := filepath.Join(dirPath, componentName)
_, err := os.OpenFile(filePath, os.O_CREATE, os.ModePerm)
if err != nil {
tracer.Error(err)
return nil, err
}
c := &MetricWriterImpl{
tracer: tracer,
fileWriter: common.NewRollingFileWriter(filePath),
lock: sync.RWMutex{},
values: make(map[uint32]*rawMetric),
}
go c.startReporting()
return c, nil
}
// Write - writes the new metric or updating the value of the existing cached one
func (metricWriter *MetricWriterImpl) Write(metric *rawMetric) {
metricWriter.lock.RLock()
hash := metric.GetHashExcludingValue()
if _, ok := metricWriter.values[hash]; !ok {
metricWriter.lock.RUnlock()
metricWriter.lock.Lock()
defer metricWriter.lock.Unlock()
metricWriter.values[hash] = metric
} else {
defer metricWriter.lock.RUnlock()
atomic.AddUint32(&metricWriter.values[hash].Value, metric.Value)
}
}
func (metricWriter *MetricWriterImpl) startReporting() {
ticker := time.NewTicker(_reportingInterval)
for range ticker.C {
metricWriter.report()
}
}
func (metricWriter *MetricWriterImpl) report() {
metricWriter.lock.Lock()
defer metricWriter.lock.Unlock()
for _, value := range metricWriter.values {
err := metricWriter.fileWriter.Write(value)
if err != nil {
metricWriter.tracer.Error("Failed to send metric", err)
}
}
metricWriter.values = make(map[uint32]*rawMetric)
}