Debian Codegraph @

cmd/server/app/server.go

raw symbols SCIP
1 /*
2 Copyright 2022 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package app
18
19 import (
20 "context"
21 "crypto/tls"
22 "crypto/x509"
23 "fmt"
24 "net"
25 "net/http"
26 netpprof "net/http/pprof"
27 "os"
28 "os/signal"
29 "path/filepath"
30 "runtime"
31 runpprof "runtime/pprof"
32 "strconv"
33 "sync"
34 "syscall"
35 "time"
36
37 "github.com/prometheus/client_golang/prometheus/promhttp"
38 "github.com/spf13/cobra"
39 "google.golang.org/grpc"
40 "google.golang.org/grpc/credentials"
41 "google.golang.org/grpc/keepalive"
42 "k8s.io/client-go/kubernetes"
43 "k8s.io/client-go/tools/clientcmd"
44 "k8s.io/klog/v2"
45 "sigs.k8s.io/apiserver-network-proxy/cmd/server/app/options"
46 "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client"
47 "sigs.k8s.io/apiserver-network-proxy/pkg/server"
48 "sigs.k8s.io/apiserver-network-proxy/pkg/server/leases"
49 "sigs.k8s.io/apiserver-network-proxy/pkg/util"
50 "sigs.k8s.io/apiserver-network-proxy/proto/agent"
51 )
52
53 var udsListenerLock sync.Mutex
54
55 const (
56 ReadHeaderTimeout = 60 * time.Second
57 LeaseDuration = 30 * time.Second
58 LeaseRenewalInterval = 15 * time.Second
59 LeaseGCInterval = 15 * time.Second
60 )
61
62 func NewProxyCommand(p *Proxy, o *options.ProxyRunOptions) *cobra.Command {
63 cmd := &cobra.Command{
64 Use: "proxy",
65 Long: `A gRPC proxy server, receives requests from the API server and forwards to the agent.`,
66 RunE: func(_ *cobra.Command, _ []string) error {
67 stopCh := SetupSignalHandler()
68 return p.Run(o, stopCh)
69 },
70 }
71
72 return cmd
73 }
74
75 func tlsCipherSuites(cipherNames []string) []uint16 {
76 // return nil, so use default cipher list
77 if len(cipherNames) == 0 {
78 return nil
79 }
80
81 acceptedCiphers := util.GetAcceptedCiphers()
82 ciphersIntSlice := make([]uint16, 0)
83 for _, cipher := range cipherNames {
84 ciphersIntSlice = append(ciphersIntSlice, acceptedCiphers[cipher])
85 }
86 return ciphersIntSlice
87 }
88
89 type Proxy struct {
90 agentServer *grpc.Server
91 adminServer *http.Server
92 healthServer *http.Server
93
94 server *server.ProxyServer
95 }
96
97 type StopFunc func()
98
99 func (p *Proxy) Run(o *options.ProxyRunOptions, stopCh <-chan struct{}) error {
100 o.Print()
101 if err := o.Validate(); err != nil {
102 return fmt.Errorf("failed to validate server options with %v", err)
103 }
104 ctx, cancel := context.WithCancel(context.Background())
105 defer cancel()
106
107 var k8sClient *kubernetes.Clientset
108 if o.NeedsKubernetesClient {
109 config, err := clientcmd.BuildConfigFromFlags("", o.KubeconfigPath)
110 if err != nil {
111 return fmt.Errorf("failed to load kubernetes client config: %v", err)
112 }
113
114 if o.KubeconfigQPS != 0 {
115 klog.V(1).Infof("Setting k8s client QPS: %v", o.KubeconfigQPS)
116 config.QPS = o.KubeconfigQPS
117 }
118 if o.KubeconfigBurst != 0 {
119 klog.V(1).Infof("Setting k8s client Burst: %v", o.KubeconfigBurst)
120 config.Burst = o.KubeconfigBurst
121 }
122 config.ContentType = o.APIContentType
123 k8sClient, err = kubernetes.NewForConfig(config)
124 if err != nil {
125 return fmt.Errorf("failed to create kubernetes clientset: %v", err)
126 }
127 }
128
129 authOpt := &server.AgentTokenAuthenticationOptions{
130 Enabled: o.AgentNamespace != "",
131 AgentNamespace: o.AgentNamespace,
132 AgentServiceAccount: o.AgentServiceAccount,
133 KubernetesClient: k8sClient,
134 AuthenticationAudience: o.AuthenticationAudience,
135 }
136 klog.V(1).Infoln("Starting frontend server for client connections.")
137 ps, err := server.ParseProxyStrategies(o.ProxyStrategies)
138 if err != nil {
139 return err
140 }
141 p.server = server.NewProxyServer(o.ServerID, ps, o.ServerCount, authOpt, o.XfrChannelSize)
142
143 frontendStop, err := p.runFrontendServer(ctx, o, p.server)
144 if err != nil {
145 return fmt.Errorf("failed to run the frontend server: %v", err)
146 }
147 if frontendStop != nil {
148 defer frontendStop()
149 }
150
151 klog.V(1).Infoln("Starting agent server for tunnel connections.")
152 err = p.runAgentServer(o, p.server)
153 if err != nil {
154 return fmt.Errorf("failed to run the agent server: %v", err)
155 }
156 defer p.agentServer.Stop()
157
158 labels, err := util.ParseLabels(o.LeaseLabel)
159 if err != nil {
160 return err
161 }
162
163 if o.EnableLeaseController {
164 leaseController := leases.NewController(
165 k8sClient,
166 o.ServerID,
167 int32(LeaseDuration.Seconds()),
168 LeaseRenewalInterval,
169 LeaseGCInterval,
170 fmt.Sprintf("konnectivity-proxy-server-%v", o.ServerID),
171 o.LeaseNamespace,
172 labels,
173 )
174 klog.V(1).Infoln("Starting lease acquisition and garbage collection controller.")
175 leaseController.Run(ctx)
176 defer leaseController.Stop()
177 }
178
179 klog.V(1).Infoln("Starting admin server for debug connections.")
180 err = p.runAdminServer(o, p.server)
181 if err != nil {
182 return fmt.Errorf("failed to run the admin server: %v", err)
183 }
184 defer p.adminServer.Close()
185
186 klog.V(1).Infoln("Starting health server for healthchecks.")
187 err = p.runHealthServer(o, p.server)
188 if err != nil {
189 return fmt.Errorf("failed to run the health server: %v", err)
190 }
191 defer p.healthServer.Close()
192
193 <-stopCh
194 klog.V(1).Infoln("Shutting down server.")
195
196 return nil
197 }
198
199 var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
200
201 func SetupSignalHandler() (stopCh <-chan struct{}) {
202 stop := make(chan struct{})
203 c := make(chan os.Signal, 2)
204 signal.Notify(c, shutdownSignals...)
205 labels := runpprof.Labels(
206 "core", "signalHandler",
207 )
208 go runpprof.Do(context.Background(), labels, func(context.Context) { handleSignals(c, stop) })
209
210 return stop
211 }
212
213 func handleSignals(signalCh chan os.Signal, stopCh chan struct{}) {
214 <-signalCh
215 close(stopCh)
216 <-signalCh
217 os.Exit(1) // second signal. Exit directly.
218 }
219
220 func getUDSListener(ctx context.Context, udsName string) (net.Listener, error) {
221 udsListenerLock.Lock()
222 defer udsListenerLock.Unlock()
223 oldUmask := syscall.Umask(0007)
224 defer syscall.Umask(oldUmask)
225 var lc net.ListenConfig
226 lis, err := lc.Listen(ctx, "unix", udsName)
227 if err != nil {
228 return nil, fmt.Errorf("failed to listen(unix) name %s: %v", udsName, err)
229 }
230 return lis, nil
231 }
232
233 func (p *Proxy) runFrontendServer(ctx context.Context, o *options.ProxyRunOptions, server *server.ProxyServer) (StopFunc, error) {
234 if o.UdsName != "" {
235 return p.runUDSFrontendServer(ctx, o, server)
236 }
237 return p.runMTLSFrontendServer(ctx, o, server)
238 }
239
240 func (p *Proxy) runUDSFrontendServer(ctx context.Context, o *options.ProxyRunOptions, s *server.ProxyServer) (StopFunc, error) {
241 if o.DeleteUDSFile {
242 if err := os.Remove(o.UdsName); err != nil && !os.IsNotExist(err) {
243 klog.ErrorS(err, "failed to delete file", "file", o.UdsName)
244 }
245 }
246 var stop StopFunc
247 if o.Mode == "grpc" {
248 frontendServerOptions := []grpc.ServerOption{
249 grpc.KeepaliveParams(keepalive.ServerParameters{Time: o.FrontendKeepaliveTime}),
250 }
251 grpcServer := grpc.NewServer(frontendServerOptions...)
252 client.RegisterProxyServiceServer(grpcServer, s)
253 lis, err := getUDSListener(ctx, o.UdsName)
254 if err != nil {
255 return nil, fmt.Errorf("failed to get uds listener: %v", err)
256 }
257 labels := runpprof.Labels(
258 "core", "udsGrpcFrontend",
259 "udsFile", o.UdsName,
260 )
261 go runpprof.Do(context.Background(), labels, func(context.Context) { grpcServer.Serve(lis) })
262 stop = grpcServer.GracefulStop
263 } else {
264 // http-connect
265 server := &http.Server{
266 ReadHeaderTimeout: ReadHeaderTimeout,
267 Handler: &server.Tunnel{
268 Server: s,
269 },
270 }
271 stop = func() {
272 err := server.Shutdown(ctx)
273 klog.ErrorS(err, "error shutting down server")
274 }
275 labels := runpprof.Labels(
276 "core", "udsHttpFrontend",
277 "udsFile", o.UdsName,
278 )
279 go runpprof.Do(context.Background(), labels, func(context.Context) {
280 udsListener, err := getUDSListener(ctx, o.UdsName)
281 if err != nil {
282 klog.ErrorS(err, "failed to get uds listener")
283 }
284 defer func() {
285 err := udsListener.Close()
286 klog.ErrorS(err, "failed to close uds listener")
287 }()
288 err = server.Serve(udsListener)
289 if err != nil {
290 klog.ErrorS(err, "failed to serve uds requests")
291 }
292 })
293 }
294
295 return stop, nil
296 }
297
298 func (p *Proxy) getTLSConfig(caFile, certFile, keyFile string, cipherSuites []string) (*tls.Config, error) {
299 cert, err := tls.LoadX509KeyPair(certFile, keyFile)
300 if err != nil {
301 return nil, fmt.Errorf("failed to load X509 key pair %s and %s: %v", certFile, keyFile, err)
302 }
303
304 cipherSuiteIDs := tlsCipherSuites(cipherSuites)
305
306 if caFile == "" {
307 return &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS12, CipherSuites: cipherSuiteIDs}, nil
308 }
309
310 certPool := x509.NewCertPool()
311 caCert, err := os.ReadFile(filepath.Clean(caFile))
312 if err != nil {
313 return nil, fmt.Errorf("failed to read cluster CA cert %s: %v", caFile, err)
314 }
315 ok := certPool.AppendCertsFromPEM(caCert)
316 if !ok {
317 return nil, fmt.Errorf("failed to append cluster CA cert to the cert pool")
318 }
319
320 tlsConfig := &tls.Config{
321 ClientAuth: tls.RequireAndVerifyClientCert,
322 Certificates: []tls.Certificate{cert},
323 ClientCAs: certPool,
324 MinVersion: tls.VersionTLS12,
325 CipherSuites: cipherSuiteIDs,
326 }
327
328 return tlsConfig, nil
329 }
330
331 func (p *Proxy) runMTLSFrontendServer(ctx context.Context, o *options.ProxyRunOptions, s *server.ProxyServer) (StopFunc, error) {
332 var stop StopFunc
333
334 var tlsConfig *tls.Config
335 var err error
336 if tlsConfig, err = p.getTLSConfig(o.ServerCaCert, o.ServerCert, o.ServerKey, o.CipherSuites); err != nil {
337 return nil, err
338 }
339
340 addr := net.JoinHostPort(o.ServerBindAddress, strconv.Itoa(o.ServerPort))
341
342 if o.Mode == "grpc" {
343 frontendServerOptions := []grpc.ServerOption{
344 grpc.Creds(credentials.NewTLS(tlsConfig)),
345 grpc.KeepaliveParams(keepalive.ServerParameters{Time: o.FrontendKeepaliveTime}),
346 }
347 grpcServer := grpc.NewServer(frontendServerOptions...)
348 client.RegisterProxyServiceServer(grpcServer, s)
349 lis, err := net.Listen("tcp", addr)
350 if err != nil {
351 return nil, fmt.Errorf("failed to listen on %s: %v", addr, err)
352 }
353 labels := runpprof.Labels(
354 "core", "mtlsGrpcFrontend",
355 "port", strconv.Itoa(o.ServerPort),
356 )
357 go runpprof.Do(context.Background(), labels, func(context.Context) { grpcServer.Serve(lis) })
358 stop = grpcServer.GracefulStop
359 } else {
360 // http-connect
361 server := &http.Server{
362 ReadHeaderTimeout: ReadHeaderTimeout,
363 Addr: addr,
364 TLSConfig: tlsConfig,
365 Handler: &server.Tunnel{
366 Server: s,
367 },
368 TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
369 }
370 stop = func() {
371 err := server.Shutdown(ctx)
372 if err != nil {
373 klog.ErrorS(err, "failed to shutdown server")
374 }
375 }
376 labels := runpprof.Labels(
377 "core", "mtlsHttpFrontend",
378 "port", strconv.Itoa(o.ServerPort),
379 )
380 go runpprof.Do(context.Background(), labels, func(context.Context) {
381 err := server.ListenAndServeTLS("", "") // empty files defaults to tlsConfig
382 if err != nil {
383 klog.ErrorS(err, "failed to listen on frontend port")
384 }
385 })
386 }
387
388 return stop, nil
389 }
390
391 func (p *Proxy) runAgentServer(o *options.ProxyRunOptions, server *server.ProxyServer) error {
392 var tlsConfig *tls.Config
393 var err error
394 if tlsConfig, err = p.getTLSConfig(o.ClusterCaCert, o.ClusterCert, o.ClusterKey, o.CipherSuites); err != nil {
395 return err
396 }
397
398 addr := net.JoinHostPort(o.AgentBindAddress, strconv.Itoa(o.AgentPort))
399 agentServerOptions := []grpc.ServerOption{
400 grpc.Creds(credentials.NewTLS(tlsConfig)),
401 grpc.KeepaliveParams(keepalive.ServerParameters{Time: o.KeepaliveTime}),
402 grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
403 MinTime: 30 * time.Second,
404 PermitWithoutStream: true,
405 }),
406 }
407 grpcServer := grpc.NewServer(agentServerOptions...)
408 agent.RegisterAgentServiceServer(grpcServer, server)
409 lis, err := net.Listen("tcp", addr)
410 if err != nil {
411 return fmt.Errorf("failed to listen on %s: %v", addr, err)
412 }
413 labels := runpprof.Labels(
414 "core", "agentListener",
415 "port", strconv.Itoa(o.AgentPort),
416 )
417 go runpprof.Do(context.Background(), labels, func(context.Context) { grpcServer.Serve(lis) })
418 p.agentServer = grpcServer
419
420 return nil
421 }
422
423 func (p *Proxy) runAdminServer(o *options.ProxyRunOptions, _ *server.ProxyServer) error {
424 muxHandler := http.NewServeMux()
425 muxHandler.Handle("/metrics", promhttp.Handler())
426 if o.EnableProfiling {
427 muxHandler.HandleFunc("/debug/pprof", util.RedirectTo("/debug/pprof/"))
428 muxHandler.HandleFunc("/debug/pprof/", netpprof.Index)
429 muxHandler.HandleFunc("/debug/pprof/profile", netpprof.Profile)
430 muxHandler.HandleFunc("/debug/pprof/symbol", netpprof.Symbol)
431 muxHandler.HandleFunc("/debug/pprof/trace", netpprof.Trace)
432 if o.EnableContentionProfiling {
433 runtime.SetBlockProfileRate(1)
434 }
435 }
436 p.adminServer = &http.Server{
437 Addr: net.JoinHostPort(o.AdminBindAddress, strconv.Itoa(o.AdminPort)),
438 Handler: muxHandler,
439 MaxHeaderBytes: 1 << 20,
440 ReadHeaderTimeout: ReadHeaderTimeout,
441 }
442
443 labels := runpprof.Labels(
444 "core", "adminListener",
445 "port", strconv.Itoa(o.AdminPort),
446 )
447 go runpprof.Do(context.Background(), labels, func(context.Context) {
448 err := p.adminServer.ListenAndServe()
449 if err != nil {
450 klog.ErrorS(err, "admin server could not listen")
451 }
452 klog.V(1).Infoln("Admin server stopped listening")
453 })
454
455 return nil
456 }
457
458 func (p *Proxy) runHealthServer(o *options.ProxyRunOptions, server *server.ProxyServer) error {
459 livenessHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
460 fmt.Fprintf(w, "ok")
461 })
462 readinessHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
463 ready, msg := server.Readiness.Ready()
464 if ready {
465 w.WriteHeader(200)
466 fmt.Fprintf(w, "ok")
467 return
468 }
469 w.WriteHeader(500)
470 fmt.Fprint(w, msg)
471 })
472
473 muxHandler := http.NewServeMux()
474 muxHandler.HandleFunc("/healthz", livenessHandler)
475 // "/ready" is deprecated but being maintained for backward compatibility
476 muxHandler.HandleFunc("/ready", readinessHandler)
477 muxHandler.HandleFunc("/readyz", readinessHandler)
478 p.healthServer = &http.Server{
479 Addr: net.JoinHostPort(o.HealthBindAddress, strconv.Itoa(o.HealthPort)),
480 Handler: muxHandler,
481 MaxHeaderBytes: 1 << 20,
482 ReadHeaderTimeout: ReadHeaderTimeout,
483 }
484
485 labels := runpprof.Labels(
486 "core", "healthListener",
487 "port", strconv.Itoa(o.HealthPort),
488 )
489 go runpprof.Do(context.Background(), labels, func(context.Context) {
490 err := p.healthServer.ListenAndServe()
491 if err != nil {
492 klog.ErrorS(err, "health server could not listen")
493 }
494 klog.V(1).Infoln("Health server stopped listening")
495 })
496
497 return nil
498 }
499
500 // ProxyServer exposes internal state for testing.
501 func (p *Proxy) ProxyServer() *server.ProxyServer {
502 return p.server
503 }