This repository has been archived by the owner on May 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
router.go
175 lines (154 loc) · 4.06 KB
/
router.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
package ultron
import (
"bytes"
"compress/gzip"
"embed"
"encoding/json"
"io"
"io/fs"
"net/http"
"net/http/httptest"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
chimiddleware "github.com/jacexh/gopkg/chi-middleware"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/prom2json"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
)
type (
restServer struct {
runner *masterRunner
}
restResponse struct {
Result bool `json:"result,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
}
requestStartPlan struct {
Name string `json:"name"`
Stages []*V1StageConfig `json:"stages"`
}
)
var (
//go:embed web/static/*
statics embed.FS
//go:embed web/index.html
indexhtml []byte
)
func (rest *restServer) handleStartNewPlan() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
req := new(requestStartPlan)
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
Logger.Error("failed to parse request body", zap.Error(err))
renderResponse(err, rw, r)
return
}
plan := NewPlan(req.Name)
for _, stage := range req.Stages {
plan.AddStages(stage)
}
err := rest.runner.StartPlan(plan)
renderResponse(err, rw, r)
}
}
func (rest *restServer) handleStopPlan() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
rest.runner.StopPlan()
renderResponse(nil, rw, r)
}
}
func metricToJson(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// before
recorder := httptest.NewRecorder()
next.ServeHTTP(recorder, r)
// after
res := recorder.Result()
ch := make(chan *dto.MetricFamily, 1)
var jsonBytes []byte
eg, _ := errgroup.WithContext(r.Context())
eg.Go(func() error {
reader, err := gzip.NewReader(res.Body)
if err != nil {
return err
}
data, err := io.ReadAll(reader)
if err != nil {
return err
}
return prom2json.ParseReader(bytes.NewBuffer(data), ch)
})
eg.Go(func() error {
result := []*prom2json.Family{}
for m := range ch {
result = append(result, prom2json.NewFamily(m))
}
var err error
jsonBytes, err = json.Marshal(result)
return err
})
if err := eg.Wait(); err != nil {
Logger.Error("failed to parse prometheus metrics", zap.Error(err))
renderResponse(err, w, r)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonBytes)
}
return http.HandlerFunc(fn)
}
func renderResponse(err error, w http.ResponseWriter, r *http.Request) {
ret := &restResponse{}
if err == nil {
ret.Result = true
} else {
ret.ErrorMessage = err.Error()
}
data, err := json.Marshal(ret)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(http.StatusText(http.StatusInternalServerError)))
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
func buildHTTPRouter(runner *masterRunner) http.Handler {
route := chi.NewRouter()
rest := &restServer{runner: runner}
{ // middlewares
route.Use(middleware.RequestID)
route.Use(middleware.RealIP)
route.Use(chimiddleware.RequestZapLog(Logger))
route.Use(middleware.Recoverer)
}
// http api
{
route.Post("/api/v1/plan", rest.handleStartNewPlan())
route.Delete("/api/v1/plan", rest.handleStopPlan())
}
// static files
content, err := fs.Sub(statics, "web/static")
if err != nil {
panic(err)
}
route.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write(indexhtml)
})
route.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.FS(content))))
// prometheus exporter
exporter := newMetric(runner)
runner.SubscribeReport(exporter.handleReport()) // 订阅report
reg := prometheus.NewRegistry()
reg.MustRegister(exporter)
handler := promhttp.HandlerFor(reg, promhttp.HandlerOpts{})
route.Handle("/metrics", handler)
route.Route("/metrics.json", func(r chi.Router) {
r.Use(metricToJson)
r.Handle("/", handler)
})
return route
}