-
Notifications
You must be signed in to change notification settings - Fork 19
/
server.go
302 lines (248 loc) · 8.26 KB
/
server.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package server
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/openshift/monitoring-plugin/pkg/proxy"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"k8s.io/apiserver/pkg/server/dynamiccertificates"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
)
var log = logrus.WithField("module", "server")
type Config struct {
Port int
CertFile string
PrivateKeyFile string
Features map[Feature]bool
StaticPath string
ConfigPath string
PluginConfigPath string
LogLevel string
AlertmanagerUrl string
ThanosQuerierUrl string
}
type PluginConfig struct {
Timeout time.Duration `json:"timeout,omitempty" yaml:"timeout,omitempty"`
}
type Feature string
const (
AcmAlerting Feature = "acm-alerting"
Incidents Feature = "incidents"
)
func (pluginConfig *PluginConfig) MarshalJSON() ([]byte, error) {
type Alias PluginConfig
return json.Marshal(&struct {
Timeout float64 `json:"timeout,omitempty"`
*Alias
}{
Timeout: pluginConfig.Timeout.Seconds(),
Alias: (*Alias)(pluginConfig),
})
}
func Start(cfg *Config) {
acmMode := cfg.Features[AcmAlerting]
acmLocationsLength := len(cfg.AlertmanagerUrl) + len(cfg.ThanosQuerierUrl)
if acmLocationsLength > 0 && !acmMode {
log.Panic("alertmanager and thanos-querier cannot be set without the 'acm-alerting' feature flag")
}
if acmLocationsLength == 0 && acmMode {
log.Panic("alertmanager and thanos-querier must be set to use the 'acm-alerting' feature flag")
}
if cfg.Port == int(proxy.AlertmanagerPort) || cfg.Port == int(proxy.ThanosQuerierPort) {
log.Panic(fmt.Printf("Cannot set default port to reserved port %d", cfg.Port))
}
// Uncomment the following line for local development:
// k8sconfig, err := clientcmd.BuildConfigFromFlags("", "$HOME/.kube/config")
// Comment the following line for local development:
var k8sclient *dynamic.DynamicClient
if acmMode {
k8sconfig, err := rest.InClusterConfig()
if err != nil {
panic(fmt.Errorf("cannot get in cluster config: %w", err))
}
k8sclient, err = dynamic.NewForConfig(k8sconfig)
if err != nil {
panic(fmt.Errorf("error creating dynamicClient: %w", err))
}
} else {
k8sclient = nil
}
router, pluginConfig := setupRoutes(cfg)
router.Use(corsHeaderMiddleware())
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
}
tlsEnabled := cfg.CertFile != "" && cfg.PrivateKeyFile != ""
if tlsEnabled {
// Build and run the controller which reloads the certificate and key
// files whenever they change.
certKeyPair, err := dynamiccertificates.NewDynamicServingContentFromFiles("serving-cert", cfg.CertFile, cfg.PrivateKeyFile)
if err != nil {
logrus.WithError(err).Fatal("unable to create TLS controller")
}
ctrl := dynamiccertificates.NewDynamicServingCertificateController(
tlsConfig,
nil,
certKeyPair,
nil,
nil,
)
// Check that the cert and key files are valid.
if err := ctrl.RunOnce(); err != nil {
logrus.WithError(err).Fatal("invalid certificate/key files")
}
ctx := context.Background()
go ctrl.Run(1, ctx.Done())
}
timeout := 30 * time.Second
if pluginConfig != nil {
timeout = pluginConfig.Timeout
}
logrusLevel, err := logrus.ParseLevel(cfg.LogLevel)
if err != nil {
logrus.WithError(err).Warn("Invalid log level. Defaulting to 'error'")
logrusLevel = logrus.ErrorLevel
}
httpServer := &http.Server{
Handler: router,
Addr: fmt.Sprintf(":%d", cfg.Port),
TLSConfig: tlsConfig,
ReadTimeout: timeout,
WriteTimeout: timeout,
}
if logrusLevel == logrus.TraceLevel {
loggedRouter := handlers.LoggingHandler(log.Logger.Out, router)
httpServer.Handler = loggedRouter
}
if tlsEnabled {
log.Infof("listening on https. port: %d", cfg.Port)
if acmMode {
startProxy(cfg, k8sclient, tlsConfig, timeout, proxy.AlertManagerKind, proxy.AlertmanagerPort)
startProxy(cfg, k8sclient, tlsConfig, timeout, proxy.ThanosQuerierKind, proxy.ThanosQuerierPort)
}
logrus.SetLevel(logrusLevel)
panic(httpServer.ListenAndServeTLS(cfg.CertFile, cfg.PrivateKeyFile))
} else {
log.Infof("listening on http. port: %d", cfg.Port)
logrus.SetLevel(logrusLevel)
panic(httpServer.ListenAndServe())
}
}
func setupRoutes(cfg *Config) (*mux.Router, *PluginConfig) {
configHandlerFunc, pluginConfig := configHandler(cfg)
router := mux.NewRouter()
router.PathPrefix("/health").HandlerFunc(healthHandler())
router.Path("/plugin-manifest.json").Handler(manifestHandler(cfg))
router.PathPrefix("/features").HandlerFunc(featuresHandler(cfg))
router.PathPrefix("/config").HandlerFunc(configHandlerFunc)
router.PathPrefix("/").Handler(filesHandler(http.Dir(cfg.StaticPath)))
return router, pluginConfig
}
func setupProxyRoutes(cfg *Config, k8sclient *dynamic.DynamicClient, kind proxy.KindType) *mux.Router {
router := mux.NewRouter()
var proxyUrl string
switch kind {
case proxy.AlertManagerKind:
proxyUrl = cfg.AlertmanagerUrl
case proxy.ThanosQuerierKind:
proxyUrl = cfg.ThanosQuerierUrl
}
router.PathPrefix("/").Handler(proxy.NewProxyHandler(
k8sclient,
cfg.CertFile,
kind,
proxyUrl,
))
return router
}
func filesHandler(root http.FileSystem) http.Handler {
fileServer := http.FileServer(root)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
filePath := r.URL.Path
// disable caching for plugin entry point
if strings.HasPrefix(filePath, "/plugin-entry.js") {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Expires", "0")
}
fileServer.ServeHTTP(w, r)
})
}
func healthHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
}
func corsHeaderMiddleware() func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
headers := w.Header()
headers.Set("Access-Control-Allow-Origin", "*")
next.ServeHTTP(w, r)
})
}
}
func featuresHandler(cfg *Config) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
jsonFeatures, err := json.Marshal(cfg.Features)
if err != nil {
log.WithError(err).Errorf("cannot marshall, features were: %v", string(jsonFeatures))
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonFeatures)
})
}
func configHandler(cfg *Config) (http.HandlerFunc, *PluginConfig) {
pluginConfData, err := os.ReadFile(cfg.PluginConfigPath)
if err != nil {
log.WithError(err).Warnf("cannot read config file, serving plugin with default configuration, tried %s", cfg.PluginConfigPath)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{}"))
}), nil
}
var pluginConfig PluginConfig
err = yaml.Unmarshal(pluginConfData, &pluginConfig)
if err != nil {
log.WithError(err).Error("unable to unmarshall config data")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "unable to unmarshall config data", http.StatusInternalServerError)
}), nil
}
jsonPluginConfig, err := pluginConfig.MarshalJSON()
if err != nil {
log.WithError(err).Errorf("unable to marshall, config data: %v", pluginConfig)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "unable to marshall config data", http.StatusInternalServerError)
}), nil
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write(jsonPluginConfig)
}), &pluginConfig
}
func startProxy(cfg *Config, k8sclient *dynamic.DynamicClient, tlsConfig *tls.Config, timeout time.Duration, kind proxy.KindType, port proxy.ProxyPort) {
log.Infof("%s proxy listening on https. port %d", kind, port)
proxyRouter := setupProxyRoutes(cfg, k8sclient, kind)
proxyRouter.Use(corsHeaderMiddleware())
proxyServer := &http.Server{
Handler: proxyRouter,
Addr: fmt.Sprintf(":%d", port),
TLSConfig: tlsConfig,
ReadTimeout: timeout,
WriteTimeout: timeout,
}
go func() {
panic(proxyServer.ListenAndServeTLS(cfg.CertFile, cfg.PrivateKeyFile))
}()
}