This repository has been archived by the owner on Oct 28, 2024. It is now read-only.
forked from ashiddo11/sqs-exporter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
115 lines (96 loc) · 2.53 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
109
110
111
112
113
114
115
package main
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
collector "github.com/nadeemjamali/sqs-prometheus-exporter/pkg/collector"
"github.com/go-co-op/gocron"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
port = getEnv("PORT", "9434")
intervalStr = getEnv("INTERVAL", "1")
endpoint = getEnv("ENDPOINT", "metrics")
keepRunningOnErrorStr = getEnv("KEEP_RUNNING", "true")
)
func main() {
ctx := context.Background()
interval, conversionError := strconv.ParseUint(intervalStr, 10, 64)
if conversionError != nil {
panic(conversionError)
}
httpServer, err := setupMetricsServer()
if err != nil {
fmt.Println(err)
return
}
errChanel := make(chan error)
go func() {
e := httpServer.ListenAndServe()
errChanel <- e
}()
scheduler := gocron.NewScheduler(time.UTC)
scheduler.Every(interval).Minutes().Do(startMonitoring, errChanel)
scheduler.Start()
fmt.Println(fmt.Sprintf("Metrics server listening at port %v with monitoring interval of %v minute(s).", httpServer.Addr, interval))
keepRunningOnError, _ := strconv.ParseBool(keepRunningOnErrorStr)
if keepRunningOnError {
for {
err = <- errChanel
fmt.Println(err)
index := strings.Index(err.Error(), "[MONITORING ERROR]")
if index == -1 {
break
}
}
} else {
err = <- errChanel
fmt.Println(err)
}
fmt.Println("Terminating the server and monitoring")
httpServer.Shutdown(ctx)
scheduler.Clear()
}
func startMonitoring(errChanel chan error){
err := collector.MonitorSQS()
if err != nil{
errChanel <- err
}
return
}
func setupMetricsServer() (*http.Server, error) {
var (
listenAddress = flag.String("web.listen-address", ":"+port, "Address to listen on for web interface and telemetry.")
metricsPath = flag.String("web.telemetry-path", "/"+endpoint, "Path under which to expose metrics.")
)
flag.Parse()
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`
<html>
<head><title>SQS Prometheus Exporter</title></head>
<body>
<h1>SQS Prometheus Exporter</h1>
<p><a href='`+*metricsPath+`'>Metrics</a></p>
</body>
</html>`))
})
mux.Handle(*metricsPath, promhttp.Handler())
httpServer := &http.Server{
Addr: *listenAddress,
Handler: mux,
}
return httpServer, nil
}
// GetEnv returns the value of an environment variable with a fallback
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}