patroni.dcs.kubernetes module

class patroni.dcs.kubernetes.CoreV1ApiProxy(use_endpoints: Optional[bool] = False, bypass_api_service: Optional[bool] = False)

Bases: object

Proxy class to work with k8s_client.CoreV1Api() object

configure_retriable_http_codes(retriable_http_codes: List[int]) None
configure_timeouts(loop_wait: int, retry_timeout: Union[int, float], ttl: int) None
refresh_api_servers_cache() None
property use_endpoints: bool
class patroni.dcs.kubernetes.K8sClient

Bases: object

class ApiClient(bypass_api_service: Optional[bool] = False)

Bases: object

property api_servers_cache: List[str]
call_api(method: str, path: str, headers: Optional[Dict[str, str]] = None, body: Optional[Any] = None, _retry: Optional[patroni.utils.Retry] = None, _preload_content: bool = True, _request_timeout: Optional[float] = None, **kwargs: Any) Union[urllib3.response.HTTPResponse, patroni.dcs.kubernetes.K8sObject]
refresh_api_servers_cache() None
request(retry: Optional[patroni.utils.Retry], method: str, path: str, timeout: Optional[Union[int, float, Tuple[Union[int, float], Union[int, float]], urllib3.util.timeout.Timeout]] = None, **kwargs: Any) urllib3.response.HTTPResponse
set_api_servers_cache_ttl(ttl: int) None
set_base_uri(value: str) None
set_read_timeout(timeout: Union[int, float]) None
class CoreV1Api(api_client: Optional[patroni.dcs.kubernetes.K8sClient.ApiClient] = None)

Bases: object

class rest

Bases: object

exception ApiException(status: Optional[int] = None, reason: Optional[str] = None, http_resp: Optional[urllib3.response.HTTPResponse] = None)

Bases: Exception

class patroni.dcs.kubernetes.K8sConfig

Bases: object

exception ConfigException

Bases: Exception

property headers: Dict[str, str]
load_incluster_config(ca_certs: str = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt', token_refresh_interval: datetime.timedelta = datetime.timedelta(seconds=60)) None
load_kube_config(context: Optional[str] = None) None
property server: str
exception patroni.dcs.kubernetes.K8sConnectionFailed

Bases: patroni.dcs.kubernetes.K8sException

exception patroni.dcs.kubernetes.K8sException

Bases: Exception

class patroni.dcs.kubernetes.K8sObject(kwargs: Dict[str, Any])

Bases: object

get(name: str, default: Optional[Any] = None) Optional[Any]
to_dict() Dict[str, Any]
class patroni.dcs.kubernetes.Kubernetes(config: Dict[str, Any])

Bases: patroni.dcs.AbstractDCS

attempt_to_acquire_leader() bool

Attempt to acquire leader lock.

Note

This method should create /leader key with the value _name.

The key must be created atomically. In case the key already exists it should not be overwritten and False must be returned.

If key creation fails due to DCS not being accessible or because it is not able to process requests (hopefully temporary), the DCSError exception should be raised.

Returns

True if key has been created successfully.

cancel_initialization() bool

Removes the initialize key for a cluster.

Returns

True if successfully committed to DCS.

client_path(path: str) str

Construct the absolute key name from appropriate parts for the DCS type.

Parameters

path – The key name within the current Patroni cluster.

Returns

absolute key name for the current Patroni cluster.

static compare_ports(p1: patroni.dcs.kubernetes.K8sObject, p2: patroni.dcs.kubernetes.K8sObject) bool
delete_cluster(*args: Any, **kwargs: Any) Any

Delete cluster from DCS.

Returns

True if successfully committed to DCS.

delete_leader(last_lsn: Optional[int] = None) bool

Update optime/leader and voluntarily remove leader key from DCS.

This method should remove leader key if current instance is the leader.

Parameters

last_lsn – latest checkpoint location in bytes.

Returns

boolean result of called abstract _delete_leader().

delete_sync_state(version: Optional[str] = None) bool

Patch annotations of $SCOPE-sync Endpoint or ConfigMap with empty values.

Effectively it removes “leader” and “sync_standby” annotations from the object. :param version: last known resource_version for conditional update of the object :returns: True if “delete” was successful

get_citus_coordinator() Optional[patroni.dcs.Cluster]

Load the Patroni cluster for the Citus Coordinator.

Note

This method is only executed on the worker nodes (group!=0) to find the coordinator.

Returns

Select Cluster instance associated with the Citus Coordinator group ID.

initialize(create_new: bool = True, sysid: str = '') bool

Race for cluster initialization.

This method should atomically create initialize key and return True, otherwise it should return False.

Parameters
  • create_newFalse if the key should already exist (in the case we are setting the system_id).

  • sysid – PostgreSQL cluster system identifier, if specified, is written to the key.

Returns

True if key has been created successfully.

property leader_path: str

Get the client path for leader.

manual_failover(leader: Optional[str], candidate: Optional[str], scheduled_at: Optional[datetime.datetime] = None, version: Optional[str] = None) bool

Prepare dictionary with given values and set /failover key in DCS.

Parameters
  • leader – value to set for leader.

  • candidate – value to set for member.

  • scheduled_at – value converted to ISO date format for scheduled_at.

  • version – for conditional update of the key/object.

Returns

True if successfully committed to DCS.

static member(pod: patroni.dcs.kubernetes.K8sObject) patroni.dcs.Member
patch_or_create(*args: Any, **kwargs: Any) Any
patch_or_create_config(annotations: Dict[str, Any], resource_version: Optional[str] = None, patch: bool = False, retry: bool = True) bool
reload_config(config: Union[Config, Dict[str, Any]]) None

Handles dynamic config changes.

Either cause by changes in the local configuration file + SIGHUP or by changes of dynamic configuration

retry(method: Callable[[...], Any], *args: Any, **kwargs: Any) Any
set_config_value(value: str, version: Optional[str] = None) bool

Create or update /config key in DCS.

Parameters
  • value – new value to set in the config key.

  • version – for conditional update of the key/object.

Returns

True if successfully committed to DCS.

set_failover_value(value: str, version: Optional[str] = None) bool

Unused

set_history_value(value: str) bool

Set value for history in DCS.

Parameters

value – new value of history key/object.

Returns

True if successfully committed to DCS.

set_retry_timeout(retry_timeout: int) None

Set the new value for retry_timeout.

set_sync_state_value(value: str, version: Optional[str] = None) bool

Unused

set_ttl(ttl: int) Optional[bool]

Set the new ttl value for DCS keys.

static subsets_changed(last_observed_subsets: List[patroni.dcs.kubernetes.K8sObject], ip: str, ports: List[patroni.dcs.kubernetes.K8sObject]) bool
>>> ip = '1.2.3.4'
>>> a = [k8s_client.V1EndpointAddress(ip=ip)]
>>> s = [k8s_client.V1EndpointSubset(addresses=a)]
>>> Kubernetes.subsets_changed(s, '1.2.3.5', [])
True
>>> s = [k8s_client.V1EndpointSubset(addresses=a, ports=[k8s_client.V1EndpointPort(protocol='TCP', port=1)])]
>>> Kubernetes.subsets_changed(s, '1.2.3.4', [k8s_client.V1EndpointPort(port=5432)])
True
>>> p1 = k8s_client.V1EndpointPort(name='port1', port=1)
>>> p2 = k8s_client.V1EndpointPort(name='port2', port=2)
>>> p3 = k8s_client.V1EndpointPort(name='port3', port=3)
>>> s = [k8s_client.V1EndpointSubset(addresses=a, ports=[p1, p2])]
>>> Kubernetes.subsets_changed(s, ip, [p2, p3])
True
>>> s2 = [k8s_client.V1EndpointSubset(addresses=a, ports=[p2, p1])]
>>> Kubernetes.subsets_changed(s, ip, [p2, p1])
False
take_leader() bool

Establish a new leader in DCS.

Note

This method should create leader key with value of _name and ttl of ttl.

Since it could be called only on initial cluster bootstrap it could create this key regardless, overwriting the key if necessary.

Returns

True if successfully committed to DCS.

touch_member(*args: Any, **kwargs: Any) Any

Update member key in DCS.

Note

This method should create or update key with the name with /members/ + _name and the value of data in a given DCS.

Parameters

data – information about an instance (including connection strings).

Returns

True if successfully committed to DCS.

property ttl: int

Get current ttl value.

update_leader(leader: patroni.dcs.Leader, last_lsn: Optional[int], slots: Optional[Dict[str, int]] = None, failsafe: Optional[Dict[str, str]] = None) bool

Update leader key (or session) ttl and optime/leader.

Parameters
  • leaderLeader object with information about the leader.

  • last_lsn – absolute WAL LSN in bytes.

  • slots – dictionary with permanent slots confirmed_flush_lsn.

  • failsafe – if defined dictionary passed to write_failsafe().

Returns

True if leader key (or session) has been updated successfully.

watch(leader_version: Optional[str], timeout: float) bool

Sleep if the current node is a leader, otherwise, watch for changes of leader key with a given timeout.

Parameters
  • leader_version – version of a leader key.

  • timeout – timeout in seconds.

Returns

if True this will reschedule the next run of the HA cycle.

write_leader_optime(last_lsn: int) None

Write value for WAL LSN to optime annotation of the leader object.

Parameters

last_lsn – absolute WAL LSN in bytes.

write_sync_state(leader: Optional[str], sync_standby: Optional[Collection[str]], version: Optional[str] = None) Optional[patroni.dcs.SyncState]

Prepare and write annotations to $SCOPE-sync Endpoint or ConfigMap.

Parameters
  • leader – name of the leader node that manages /sync key

  • sync_standby – collection of currently known synchronous standby node names

  • version – last known resource_version for conditional update of the object

Returns

the new SyncState object or None

exception patroni.dcs.kubernetes.KubernetesError(value: Any)

Bases: patroni.exceptions.DCSError

exception patroni.dcs.kubernetes.KubernetesRetriableException(orig: patroni.dcs.kubernetes.K8sClient.rest.ApiException)

Bases: patroni.dcs.kubernetes.K8sClient.rest.ApiException

property sleeptime: Optional[int]
class patroni.dcs.kubernetes.ObjectCache(dcs: patroni.dcs.kubernetes.Kubernetes, func: Callable[[...], Any], retry: patroni.utils.Retry, condition: threading.Condition, name: Optional[str] = None)

Bases: threading.Thread

copy() Dict[str, patroni.dcs.kubernetes.K8sObject]
delete(name: str, resource_version: str) Tuple[bool, Optional[patroni.dcs.kubernetes.K8sObject]]
get(name: str) Optional[patroni.dcs.kubernetes.K8sObject]
is_ready() bool

Must be called only when holding the lock on _condition

kill_stream() None
run() None

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

set(name: str, value: patroni.dcs.kubernetes.K8sObject) Tuple[bool, Optional[patroni.dcs.kubernetes.K8sObject]]
patroni.dcs.kubernetes.catch_kubernetes_errors(func: Callable[[...], Any]) Callable[[...], Any]
patroni.dcs.kubernetes.k8s_client
patroni.dcs.kubernetes.to_camel_case(value: str) str