| 1 | /* |
| 2 | Copyright 2024 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 | package agent |
| 17 | |
| 18 | import ( |
| 19 | "context" |
| 20 | "errors" |
| 21 | "time" |
| 22 | |
| 23 | "k8s.io/apimachinery/pkg/labels" |
| 24 | "k8s.io/apimachinery/pkg/runtime" |
| 25 | "k8s.io/apimachinery/pkg/watch" |
| 26 | "k8s.io/client-go/kubernetes" |
| 27 | "k8s.io/client-go/tools/cache" |
| 28 | "k8s.io/klog/v2" |
| 29 | "k8s.io/utils/clock" |
| 30 | "sigs.k8s.io/apiserver-network-proxy/pkg/agent/metrics" |
| 31 | "sigs.k8s.io/apiserver-network-proxy/pkg/util" |
| 32 | |
| 33 | coordinationv1api "k8s.io/api/coordination/v1" |
| 34 | apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 35 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 36 | coordinationv1lister "k8s.io/client-go/listers/coordination/v1" |
| 37 | ) |
| 38 | |
| 39 | type ServerCounter interface { |
| 40 | Count() int |
| 41 | } |
| 42 | |
| 43 | // A ServerLeaseCounter counts leases in the k8s apiserver to determine the |
| 44 | // current proxy server count. |
| 45 | type ServerLeaseCounter struct { |
| 46 | leaseLister coordinationv1lister.LeaseLister |
| 47 | selector labels.Selector |
| 48 | fallbackCount int |
| 49 | pc clock.PassiveClock |
| 50 | } |
| 51 | |
| 52 | // NewServerLeaseCounter creates a server counter that counts valid leases that match the label |
| 53 | // selector and provides the fallback count (initially 0) if this fails. |
| 54 | func NewServerLeaseCounter(pc clock.PassiveClock, leaseLister coordinationv1lister.LeaseLister, labelSelector labels.Selector) *ServerLeaseCounter { |
| 55 | return &ServerLeaseCounter{ |
| 56 | leaseLister: leaseLister, |
| 57 | selector: labelSelector, |
| 58 | fallbackCount: 1, |
| 59 | pc: pc, |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // Count counts the number of leases in the apiserver matching the provided |
| 64 | // label selector. |
| 65 | // |
| 66 | // In the event that no valid leases are found or lease listing fails, the |
| 67 | // fallback count is returned. This fallback count is updated upon successful |
| 68 | // discovery of valid leases. |
| 69 | func (lc *ServerLeaseCounter) Count() int { |
| 70 | leases, err := lc.leaseLister.List(lc.selector) |
| 71 | if err != nil { |
| 72 | klog.Errorf("Could not list leases to update server count, using fallback count (%v): %v", lc.fallbackCount, err) |
| 73 | |
| 74 | return lc.fallbackCount |
| 75 | } |
| 76 | |
| 77 | count := 0 |
| 78 | for _, lease := range leases { |
| 79 | if util.IsLeaseValid(lc.pc, *lease) { |
| 80 | count++ |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | // Ensure returned count is always at least 1. |
| 85 | if count == 0 { |
| 86 | klog.Warningf("No valid leases found, assuming server count of 1") |
| 87 | count = 1 |
| 88 | } |
| 89 | |
| 90 | if count != lc.fallbackCount { |
| 91 | lc.fallbackCount = count |
| 92 | } |
| 93 | |
| 94 | return count |
| 95 | } |
| 96 | |
| 97 | func NewLeaseInformerWithMetrics(client kubernetes.Interface, namespace string, resyncPeriod time.Duration) cache.SharedIndexInformer { |
| 98 | return cache.NewSharedIndexInformer( |
| 99 | &cache.ListWatch{ |
| 100 | ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { |
| 101 | start := time.Now() |
| 102 | httpCode := 200 |
| 103 | defer func() { |
| 104 | latency := time.Now().Sub(start) |
| 105 | metrics.Metrics.ObserveLeaseListLatency(latency, httpCode) |
| 106 | }() |
| 107 | obj, err := client.CoordinationV1().Leases(namespace).List(context.TODO(), options) |
| 108 | if err != nil { |
| 109 | klog.Errorf("Could not list leases: %v", err) |
| 110 | |
| 111 | var apiStatus apierrors.APIStatus |
| 112 | if errors.As(err, &apiStatus) { |
| 113 | status := apiStatus.Status() |
| 114 | httpCode = int(status.Code) |
| 115 | metrics.Metrics.ObserveLeaseList(int(status.Code), string(status.Reason)) |
| 116 | } else { |
| 117 | klog.Errorf("Lease list error could not be logged to metrics as it is not an APIStatus: %v", err) |
| 118 | } |
| 119 | return nil, err |
| 120 | } |
| 121 | |
| 122 | metrics.Metrics.ObserveLeaseList(200, "") |
| 123 | return obj, nil |
| 124 | }, |
| 125 | WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { |
| 126 | obj, err := client.CoordinationV1().Leases(namespace).Watch(context.TODO(), options) |
| 127 | if err != nil { |
| 128 | klog.Errorf("Could not watch leases: %v", err) |
| 129 | |
| 130 | var apiStatus apierrors.APIStatus |
| 131 | if errors.As(err, &apiStatus) { |
| 132 | status := apiStatus.Status() |
| 133 | metrics.Metrics.ObserveLeaseWatch(int(status.Code), string(status.Reason)) |
| 134 | } else { |
| 135 | klog.Errorf("Lease watch error could not be logged to metrics as it is not an APIStatus: %v", err) |
| 136 | } |
| 137 | return nil, err |
| 138 | } |
| 139 | |
| 140 | metrics.Metrics.ObserveLeaseWatch(200, "") |
| 141 | return obj, nil |
| 142 | }, |
| 143 | }, |
| 144 | &coordinationv1api.Lease{}, |
| 145 | resyncPeriod, |
| 146 | cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, |
| 147 | ) |
| 148 | } |