Debian Codegraph @

cmd/agent/app/server.go

raw
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 var leaseCounter agent.ServerCounter
147 if o.CountServerLeases {
148 var config *rest.Config
149 if o.KubeconfigPath != "" {
150 config, err = clientcmd.BuildConfigFromFlags("", o.KubeconfigPath)
151 if err != nil {
152 return nil, fmt.Errorf("failed to load kubernetes client config: %v", err)
153 }
154 } else {
155 config, err = rest.InClusterConfig()
156 if err != nil {
157 return nil, fmt.Errorf("failed to load in cluster kubernetes client config: %w", err)
158 }
159 }
160 config.ContentType = o.APIContentType
161
162 k8sClient, err := kubernetes.NewForConfig(config)
163 if err != nil {
164 return nil, fmt.Errorf("failed to create kubernetes clientset: %v", err)
165 }
166 leaseInformer := agent.NewLeaseInformerWithMetrics(k8sClient, o.LeaseNamespace, LeaseInformerResync)
167 go leaseInformer.Run(stopCh)
168 cache.WaitForCacheSync(stopCh, leaseInformer.HasSynced)
169 leaseLister := coordinationv1lister.NewLeaseLister(leaseInformer.GetIndexer())
170 serverLeaseSelector, _ := labels.Parse(o.LeaseLabel)
171 leaseCounter = agent.NewServerLeaseCounter(
172 clock.RealClock{},
173 leaseLister,
174 serverLeaseSelector,
175 )
176 }
177
178 cs := cc.NewAgentClientSet(drainCh, stopCh)
179 // Always create the response-based counter.
180 responseCounter := agent.NewResponseBasedCounter(cs)
181 // Create the aggregate counter which acts as the master strategy.
182 aggregateCounter := agent.NewAggregateServerCounter(leaseCounter, responseCounter, o.ServerCountSource)
183 cs.SetServerCounter(aggregateCounter)
184
185 cs.Serve()
186
187 return cs, nil
188 }
189
190 func (a *Agent) runHealthServer(o *options.GrpcProxyAgentOptions, cs agent.ReadinessManager) error {
191 livenessHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
192 fmt.Fprintf(w, "ok")
193 })
194
195 checks := []agent.HealthChecker{agent.Ping, agent.NewServerConnected(cs)}
196 readinessHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
197 var failedChecks []string
198 var individualCheckOutput bytes.Buffer
199 for _, check := range checks {
200 if err := check.Check(r); err != nil {
201 fmt.Fprintf(&individualCheckOutput, "[-]%s failed: %v\n", check.Name(), err)
202 failedChecks = append(failedChecks, check.Name())
203 } else {
204 fmt.Fprintf(&individualCheckOutput, "[+]%s ok\n", check.Name())
205 }
206 }
207
208 // Always be verbose if the check has failed
209 if len(failedChecks) > 0 {
210 klog.V(0).Infof("%s check failed: \n%v", strings.Join(failedChecks, ","), individualCheckOutput.String())
211 w.WriteHeader(http.StatusServiceUnavailable)
212 fmt.Fprint(w, individualCheckOutput.String())
213 return
214 }
215
216 if _, found := r.URL.Query()["verbose"]; !found {
217 w.WriteHeader(http.StatusOK)
218 fmt.Fprint(w, "ok")
219 return
220 }
221
222 fmt.Fprintf(&individualCheckOutput, "check passed\n")
223
224 w.WriteHeader(http.StatusOK)
225 fmt.Fprint(w, individualCheckOutput.String())
226 })
227
228 muxHandler := http.NewServeMux()
229 muxHandler.Handle("/metrics", promhttp.Handler())
230 muxHandler.HandleFunc("/healthz", livenessHandler)
231 // "/ready" is deprecated but being maintained for backward compatibility
232 muxHandler.HandleFunc("/ready", readinessHandler)
233 muxHandler.HandleFunc("/readyz", readinessHandler)
234 a.healthServer = &http.Server{
235 Addr: net.JoinHostPort(o.HealthServerHost, strconv.Itoa(o.HealthServerPort)),
236 Handler: muxHandler,
237 MaxHeaderBytes: 1 << 20,
238 ReadHeaderTimeout: ReadHeaderTimeout,
239 }
240
241 labels := runpprof.Labels(
242 "core", "healthListener",
243 "port", strconv.Itoa(o.HealthServerPort),
244 )
245 go runpprof.Do(context.Background(), labels, func(context.Context) { a.serveHealth(a.healthServer) })
246
247 return nil
248 }
249
250 func (a *Agent) serveHealth(healthServer *http.Server) {
251 err := healthServer.ListenAndServe()
252 if err != nil {
253 klog.ErrorS(err, "health server could not listen")
254 }
255 klog.V(0).Infoln("Health server stopped listening")
256 }
257
258 func (a *Agent) runAdminServer(o *options.GrpcProxyAgentOptions) error {
259 muxHandler := http.NewServeMux()
260 muxHandler.Handle("/metrics", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
261 host, _, err := net.SplitHostPort(r.Host)
262 // The port number may be omitted if the admin server is running on port
263 // 80, the default port for HTTP
264 if err != nil {
265 host = r.Host
266 }
267 dest := *r.URL
268 dest.Host = net.JoinHostPort(host, strconv.Itoa(o.HealthServerPort))
269 http.Redirect(w, r, dest.String(), http.StatusMovedPermanently)
270 }))
271 if o.EnableProfiling {
272 muxHandler.HandleFunc("/debug/pprof", util.RedirectTo("/debug/pprof/"))
273 muxHandler.HandleFunc("/debug/pprof/", pprof.Index)
274 muxHandler.HandleFunc("/debug/pprof/profile", pprof.Profile)
275 muxHandler.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
276 muxHandler.HandleFunc("/debug/pprof/trace", pprof.Trace)
277 if o.EnableContentionProfiling {
278 runtime.SetBlockProfileRate(1)
279 }
280 }
281
282 a.adminServer = &http.Server{
283 Addr: net.JoinHostPort(o.AdminBindAddress, strconv.Itoa(o.AdminServerPort)),
284 Handler: muxHandler,
285 MaxHeaderBytes: 1 << 20,
286 ReadHeaderTimeout: ReadHeaderTimeout,
287 }
288
289 labels := runpprof.Labels(
290 "core", "adminListener",
291 "port", strconv.Itoa(o.AdminServerPort),
292 )
293 go runpprof.Do(context.Background(), labels, func(context.Context) { a.serveAdmin(a.adminServer) })
294
295 return nil
296 }
297
298 func (a *Agent) serveAdmin(adminServer *http.Server) {
299 err := adminServer.ListenAndServe()
300 if err != nil {
301 klog.ErrorS(err, "admin server could not listen")
302 }
303 klog.V(0).Infoln("Admin server stopped listening")
304 }
305
306 // ClientSet exposes internal state for testing.
307 func (a *Agent) ClientSet() *agent.ClientSet {
308 return a.cs
309 }