-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
214 lines (181 loc) · 5.6 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"time"
"net/http"
"os"
log "github.com/gookit/slog"
)
const (
logTemplate = "[{{datetime}}] [{{level}}] {{caller}} {{message}} \n"
)
// Prometheus response struct
type PrometheusResponse struct {
Status string `json:"status"`
Data struct {
ResultType string `json:"resultType"`
Result []struct {
Metric map[string]string `json:"metric"`
Value []interface{} `json:"value"`
} `json:"result"`
} `json:"data"`
}
// Thanos response struct
type ThanosResponse struct {
Status string `json:"status"`
Data struct {
ResultType string `json:"resultType"`
Result []struct {
Metric map[string]string `json:"metric"`
Value []interface{} `json:"value"`
} `json:"result"`
Analysis map[string]interface{} `json:"analysis,omitempty"`
} `json:"data"`
}
// Alertmanager response struct
type AlertmanagerAlert struct {
Labels map[string]string `json:"labels"`
}
// HTML content moved to external file
// Query Prometheus
func queryPrometheus(promQuery string, thanosEnabled bool) (interface{}, error) {
prometheusURL := "http://127.0.0.1:9090/api/v1/query"
if os.Getenv("PROMETHEUS_URL") != "" {
prometheusURL = os.Getenv("PROMETHEUS_URL")
}
url := fmt.Sprintf("%s?query=%s", prometheusURL, promQuery)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
log.Info("Prometheus response status: ", resp.Status)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("Error querying Prometheus: %v", err)
return nil, err
}
log.Debug("Prometheus response body: %s", body)
if thanosEnabled {
var thanosResponse ThanosResponse
err = json.Unmarshal(body, &thanosResponse)
if err != nil {
log.Errorf("Error unmarshalling thanosResponse: %v", err)
return nil, err
}
return thanosResponse, nil
} else {
var prometheusResponse PrometheusResponse
err = json.Unmarshal(body, &prometheusResponse)
if err != nil {
log.Errorf("Error unmarshalling prometheusResponse: %v", err)
return nil, err
}
return prometheusResponse, nil
}
}
// Query Alertmanager
func queryAlertmanager() (map[string]int, error) {
alertmanagerURL := "http://127.0.0.1:9093/api/v2/alerts"
if os.Getenv("ALERTMANAGER_URL") != "" {
alertmanagerURL = os.Getenv("ALERTMANAGER_URL")
}
resp, err := http.Get(alertmanagerURL)
if err != nil {
log.Errorf("Error querying Alertmanager: %v", err)
return nil, err
}
defer resp.Body.Close()
log.Info("Alertmanager response status: ", resp.Status)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("Error reading body Alertmanager: %v", err)
return nil, err
}
log.Debug("Alertmanager response body: %s", body)
var alerts []AlertmanagerAlert
err = json.Unmarshal(body, &alerts)
if err != nil {
return nil, err
}
// Aggregate alerts by severity
severityCount := make(map[string]int)
for _, alert := range alerts {
severity := alert.Labels["severity"]
if severity != "" {
severityCount[severity]++
}
}
return severityCount, nil
}
// LoggingMiddleware logs each incoming HTTP request
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
log.Infof("Received %s request for %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
next.ServeHTTP(w, r)
duration := time.Since(startTime)
log.Infof("Handled request for %s in %v", r.URL.Path, duration)
})
}
func main() {
logLevel := flag.String("logLevel", "info", "loglevel of app, e.g info, debug, warn, error, fatal")
thanosEnabled := flag.Bool("thanos", false, "enable Thanos response struct")
indexTemplate := flag.String("indexTemplate", "index.html", "template to serve the dashboard, default: index.html")
flag.Parse()
// set log level
switch *logLevel {
case "fatal":
log.SetLogLevel(log.FatalLevel)
case "trace":
log.SetLogLevel(log.TraceLevel)
case "debug":
log.SetLogLevel(log.DebugLevel)
case "error":
log.SetLogLevel(log.ErrorLevel)
case "warn":
log.SetLogLevel(log.WarnLevel)
case "info":
log.SetLogLevel(log.InfoLevel)
default:
log.SetLogLevel(log.InfoLevel)
}
log.GetFormatter().(*log.TextFormatter).SetTemplate(logTemplate)
http.Handle("/", LoggingMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Serve the HTML file
http.ServeFile(w, r, *indexTemplate)
})))
http.Handle("/api/query", LoggingMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("query")
if query == "" {
log.Error("Query parameter is required")
http.Error(w, "Query parameter is required", http.StatusBadRequest)
return
}
response, err := queryPrometheus(query, *thanosEnabled)
if err != nil {
log.Errorf("Error querying Prometheus: %v", err)
http.Error(w, "Failed to fetch data from Prometheus", http.StatusInternalServerError)
return
}
log.Debug("Prometheus handler response: %v", response)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
})))
http.Handle("/api/alerts", LoggingMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
alerts, err := queryAlertmanager()
if err != nil {
log.Errorf("Error querying Alertmanager: %v", err)
http.Error(w, "Failed to fetch data from Alertmanager", http.StatusInternalServerError)
return
}
log.Debug("Alertmanager handler response: %v", alerts)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(alerts)
})))
log.Info("Server is running on http://0.0.0.0:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}