|
| 1 | +package leases |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "time" |
| 6 | + |
| 7 | + coordinationv1api "k8s.io/api/coordination/v1" |
| 8 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 9 | + "k8s.io/apimachinery/pkg/util/wait" |
| 10 | + "k8s.io/client-go/kubernetes" |
| 11 | + coordinationv1 "k8s.io/client-go/kubernetes/typed/coordination/v1" |
| 12 | + "k8s.io/klog/v2" |
| 13 | +) |
| 14 | + |
| 15 | +var timeNow = time.Now |
| 16 | + |
| 17 | +type GarbageCollectionController struct { |
| 18 | + leaseInterface coordinationv1.LeaseInterface |
| 19 | + |
| 20 | + labelSelector string |
| 21 | + gcCheckPeriod time.Duration |
| 22 | +} |
| 23 | + |
| 24 | +func NewGarbageCollectionController(k8sclient kubernetes.Interface, namespace string, gcCheckPeriod time.Duration, leaseSelector string) *GarbageCollectionController { |
| 25 | + return &GarbageCollectionController{ |
| 26 | + leaseInterface: k8sclient.CoordinationV1().Leases(namespace), |
| 27 | + gcCheckPeriod: gcCheckPeriod, |
| 28 | + labelSelector: leaseSelector, |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +func (c *GarbageCollectionController) Run(stopCh <-chan struct{}) { |
| 33 | + go wait.Until(c.gc, c.gcCheckPeriod, stopCh) |
| 34 | + |
| 35 | + <-stopCh |
| 36 | +} |
| 37 | + |
| 38 | +func (c *GarbageCollectionController) gc() { |
| 39 | + ctx := context.Background() |
| 40 | + leases, err := c.leaseInterface.List(ctx, metav1.ListOptions{LabelSelector: c.labelSelector}) |
| 41 | + if err != nil { |
| 42 | + klog.Errorf("could not list leases to garbage collect: %v", err) |
| 43 | + return |
| 44 | + } |
| 45 | + |
| 46 | + for _, lease := range leases.Items { |
| 47 | + if isLeaseValid(lease) { |
| 48 | + continue |
| 49 | + } |
| 50 | + |
| 51 | + // Optimistic concurrency: if a lease has a different resourceVersion than |
| 52 | + // when we got it, it may have been renewed. |
| 53 | + |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +func isLeaseValid(lease coordinationv1api.Lease) bool { |
| 58 | + var lastRenewTime time.Time |
| 59 | + if lease.Spec.RenewTime != nil { |
| 60 | + lastRenewTime = lease.Spec.RenewTime.Time |
| 61 | + } else if lease.Spec.AcquireTime != nil { |
| 62 | + lastRenewTime = lease.Spec.AcquireTime.Time |
| 63 | + } else { |
| 64 | + klog.Warningf("lease %v has neither a renew time or an acquire time, marking as expired: %v", lease.Name, lease) |
| 65 | + return false |
| 66 | + } |
| 67 | + |
| 68 | + duration := time.Duration(*lease.Spec.LeaseDurationSeconds) * time.Second |
| 69 | + |
| 70 | + return lastRenewTime.Add(duration).After(timeNow()) // renewTime+duration > time.Now() |
| 71 | +} |
0 commit comments