-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathserver.go
142 lines (127 loc) · 4.46 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
// Copyright 2017 Percona LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package exporter_shared provides shared code for Percona Prometheus exporters.
package exporter_shared
import (
"bytes"
"crypto/tls"
_ "expvar" // register /debug/vars on http.DefaultServeMux
"html/template"
"log"
"net/http"
_ "net/http/pprof" // register /debug/pprof http.DefaultServeMux
"os"
"strings"
"github.com/alecthomas/kingpin/v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
sslCertFileF = kingpin.Flag("web.ssl-cert-file", "Path to SSL certificate file.").String()
sslKeyFileF = kingpin.Flag("web.ssl-key-file", "Path to SSL key file.").String()
landingPage = template.Must(template.New("home").Parse(strings.TrimSpace(`
<html>
<head>
<title>{{ .name }} exporter</title>
</head>
<body>
<h1>{{ .name }} exporter</h1>
<p><a href="{{ .path }}">Metrics</a></p>
</body>
</html>
`)))
)
// DefaultMetricsHandler returns metrics handler for default Prometheus gatherer/registerer
// with logging and continuing on error.
// Handler is not protected by HTTP basic authentication - it is done by RunServer.
func DefaultMetricsHandler() http.Handler {
h := promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{
ErrorLog: log.New(os.Stderr, "", log.LstdFlags),
ErrorHandling: promhttp.ContinueOnError,
})
return promhttp.InstrumentMetricHandler(prometheus.DefaultRegisterer, h)
}
// RunServer runs server for exporter with given name (it is used on landing page) on given address,
// with HTTP basic authentication (if configured)
// and with given HTTP handler (that should be created with DefaultMetricsHandler or manually).
// Function never returns.
func RunServer(name, addr, path string, handler http.Handler) {
if (*sslCertFileF == "") != (*sslKeyFileF == "") {
log.Fatal("One of the flags --web.ssl-cert-file or --web.ssl-key-file is missing to enable HTTPS.")
}
ssl := false
if *sslCertFileF != "" && *sslKeyFileF != "" {
if _, err := os.Stat(*sslCertFileF); os.IsNotExist(err) {
log.Fatalf("SSL certificate file does not exist: %s", *sslCertFileF)
}
if _, err := os.Stat(*sslKeyFileF); os.IsNotExist(err) {
log.Fatalf("SSL key file does not exist: %s", *sslKeyFileF)
}
ssl = true
}
var buf bytes.Buffer
data := map[string]string{"name": name, "path": path}
if err := landingPage.Execute(&buf, data); err != nil {
log.Fatal(err)
}
h := authHandler(handler)
if ssl {
runHTTPS(addr, path, h, buf.Bytes())
} else {
runHTTP(addr, path, h, buf.Bytes())
}
}
// TLSConfig returns a new tls.Config instance configured according to Percona's security baseline.
func TLSConfig() *tls.Config {
return &tls.Config{
MinVersion: tls.VersionTLS12,
PreferServerCipherSuites: true,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
},
}
}
func runHTTPS(addr, path string, handler http.Handler, landing []byte) {
mux := http.NewServeMux()
mux.Handle(path, handler)
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
w.Write(landing)
})
srv := &http.Server{
Addr: addr,
Handler: mux,
TLSConfig: TLSConfig(),
}
log.Printf("Starting HTTPS server for https://%s%s ...", addr, path)
log.Fatal(srv.ListenAndServeTLS(*sslCertFileF, *sslKeyFileF))
}
func runHTTP(addr, path string, handler http.Handler, landing []byte) {
mux := http.NewServeMux()
mux.Handle(path, handler)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write(landing)
})
srv := &http.Server{
Addr: addr,
Handler: mux,
}
log.Printf("Starting HTTP server for http://%s%s ...", addr, path)
log.Fatal(srv.ListenAndServe())
}