-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
108 lines (88 loc) · 2.29 KB
/
main.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
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
"github.com/ZipRecruiter/cloudwatching/pkg/exportcloudwatch"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var metrics map[string]exportcloudwatch.MetricStat
var listMetricsSleep = prometheus.NewSummary(prometheus.SummaryOpts{
Name: "monitoring_cloudwatch_list_metrics_sleep",
Help: "Amount of time we are going to sleep between updating our metrics list",
})
func init() {
prometheus.MustRegister(listMetricsSleep)
}
func handler(c configuration, cw *cloudwatch.CloudWatch, inner http.Handler) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
period := 60 * time.Second
start := time.Now().Add(-2 * period).Truncate(time.Minute)
if err := exportcloudwatch.ReadMetrics(cw, start, period, metrics); err != nil {
rw.WriteHeader(500)
log.Print(err)
return
}
inner.ServeHTTP(rw, r)
}
}
func sleepRange(got, min, max time.Duration) time.Duration {
if got < min {
return min
}
if got > max {
return max
}
return got
}
func main() {
path := os.Getenv("MC_CONFIG")
if path == "" {
log.Fatal("MC_CONFIG not set!")
}
configFile, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
var c configuration
d := json.NewDecoder(configFile)
if err := d.Decode(&c); err != nil {
log.Fatal(err)
}
if err := c.Validate(); err != nil {
log.Fatal(err)
}
cw, err := initDependencies(c)
if err != nil {
log.Fatal(err)
}
var listMetricsDuration time.Duration
start := time.Now()
metrics, err = exportcloudwatch.MetricsToRead(c.exportConfigs, cw)
if err != nil {
log.Fatal(err)
}
listMetricsDuration = time.Now().Sub(start)
go func() {
for {
duration := sleepRange(10*listMetricsDuration, 5*time.Minute, time.Hour)
listMetricsSleep.Observe(duration.Seconds())
time.Sleep(duration)
start := time.Now()
metrics, err = exportcloudwatch.MetricsToRead(c.exportConfigs, cw)
if err != nil {
log.Fatal(err)
}
listMetricsDuration = time.Now().Sub(start)
}
}()
log.Printf("starting httpserver on :8080")
http.Handle("/metrics", handler(c, cw, promhttp.Handler()))
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}