Debian Codegraph @

pkg/agent/clientset.go

raw
1 /*
2 Copyright 2020 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 agent
18
19 import (
20 "context"
21 "math"
22 runpprof "runtime/pprof"
23 "sync"
24 "time"
25
26 "google.golang.org/grpc"
27 "google.golang.org/grpc/connectivity"
28 "k8s.io/apimachinery/pkg/util/wait"
29 "k8s.io/klog/v2"
30 "sigs.k8s.io/apiserver-network-proxy/pkg/agent/metrics"
31 )
32
33 const (
34 fromResponses = "KNP server response headers"
35 fromLeases = "KNP lease count"
36 fromFallback = "fallback to 1"
37 )
38
39 // ClientSet consists of clients connected to each instance of an HA proxy server.
40 type ClientSet struct {
41 // mu guards access to the clients map
42 mu sync.Mutex
43
44 // clients is a map between serverID and the client
45 // connected to this server.
46 clients map[string]*Client
47
48 // agentID is "our ID" - the ID of this agent.
49 agentID string
50
51 // Address is the proxy server address. Assuming HA proxy server
52 address string
53
54 // serverCounter counts number of proxy server leases
55 serverCounter ServerCounter
56
57 // lastReceivedServerCount is the last serverCount value received when connecting to a proxy server
58 lastReceivedServerCount int
59
60 // syncInterval is the interval at which the agent periodically checks
61 // that it has connections to all instances of the proxy server.
62 syncInterval time.Duration
63
64 // The maximum interval for the syncInterval to back off to when unable to connect to the proxy server
65 syncIntervalCap time.Duration
66
67 // syncForever is true if we should continue syncing (support dynamic server count).
68 syncForever bool
69
70 // probeInterval is the interval at which the agent
71 // periodically checks if its connections to the proxy server is ready.
72 probeInterval time.Duration
73
74 dialOptions []grpc.DialOption
75
76 // serviceAccountTokenPath is the file path to our kubernetes service account token
77 serviceAccountTokenPath string
78
79 // channel to signal that the agent is pending termination.
80 drainCh <-chan struct{}
81
82 // channel to signal shutting down the client set. Primarily for test.
83 stopCh <-chan struct{}
84
85 // agentIdentifiers is the identifiers of the agent, which will be used
86 // by the server when choosing agent
87 agentIdentifiers string
88
89 warnOnChannelLimit bool
90 xfrChannelSize int
91
92 // serverCountSource controls how we compute the server count.
93 // The proxy server sends the serverCount header to each connecting agent,
94 // and the agent figures out from these observations how many
95 // agent-to-proxy-server connections it should maintain.
96 serverCountSource string
97 }
98
99 func (cs *ClientSet) ClientsCount() int {
100 cs.mu.Lock()
101 defer cs.mu.Unlock()
102 return len(cs.clients)
103 }
104
105 // SetServerCounter sets the strategy for determining the server count.
106 func (cs *ClientSet) SetServerCounter(counter ServerCounter) {
107 cs.serverCounter = counter
108 }
109
110 func (cs *ClientSet) HealthyClientsCount() int {
111 cs.mu.Lock()
112 defer cs.mu.Unlock()
113 var count int
114 for _, c := range cs.clients {
115 if c.conn.GetState() == connectivity.Ready {
116 count++
117 }
118 }
119 return count
120
121 }
122
123 // HasID returns true if the ClientSet has a client to the specified serverID.
124 func (cs *ClientSet) HasID(serverID string) bool {
125 cs.mu.Lock()
126 defer cs.mu.Unlock()
127 _, exists := cs.clients[serverID]
128 return exists
129 }
130
131 type DuplicateServerError struct {
132 ServerID string
133 }
134
135 func (dse *DuplicateServerError) Error() string {
136 return "duplicate server: " + dse.ServerID
137 }
138
139 // AddClient adds the specified client to our set of clients.
140 // If we already have a connection with the same serverID, we will return *DuplicateServerError.
141 func (cs *ClientSet) AddClient(serverID string, c *Client) error {
142 cs.mu.Lock()
143 defer cs.mu.Unlock()
144
145 _, exists := cs.clients[serverID]
146 if exists {
147 return &DuplicateServerError{ServerID: serverID}
148 }
149 cs.clients[serverID] = c
150 metrics.Metrics.SetServerConnectionsCount(len(cs.clients))
151 return nil
152 }
153
154 func (cs *ClientSet) RemoveClient(serverID string) {
155 cs.mu.Lock()
156 defer cs.mu.Unlock()
157 if cs.clients[serverID] == nil {
158 return
159 }
160 cs.clients[serverID].Close()
161 delete(cs.clients, serverID)
162 metrics.Metrics.SetServerConnectionsCount(len(cs.clients))
163 }
164
165 type ClientSetConfig struct {
166 Address string
167 AgentID string
168 AgentIdentifiers string
169 SyncInterval time.Duration
170 ProbeInterval time.Duration
171 SyncIntervalCap time.Duration
172 DialOptions []grpc.DialOption
173 ServiceAccountTokenPath string
174 WarnOnChannelLimit bool
175 SyncForever bool
176 XfrChannelSize int
177 ServerCountSource string
178 }
179
180 func (cc *ClientSetConfig) NewAgentClientSet(drainCh, stopCh <-chan struct{}) *ClientSet {
181 return &ClientSet{
182 clients: make(map[string]*Client),
183 agentID: cc.AgentID,
184 agentIdentifiers: cc.AgentIdentifiers,
185 address: cc.Address,
186 syncInterval: cc.SyncInterval,
187 probeInterval: cc.ProbeInterval,
188 syncIntervalCap: cc.SyncIntervalCap,
189 dialOptions: cc.DialOptions,
190 serviceAccountTokenPath: cc.ServiceAccountTokenPath,
191 warnOnChannelLimit: cc.WarnOnChannelLimit,
192 syncForever: cc.SyncForever,
193 drainCh: drainCh,
194 xfrChannelSize: cc.XfrChannelSize,
195 stopCh: stopCh,
196 serverCountSource: cc.ServerCountSource,
197 }
198 }
199
200 func (cs *ClientSet) newAgentClient() (*Client, int, error) {
201 return newAgentClient(cs.address, cs.agentID, cs.agentIdentifiers, cs, cs.dialOptions...)
202 }
203
204 func (cs *ClientSet) resetBackoff() *wait.Backoff {
205 return &wait.Backoff{
206 Steps: math.MaxInt32,
207 Jitter: 0.1,
208 Factor: 1.5,
209 Duration: cs.syncInterval,
210 Cap: cs.syncIntervalCap,
211 }
212 }
213
214 // determineServerCount determines the number of proxy servers by delegating to its configured counter strategy.
215 func (cs *ClientSet) determineServerCount() int {
216 serverCount := cs.serverCounter.Count()
217 metrics.Metrics.SetServerCount(serverCount)
218 return serverCount
219 }
220
221 // sync manages the backoff and the connection attempts to the proxy server.
222 // sync runs until stopCh is closed
223 func (cs *ClientSet) sync() {
224 defer cs.shutdown()
225 backoff := cs.resetBackoff()
226 var duration time.Duration
227 for {
228 if err := cs.connectOnce(); err != nil {
229 if dse, ok := err.(*DuplicateServerError); ok {
230 klog.V(4).InfoS("duplicate server connection attempt", "serverID", dse.ServerID)
231 // We connected to a server we already have a connection to.
232 // This is expected in syncForever mode. We just wait for the
233 // next sync period to try again. No need for backoff.
234 backoff = cs.resetBackoff()
235 duration = wait.Jitter(backoff.Duration, backoff.Jitter)
236 } else {
237 // A 'real' error, so we backoff.
238 klog.ErrorS(err, "cannot connect once")
239 duration = backoff.Step()
240 }
241 } else {
242 // A successful connection was made, or no new connection was needed.
243 // Reset the backoff and wait for the next sync period.
244 backoff = cs.resetBackoff()
245 duration = wait.Jitter(backoff.Duration, backoff.Jitter)
246 }
247
248 time.Sleep(duration)
249 select {
250 case <-cs.stopCh:
251 return
252 default:
253 }
254 }
255 }
256
257 func (cs *ClientSet) connectOnce() error {
258 // Skip establishing new connections if draining
259 select {
260 case <-cs.drainCh:
261 klog.V(2).InfoS("Skipping connectOnce - agent is draining")
262 return nil
263 default:
264 }
265
266 serverCount := cs.determineServerCount()
267
268 // If not in syncForever mode, we only connect if we have fewer connections than the server count.
269 if !cs.syncForever && cs.ClientsCount() >= serverCount && serverCount > 0 {
270 return nil // Nothing to do.
271 }
272
273 // In syncForever mode, we always try to connect, to discover new servers.
274 c, receivedServerCount, err := cs.newAgentClient()
275 if err != nil {
276 return err
277 }
278
279 if err := cs.AddClient(c.serverID, c); err != nil {
280 c.Close()
281 return err // likely *DuplicateServerError
282 }
283 // SUCCESS: We connected to a new, unique server.
284 // Only now do we update our view of the server count.
285 cs.lastReceivedServerCount = receivedServerCount
286 klog.V(2).InfoS("successfully connected to new proxy server", "serverID", c.serverID, "newServerCount", receivedServerCount)
287
288 labels := runpprof.Labels(
289 "agentIdentifiers", cs.agentIdentifiers,
290 "serverAddress", cs.address,
291 "serverID", c.serverID,
292 )
293 go runpprof.Do(context.Background(), labels, func(context.Context) { c.Serve() })
294
295 return nil
296 }
297
298 func (cs *ClientSet) Serve() {
299 labels := runpprof.Labels(
300 "agentIdentifiers", cs.agentIdentifiers,
301 "serverAddress", cs.address,
302 )
303 go runpprof.Do(context.Background(), labels, func(context.Context) { cs.sync() })
304 }
305
306 func (cs *ClientSet) shutdown() {
307 cs.mu.Lock()
308 defer cs.mu.Unlock()
309 for serverID, client := range cs.clients {
310 client.Close()
311 delete(cs.clients, serverID)
312 }
313 }