leaselock

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2025 License: Apache-2.0 Imports: 17 Imported by: 0

README

leaselock

leaselock is a distributed mutex facilitated by the Kubernetes Lease API.

Usage

Running the following program in a Deployment, with more than 1 replica, will result in only one pod running the user-provided function at any given time:

package main

import (
	"context"
	"fmt"
	"os"
    "log"

	"go.chrisrx.dev/leaselock"
)

func main() {
	if err := leaselock.Run(context.TODO(), func(ctx context.Context, l *leaselock.LeaseLock) error {
		fmt.Printf("%s: I'm the leader!", l)
		return nil
	}, leaselock.Options{
		Name:      "my-test-lock",
		Namespace: "my-namespace",
		ID:        os.Getenv("POD_NAME"),
	}); err != nil {
		log.Fatal(err)
	}
}
Kubernetes Lease API

This library uses leaderelection, which utilizes the Kubernetes Lease API to coordinate leader election. Here is an example Role/RoleBinding showing the API access leaselock needs to use the Lease API:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: leases
  namespace: my-namespace
rules:
- apiGroups: ["coordination.k8s.io"]
  resources: ["leases"]
  verbs: ["get", "create", "update"]
- apiGroups: ["coordination.k8s.io"]
  resources: ["leases"]
  resourceNames: ["my-test-lock"]
  verbs: ["delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: leases
  namespace: my-namespace
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: leases
subjects:
- kind: ServiceAccount
  name: default
  namespace: my-namespace

This Role also specifies the resource name of the lock to further reduce the scope, but isn't necessary.

Documentation

Overview

Package leaselock provides a distributed mutex using the Kubernetes Lease API. It utilizes the Kubernetes leaderelection library, so has roughly the same guarantees as provided by Kubernetes for coordinated leader election.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(ctx context.Context, fn func(context.Context, *LeaseLock) error, opts Options) error

Run establishes a LeaseLock and only runs the provided callback when the participating client is elected leader. This should in most cases ensure that only the leader will be running the callback, however, the guarantees of this library are based on the guarantees of the Kubernetes leaderelection library, so if a stronger guarantee is required to ensure business-logic is executed only by one client at at a time, another distributed lock mechanism should be used.

Types

type LeaseLock

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

LeaseLock represents a mutex coordinated through Kubernetes leases. The leader election is provided by the Kubernetes leaderelection library, so guarantees on correctness will be based on what is provided by that package. In particular, it doesn't tolerate arbitrary clock skew rate so some of the tunables, like renew deadline, are really important to dealing with conditions in a cluster, such as high latency, that might cause leader election to fail (i.e. multiple leaders, no leaders, etc).

func New

func New(ctx context.Context, opts ...LeaseLockOption) (_ *LeaseLock, err error)

func (*LeaseLock) Lock

func (l *LeaseLock) Lock()

func (*LeaseLock) String

func (l *LeaseLock) String() string

func (*LeaseLock) Unlock

func (l *LeaseLock) Unlock()

type LeaseLockOption

type LeaseLockOption func(*LeaseLock)

func WithClient

func WithClient(client kubernetes.Interface) LeaseLockOption

WithClient allows passing in a Kubernetes client. By default, a client tries to use an in-cluster configuration, followed by attempting to read a kubeconfig from user configuration. This option is helpful in situations like unit testing, where a real cluster isn't being used.

func WithID

func WithID(id string) LeaseLockOption

WithID overrides the default random ID with a user-provided ID.

func WithLeaseDuration

func WithLeaseDuration(d time.Duration) LeaseLockOption

WithLeaseDuration specifies the lease duration for leader election. This value defaults to 60s and will determine how long non-leader candidates for a lock will wait before attempting to acquire leadership. Too small of a value may cause issues with leader election, so recommended to keep this above 10s.

func WithName

func WithName(name string) LeaseLockOption

WithName specifies the Kubernetes resource name for the lock.

func WithNamespace

func WithNamespace(ns string) LeaseLockOption

WithNamespace specifies the Kubernetes namespace where the lock will be created.

func WithRenewDeadline

func WithRenewDeadline(d time.Duration) LeaseLockOption

WithRenewDeadline specifies the duration a leader will retry refreshing leadership before giving up. Defaults to 15s.

func WithRetryPeriod

func WithRetryPeriod(d time.Duration) LeaseLockOption

WithRetryPeriod specifies the duration between client actions.

type Options

type Options struct {
	Name          string
	Namespace     string
	ID            string
	LeaseDuration time.Duration
	RenewDeadline time.Duration
	RetryPeriod   time.Duration
}

Jump to

Keyboard shortcuts

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