Skip to content

linka-cloud/leaderelection

Repository files navigation

leaderelection

Language: Go Go Reference

Project status: alpha

The API, spec, status and other user facing objects are subject to change. We do not support backward-compatibility for the alpha releases.

Overview

This module is extracted from the k8s.io/client-go package. It provides a simple interface for implementing leader election in a distributed system using different backends:

  • kubernetes: using Lease (Kubernetes API)

    Go Reference

  • gossip: using distributed in memory key-value store (based on hashicorp/memberlist)

    Go Reference

  • s3: using a simple json file stored in a s3 bucket

    Go Reference

  • git: using a simple json file stored in a git repository

    Go Reference

Usage

package main

import (
    "context"
    "time"
    
    "k8s.io/apimachinery/pkg/util/rand"
    
    le "go.linka.cloud/leaderelection"
    "go.linka.cloud/leaderelection/[backend]"
)

const (
	lockName = "test"
)

func main() {
	ctx, cancel := context.WithCancel(le.SetupSignalHandler())
	defer cancel()

	
	l, err := [backend].New(ctx, lockName, rand.String(8), ...)
	if err != nil {
		logrus.Fatal(err)
	}
	config := le.Config{
		Lock:            l,
		LeaseDuration:   15 * time.Second,
		RenewDeadline:   10 * time.Second,
		RetryPeriod:     2 * time.Second,
		ReleaseOnCancel: true,
		Name:            lockName,
		Callbacks: le.Callbacks{
			OnStartedLeading: func(ctx context.Context) {
				logrus.Info("started leading")
			},
			OnStoppedLeading: func() {
				logrus.Info("stopped leading")
			},
			OnNewLeader: func(identity string) {
				logrus.Infof("new leader: %s", identity)
			},
		},
	}
	e, err := le.New(config)
	if err != nil {
		logrus.Fatal(err)
	}
	e.Run(ctx)
}