Debian Codegraph @

cmd/server/app/options/options.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 options
18
19 import (
20 "fmt"
21 "os"
22 "time"
23
24 "github.com/google/uuid"
25 "github.com/spf13/pflag"
26 "k8s.io/apimachinery/pkg/runtime"
27 "k8s.io/klog/v2"
28
29 "sigs.k8s.io/apiserver-network-proxy/pkg/server"
30 "sigs.k8s.io/apiserver-network-proxy/pkg/util"
31 )
32
33 type ProxyRunOptions struct {
34 // Certificate setup for securing communication to the "client" i.e. the Kube API Server.
35 ServerCert string
36 ServerKey string
37 ServerCaCert string
38 // Certificate setup for securing communication to the "agent" i.e. the managed cluster.
39 ClusterCert string
40 ClusterKey string
41 ClusterCaCert string
42 // Flag to switch between gRPC and HTTP Connect
43 Mode string
44 // Location for use by the "unix" network. Setting enables UDS for server connections.
45 UdsName string
46 // If file UdsName already exists, delete the file before listen on that UDS file.
47 DeleteUDSFile bool
48 // Port we listen for server connections on.
49 ServerPort int
50 // Bind address for the server.
51 ServerBindAddress string
52 // Port we listen for agent connections on.
53 AgentPort int
54 // Bind address for the agent.
55 AgentBindAddress string
56 // Port we listen for admin connections on.
57 AdminPort int
58 // Bind address for the admin connections.
59 AdminBindAddress string
60 // Port we listen for health connections on.
61 HealthPort int
62 // Bind address for the health connections.
63 HealthBindAddress string
64 // After a duration of this time if the server doesn't see any activity it
65 // pings the client to see if the transport is still alive.
66 KeepaliveTime time.Duration
67 FrontendKeepaliveTime time.Duration
68 // Enables pprof at host:AdminPort/debug/pprof.
69 EnableProfiling bool
70 // If EnableProfiling is true, this enables the lock contention
71 // profiling at host:AdminPort/debug/pprof/block.
72 EnableContentionProfiling bool
73
74 // ID of this proxy server.
75 ServerID string
76 // Number of proxy server instances, should be 1 unless it is a HA proxy server.
77 ServerCount int
78 // Agent pod's namespace for token-based agent authentication
79 AgentNamespace string
80 // Agent pod's service account for token-based agent authentication
81 AgentServiceAccount string
82 // Token's audience for token-based agent authentication
83 AuthenticationAudience string
84 // Path to kubeconfig (used by kubernetes client)
85 KubeconfigPath string
86 // Client maximum QPS.
87 KubeconfigQPS float32
88 // Client maximum burst for throttle.
89 KubeconfigBurst int
90 // Content type of requests sent to apiserver.
91 APIContentType string
92
93 // Proxy strategies used by the server.
94 // NOTE the order of the strategies matters. e.g., for list
95 // "destHost,destCIDR,default", the server will try to find a backend associating
96 // to the destination host first, if not found, it will try to find a
97 // backend within the destCIDR. if it still can't find any backend,
98 // it will choose a random backend.
99 ProxyStrategies string
100
101 // Cipher suites used by the server.
102 // If empty, the default suite will be used from tls.CipherSuites(),
103 // also checks if given comma separated list contains cipher from tls.InsecureCipherSuites().
104 // NOTE that cipher suites are not configurable for TLS1.3,
105 // see: https://pkg.go.dev/crypto/tls#Config, so in that case, this option won't have any effect.
106 CipherSuites []string
107 XfrChannelSize int
108
109 // Lease controller configuration
110 EnableLeaseController bool
111 // Lease Namespace
112 LeaseNamespace string
113 // Lease Labels
114 LeaseLabel string
115 // Needs kubernetes client
116 NeedsKubernetesClient bool
117 }
118
119 func (o *ProxyRunOptions) Flags() *pflag.FlagSet {
120 flags := pflag.NewFlagSet("proxy-server", pflag.ContinueOnError)
121 flags.StringVar(&o.ServerCert, "server-cert", o.ServerCert, "If non-empty secure communication with this cert.")
122 flags.StringVar(&o.ServerKey, "server-key", o.ServerKey, "If non-empty secure communication with this key.")
123 flags.StringVar(&o.ServerCaCert, "server-ca-cert", o.ServerCaCert, "If non-empty the CA we use to validate KAS clients.")
124 flags.StringVar(&o.ClusterCert, "cluster-cert", o.ClusterCert, "If non-empty secure communication with this cert.")
125 flags.StringVar(&o.ClusterKey, "cluster-key", o.ClusterKey, "If non-empty secure communication with this key.")
126 flags.StringVar(&o.ClusterCaCert, "cluster-ca-cert", o.ClusterCaCert, "If non-empty the CA we use to validate Agent clients.")
127 flags.StringVar(&o.Mode, "mode", o.Mode, "mode can be either 'grpc' or 'http-connect'.")
128 flags.StringVar(&o.UdsName, "uds-name", o.UdsName, "uds-name should be empty for TCP traffic. For UDS set to its name.")
129 flags.BoolVar(&o.DeleteUDSFile, "delete-existing-uds-file", o.DeleteUDSFile, "If true and if file UdsName already exists, delete the file before listen on that UDS file. Default is true.")
130 flags.IntVar(&o.ServerPort, "server-port", o.ServerPort, "Port we listen for server connections on. Set to 0 for UDS.")
131 flags.StringVar(&o.ServerBindAddress, "server-bind-address", o.ServerBindAddress, "Bind address for server connections. If empty, we will bind to all interfaces.")
132 flags.IntVar(&o.AgentPort, "agent-port", o.AgentPort, "Port we listen for agent connections on.")
133 flags.StringVar(&o.AgentBindAddress, "agent-bind-address", o.AgentBindAddress, "Bind address for agent connections. If empty, we will bind to all interfaces.")
134 flags.IntVar(&o.AdminPort, "admin-port", o.AdminPort, "Port we listen for admin connections on.")
135 flags.StringVar(&o.AdminBindAddress, "admin-bind-address", o.AdminBindAddress, "Bind address for admin connections. If empty, we will bind to localhost.")
136 flags.IntVar(&o.HealthPort, "health-port", o.HealthPort, "Port we listen for health connections on.")
137 flags.StringVar(&o.HealthBindAddress, "health-bind-address", o.HealthBindAddress, "Bind address for health connections. If empty, we will bind to all interfaces.")
138 flags.DurationVar(&o.KeepaliveTime, "keepalive-time", o.KeepaliveTime, "Time for gRPC agent server keepalive.")
139 flags.DurationVar(&o.FrontendKeepaliveTime, "frontend-keepalive-time", o.FrontendKeepaliveTime, "Time for gRPC frontend server keepalive.")
140 flags.BoolVar(&o.EnableProfiling, "enable-profiling", o.EnableProfiling, "enable pprof at host:admin-port/debug/pprof")
141 flags.BoolVar(&o.EnableContentionProfiling, "enable-contention-profiling", o.EnableContentionProfiling, "enable contention profiling at host:admin-port/debug/pprof/block. \"--enable-profiling\" must also be set.")
142 flags.StringVar(&o.ServerID, "server-id", o.ServerID, "The unique ID of this server. Can also be set by the 'PROXY_SERVER_ID' environment variable.")
143 flags.IntVar(&o.ServerCount, "server-count", o.ServerCount, "The number of proxy server instances, should be 1 unless it is an HA server.")
144 flags.StringVar(&o.AgentNamespace, "agent-namespace", o.AgentNamespace, "Expected agent's namespace during agent authentication (used with agent-service-account, authentication-audience, kubeconfig).")
145 flags.StringVar(&o.AgentServiceAccount, "agent-service-account", o.AgentServiceAccount, "Expected agent's service account during agent authentication (used with agent-namespace, authentication-audience, kubeconfig).")
146 flags.StringVar(&o.KubeconfigPath, "kubeconfig", o.KubeconfigPath, "absolute path to the kubeconfig file (used with agent-namespace, agent-service-account, authentication-audience).")
147 flags.Float32Var(&o.KubeconfigQPS, "kubeconfig-qps", o.KubeconfigQPS, "Maximum client QPS (proxy server uses this client to authenticate agent tokens).")
148 flags.IntVar(&o.KubeconfigBurst, "kubeconfig-burst", o.KubeconfigBurst, "Maximum client burst (proxy server uses this client to authenticate agent tokens).")
149 flags.StringVar(&o.APIContentType, "kube-api-content-type", o.APIContentType, "Content type of requests sent to apiserver.")
150 flags.StringVar(&o.AuthenticationAudience, "authentication-audience", o.AuthenticationAudience, "Expected agent's token authentication audience (used with agent-namespace, agent-service-account, kubeconfig).")
151 flags.StringVar(&o.ProxyStrategies, "proxy-strategies", o.ProxyStrategies, "The list of proxy strategies used by the server to pick an agent/tunnel, available strategies are: default, destHost, defaultRoute.")
152 flags.StringSliceVar(&o.CipherSuites, "cipher-suites", o.CipherSuites, "The comma separated list of allowed cipher suites. Has no effect on TLS1.3. Empty means allow default list.")
153 flags.IntVar(&o.XfrChannelSize, "xfr-channel-size", o.XfrChannelSize, "The size of the two KNP server channels used in server for transferring data. One channel is for data coming from the Kubernetes API Server, and the other one is for data coming from the KNP agent.")
154 flags.BoolVar(&o.EnableLeaseController, "enable-lease-controller", o.EnableLeaseController, "Enable lease controller to publish and garbage collect proxy server leases.")
155 flags.StringVar(&o.LeaseNamespace, "lease-namespace", o.LeaseNamespace, "The namespace where lease objects are managed by the controller.")
156 flags.StringVar(&o.LeaseLabel, "lease-label", o.LeaseLabel, "The labels on which the lease objects are managed.")
157 flags.Bool("warn-on-channel-limit", true, "This behavior is now thread safe and always on. This flag will be removed in a future release.")
158 flags.MarkDeprecated("warn-on-channel-limit", "This behavior is now thread safe and always on. This flag will be removed in a future release.")
159
160 return flags
161 }
162
163 func (o *ProxyRunOptions) Print() {
164 klog.V(1).Infof("ServerCert set to %q.\n", o.ServerCert)
165 klog.V(1).Infof("ServerKey set to %q.\n", o.ServerKey)
166 klog.V(1).Infof("ServerCACert set to %q.\n", o.ServerCaCert)
167 klog.V(1).Infof("ClusterCert set to %q.\n", o.ClusterCert)
168 klog.V(1).Infof("ClusterKey set to %q.\n", o.ClusterKey)
169 klog.V(1).Infof("ClusterCACert set to %q.\n", o.ClusterCaCert)
170 klog.V(1).Infof("Mode set to %q.\n", o.Mode)
171 klog.V(1).Infof("UDSName set to %q.\n", o.UdsName)
172 klog.V(1).Infof("DeleteUDSFile set to %v.\n", o.DeleteUDSFile)
173 klog.V(1).Infof("Server port set to %d.\n", o.ServerPort)
174 klog.V(1).Infof("Server bind address set to %q.\n", o.ServerBindAddress)
175 klog.V(1).Infof("Agent port set to %d.\n", o.AgentPort)
176 klog.V(1).Infof("Agent bind address set to %q.\n", o.AgentBindAddress)
177 klog.V(1).Infof("Admin port set to %d.\n", o.AdminPort)
178 klog.V(1).Infof("Admin bind address set to %q.\n", o.AdminBindAddress)
179 klog.V(1).Infof("Health port set to %d.\n", o.HealthPort)
180 klog.V(1).Infof("Health bind address set to %q.\n", o.HealthBindAddress)
181 klog.V(1).Infof("Keepalive time set to %v.\n", o.KeepaliveTime)
182 klog.V(1).Infof("Frontend keepalive time set to %v.\n", o.FrontendKeepaliveTime)
183 klog.V(1).Infof("EnableProfiling set to %v.\n", o.EnableProfiling)
184 klog.V(1).Infof("EnableContentionProfiling set to %v.\n", o.EnableContentionProfiling)
185 klog.V(1).Infof("ServerID set to %s.\n", o.ServerID)
186 klog.V(1).Infof("ServerCount set to %d.\n", o.ServerCount)
187 klog.V(1).Infof("AgentNamespace set to %q.\n", o.AgentNamespace)
188 klog.V(1).Infof("AgentServiceAccount set to %q.\n", o.AgentServiceAccount)
189 klog.V(1).Infof("AuthenticationAudience set to %q.\n", o.AuthenticationAudience)
190 klog.V(1).Infof("KubeconfigPath set to %q.\n", o.KubeconfigPath)
191 klog.V(1).Infof("KubeconfigQPS set to %f.\n", o.KubeconfigQPS)
192 klog.V(1).Infof("KubeconfigBurst set to %d.\n", o.KubeconfigBurst)
193 klog.V(1).Infof("APIContentType set to %v.\n", o.APIContentType)
194 klog.V(1).Infof("ProxyStrategies set to %q.\n", o.ProxyStrategies)
195 klog.V(1).Infof("EnableLeaseController set to %v.\n", o.EnableLeaseController)
196 klog.V(1).Infof("LeaseNamespace set to %s.\n", o.LeaseNamespace)
197 klog.V(1).Infof("LeaseLabel set to %s.\n", o.LeaseLabel)
198 klog.V(1).Infof("CipherSuites set to %q.\n", o.CipherSuites)
199 klog.V(1).Infof("XfrChannelSize set to %d.\n", o.XfrChannelSize)
200 }
201
202 func (o *ProxyRunOptions) Validate() error {
203 if o.ServerKey != "" {
204 if _, err := os.Stat(o.ServerKey); os.IsNotExist(err) {
205 return fmt.Errorf("error checking server key %s, got %v", o.ServerKey, err)
206 }
207 if o.ServerCert == "" {
208 return fmt.Errorf("cannot have server cert empty when server key is set to %q", o.ServerKey)
209 }
210 }
211 if o.ServerCert != "" {
212 if _, err := os.Stat(o.ServerCert); os.IsNotExist(err) {
213 return fmt.Errorf("error checking server cert %s, got %v", o.ServerCert, err)
214 }
215 if o.ServerKey == "" {
216 return fmt.Errorf("cannot have server key empty when server cert is set to %q", o.ServerCert)
217 }
218 }
219 if o.ServerCaCert != "" {
220 if _, err := os.Stat(o.ServerCaCert); os.IsNotExist(err) {
221 return fmt.Errorf("error checking server CA cert %s, got %v", o.ServerCaCert, err)
222 }
223 }
224 if o.ClusterKey != "" {
225 if _, err := os.Stat(o.ClusterKey); os.IsNotExist(err) {
226 return fmt.Errorf("error checking cluster key %s, got %v", o.ClusterKey, err)
227 }
228 if o.ClusterCert == "" {
229 return fmt.Errorf("cannot have cluster cert empty when cluster key is set to %q", o.ClusterKey)
230 }
231 }
232 if o.ClusterCert != "" {
233 if _, err := os.Stat(o.ClusterCert); os.IsNotExist(err) {
234 return fmt.Errorf("error checking cluster cert %s, got %v", o.ClusterCert, err)
235 }
236 if o.ClusterKey == "" {
237 return fmt.Errorf("cannot have cluster key empty when cluster cert is set to %q", o.ClusterCert)
238 }
239 }
240 if o.ClusterCaCert != "" {
241 if _, err := os.Stat(o.ClusterCaCert); os.IsNotExist(err) {
242 return fmt.Errorf("error checking cluster CA cert %s, got %v", o.ClusterCaCert, err)
243 }
244 }
245 if o.Mode != server.ModeGRPC && o.Mode != server.ModeHTTPConnect {
246 return fmt.Errorf("mode must be set to either 'grpc' or 'http-connect' not %q", o.Mode)
247 }
248 if o.UdsName != "" {
249 if o.ServerPort != 0 {
250 return fmt.Errorf("server port should be set to 0 not %d for UDS", o.ServerPort)
251 }
252 if o.ServerKey != "" {
253 return fmt.Errorf("server key should not be set for UDS")
254 }
255 if o.ServerCert != "" {
256 return fmt.Errorf("server cert should not be set for UDS")
257 }
258 if o.ServerCaCert != "" {
259 return fmt.Errorf("server ca cert should not be set for UDS")
260 }
261 }
262 if o.ServerPort > 49151 {
263 return fmt.Errorf("please do not try to use ephemeral port %d for the server port", o.ServerPort)
264 }
265 if o.AgentPort > 49151 {
266 return fmt.Errorf("please do not try to use ephemeral port %d for the agent port", o.AgentPort)
267 }
268 if o.AdminPort > 49151 {
269 return fmt.Errorf("please do not try to use ephemeral port %d for the admin port", o.AdminPort)
270 }
271 if o.HealthPort > 49151 {
272 return fmt.Errorf("please do not try to use ephemeral port %d for the health port", o.HealthPort)
273 }
274
275 if o.ServerPort < 1024 {
276 if o.UdsName == "" {
277 return fmt.Errorf("please do not try to use reserved port %d for the server port", o.ServerPort)
278 }
279 }
280 if o.AgentPort < 1024 {
281 return fmt.Errorf("please do not try to use reserved port %d for the agent port", o.AgentPort)
282 }
283 if o.AdminPort < 1024 {
284 return fmt.Errorf("please do not try to use reserved port %d for the admin port", o.AdminPort)
285 }
286 if o.HealthPort < 1024 {
287 return fmt.Errorf("please do not try to use reserved port %d for the health port", o.HealthPort)
288 }
289 if o.EnableContentionProfiling && !o.EnableProfiling {
290 return fmt.Errorf("if --enable-contention-profiling is set, --enable-profiling must also be set")
291 }
292 usingServiceAccountAuth := o.AgentNamespace != "" || o.AgentServiceAccount != "" || o.AuthenticationAudience != ""
293 if usingServiceAccountAuth {
294 if o.ClusterCaCert != "" {
295 return fmt.Errorf("--cluster-ca-cert can not be used when agent authentication is enabled")
296 }
297 if o.AgentNamespace == "" {
298 return fmt.Errorf("--agent-namespace cannot be empty when agent authentication is enabled")
299 }
300 if o.AgentServiceAccount == "" {
301 return fmt.Errorf("--agent-service-account cannot be empty when agent authentication is enabled")
302 }
303 if o.AuthenticationAudience == "" {
304 return fmt.Errorf("--authentication-audience cannot be empty when agent authentication is enabled")
305 }
306 }
307 // Validate kubeconfig path if provided
308 if o.KubeconfigPath != "" {
309 if _, err := os.Stat(o.KubeconfigPath); os.IsNotExist(err) {
310 return fmt.Errorf("checking KubeconfigPath %q, got %v", o.KubeconfigPath, err)
311 }
312 }
313 // validate the proxy strategies
314 if len(o.ProxyStrategies) == 0 {
315 return fmt.Errorf("ProxyStrategies cannot be empty")
316 }
317 if _, err := server.ParseProxyStrategies(o.ProxyStrategies); err != nil {
318 return fmt.Errorf("invalid proxy strategies: %v", err)
319 }
320 if o.XfrChannelSize <= 0 {
321 return fmt.Errorf("channel size %d must be greater than 0", o.XfrChannelSize)
322 }
323 // validate the cipher suites
324 if len(o.CipherSuites) != 0 {
325 acceptedCiphers := util.GetAcceptedCiphers()
326 for _, cipher := range o.CipherSuites {
327 _, ok := acceptedCiphers[cipher]
328 if !ok {
329 return fmt.Errorf("cipher suite %s not supported, doesn't exist or considered as insecure", cipher)
330 }
331 }
332 }
333 // Validate labels provided.
334 if o.EnableLeaseController {
335 _, err := util.ParseLabels(o.LeaseLabel)
336 if err != nil {
337 return err
338 }
339 }
340
341 o.NeedsKubernetesClient = usingServiceAccountAuth || o.EnableLeaseController
342
343 return nil
344 }
345
346 func NewProxyRunOptions() *ProxyRunOptions {
347 o := ProxyRunOptions{
348 ServerCert: "",
349 ServerKey: "",
350 ServerCaCert: "",
351 ClusterCert: "",
352 ClusterKey: "",
353 ClusterCaCert: "",
354 Mode: "grpc",
355 UdsName: "",
356 DeleteUDSFile: true,
357 ServerPort: 8090,
358 ServerBindAddress: "",
359 AgentPort: 8091,
360 AgentBindAddress: "",
361 HealthPort: 8092,
362 HealthBindAddress: "",
363 AdminPort: 8095,
364 AdminBindAddress: "127.0.0.1",
365 KeepaliveTime: 1 * time.Hour,
366 FrontendKeepaliveTime: 1 * time.Hour,
367 EnableProfiling: false,
368 EnableContentionProfiling: false,
369 ServerID: defaultServerID(),
370 ServerCount: 1,
371 AgentNamespace: "",
372 AgentServiceAccount: "",
373 KubeconfigPath: "",
374 KubeconfigQPS: 0,
375 KubeconfigBurst: 0,
376 APIContentType: runtime.ContentTypeProtobuf,
377 AuthenticationAudience: "",
378 ProxyStrategies: "default",
379 CipherSuites: make([]string, 0),
380 XfrChannelSize: 10,
381 EnableLeaseController: false,
382 LeaseNamespace: "kube-system",
383 LeaseLabel: "k8s-app=konnectivity-server",
384 }
385 return &o
386 }
387
388 func defaultServerID() string {
389 // Default to the value set by the PROXY_SERVER_ID environment variable. If both the flag &
390 // environment variable are set, the flag always wins.
391 if id := os.Getenv("PROXY_SERVER_ID"); id != "" {
392 return id
393 }
394 return uuid.New().String()
395 }