| 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/server/proxystrategies" |
| 50 |
"sigs.k8s.io/apiserver-network-proxy/pkg/util" |
| 51 |
"sigs.k8s.io/apiserver-network-proxy/proto/agent" |
| 52 |
) |
| 53 |
|
| 54 |
var udsListenerLock sync.Mutex |
| 55 |
|
| 56 |
const ( |
| 57 |
ReadHeaderTimeout = 60 * time.Second |
| 58 |
LeaseDuration = 30 * time.Second |
| 59 |
LeaseRenewalInterval = 15 * time.Second |
| 60 |
LeaseGCInterval = 15 * time.Second |
| 61 |
) |
| 62 |
|
| 63 |
func NewProxyCommand(p *Proxy, o *options.ProxyRunOptions) *cobra.Command { |
| 64 |
cmd := &cobra.Command{ |
| 65 |
Use: "proxy", |
| 66 |
Long: `A gRPC proxy server, receives requests from the API server and forwards to the agent.`, |
| 67 |
RunE: func(_ *cobra.Command, _ []string) error { |
| 68 |
stopCh := SetupSignalHandler() |
| 69 |
return p.Run(o, stopCh) |
| 70 |
}, |
| 71 |
} |
| 72 |
|
| 73 |
return cmd |
| 74 |
} |
| 75 |
|
| 76 |
func tlsCipherSuites(cipherNames []string) []uint16 { |
| 77 |
// return nil, so use default cipher list |
| 78 |
if len(cipherNames) == 0 { |
| 79 |
return nil |
| 80 |
} |
| 81 |
|
| 82 |
acceptedCiphers := util.GetAcceptedCiphers() |
| 83 |
ciphersIntSlice := make([]uint16, 0) |
| 84 |
for _, cipher := range cipherNames { |
| 85 |
ciphersIntSlice = append(ciphersIntSlice, acceptedCiphers[cipher]) |
| 86 |
} |
| 87 |
return ciphersIntSlice |
| 88 |
} |
| 89 |
|
| 90 |
type Proxy struct { |
| 91 |
agentServer *grpc.Server |
| 92 |
adminServer *http.Server |
| 93 |
healthServer *http.Server |
| 94 |
|
| 95 |
server *server.ProxyServer |
| 96 |
} |
| 97 |
|
| 98 |
type StopFunc func(context.Context) error |
| 99 |
|
| 100 |
func (p *Proxy) Run(o *options.ProxyRunOptions, stopCh <-chan struct{}) error { |
| 101 |
o.Print() |
| 102 |
if err := o.Validate(); err != nil { |
| 103 |
return fmt.Errorf("failed to validate server options with %v", err) |
| 104 |
} |
| 105 |
ctx, cancel := context.WithCancel(context.Background()) |
| 106 |
defer cancel() |
| 107 |
|
| 108 |
var k8sClient *kubernetes.Clientset |
| 109 |
if o.NeedsKubernetesClient { |
| 110 |
config, err := clientcmd.BuildConfigFromFlags("", o.KubeconfigPath) |
| 111 |
if err != nil { |
| 112 |
return fmt.Errorf("failed to load kubernetes client config: %v", err) |
| 113 |
} |
| 114 |
|
| 115 |
if o.KubeconfigQPS != 0 { |
| 116 |
klog.V(1).Infof("Setting k8s client QPS: %v", o.KubeconfigQPS) |
| 117 |
config.QPS = o.KubeconfigQPS |
| 118 |
} |
| 119 |
if o.KubeconfigBurst != 0 { |
| 120 |
klog.V(1).Infof("Setting k8s client Burst: %v", o.KubeconfigBurst) |
| 121 |
config.Burst = o.KubeconfigBurst |
| 122 |
} |
| 123 |
config.ContentType = o.APIContentType |
| 124 |
k8sClient, err = kubernetes.NewForConfig(config) |
| 125 |
if err != nil { |
| 126 |
return fmt.Errorf("failed to create kubernetes clientset: %v", err) |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
authOpt := &server.AgentTokenAuthenticationOptions{ |
| 131 |
Enabled: o.AgentNamespace != "", |
| 132 |
AgentNamespace: o.AgentNamespace, |
| 133 |
AgentServiceAccount: o.AgentServiceAccount, |
| 134 |
KubernetesClient: k8sClient, |
| 135 |
AuthenticationAudience: o.AuthenticationAudience, |
| 136 |
} |
| 137 |
klog.V(1).Infoln("Starting frontend server for client connections.") |
| 138 |
ps, err := proxystrategies.ParseProxyStrategies(o.ProxyStrategies) |
| 139 |
if err != nil { |
| 140 |
return err |
| 141 |
} |
| 142 |
p.server = server.NewProxyServer(o.ServerID, ps, o.ServerCount, authOpt, o.XfrChannelSize) |
| 143 |
p.server.SetBackendDialTimeout(o.BackendDialTimeout) |
| 144 |
|
| 145 |
frontendStop, err := p.runFrontendServer(ctx, o, p.server) |
| 146 |
if err != nil { |
| 147 |
return fmt.Errorf("failed to run the frontend server: %v", err) |
| 148 |
} |
| 149 |
|
| 150 |
klog.V(1).Infoln("Starting agent server for tunnel connections.") |
| 151 |
err = p.runAgentServer(o, p.server) |
| 152 |
if err != nil { |
| 153 |
return fmt.Errorf("failed to run the agent server: %v", err) |
| 154 |
} |
| 155 |
|
| 156 |
labels, err := util.ParseLabels(o.LeaseLabel) |
| 157 |
if err != nil { |
| 158 |
return err |
| 159 |
} |
| 160 |
|
| 161 |
var leaseController *leases.Controller |
| 162 |
if o.EnableLeaseController { |
| 163 |
leaseController = leases.NewController( |
| 164 |
k8sClient, |
| 165 |
o.ServerID, |
| 166 |
int32(LeaseDuration.Seconds()), |
| 167 |
LeaseRenewalInterval, |
| 168 |
LeaseGCInterval, |
| 169 |
fmt.Sprintf("konnectivity-proxy-server-%v", o.ServerID), |
| 170 |
o.LeaseNamespace, |
| 171 |
labels, |
| 172 |
) |
| 173 |
klog.V(1).Infoln("Starting lease acquisition and garbage collection controller.") |
| 174 |
leaseController.Run(ctx) |
| 175 |
} |
| 176 |
|
| 177 |
klog.V(1).Infoln("Starting admin server for debug connections.") |
| 178 |
err = p.runAdminServer(o, p.server) |
| 179 |
if err != nil { |
| 180 |
return fmt.Errorf("failed to run the admin server: %v", err) |
| 181 |
} |
| 182 |
|
| 183 |
klog.V(1).Infoln("Starting health server for healthchecks.") |
| 184 |
err = p.runHealthServer(o, p.server) |
| 185 |
if err != nil { |
| 186 |
return fmt.Errorf("failed to run the health server: %v", err) |
| 187 |
} |
| 188 |
|
| 189 |
<-stopCh |
| 190 |
klog.V(1).Infoln("Shutting down server.") |
| 191 |
|
| 192 |
// If graceful shutdown timeout is 0, use the old behavior (immediate shutdown) |
| 193 |
if o.GracefulShutdownTimeout == 0 { |
| 194 |
if frontendStop != nil { |
| 195 |
if err := frontendStop(context.Background()); err != nil { |
| 196 |
klog.ErrorS(err, "failed to stop frontend server") |
| 197 |
} |
| 198 |
} |
| 199 |
if p.agentServer != nil { |
| 200 |
p.agentServer.Stop() |
| 201 |
} |
| 202 |
if p.adminServer != nil { |
| 203 |
p.adminServer.Close() |
| 204 |
} |
| 205 |
if p.healthServer != nil { |
| 206 |
p.healthServer.Close() |
| 207 |
} |
| 208 |
if leaseController != nil { |
| 209 |
leaseController.Stop() |
| 210 |
} |
| 211 |
return nil |
| 212 |
} |
| 213 |
|
| 214 |
klog.V(1).Infoln("Initiating graceful shutdown.") |
| 215 |
|
| 216 |
// Start graceful shutdown with timeout |
| 217 |
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), o.GracefulShutdownTimeout) |
| 218 |
defer shutdownCancel() |
| 219 |
|
| 220 |
// Create a WaitGroup to track shutdown of all components |
| 221 |
var wg sync.WaitGroup |
| 222 |
|
| 223 |
// Add all workers to WaitGroup upfront |
| 224 |
if frontendStop != nil { |
| 225 |
wg.Add(1) |
| 226 |
} |
| 227 |
wg.Add(3) // agent, admin, health servers |
| 228 |
|
| 229 |
// Create completion channel before starting goroutines |
| 230 |
shutdownComplete := make(chan struct{}) |
| 231 |
go func() { |
| 232 |
wg.Wait() |
| 233 |
close(shutdownComplete) |
| 234 |
}() |
| 235 |
|
| 236 |
// Shutdown frontend server gracefully (if available) |
| 237 |
if frontendStop != nil { |
| 238 |
go func() { |
| 239 |
defer wg.Done() |
| 240 |
klog.V(1).Infoln("Gracefully stopping frontend server...") |
| 241 |
if err := frontendStop(shutdownCtx); err != nil { |
| 242 |
klog.ErrorS(err, "failed to shut down frontend server") |
| 243 |
} else { |
| 244 |
klog.V(1).Infoln("frontend server stopped.") |
| 245 |
} |
| 246 |
}() |
| 247 |
} |
| 248 |
|
| 249 |
// Shutdown agent server gracefully |
| 250 |
go func() { |
| 251 |
defer wg.Done() |
| 252 |
klog.V(1).Infoln("Gracefully stopping agent server...") |
| 253 |
p.agentServer.GracefulStop() |
| 254 |
klog.V(1).Infoln("agent server stopped.") |
| 255 |
}() |
| 256 |
|
| 257 |
// Shutdown admin server gracefully |
| 258 |
go func() { |
| 259 |
defer wg.Done() |
| 260 |
klog.V(1).Infoln("Gracefully stopping admin server...") |
| 261 |
if err := p.adminServer.Shutdown(shutdownCtx); err != nil { |
| 262 |
klog.ErrorS(err, "failed to shut down admin server") |
| 263 |
} else { |
| 264 |
klog.V(1).Infoln("admin server stopped.") |
| 265 |
} |
| 266 |
}() |
| 267 |
|
| 268 |
// Shutdown health server gracefully |
| 269 |
go func() { |
| 270 |
defer wg.Done() |
| 271 |
klog.V(1).Infoln("Gracefully stopping health server...") |
| 272 |
if err := p.healthServer.Shutdown(shutdownCtx); err != nil { |
| 273 |
klog.ErrorS(err, "failed to shut down health server") |
| 274 |
} else { |
| 275 |
klog.V(1).Infoln("health server stopped.") |
| 276 |
} |
| 277 |
}() |
| 278 |
|
| 279 |
// Wait for all servers to shutdown or timeout |
| 280 |
select { |
| 281 |
case <-shutdownComplete: |
| 282 |
klog.V(1).Infoln("Graceful shutdown completed successfully.") |
| 283 |
case <-shutdownCtx.Done(): |
| 284 |
klog.Warningf("Graceful shutdown timed out after %v, forcing termination.", o.GracefulShutdownTimeout) |
| 285 |
// Force stop all servers that might still be running |
| 286 |
if p.agentServer != nil { |
| 287 |
p.agentServer.Stop() |
| 288 |
} |
| 289 |
if p.adminServer != nil { |
| 290 |
p.adminServer.Close() |
| 291 |
} |
| 292 |
if p.healthServer != nil { |
| 293 |
p.healthServer.Close() |
| 294 |
} |
| 295 |
// frontend server's force-stop is handled by its StopFunc |
| 296 |
} |
| 297 |
|
| 298 |
// Stop lease controller after servers have shut down |
| 299 |
if leaseController != nil { |
| 300 |
klog.V(1).Infoln("Stopping lease controller.") |
| 301 |
leaseController.Stop() |
| 302 |
} |
| 303 |
|
| 304 |
return nil |
| 305 |
} |
| 306 |
|
| 307 |
var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM} |
| 308 |
|
| 309 |
func SetupSignalHandler() (stopCh <-chan struct{}) { |
| 310 |
stop := make(chan struct{}) |
| 311 |
c := make(chan os.Signal, 2) |
| 312 |
signal.Notify(c, shutdownSignals...) |
| 313 |
labels := runpprof.Labels( |
| 314 |
"core", "signalHandler", |
| 315 |
) |
| 316 |
go runpprof.Do(context.Background(), labels, func(context.Context) { handleSignals(c, stop) }) |
| 317 |
|
| 318 |
return stop |
| 319 |
} |
| 320 |
|
| 321 |
func handleSignals(signalCh chan os.Signal, stopCh chan struct{}) { |
| 322 |
<-signalCh |
| 323 |
close(stopCh) |
| 324 |
<-signalCh |
| 325 |
os.Exit(1) // second signal. Exit directly. |
| 326 |
} |
| 327 |
|
| 328 |
func getUDSListener(ctx context.Context, udsName string) (net.Listener, error) { |
| 329 |
udsListenerLock.Lock() |
| 330 |
defer udsListenerLock.Unlock() |
| 331 |
oldUmask := syscall.Umask(0007) |
| 332 |
defer syscall.Umask(oldUmask) |
| 333 |
var lc net.ListenConfig |
| 334 |
lis, err := lc.Listen(ctx, "unix", udsName) |
| 335 |
if err != nil { |
| 336 |
return nil, fmt.Errorf("failed to listen(unix) name %s: %v", udsName, err) |
| 337 |
} |
| 338 |
return lis, nil |
| 339 |
} |
| 340 |
|
| 341 |
func (p *Proxy) runFrontendServer(ctx context.Context, o *options.ProxyRunOptions, server *server.ProxyServer) (StopFunc, error) { |
| 342 |
if o.UdsName != "" { |
| 343 |
return p.runUDSFrontendServer(ctx, o, server) |
| 344 |
} |
| 345 |
return p.runMTLSFrontendServer(ctx, o, server) |
| 346 |
} |
| 347 |
|
| 348 |
func (p *Proxy) runUDSFrontendServer(ctx context.Context, o *options.ProxyRunOptions, s *server.ProxyServer) (StopFunc, error) { |
| 349 |
if o.DeleteUDSFile { |
| 350 |
if err := os.Remove(o.UdsName); err != nil && !os.IsNotExist(err) { |
| 351 |
klog.ErrorS(err, "failed to delete file", "file", o.UdsName) |
| 352 |
} |
| 353 |
} |
| 354 |
var stop StopFunc |
| 355 |
if o.Mode == "grpc" { |
| 356 |
frontendServerOptions := []grpc.ServerOption{ |
| 357 |
grpc.KeepaliveParams(keepalive.ServerParameters{Time: o.FrontendKeepaliveTime}), |
| 358 |
} |
| 359 |
grpcServer := grpc.NewServer(frontendServerOptions...) |
| 360 |
client.RegisterProxyServiceServer(grpcServer, s) |
| 361 |
lis, err := getUDSListener(ctx, o.UdsName) |
| 362 |
if err != nil { |
| 363 |
return nil, fmt.Errorf("failed to get uds listener: %v", err) |
| 364 |
} |
| 365 |
labels := runpprof.Labels( |
| 366 |
"core", "udsGrpcFrontend", |
| 367 |
"udsFile", o.UdsName, |
| 368 |
) |
| 369 |
go runpprof.Do(context.Background(), labels, func(context.Context) { grpcServer.Serve(lis) }) |
| 370 |
stop = func(_ context.Context) error { |
| 371 |
grpcServer.GracefulStop() |
| 372 |
return nil |
| 373 |
} |
| 374 |
} else { |
| 375 |
// http-connect |
| 376 |
server := &http.Server{ |
| 377 |
ReadHeaderTimeout: ReadHeaderTimeout, |
| 378 |
Handler: &server.Tunnel{ |
| 379 |
Server: s, |
| 380 |
}, |
| 381 |
} |
| 382 |
stop = func(shutdownCtx context.Context) error { |
| 383 |
return server.Shutdown(shutdownCtx) |
| 384 |
} |
| 385 |
labels := runpprof.Labels( |
| 386 |
"core", "udsHttpFrontend", |
| 387 |
"udsFile", o.UdsName, |
| 388 |
) |
| 389 |
go runpprof.Do(context.Background(), labels, func(context.Context) { |
| 390 |
udsListener, err := getUDSListener(ctx, o.UdsName) |
| 391 |
if err != nil { |
| 392 |
klog.ErrorS(err, "failed to get uds listener") |
| 393 |
} |
| 394 |
defer func() { |
| 395 |
err := udsListener.Close() |
| 396 |
klog.ErrorS(err, "failed to close uds listener") |
| 397 |
}() |
| 398 |
err = server.Serve(udsListener) |
| 399 |
if err != nil { |
| 400 |
klog.ErrorS(err, "failed to serve uds requests") |
| 401 |
} |
| 402 |
}) |
| 403 |
} |
| 404 |
|
| 405 |
return stop, nil |
| 406 |
} |
| 407 |
|
| 408 |
func (p *Proxy) getTLSConfig(caFile, certFile, keyFile string, cipherSuites []string, tlsMinVersion string) (*tls.Config, error) { |
| 409 |
cert, err := tls.LoadX509KeyPair(certFile, keyFile) |
| 410 |
if err != nil { |
| 411 |
return nil, fmt.Errorf("failed to load X509 key pair %s and %s: %v", certFile, keyFile, err) |
| 412 |
} |
| 413 |
|
| 414 |
cipherSuiteIDs := tlsCipherSuites(cipherSuites) |
| 415 |
|
| 416 |
minVersion, err := util.GetTLSVersion(tlsMinVersion) |
| 417 |
if err != nil { |
| 418 |
return nil, fmt.Errorf("failed to parse TLS min version: %v", err) |
| 419 |
} |
| 420 |
|
| 421 |
if caFile == "" { |
| 422 |
return &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: minVersion, CipherSuites: cipherSuiteIDs}, nil // #nosec G402 |
| 423 |
} |
| 424 |
|
| 425 |
certPool := x509.NewCertPool() |
| 426 |
caCert, err := os.ReadFile(filepath.Clean(caFile)) |
| 427 |
if err != nil { |
| 428 |
return nil, fmt.Errorf("failed to read cluster CA cert %s: %v", caFile, err) |
| 429 |
} |
| 430 |
ok := certPool.AppendCertsFromPEM(caCert) |
| 431 |
if !ok { |
| 432 |
return nil, fmt.Errorf("failed to append cluster CA cert to the cert pool") |
| 433 |
} |
| 434 |
|
| 435 |
tlsConfig := &tls.Config{ // #nosec G402 |
| 436 |
ClientAuth: tls.RequireAndVerifyClientCert, |
| 437 |
Certificates: []tls.Certificate{cert}, |
| 438 |
ClientCAs: certPool, |
| 439 |
MinVersion: minVersion, |
| 440 |
CipherSuites: cipherSuiteIDs, |
| 441 |
} |
| 442 |
|
| 443 |
return tlsConfig, nil |
| 444 |
} |
| 445 |
|
| 446 |
func (p *Proxy) runMTLSFrontendServer(_ context.Context, o *options.ProxyRunOptions, s *server.ProxyServer) (StopFunc, error) { |
| 447 |
var stop StopFunc |
| 448 |
|
| 449 |
var tlsConfig *tls.Config |
| 450 |
var err error |
| 451 |
if tlsConfig, err = p.getTLSConfig(o.ServerCaCert, o.ServerCert, o.ServerKey, o.CipherSuites, o.TLSMinVersion); err != nil { |
| 452 |
return nil, err |
| 453 |
} |
| 454 |
|
| 455 |
addr := net.JoinHostPort(o.ServerBindAddress, strconv.Itoa(o.ServerPort)) |
| 456 |
|
| 457 |
if o.Mode == "grpc" { |
| 458 |
frontendServerOptions := []grpc.ServerOption{ |
| 459 |
grpc.Creds(credentials.NewTLS(tlsConfig)), |
| 460 |
grpc.KeepaliveParams(keepalive.ServerParameters{Time: o.FrontendKeepaliveTime}), |
| 461 |
} |
| 462 |
grpcServer := grpc.NewServer(frontendServerOptions...) |
| 463 |
client.RegisterProxyServiceServer(grpcServer, s) |
| 464 |
lis, err := net.Listen("tcp", addr) |
| 465 |
if err != nil { |
| 466 |
return nil, fmt.Errorf("failed to listen on %s: %v", addr, err) |
| 467 |
} |
| 468 |
labels := runpprof.Labels( |
| 469 |
"core", "mtlsGrpcFrontend", |
| 470 |
"port", strconv.Itoa(o.ServerPort), |
| 471 |
) |
| 472 |
go runpprof.Do(context.Background(), labels, func(context.Context) { grpcServer.Serve(lis) }) |
| 473 |
stop = func(_ context.Context) error { |
| 474 |
grpcServer.GracefulStop() |
| 475 |
return nil |
| 476 |
} |
| 477 |
} else { |
| 478 |
// http-connect |
| 479 |
server := &http.Server{ |
| 480 |
ReadHeaderTimeout: ReadHeaderTimeout, |
| 481 |
Addr: addr, |
| 482 |
TLSConfig: tlsConfig, |
| 483 |
Handler: &server.Tunnel{ |
| 484 |
Server: s, |
| 485 |
}, |
| 486 |
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)), |
| 487 |
} |
| 488 |
stop = func(shutdownCtx context.Context) error { |
| 489 |
return server.Shutdown(shutdownCtx) |
| 490 |
} |
| 491 |
labels := runpprof.Labels( |
| 492 |
"core", "mtlsHttpFrontend", |
| 493 |
"port", strconv.Itoa(o.ServerPort), |
| 494 |
) |
| 495 |
go runpprof.Do(context.Background(), labels, func(context.Context) { |
| 496 |
err := server.ListenAndServeTLS("", "") // empty files defaults to tlsConfig |
| 497 |
if err != nil { |
| 498 |
klog.ErrorS(err, "failed to listen on frontend port") |
| 499 |
} |
| 500 |
}) |
| 501 |
} |
| 502 |
|
| 503 |
return stop, nil |
| 504 |
} |
| 505 |
|
| 506 |
func (p *Proxy) runAgentServer(o *options.ProxyRunOptions, server *server.ProxyServer) error { |
| 507 |
var tlsConfig *tls.Config |
| 508 |
var err error |
| 509 |
if tlsConfig, err = p.getTLSConfig(o.ClusterCaCert, o.ClusterCert, o.ClusterKey, o.CipherSuites, o.TLSMinVersion); err != nil { |
| 510 |
return err |
| 511 |
} |
| 512 |
|
| 513 |
addr := net.JoinHostPort(o.AgentBindAddress, strconv.Itoa(o.AgentPort)) |
| 514 |
agentServerOptions := []grpc.ServerOption{ |
| 515 |
grpc.Creds(credentials.NewTLS(tlsConfig)), |
| 516 |
grpc.KeepaliveParams(keepalive.ServerParameters{Time: o.KeepaliveTime}), |
| 517 |
grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{ |
| 518 |
MinTime: 30 * time.Second, |
| 519 |
PermitWithoutStream: true, |
| 520 |
}), |
| 521 |
} |
| 522 |
grpcServer := grpc.NewServer(agentServerOptions...) |
| 523 |
agent.RegisterAgentServiceServer(grpcServer, server) |
| 524 |
lis, err := net.Listen("tcp", addr) |
| 525 |
if err != nil { |
| 526 |
return fmt.Errorf("failed to listen on %s: %v", addr, err) |
| 527 |
} |
| 528 |
labels := runpprof.Labels( |
| 529 |
"core", "agentListener", |
| 530 |
"port", strconv.Itoa(o.AgentPort), |
| 531 |
) |
| 532 |
go runpprof.Do(context.Background(), labels, func(context.Context) { grpcServer.Serve(lis) }) |
| 533 |
p.agentServer = grpcServer |
| 534 |
|
| 535 |
return nil |
| 536 |
} |
| 537 |
|
| 538 |
func (p *Proxy) runAdminServer(o *options.ProxyRunOptions, _ *server.ProxyServer) error { |
| 539 |
muxHandler := http.NewServeMux() |
| 540 |
// /metrics moved to HealthServer but being maintained here for backward compatibility |
| 541 |
muxHandler.Handle("/metrics", promhttp.Handler()) |
| 542 |
if o.EnableProfiling { |
| 543 |
muxHandler.HandleFunc("/debug/pprof", util.RedirectTo("/debug/pprof/")) |
| 544 |
muxHandler.HandleFunc("/debug/pprof/", netpprof.Index) |
| 545 |
muxHandler.HandleFunc("/debug/pprof/profile", netpprof.Profile) |
| 546 |
muxHandler.HandleFunc("/debug/pprof/symbol", netpprof.Symbol) |
| 547 |
muxHandler.HandleFunc("/debug/pprof/trace", netpprof.Trace) |
| 548 |
if o.EnableContentionProfiling { |
| 549 |
runtime.SetBlockProfileRate(1) |
| 550 |
} |
| 551 |
} |
| 552 |
p.adminServer = &http.Server{ |
| 553 |
Addr: net.JoinHostPort(o.AdminBindAddress, strconv.Itoa(o.AdminPort)), |
| 554 |
Handler: muxHandler, |
| 555 |
MaxHeaderBytes: 1 << 20, |
| 556 |
ReadHeaderTimeout: ReadHeaderTimeout, |
| 557 |
} |
| 558 |
|
| 559 |
labels := runpprof.Labels( |
| 560 |
"core", "adminListener", |
| 561 |
"port", strconv.Itoa(o.AdminPort), |
| 562 |
) |
| 563 |
go runpprof.Do(context.Background(), labels, func(context.Context) { |
| 564 |
err := p.adminServer.ListenAndServe() |
| 565 |
if err != nil { |
| 566 |
klog.ErrorS(err, "admin server could not listen") |
| 567 |
} |
| 568 |
klog.V(1).Infoln("Admin server stopped listening") |
| 569 |
}) |
| 570 |
|
| 571 |
return nil |
| 572 |
} |
| 573 |
|
| 574 |
func (p *Proxy) runHealthServer(o *options.ProxyRunOptions, server *server.ProxyServer) error { |
| 575 |
livenessHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 576 |
fmt.Fprintf(w, "ok") |
| 577 |
}) |
| 578 |
readinessHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 579 |
ready, msg := server.Readiness.Ready() |
| 580 |
if ready { |
| 581 |
w.WriteHeader(200) |
| 582 |
fmt.Fprintf(w, "ok") |
| 583 |
return |
| 584 |
} |
| 585 |
w.WriteHeader(500) |
| 586 |
fmt.Fprint(w, msg) |
| 587 |
}) |
| 588 |
|
| 589 |
muxHandler := http.NewServeMux() |
| 590 |
muxHandler.Handle("/metrics", promhttp.Handler()) |
| 591 |
muxHandler.HandleFunc("/healthz", livenessHandler) |
| 592 |
// "/ready" is deprecated but being maintained for backward compatibility |
| 593 |
muxHandler.HandleFunc("/ready", readinessHandler) |
| 594 |
muxHandler.HandleFunc("/readyz", readinessHandler) |
| 595 |
p.healthServer = &http.Server{ |
| 596 |
Addr: net.JoinHostPort(o.HealthBindAddress, strconv.Itoa(o.HealthPort)), |
| 597 |
Handler: muxHandler, |
| 598 |
MaxHeaderBytes: 1 << 20, |
| 599 |
ReadHeaderTimeout: ReadHeaderTimeout, |
| 600 |
} |
| 601 |
|
| 602 |
labels := runpprof.Labels( |
| 603 |
"core", "healthListener", |
| 604 |
"port", strconv.Itoa(o.HealthPort), |
| 605 |
) |
| 606 |
go runpprof.Do(context.Background(), labels, func(context.Context) { |
| 607 |
err := p.healthServer.ListenAndServe() |
| 608 |
if err != nil { |
| 609 |
klog.ErrorS(err, "health server could not listen") |
| 610 |
} |
| 611 |
klog.V(1).Infoln("Health server stopped listening") |
| 612 |
}) |
| 613 |
|
| 614 |
return nil |
| 615 |
} |
| 616 |
|
| 617 |
// ProxyServer exposes internal state for testing. |
| 618 |
func (p *Proxy) ProxyServer() *server.ProxyServer { |
| 619 |
return p.server |
| 620 |
} |