leaselocker

package module
v0.4.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 16, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

README

leaselocker

Disclaimer: This project is currently in MVP status and may have limited functionality or stability. Use with caution.

Description

This package provides a solution to avoid race conditions in Kubernetes when multiple processes are updating the same resource. It offers a set of utility functions and classes that handle synchronization and locking mechanisms, ensuring that only one process can modify the resource at a time. By using this package, developers can prevent conflicts and maintain data integrity in distributed systems running on Kubernetes.

License

This package is licensed under the Apache License, Version 2.0.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func LeaseLockRecordToLeaseSpec

func LeaseLockRecordToLeaseSpec(lr *LockRecord) v1.LeaseSpec

Types

type Config

type Config struct {
	// Lock is the resource that will be used for locking
	Lock Interface

	// LeaseDuration is the duration that candidates waiting for lock will
	// wait to force acquire leadership. This is measured against time of
	// last renewal (or last observed ack depending on UseObservedTime).
	//
	// A client needs to wait a full LeaseDuration without observing a change to
	// the record before it can attempt to take over. When all clients are
	// shutdown and a new set of clients are started with different names against
	// the same lock record, they must wait the full LeaseDuration before
	// attempting to acquire the lease. Thus LeaseDuration should be as short as
	// possible (within your tolerance for clock skew rate) to avoid a possible
	// long waits in the scenario.
	//
	// Core clients default this value to 15 seconds.
	LeaseDuration time.Duration
	// RenewDeadline is the duration that the acting master will retry
	// refreshing lock ownership before giving up.
	//
	// Core clients default this value to 10 seconds.
	RenewDeadline time.Duration
	// RetryPeriod is the duration the LeaseLocker clients should wait
	// between tries of actions.
	//
	// Core clients default this value to 2 seconds.
	RetryPeriod time.Duration

	// UnlockWithRetryPeriod is the duration the LeaseLocker clients should retry
	// unlocking the lease if the first attempt fails.
	UnlockWithRetryPeriod time.Duration

	// ReleaseOnCancel should be set true if the lock should be released
	// when the run context is cancelled. If you set this to true, you must
	// ensure all code guarded by this lease has successfully completed
	// prior to cancelling the context, or you may have two processes
	// simultaneously acting on the critical path.
	ReleaseOnCancel bool

	// Defines whether to use the timestamp in the LockRecord (false) or use
	// the locally observed time (true) when deciding when to force a lock
	UseObservedTime bool

	// Name is the name of the resource lock for debugging
	Name string
}

type Interface

type Interface interface {
	// Get returns the LockRecord
	Get(ctx context.Context) (*LockRecord, []byte, error)

	// Create attempts to create a LockRecord
	Create(ctx context.Context, lr LockRecord) error

	// Update will update and existing LockRecord
	Update(ctx context.Context, lr LockRecord) error

	// RecordEvent is used to record events
	RecordEvent(string)

	// Identity will return the locks Identity
	Identity() string

	// Describe is used to convert details on current resource lock
	// into a string
	Describe() string
}

Interface offers a common interface for locking on arbitrary resources used in locking. The Interface is used to hide the details on specific implementations in order to allow them to change over time. This interface is strictly for use by the leaselocker code.

type LeaseLock

type LeaseLock struct {
	// LeaseMeta should contain a Name and a Namespace of a
	// LeaseMeta object that the LeaseLock will attempt to lock.
	LeaseMeta  metav1.ObjectMeta
	Client     coordinationv1.LeasesGetter
	LockConfig ResourceLockConfig
	// contains filtered or unexported fields
}

func (*LeaseLock) Create

func (ll *LeaseLock) Create(ctx context.Context, lr LockRecord) error

Create attempts to create a Lease

func (*LeaseLock) Describe

func (ll *LeaseLock) Describe() string

Describe is used to convert details on current resource lock into a string

func (*LeaseLock) Get

func (ll *LeaseLock) Get(ctx context.Context) (*LockRecord, []byte, error)

Get returns the lock record from a Lease spec

func (*LeaseLock) Identity

func (ll *LeaseLock) Identity() string

Identity returns the Identity of the lock

func (*LeaseLock) RecordEvent

func (ll *LeaseLock) RecordEvent(s string)

RecordEvent in lock while adding metadata

func (*LeaseLock) Update

func (ll *LeaseLock) Update(ctx context.Context, lr LockRecord) error

Update will update an existing Lease spec.

type LeaseLocker

type LeaseLocker struct {
	// contains filtered or unexported fields
}

func NewLeaseLocker

func NewLeaseLocker(config *rest.Config, namespacedName types.NamespacedName, owner string) (*LeaseLocker, error)

NewLeaseLocker creates a new LeaseLocker instance which uses the given rest.Config to create a client to communicate with the k8s API namespacedName will have the Name transformed to lowercase automatically

func (*LeaseLocker) Check

func (l *LeaseLocker) Check(maxTolerableExpiredLease time.Duration) error

Check will determine if the current lease is expired by more than timeout.

func (*LeaseLocker) Lock

func (l *LeaseLocker) Lock(ctx context.Context)

func (*LeaseLocker) TryLock

func (l *LeaseLocker) TryLock(ctx context.Context) bool

func (*LeaseLocker) Unlock

func (l *LeaseLocker) Unlock() bool

Unlock releases the lock held by the LeaseLocker instance. Returns true if the lock was successfully released.

func (*LeaseLocker) UnlockWithRetry added in v0.3.0

func (l *LeaseLocker) UnlockWithRetry(ctx context.Context)

UnlockWithRetry releases the lock held by the LeaseLocker instance and retries if the release fails.

type LockRecord

type LockRecord struct {
	Identity string
	// HolderIdentity is the ID that owns the lease. If empty, no one owns this lease and
	// all callers may acquire. Versions of this library prior to Kubernetes 1.14 will not
	// attempt to acquire leases with empty identities and will wait for the full lease
	// interval to expire before attempting to reacquire. This value is set to empty when
	// a client voluntarily steps down.
	HolderIdentity       string      `json:"holderIdentity"`
	LeaseDurationSeconds int         `json:"leaseDurationSeconds"`
	AcquireTime          metav1.Time `json:"acquireTime"`
	RenewTime            metav1.Time `json:"renewTime"`
	LeaseTransitions     int         `json:"leaseTransitions"`
}

LockRecord is the record that is stored in the lease. This information should be used for observational purposes only and could be replaced with a random string (e.g. UUID) with only slight modification of this code.

func LeaseSpecToLeaseLockRecord

func LeaseSpecToLeaseLockRecord(spec *v1.LeaseSpec) *LockRecord

type ResourceLockConfig

type ResourceLockConfig struct {
	// Identity is the unique string identifying a lock holder across
	// all participants.
	Identity string
	// EventRecorder is optional.
	EventRecorder record.EventRecorder
}

ResourceLockConfig common data that exists across different resource locks

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL