| 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 | // leaseCounter counts number of proxy server leases |
| 55 | leaseCounter ServerCounter |
| 56 | |
| 57 | // lastReceivedServerCount is the last serverCount value received when connecting to a proxy server |
| 58 | lastReceivedServerCount int |
| 59 | |
| 60 | // lastServerCount is the most-recently observed serverCount value from either lease system or proxy server, |
| 61 | // former takes priority unless it is an HA server. |
| 62 | // Initialized when the ClientSet creates the first client. |
| 63 | // When syncForever is set, it will be the most recently seen. |
| 64 | lastServerCount int |
| 65 | |
| 66 | // syncInterval is the interval at which the agent periodically checks |
| 67 | // that it has connections to all instances of the proxy server. |
| 68 | syncInterval time.Duration |
| 69 | |
| 70 | // The maximum interval for the syncInterval to back off to when unable to connect to the proxy server |
| 71 | syncIntervalCap time.Duration |
| 72 | |
| 73 | // syncForever is true if we should continue syncing (support dynamic server count). |
| 74 | syncForever bool |
| 75 | |
| 76 | // probeInterval is the interval at which the agent |
| 77 | // periodically checks if its connections to the proxy server is ready. |
| 78 | probeInterval time.Duration |
| 79 | |
| 80 | dialOptions []grpc.DialOption |
| 81 | |
| 82 | // serviceAccountTokenPath is the file path to our kubernetes service account token |
| 83 | serviceAccountTokenPath string |
| 84 | |
| 85 | // channel to signal that the agent is pending termination. |
| 86 | drainCh <-chan struct{} |
| 87 | |
| 88 | // channel to signal shutting down the client set. Primarily for test. |
| 89 | stopCh <-chan struct{} |
| 90 | |
| 91 | // agentIdentifiers is the identifiers of the agent, which will be used |
| 92 | // by the server when choosing agent |
| 93 | agentIdentifiers string |
| 94 | |
| 95 | warnOnChannelLimit bool |
| 96 | xfrChannelSize int |
| 97 | |
| 98 | // serverCountSource controls how we compute the server count. |
| 99 | // The proxy server sends the serverCount header to each connecting agent, |
| 100 | // and the agent figures out from these observations how many |
| 101 | // agent-to-proxy-server connections it should maintain. |
| 102 | serverCountSource string |
| 103 | } |
| 104 | |
| 105 | func (cs *ClientSet) ClientsCount() int { |
| 106 | cs.mu.Lock() |
| 107 | defer cs.mu.Unlock() |
| 108 | return len(cs.clients) |
| 109 | } |
| 110 | |
| 111 | func (cs *ClientSet) HealthyClientsCount() int { |
| 112 | cs.mu.Lock() |
| 113 | defer cs.mu.Unlock() |
| 114 | var count int |
| 115 | for _, c := range cs.clients { |
| 116 | if c.conn.GetState() == connectivity.Ready { |
| 117 | count++ |
| 118 | } |
| 119 | } |
| 120 | return count |
| 121 | |
| 122 | } |
| 123 | |
| 124 | // HasID returns true if the ClientSet has a client to the specified serverID. |
| 125 | func (cs *ClientSet) HasID(serverID string) bool { |
| 126 | cs.mu.Lock() |
| 127 | defer cs.mu.Unlock() |
| 128 | _, exists := cs.clients[serverID] |
| 129 | return exists |
| 130 | } |
| 131 | |
| 132 | type DuplicateServerError struct { |
| 133 | ServerID string |
| 134 | } |
| 135 | |
| 136 | func (dse *DuplicateServerError) Error() string { |
| 137 | return "duplicate server: " + dse.ServerID |
| 138 | } |
| 139 | |
| 140 | // AddClient adds the specified client to our set of clients. |
| 141 | // If we already have a connection with the same serverID, we will return *DuplicateServerError. |
| 142 | func (cs *ClientSet) AddClient(serverID string, c *Client) error { |
| 143 | cs.mu.Lock() |
| 144 | defer cs.mu.Unlock() |
| 145 | |
| 146 | _, exists := cs.clients[serverID] |
| 147 | if exists { |
| 148 | return &DuplicateServerError{ServerID: serverID} |
| 149 | } |
| 150 | cs.clients[serverID] = c |
| 151 | metrics.Metrics.SetServerConnectionsCount(len(cs.clients)) |
| 152 | return nil |
| 153 | } |
| 154 | |
| 155 | func (cs *ClientSet) RemoveClient(serverID string) { |
| 156 | cs.mu.Lock() |
| 157 | defer cs.mu.Unlock() |
| 158 | if cs.clients[serverID] == nil { |
| 159 | return |
| 160 | } |
| 161 | cs.clients[serverID].Close() |
| 162 | delete(cs.clients, serverID) |
| 163 | metrics.Metrics.SetServerConnectionsCount(len(cs.clients)) |
| 164 | } |
| 165 | |
| 166 | type ClientSetConfig struct { |
| 167 | Address string |
| 168 | AgentID string |
| 169 | AgentIdentifiers string |
| 170 | SyncInterval time.Duration |
| 171 | ProbeInterval time.Duration |
| 172 | SyncIntervalCap time.Duration |
| 173 | DialOptions []grpc.DialOption |
| 174 | ServiceAccountTokenPath string |
| 175 | WarnOnChannelLimit bool |
| 176 | SyncForever bool |
| 177 | XfrChannelSize int |
| 178 | ServerLeaseCounter ServerCounter |
| 179 | ServerCountSource string |
| 180 | } |
| 181 | |
| 182 | func (cc *ClientSetConfig) NewAgentClientSet(drainCh, stopCh <-chan struct{}) *ClientSet { |
| 183 | return &ClientSet{ |
| 184 | clients: make(map[string]*Client), |
| 185 | agentID: cc.AgentID, |
| 186 | agentIdentifiers: cc.AgentIdentifiers, |
| 187 | address: cc.Address, |
| 188 | syncInterval: cc.SyncInterval, |
| 189 | probeInterval: cc.ProbeInterval, |
| 190 | syncIntervalCap: cc.SyncIntervalCap, |
| 191 | dialOptions: cc.DialOptions, |
| 192 | serviceAccountTokenPath: cc.ServiceAccountTokenPath, |
| 193 | warnOnChannelLimit: cc.WarnOnChannelLimit, |
| 194 | syncForever: cc.SyncForever, |
| 195 | drainCh: drainCh, |
| 196 | xfrChannelSize: cc.XfrChannelSize, |
| 197 | stopCh: stopCh, |
| 198 | leaseCounter: cc.ServerLeaseCounter, |
| 199 | serverCountSource: cc.ServerCountSource, |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | func (cs *ClientSet) newAgentClient() (*Client, int, error) { |
| 204 | return newAgentClient(cs.address, cs.agentID, cs.agentIdentifiers, cs, cs.dialOptions...) |
| 205 | } |
| 206 | |
| 207 | func (cs *ClientSet) resetBackoff() *wait.Backoff { |
| 208 | return &wait.Backoff{ |
| 209 | Steps: math.MaxInt32, |
| 210 | Jitter: 0.1, |
| 211 | Factor: 1.5, |
| 212 | Duration: cs.syncInterval, |
| 213 | Cap: cs.syncIntervalCap, |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // sync makes sure that #clients >= #proxy servers |
| 218 | func (cs *ClientSet) sync() { |
| 219 | defer cs.shutdown() |
| 220 | backoff := cs.resetBackoff() |
| 221 | var duration time.Duration |
| 222 | for { |
| 223 | if serverCount, err := cs.connectOnce(); err != nil { |
| 224 | if dse, ok := err.(*DuplicateServerError); ok { |
| 225 | clientsCount := cs.ClientsCount() |
| 226 | klog.V(4).InfoS("duplicate server", "serverID", dse.ServerID, "serverCount", serverCount, "clientsCount", clientsCount) |
| 227 | if serverCount != 0 && clientsCount >= serverCount { |
| 228 | duration = backoff.Step() |
| 229 | } else { |
| 230 | backoff = cs.resetBackoff() |
| 231 | duration = wait.Jitter(backoff.Duration, backoff.Jitter) |
| 232 | } |
| 233 | } else { |
| 234 | klog.ErrorS(err, "cannot connect once") |
| 235 | duration = backoff.Step() |
| 236 | } |
| 237 | } else { |
| 238 | backoff = cs.resetBackoff() |
| 239 | duration = wait.Jitter(backoff.Duration, backoff.Jitter) |
| 240 | } |
| 241 | time.Sleep(duration) |
| 242 | select { |
| 243 | case <-cs.stopCh: |
| 244 | return |
| 245 | default: |
| 246 | } |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | func (cs *ClientSet) ServerCount() int { |
| 251 | |
| 252 | var serverCount int |
| 253 | var countSourceLabel string |
| 254 | |
| 255 | switch cs.serverCountSource { |
| 256 | case "", "default": |
| 257 | if cs.leaseCounter != nil { |
| 258 | serverCount = cs.leaseCounter.Count() |
| 259 | countSourceLabel = fromLeases |
| 260 | } else { |
| 261 | serverCount = cs.lastReceivedServerCount |
| 262 | countSourceLabel = fromResponses |
| 263 | } |
| 264 | case "max": |
| 265 | countFromLeases := 0 |
| 266 | if cs.leaseCounter != nil { |
| 267 | countFromLeases = cs.leaseCounter.Count() |
| 268 | } |
| 269 | countFromResponses := cs.lastReceivedServerCount |
| 270 | |
| 271 | serverCount = countFromLeases |
| 272 | countSourceLabel = fromLeases |
| 273 | if countFromResponses > serverCount { |
| 274 | serverCount = countFromResponses |
| 275 | countSourceLabel = fromResponses |
| 276 | } |
| 277 | if serverCount == 0 { |
| 278 | serverCount = 1 |
| 279 | countSourceLabel = fromFallback |
| 280 | } |
| 281 | |
| 282 | } |
| 283 | |
| 284 | if serverCount != cs.lastServerCount { |
| 285 | klog.Warningf("change detected in proxy server count (was: %d, now: %d, source: %q)", cs.lastServerCount, serverCount, countSourceLabel) |
| 286 | cs.lastServerCount = serverCount |
| 287 | } |
| 288 | |
| 289 | metrics.Metrics.SetServerCount(serverCount) |
| 290 | return serverCount |
| 291 | } |
| 292 | |
| 293 | func (cs *ClientSet) connectOnce() (int, error) { |
| 294 | serverCount := cs.ServerCount() |
| 295 | |
| 296 | if !cs.syncForever && serverCount != 0 && cs.ClientsCount() >= serverCount { |
| 297 | return serverCount, nil |
| 298 | } |
| 299 | c, receivedServerCount, err := cs.newAgentClient() |
| 300 | if err != nil { |
| 301 | return serverCount, err |
| 302 | } |
| 303 | cs.lastReceivedServerCount = receivedServerCount |
| 304 | if err := cs.AddClient(c.serverID, c); err != nil { |
| 305 | c.Close() |
| 306 | return serverCount, err |
| 307 | } |
| 308 | klog.V(2).InfoS("sync added client connecting to proxy server", "serverID", c.serverID) |
| 309 | |
| 310 | labels := runpprof.Labels( |
| 311 | "agentIdentifiers", cs.agentIdentifiers, |
| 312 | "serverAddress", cs.address, |
| 313 | "serverID", c.serverID, |
| 314 | ) |
| 315 | go runpprof.Do(context.Background(), labels, func(context.Context) { c.Serve() }) |
| 316 | return serverCount, nil |
| 317 | } |
| 318 | |
| 319 | func (cs *ClientSet) Serve() { |
| 320 | labels := runpprof.Labels( |
| 321 | "agentIdentifiers", cs.agentIdentifiers, |
| 322 | "serverAddress", cs.address, |
| 323 | ) |
| 324 | go runpprof.Do(context.Background(), labels, func(context.Context) { cs.sync() }) |
| 325 | } |
| 326 | |
| 327 | func (cs *ClientSet) shutdown() { |
| 328 | cs.mu.Lock() |
| 329 | defer cs.mu.Unlock() |
| 330 | for serverID, client := range cs.clients { |
| 331 | client.Close() |
| 332 | delete(cs.clients, serverID) |
| 333 | } |
| 334 | } |