Debian Codegraph @

transport/cache.go

raw
1 /*
2 Copyright 2015 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 transport
18
19 import (
20 "context"
21 "fmt"
22 "net"
23 "net/http"
24 "strings"
25 "sync"
26 "time"
27
28 utilnet "k8s.io/apimachinery/pkg/util/net"
29 "k8s.io/apimachinery/pkg/util/wait"
30 "k8s.io/client-go/tools/metrics"
31 "k8s.io/klog/v2"
32 )
33
34 // TlsTransportCache caches TLS http.RoundTrippers different configurations. The
35 // same RoundTripper will be returned for configs with identical TLS options If
36 // the config has no custom TLS options, http.DefaultTransport is returned.
37 type tlsTransportCache struct {
38 mu sync.Mutex
39 transports map[tlsCacheKey]*http.Transport
40 }
41
42 // DialerStopCh is stop channel that is passed down to dynamic cert dialer.
43 // It's exposed as variable for testing purposes to avoid testing for goroutine
44 // leakages.
45 var DialerStopCh = wait.NeverStop
46
47 const idleConnsPerHost = 25
48
49 var tlsCache = &tlsTransportCache{transports: make(map[tlsCacheKey]*http.Transport)}
50
51 type tlsCacheKey struct {
52 insecure bool
53 caData string
54 certData string
55 keyData string `datapolicy:"security-key"`
56 certFile string
57 keyFile string
58 serverName string
59 nextProtos string
60 disableCompression bool
61 // these functions are wrapped to allow them to be used as map keys
62 getCert *GetCertHolder
63 dial *DialHolder
64 }
65
66 func (t tlsCacheKey) String() string {
67 keyText := "<none>"
68 if len(t.keyData) > 0 {
69 keyText = "<redacted>"
70 }
71 return fmt.Sprintf("insecure:%v, caData:%#v, certData:%#v, keyData:%s, serverName:%s, disableCompression:%t, getCert:%p, dial:%p",
72 t.insecure, t.caData, t.certData, keyText, t.serverName, t.disableCompression, t.getCert, t.dial)
73 }
74
75 func (c *tlsTransportCache) get(config *Config) (http.RoundTripper, error) {
76 key, canCache, err := tlsConfigKey(config)
77 if err != nil {
78 return nil, err
79 }
80
81 if canCache {
82 // Ensure we only create a single transport for the given TLS options
83 c.mu.Lock()
84 defer c.mu.Unlock()
85 defer metrics.TransportCacheEntries.Observe(len(c.transports))
86
87 // See if we already have a custom transport for this config
88 if t, ok := c.transports[key]; ok {
89 metrics.TransportCreateCalls.Increment("hit")
90 return t, nil
91 }
92 metrics.TransportCreateCalls.Increment("miss")
93 } else {
94 metrics.TransportCreateCalls.Increment("uncacheable")
95 }
96
97 // Get the TLS options for this client config
98 tlsConfig, err := TLSConfigFor(config)
99 if err != nil {
100 return nil, err
101 }
102 // The options didn't require a custom TLS config
103 if tlsConfig == nil && config.DialHolder == nil && config.Proxy == nil {
104 return http.DefaultTransport, nil
105 }
106
107 var dial func(ctx context.Context, network, address string) (net.Conn, error)
108 if config.DialHolder != nil {
109 dial = config.DialHolder.Dial
110 } else {
111 dial = (&net.Dialer{
112 Timeout: 30 * time.Second,
113 KeepAlive: 30 * time.Second,
114 }).DialContext
115 }
116
117 // If we use are reloading files, we need to handle certificate rotation properly
118 // TODO(jackkleeman): We can also add rotation here when config.HasCertCallback() is true
119 if config.TLS.ReloadTLSFiles && tlsConfig != nil && tlsConfig.GetClientCertificate != nil {
120 // The TLS cache is a singleton, so sharing the same name for all of its
121 // background activity seems okay.
122 logger := klog.Background().WithName("tls-transport-cache")
123 dynamicCertDialer := certRotatingDialer(logger, tlsConfig.GetClientCertificate, dial)
124 tlsConfig.GetClientCertificate = dynamicCertDialer.GetClientCertificate
125 dial = dynamicCertDialer.connDialer.DialContext
126 go dynamicCertDialer.run(DialerStopCh)
127 }
128
129 proxy := http.ProxyFromEnvironment
130 if config.Proxy != nil {
131 proxy = config.Proxy
132 }
133
134 transport := utilnet.SetTransportDefaults(&http.Transport{
135 Proxy: proxy,
136 TLSHandshakeTimeout: 10 * time.Second,
137 TLSClientConfig: tlsConfig,
138 MaxIdleConnsPerHost: idleConnsPerHost,
139 DialContext: dial,
140 DisableCompression: config.DisableCompression,
141 })
142
143 if canCache {
144 // Cache a single transport for these options
145 c.transports[key] = transport
146 }
147
148 return transport, nil
149 }
150
151 // tlsConfigKey returns a unique key for tls.Config objects returned from TLSConfigFor
152 func tlsConfigKey(c *Config) (tlsCacheKey, bool, error) {
153 // Make sure ca/key/cert content is loaded
154 if err := loadTLSFiles(c); err != nil {
155 return tlsCacheKey{}, false, err
156 }
157
158 if c.Proxy != nil {
159 // cannot determine equality for functions
160 return tlsCacheKey{}, false, nil
161 }
162
163 k := tlsCacheKey{
164 insecure: c.TLS.Insecure,
165 caData: string(c.TLS.CAData),
166 serverName: c.TLS.ServerName,
167 nextProtos: strings.Join(c.TLS.NextProtos, ","),
168 disableCompression: c.DisableCompression,
169 getCert: c.TLS.GetCertHolder,
170 dial: c.DialHolder,
171 }
172
173 if c.TLS.ReloadTLSFiles {
174 k.certFile = c.TLS.CertFile
175 k.keyFile = c.TLS.KeyFile
176 } else {
177 k.certData = string(c.TLS.CertData)
178 k.keyData = string(c.TLS.KeyData)
179 }
180
181 return k, true, nil
182 }