/
main.go
279 lines (247 loc) · 10 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
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
package main
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/SermoDigital/jose/crypto"
"github.com/amimof/multikube/pkg/proxy"
"github.com/amimof/multikube/pkg/server"
"github.com/opentracing/opentracing-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/pflag"
"github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/config"
"io/ioutil"
"k8s.io/client-go/tools/clientcmd"
"log"
"os"
"time"
)
var (
// VERSION of the app. Is set when project is built and should never be set manually
VERSION string
// COMMIT is the Git commit currently used when compiling. Is set when project is built and should never be set manually
COMMIT string
// BRANCH is the Git branch currently used when compiling. Is set when project is built and should never be set manually
BRANCH string
// GOVERSION used to compile. Is set when project is built and should never be set manually
GOVERSION string
enabledListeners []string
cleanupTimeout time.Duration
maxHeaderSize uint64
socketPath string
host string
port int
metricsHost string
metricsPort int
listenLimit int
keepAlive time.Duration
readTimeout time.Duration
writeTimeout time.Duration
oidcPollInterval time.Duration
oidcIssuerURL string
oidcUsernameClaim string
oidcCaFile string
oidcInsecureSkipVerify bool
tlsHost string
tlsPort int
tlsListenLimit int
tlsKeepAlive time.Duration
tlsReadTimeout time.Duration
tlsWriteTimeout time.Duration
tlsCertificate string
tlsCertificateKey string
tlsCACertificate string
rs256PublicKey string
kubeconfigPath string
cacheTTL time.Duration
)
func init() {
pflag.StringVar(&socketPath, "socket-path", "/var/run/multikube.sock", "the unix socket to listen on")
pflag.StringVar(&host, "host", "localhost", "The host address on which to listen for the --port port")
pflag.StringVar(&tlsHost, "tls-host", "localhost", "The host address on which to listen for the --tls-port port")
pflag.StringVar(&tlsCertificate, "tls-certificate", "", "the certificate to use for secure connections")
pflag.StringVar(&tlsCertificateKey, "tls-key", "", "the private key to use for secure conections")
pflag.StringVar(&tlsCACertificate, "tls-ca", "", "the certificate authority file to be used with mutual tls auth")
pflag.StringVar(&rs256PublicKey, "rs256-public-key", "", "the RS256 public key used to validate the signature of client JWT's")
pflag.StringVar(&kubeconfigPath, "kubeconfig", "/etc/multikube/kubeconfig", "absolute path to a kubeconfig file")
pflag.StringVar(&metricsHost, "metrics-host", "localhost", "The host address on which to listen for the --metrics-port port")
pflag.StringVar(&oidcIssuerURL, "oidc-issuer-url", "", "The URL of the OpenID issuer, only HTTPS scheme will be accepted. If set, it will be used to verify the OIDC JSON Web Token (JWT)")
pflag.StringVar(&oidcUsernameClaim, "oidc-username-claim", "sub", " The OpenID claim to use as the user name. Note that claims other than the default is not guaranteed to be unique and immutable")
pflag.StringVar(&oidcCaFile, "oidc-ca-file", "", "the certificate authority file to be used for verifyign the OpenID server")
pflag.StringSliceVar(&enabledListeners, "scheme", []string{"https"}, "the listeners to enable, this can be repeated and defaults to the schemes in the swagger spec")
pflag.IntVar(&port, "port", 8080, "the port to listen on for insecure connections, defaults to 8080")
pflag.IntVar(&tlsPort, "tls-port", 8443, "the port to listen on for secure connections, defaults to 8443")
pflag.IntVar(&metricsPort, "metrics-port", 8888, "the port to listen on for Prometheus metrics, defaults to 8888")
pflag.IntVar(&listenLimit, "listen-limit", 0, "limit the number of outstanding requests")
pflag.IntVar(&tlsListenLimit, "tls-listen-limit", 0, "limit the number of outstanding requests")
pflag.Uint64Var(&maxHeaderSize, "max-header-size", 1000000, "controls the maximum number of bytes the server will read parsing the request header's keys and values, including the request line. It does not limit the size of the request body")
pflag.DurationVar(&cleanupTimeout, "cleanup-timeout", 10*time.Second, "grace period for which to wait before shutting down the server")
pflag.DurationVar(&keepAlive, "keep-alive", 3*time.Minute, "sets the TCP keep-alive timeouts on accepted connections. It prunes dead TCP connections ( e.g. closing laptop mid-download)")
pflag.DurationVar(&readTimeout, "read-timeout", 30*time.Second, "maximum duration before timing out read of the request")
pflag.DurationVar(&writeTimeout, "write-timeout", 30*time.Second, "maximum duration before timing out write of the response")
pflag.DurationVar(&tlsKeepAlive, "tls-keep-alive", 3*time.Minute, "sets the TCP keep-alive timeouts on accepted connections. It prunes dead TCP connections ( e.g. closing laptop mid-download)")
pflag.DurationVar(&tlsReadTimeout, "tls-read-timeout", 30*time.Second, "maximum duration before timing out read of the request")
pflag.DurationVar(&tlsWriteTimeout, "tls-write-timeout", 30*time.Second, "maximum duration before timing out write of the response")
pflag.DurationVar(&oidcPollInterval, "oidc-poll-interval", 2*time.Second, "maximum duration between intervals in which the oidc issuer url (--oidc-issuer-url) is polled")
pflag.DurationVar(&cacheTTL, "cache-ttl", 1*time.Second, "maximum duration before cached responses are invalidated. Set this value to 0s to disable the cache")
pflag.BoolVar(&oidcInsecureSkipVerify, "oidc-insecure-skip-verify", false, "")
// Create build_info metrics
if err := prometheus.Register(prometheus.NewGaugeFunc(
prometheus.GaugeOpts{
Name: "multikube_build_info",
Help: "A constant gauge with build info labels.",
ConstLabels: prometheus.Labels{
"branch": BRANCH,
"goversion": GOVERSION,
"commit": COMMIT,
"version": VERSION,
},
},
func() float64 { return 1 },
)); err != nil {
log.Printf("Unable to register 'multikube_build_info metric %s'", err.Error())
}
}
func main() {
showver := pflag.Bool("version", false, "Print version")
pflag.Usage = func() {
fmt.Fprint(os.Stderr, "Usage:\n")
fmt.Fprint(os.Stderr, " multikube [OPTIONS]\n\n")
title := "Kubernetes multi-cluster manager"
fmt.Fprint(os.Stderr, title+"\n\n")
desc := "Manages multiple Kubernetes clusters and provides a single API to clients"
if desc != "" {
fmt.Fprintf(os.Stderr, desc+"\n\n")
}
fmt.Fprintln(os.Stderr, pflag.CommandLine.FlagUsages())
}
// parse the CLI flags
pflag.Parse()
// Show version if requested
if *showver {
fmt.Printf("Version: %s\nCommit: %s\nBranch: %s\nGoVersion: %s\n", VERSION, COMMIT, BRANCH, GOVERSION)
return
}
// Only allow one of the flags rs256-public-key and oidc-issuer-url
if rs256PublicKey != "" && oidcIssuerURL != "" {
log.Fatalf("Both flags `--rs256-public-key` and `--oidc-issue-url` cannot be set")
}
// Read provided kubeconfig file
c, err := clientcmd.LoadFromFile(kubeconfigPath)
if err != nil {
log.Fatal(err)
}
// Create the proxy
p, err := proxy.New(c)
if err != nil {
log.Fatal(err)
}
p.CacheTTL(cacheTTL)
p.Use(
proxy.WithEmpty(),
proxy.WithLogging(),
proxy.WithJWT(),
proxy.WithHeader(),
)
// Add JWK validation middleware if issuer url is provided on cmd line
if oidcIssuerURL != "" {
oidcConfig := proxy.OIDCConfig{
OIDCIssuerURL: oidcIssuerURL,
OIDCPollInterval: oidcPollInterval,
OIDCUsernameClaim: oidcUsernameClaim,
OIDCInsecureSkipVerify: oidcInsecureSkipVerify,
OIDCCa: readCert(oidcCaFile),
}
//middlewares = append(middlewares, proxy.WithOIDC(oidcConfig))
p.Use(proxy.WithOIDC(oidcConfig))
}
// // Add x509 public key validation middleware if cert provided on cmd line
if rs256PublicKey != "" {
rs256Config := proxy.RS256Config{
PublicKey: readPublicKey(rs256PublicKey),
}
p.Use(proxy.WithRS256(rs256Config))
}
// Create the server
s := &server.Server{
EnabledListeners: enabledListeners,
CleanupTimeout: cleanupTimeout,
MaxHeaderSize: maxHeaderSize,
SocketPath: socketPath,
Host: host,
Port: port,
ListenLimit: listenLimit,
KeepAlive: keepAlive,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
TLSHost: tlsHost,
TLSPort: tlsPort,
TLSCertificate: tlsCertificate,
TLSCertificateKey: tlsCertificateKey,
TLSCACertificate: tlsCACertificate,
TLSListenLimit: tlsListenLimit,
TLSKeepAlive: tlsKeepAlive,
TLSReadTimeout: tlsReadTimeout,
TLSWriteTimeout: tlsWriteTimeout,
Handler: p.Chain(),
}
// Metrics server
ms := server.NewServer()
ms.Port = metricsPort
ms.Host = metricsHost
ms.Name = "metrics"
ms.Handler = promhttp.Handler()
go ms.Serve()
// Setup opentracing
cfg := config.Configuration{
ServiceName: "multikube",
Sampler: &config.SamplerConfig{
Type: "const",
Param: 1,
},
Reporter: &config.ReporterConfig{
LogSpans: true,
BufferFlushInterval: 1 * time.Second,
},
}
tracer, closer, err := cfg.New("multikube", config.Logger(jaeger.StdLogger))
if err != nil {
log.Fatal(err)
}
opentracing.SetGlobalTracer(tracer)
defer closer.Close()
// Listen and serve!
err = s.Serve()
if err != nil {
log.Fatal(err)
}
}
// Reads an x509 certificate from the filesystem and returns an instance of x509.Certiticate. Returns nil on errors
func readCert(p string) *x509.Certificate {
signer, err := ioutil.ReadFile(p)
if err != nil {
return nil
}
block, _ := pem.Decode(signer)
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil
}
return cert
}
// Reads a RSA public key file from the filesystem and parses it into an instance of rsa.PublicKey
func readPublicKey(p string) *rsa.PublicKey {
f, err := ioutil.ReadFile(p)
if err != nil {
log.Fatal(err)
return nil
}
pubkey, err := crypto.ParseRSAPublicKeyFromPEM(f)
if err != nil {
return nil
}
return pubkey
}