Leader election mechanism for apps
Revision | Date | Description |
|---|
1.0
| 24.07.2024 | Init Changelog |
Introduction
This article explains how to implement Leader election mechanism for apps. If you want to know how Leader Elections and leases in Kubernetes works - check official docs.
RBAC
To use leader election mechanism you may need to prepare RBAC for your application. The easiest way is to use build-in ServiceAccount with proper Role rules and attach it into application deployment. Sample code with minimal permissions below.
LeaseLock
Kubernetes client creates Lease resource wit all information about leader. Every election checks this resource for current state.
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: leaderelection
automountServiceAccountToken: true
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: leaderelection
rules:
- apiGroups:
- ""
resources:
- configmaps
verbs:
- "*"
- apiGroups:
- ""
resources:
- events
verbs:
- create
- patch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: leaderelection
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: leaderelection
subjects:
- kind: ServiceAccount
name: leaderelection
ConfigMapLock
Kubernetes client creates ConfigMap with lock information in .metadata.annotations. Every election checks this resource and its annotations for getting current state.
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: leaderelection
automountServiceAccountToken: true
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: leaderelection
rules:
- apiGroups:
- ""
resources:
- configmaps
verbs:
- "*"
- apiGroups:
- ""
resources:
- events
verbs:
- create
- patch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: leaderelection
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: leaderelection
subjects:
- kind: ServiceAccount
name: leaderelection
Implementation
Here you have some example implementation of leader election mechanism for apps running on Kubernetes. All of them are using in-cluster authorization with ServiceAccountToken mounts in pod.
Python
__main__.py
"""Module main executable"""
import logging
import os
from kubernetes import config
from kubernetes.leaderelection import leaderelection, electionconfig
from kubernetes.leaderelection.resourcelock.configmaplock import ConfigMapLock
def onstarted_func() -> None:
"""Function that run once a candidate is elected as a leader"""
logging.info("I am leader!")
def onstopped_func() -> None:
"""Function that runs once candidate fails to lead """
logging.warning("I am follower!")
def main() -> None:
"""Main module function"""
# load kube-config from ServiceAccountToken
config.load_incluster_config()
# get settings for creating lease lock
lock_name: str = "leader-election-demo"
lock_candidate_identity: str = os.environ.get("POD_NAME")
lock_namespace: str = os.environ.get("POD_NAMESPACE")
# create leader election config
election_config = electionconfig.Config(
ConfigMapLock(name=lock_name, namespace=lock_namespace, identity=lock_candidate_identity),
lease_duration=17, renew_deadline=15, retry_period=5,
onstarted_leading=onstarted_func, onstopped_leading=None
)
# run elections
leaderelection.LeaderElection(election_config).run()
logging.info("Exited leader election.")
Last modified: 17 February 2025