Debian Codegraph @

cmd/agent/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 "bytes"
21 "context"
22 "crypto/tls"
23 "fmt"
24 "net"
25 "net/http"
26 "net/http/pprof"
27 "os"
28 "os/signal"
29 "runtime"
30 runpprof "runtime/pprof"
31 "strconv"
32 "strings"
33 "syscall"
34 "time"
35
36 "github.com/prometheus/client_golang/prometheus/promhttp"
37 "github.com/spf13/cobra"
38 "google.golang.org/grpc"
39 "google.golang.org/grpc/credentials"
40 "google.golang.org/grpc/keepalive"
41 "k8s.io/apimachinery/pkg/labels"
42 "k8s.io/client-go/kubernetes"
43 coordinationv1lister "k8s.io/client-go/listers/coordination/v1"
44 "k8s.io/client-go/rest"
45 "k8s.io/client-go/tools/cache"
46 "k8s.io/client-go/tools/clientcmd"
47 "k8s.io/klog/v2"
48 "k8s.io/utils/clock"
49 "sigs.k8s.io/apiserver-network-proxy/cmd/agent/app/options"
50 "sigs.k8s.io/apiserver-network-proxy/pkg/agent"
51 "sigs.k8s.io/apiserver-network-proxy/pkg/util"
52 )
53
54 const (
55 ReadHeaderTimeout = 60 * time.Second
56 LeaseInformerResync = time.Second * 10
57 )
58
59 func NewAgentCommand(a *Agent, o *options.GrpcProxyAgentOptions) *cobra.Command {
60 cmd := &cobra.Command{
61 Use: "agent",
62 Long: `A gRPC agent, Connects to the proxy and then allows traffic to be forwarded to it.`,
63 RunE: func(_ *cobra.Command, _ []string) error {
64 drainCh, stopCh := SetupSignalHandler()
65 return a.Run(o, drainCh, stopCh)
66 },
67 }
68
69 return cmd
70 }
71
72 type Agent struct {
73 adminServer *http.Server
74 healthServer *http.Server
75
76 cs *agent.ClientSet
77 }
78
79 func (a *Agent) Run(o *options.GrpcProxyAgentOptions, drainCh, stopCh <-chan struct{}) error {
80 o.Print()
81 if err := o.Validate(); err != nil {
82 return fmt.Errorf("failed to validate agent options with %v", err)
83 }
84
85 cs, err := a.runProxyConnection(o, drainCh, stopCh)
86 if err != nil {
87 return fmt.Errorf("failed to run proxy connection with %v", err)
88 }
89 a.cs = cs
90
91 if err := a.runHealthServer(o, cs); err != nil {
92 return fmt.Errorf("failed to run health server with %v", err)
93 }
94 defer a.healthServer.Close()
95
96 if err := a.runAdminServer(o); err != nil {
97 return fmt.Errorf("failed to run admin server with %v", err)
98 }
99 defer a.adminServer.Close()
100
101 <-stopCh
102 klog.V(1).Infoln("Shutting down agent.")
103
104 return nil
105 }
106
107 var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
108
109 func SetupSignalHandler() (drainCh, stopCh <-chan struct{}) {
110 drain := make(chan struct{})
111 stop := make(chan struct{})
112 c := make(chan os.Signal, 2)
113 signal.Notify(c, shutdownSignals...)
114 labels := runpprof.Labels(
115 "core", "signalHandler",
116 )
117 go runpprof.Do(context.Background(), labels, func(context.Context) { handleSignals(c, drain, stop) })
118
119 return drain, stop
120 }
121
122 func handleSignals(signalCh chan os.Signal, drainCh, stopCh chan struct{}) {
123 s := <-signalCh
124 klog.V(2).InfoS("Received first signal", "signal", s)
125 close(drainCh)
126 s = <-signalCh
127 klog.V(2).InfoS("Received second signal", "signal", s)
128 close(stopCh)
129 }
130
131 func (a *Agent) runProxyConnection(o *options.GrpcProxyAgentOptions, drainCh, stopCh <-chan struct{}) (*agent.ClientSet, error) {
132 var tlsConfig *tls.Config
133 var err error
134 if tlsConfig, err = util.GetClientTLSConfig(o.CaCert, o.AgentCert, o.AgentKey, o.ProxyServerHost, o.AlpnProtos); err != nil {
135 return nil, err
136 }
137 dialOptions := []grpc.DialOption{
138 grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
139 grpc.WithKeepaliveParams(keepalive.ClientParameters{
140 Time: o.KeepaliveTime,
141 PermitWithoutStream: true,
142 }),
143 }
144 cc := o.ClientSetConfig(dialOptions...)
145
146 if o.CountServerLeases {
147 var config *rest.Config
148 if o.KubeconfigPath != "" {
149 config, err = clientcmd.BuildConfigFromFlags("", o.KubeconfigPath)
150 if err != nil {
151 return nil, fmt.Errorf("failed to load kubernetes client config: %v", err)
152 }
153 } else {
154 config, err = rest.InClusterConfig()
155 if err != nil {
156 return nil, fmt.Errorf("failed to load in cluster kubernetes client config: %w", err)
157 }
158 }
159 config.ContentType = o.APIContentType
160
161 k8sClient, err := kubernetes.NewForConfig(config)
162 if err != nil {
163 return nil, fmt.Errorf("failed to create kubernetes clientset: %v", err)
164 }
165 leaseInformer := agent.NewLeaseInformerWithMetrics(k8sClient, o.LeaseNamespace, LeaseInformerResync)
166 go leaseInformer.Run(stopCh)
167 cache.WaitForCacheSync(stopCh, leaseInformer.HasSynced)
168 leaseLister := coordinationv1lister.NewLeaseLister(leaseInformer.GetIndexer())
169 serverLeaseSelector, _ := labels.Parse(o.LeaseLabel)
170 serverLeaseCounter := agent.NewServerLeaseCounter(
171 clock.RealClock{},
172 leaseLister,
173 serverLeaseSelector,
174 )
175 cc.ServerLeaseCounter = serverLeaseCounter
176 }
177
178 cs := cc.NewAgentClientSet(drainCh, stopCh)
179 cs.Serve()
180
181 return cs, nil
182 }
183
184 func (a *Agent) runHealthServer(o *options.GrpcProxyAgentOptions, cs agent.ReadinessManager) error {
185 livenessHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
186 fmt.Fprintf(w, "ok")
187 })
188
189 checks := []agent.HealthChecker{agent.Ping, agent.NewServerConnected(cs)}
190 readinessHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
191 var failedChecks []string
192 var individualCheckOutput bytes.Buffer
193 for _, check := range checks {
194 if err := check.Check(r); err != nil {
195 fmt.Fprintf(&individualCheckOutput, "[-]%s failed: %v\n", check.Name(), err)
196 failedChecks = append(failedChecks, check.Name())
197 } else {
198 fmt.Fprintf(&individualCheckOutput, "[+]%s ok\n", check.Name())
199 }
200 }
201
202 // Always be verbose if the check has failed
203 if len(failedChecks) > 0 {
204 klog.V(0).Infof("%s check failed: \n%v", strings.Join(failedChecks, ","), individualCheckOutput.String())
205 w.WriteHeader(http.StatusServiceUnavailable)
206 fmt.Fprint(w, individualCheckOutput.String())
207 return
208 }
209
210 if _, found := r.URL.Query()["verbose"]; !found {
211 w.WriteHeader(http.StatusOK)
212 fmt.Fprint(w, "ok")
213 return
214 }
215
216 fmt.Fprintf(&individualCheckOutput, "check passed\n")
217
218 w.WriteHeader(http.StatusOK)
219 fmt.Fprint(w, individualCheckOutput.String())
220 })
221
222 muxHandler := http.NewServeMux()
223 muxHandler.Handle("/metrics", promhttp.Handler())
224 muxHandler.HandleFunc("/healthz", livenessHandler)
225 // "/ready" is deprecated but being maintained for backward compatibility
226 muxHandler.HandleFunc("/ready", readinessHandler)
227 muxHandler.HandleFunc("/readyz", readinessHandler)
228 a.healthServer = &http.Server{
229 Addr: net.JoinHostPort(o.HealthServerHost, strconv.Itoa(o.HealthServerPort)),
230 Handler: muxHandler,
231 MaxHeaderBytes: 1 << 20,
232 ReadHeaderTimeout: ReadHeaderTimeout,
233 }
234
235 labels := runpprof.Labels(
236 "core", "healthListener",
237 "port", strconv.Itoa(o.HealthServerPort),
238 )
239 go runpprof.Do(context.Background(), labels, func(context.Context) { a.serveHealth(a.healthServer) })
240
241 return nil
242 }
243
244 func (a *Agent) serveHealth(healthServer *http.Server) {
245 err := healthServer.ListenAndServe()
246 if err != nil {
247 klog.ErrorS(err, "health server could not listen")
248 }
249 klog.V(0).Infoln("Health server stopped listening")
250 }
251
252 func (a *Agent) runAdminServer(o *options.GrpcProxyAgentOptions) error {
253 muxHandler := http.NewServeMux()
254 muxHandler.Handle("/metrics", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
255 host, _, err := net.SplitHostPort(r.Host)
256 // The port number may be omitted if the admin server is running on port
257 // 80, the default port for HTTP
258 if err != nil {
259 host = r.Host
260 }
261 dest := *r.URL
262 dest.Host = net.JoinHostPort(host, strconv.Itoa(o.HealthServerPort))
263 http.Redirect(w, r, dest.String(), http.StatusMovedPermanently)
264 }))
265 if o.EnableProfiling {
266 muxHandler.HandleFunc("/debug/pprof", util.RedirectTo("/debug/pprof/"))
267 muxHandler.HandleFunc("/debug/pprof/", pprof.Index)
268 muxHandler.HandleFunc("/debug/pprof/profile", pprof.Profile)
269 muxHandler.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
270 muxHandler.HandleFunc("/debug/pprof/trace", pprof.Trace)
271 if o.EnableContentionProfiling {
272 runtime.SetBlockProfileRate(1)
273 }
274 }
275
276 a.adminServer = &http.Server{
277 Addr: net.JoinHostPort(o.AdminBindAddress, strconv.Itoa(o.AdminServerPort)),
278 Handler: muxHandler,
279 MaxHeaderBytes: 1 << 20,
280 ReadHeaderTimeout: ReadHeaderTimeout,
281 }
282
283 labels := runpprof.Labels(
284 "core", "adminListener",
285 "port", strconv.Itoa(o.AdminServerPort),
286 )
287 go runpprof.Do(context.Background(), labels, func(context.Context) { a.serveAdmin(a.adminServer) })
288
289 return nil
290 }
291
292 func (a *Agent) serveAdmin(adminServer *http.Server) {
293 err := adminServer.ListenAndServe()
294 if err != nil {
295 klog.ErrorS(err, "admin server could not listen")
296 }
297 klog.V(0).Infoln("Admin server stopped listening")
298 }
299
300 // ClientSet exposes internal state for testing.
301 func (a *Agent) ClientSet() *agent.ClientSet {
302 return a.cs
303 }