-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
244 lines (202 loc) · 6.37 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"regexp"
"strings"
"github.com/ghodss/yaml"
"github.com/go-chi/chi"
"github.com/go-playground/validator/v10"
"github.com/google/go-jsonnet"
)
func main() {
vm := jsonnet.MakeVM()
vm.Importer(&jsonnet.FileImporter{
JPaths: []string{"vendor"},
})
r := chi.NewRouter()
r.Post("/generate", HandleFunc(generate(vm)))
r.Handle("/web/*", http.StripPrefix("/web", http.FileServer(http.Dir("./web"))))
r.Get("/", HandleFunc(file("./web/index.html")))
r.NotFound(HandleFunc(file("./web/index.html")))
log.Println("Serving on port :9099")
if err := http.ListenAndServe(":9099", r); err != nil {
log.Println(err)
}
}
type HandlerFunc func(http.ResponseWriter, *http.Request) (int, error)
func HandleFunc(h HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
statusCode, err := h(w, r)
if err != nil {
http.Error(w, err.Error(), statusCode)
fmt.Println(err)
return
}
if statusCode != http.StatusOK {
w.WriteHeader(statusCode)
}
}
}
func file(filename string) HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) (int, error) {
http.ServeFile(w, r, filename)
return http.StatusOK, nil
}
}
var errorBurnRate = `
local slo = import 'github.com/metalmatze/slo-libsonnet/slo-libsonnet/slo.libsonnet';
local errorParams = %s;
{
local errorburnrate = slo.errorburn(errorParams),
groups: [
{
name: 'SLOs-%%s' %% errorParams.metric,
rules:
errorburnrate.alerts +
errorburnrate.recordingrules,
},
],
}
`
var latencyBurnRate = `
local slo = import 'github.com/metalmatze/slo-libsonnet/slo-libsonnet/slo.libsonnet';
local latencyParams = %s;
{
local latencyburn = slo.latencyburn(latencyParams),
groups: [
{
name: 'SLOs-%%s' %% latencyParams.metric,
rules:
latencyburn.alerts +
latencyburn.recordingrules,
},
],
}
`
type Request struct {
Function string `json:"function"`
Metric string `json:"metric" validate:"required,metric"`
Selectors map[string]string `json:"selectors"`
ErrorSelectors string `json:"errorSelectors"`
AlertName string `json:"alertName" validate:"omitempty,alphanum"`
AlertMessage string `json:"alertMessage" validate:"omitempty,alphanumunicode"`
}
type errorRequest struct {
Request
Availability float64 `json:"availability" validate:"required,gte=0,lte=100"`
}
type errorParams struct {
Target float64 `json:"target"`
Metric string `json:"metric"`
Selectors []string `json:"selectors"`
ErrorSelectors []string `json:"errorSelectors,omitempty"`
AlertName string `json:"alertName,omitempty"`
AlertMessage string `json:"alertMessage,omitempty"`
}
type latencyRequest struct {
Request
Target float64 `json:"target" validate:"required,gte=0"`
}
type latencyParams struct {
Target float64 `json:"latencyTarget"`
Budget float64 `json:"latencyBudget"`
Metric string `json:"metric"`
Selectors []string `json:"selectors"`
AlertName string `json:"alertName,omitempty"`
}
func generate(vm *jsonnet.VM) HandlerFunc {
validate := validator.New()
if err := validate.RegisterValidation("metric", func(fl validator.FieldLevel) bool {
metricNameExp := regexp.MustCompile(`^[a-zA-Z_:][a-zA-Z0-9_:]*$`)
return metricNameExp.MatchString(fl.Field().String())
}); err != nil {
panic("failed to register metric validator")
}
validate.RegisterStructValidation(func(sl validator.StructLevel) {
labelNameExp := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
req := sl.Current().Interface().(Request)
for name, value := range req.Selectors {
if !labelNameExp.MatchString(name) {
sl.ReportError(req.Selectors, "selector.name", "Selector Name", "label", "")
}
if !labelNameExp.MatchString(value) {
sl.ReportError(req.Selectors, "selector.value", "Selector value", "label", "")
}
}
}, Request{})
return func(w http.ResponseWriter, r *http.Request) (int, error) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return http.StatusInternalServerError, err
}
var req Request
if err := json.Unmarshal(body, &req); err != nil {
return http.StatusInternalServerError, fmt.Errorf("failed to parse JSON: %w", err)
}
defer r.Body.Close()
var snippet string
if req.Function == "errorburn" {
var errorReq errorRequest
if err := json.Unmarshal(body, &errorReq); err != nil {
return http.StatusInternalServerError, err
}
if err := validate.Struct(errorReq); err != nil {
return http.StatusUnprocessableEntity, err
}
p := errorParams{
Target: errorReq.Availability / 100,
Metric: errorReq.Metric,
AlertName: errorReq.AlertName,
AlertMessage: errorReq.AlertMessage,
}
for name, value := range errorReq.Selectors {
p.Selectors = append(p.Selectors, fmt.Sprintf(`%s="%s"`, name, strings.Replace(value, `"`, `\"`, -1)))
}
params, err := json.Marshal(p)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("failed to marshal Request: %w", err)
}
snippet = fmt.Sprintf(errorBurnRate, string(params))
}
if req.Function == "latencyburn" {
var latencyReq latencyRequest
if err := json.Unmarshal(body, &latencyReq); err != nil {
return http.StatusInternalServerError, err
}
if err := validate.Struct(latencyReq); err != nil {
return http.StatusUnprocessableEntity, err
}
p := latencyParams{
Target: latencyReq.Target / 1000, // we want seconds
Budget: 0.01,
Metric: latencyReq.Metric,
AlertName: latencyReq.AlertName,
}
for name, value := range latencyReq.Selectors {
p.Selectors = append(p.Selectors, fmt.Sprintf(`%s="%s"`, name, strings.Replace(value, `"`, `\"`, -1)))
}
params, err := json.Marshal(p)
if err != nil {
return http.StatusInternalServerError, fmt.Errorf("failed to marshal Request: %w", err)
}
snippet = fmt.Sprintf(latencyBurnRate, string(params))
}
//w.Write([]byte(snippet))
//return http.StatusOK, nil
json, err := vm.EvaluateSnippet("", snippet)
if err != nil {
return http.StatusInternalServerError, err
}
y, err := yaml.JSONToYAML([]byte(json))
if err != nil {
return http.StatusInternalServerError, err
}
w.Header().Set("Content-Type", "text/plain")
_, _ = fmt.Fprintln(w, string(y))
return http.StatusOK, nil
}
}