patroni.dcs.kubernetes module

class _patroni.dcs.kubernetes.CoreV1ApiProxy(_use_endpoints: bool | None = False, bypass_api_service: bool | None = False) View on GitHub

Bases: object + Proxy class to work with k8s_client.CoreV1Api() object +

DEFAULT_RETRIABLE_HTTP_CODES = frozenset(\{500, 503, 504})_

+

__init\\__(use_endpoints: bool | None = False, bypass_api_service: bool | None = False) → None View on GitHub

+

configure_retriable_ http_codes(retriable http_codes: List[ int]) → None View on GitHublink:#patroni.dcs.kubernetes.CoreV1ApiProxy.configure_retriable http_codes[]

+

configure_timeouts(loop_wait: int, retry_timeout: int | float, ttl: int) → None View on GitHub

+

refresh_api_servers_cache() → None View on GitHub

+

property _use_endpoints: bool_
_class _patroni.dcs.kubernetes.K8sClient View on GitHub

Bases: object +

class _ApiClient(_bypass_api_service: bool | None = False) View on GitHub

Bases: object +

API_URL_PREFIX = '/api/v1/namespaces/'_

+

__init\\__(bypass_api_service: bool | None = False) → None View on GitHub

+

calculate_timeouts(_api_servers: int, timeout: float | None = None) → Tuple[ int, float, int] View on GitHub

Calculate a request timeout and number of retries per single K8s API server node. In case if the timeout per node is too small (less than one second) we will reduce the number of nodes. For the cluster with only one API server node we will try to do 1 retry. No retries for clusters with 2 or more API server nodes. We better rely on switching to a different node. +

do http_request(retry: Retry | None, api_servers_cache: List[ str], method: str, path: str, **kwargs: Any) → HTTPResponse View on GitHublink:#patroni.dcs.kubernetes.K8sClient.ApiClient.do http_request[]

+

get_api_servers(_api_servers_cache: List[ str]) → List[ str] View on GitHub

+

static \__handle_server_response(_response: HTTPResponse, \__preload_content: bool_) → HTTPResponse | K8sObject View on GitHub

+

_load_api_servers_cache() → None View on GitHub

+

static \\__make_headers(_headers: Dict[ str, str] | None) → Dict[ str, str] View on GitHub

+

refresh_api_servers_cache(_updating_cache: bool | None = False) → None View on GitHub

+

property _api_servers_cache: List[ str]_

+

call_api(method: str, path: str, headers: Dict[ str, str] | None = None, body: Any | None = None, __retry: Retry | None = None_, \__preload_content: bool = True_, \__request_timeout: float | None = None_, **kwargs: Any) → HTTPResponse | K8sObject View on GitHub

+

refresh_api_servers_cache() → None View on GitHub

+

request(retry: Retry | None, method: str, path: str, timeout: int | float | Tuple[ int | float, int | float] | Timeout | None = None, **kwargs: Any) → HTTPResponse View on GitHub

+

set_api_servers_cache_ttl(ttl: int) → None View on GitHub

+

set_base_uri(value: str) → None View on GitHub

+

set_read_timeout(timeout: int | float) → None View on GitHub

+

class _CoreV1Api(_api_client: ApiClient | None = None) View on GitHub

Bases: object +

__init\\__(api_client: ApiClient | None = None) → None View on GitHub

+

class \\__K8sObjectTemplate(**kwargs: Any_) View on GitHub

Bases: K8sObject + The template for objects which we create locally, e.g. k8s_client.V1ObjectMeta & co +

__init\\__(**kwargs: Any) → None View on GitHub

+

__init\\__() → None View on GitHub

+

_class _rest View on GitHub

Bases: object +

exception _ApiException(_status: int | None = None, reason: str | None = None, _ http_resp: HTTPResponse | None = None_) View on GitHub

Bases: Exception +

__init\\__(status: int | None = None, reason: str | None = None, _ http_resp: HTTPResponse | None = None_) → None View on GitHub
_class _patroni.dcs.kubernetes.K8sConfig View on GitHub

Bases: object +

_exception _ConfigException View on GitHub

Bases: Exception +

__init\\__() → None View on GitHub

+

static \\__get_by_name(_config: Dict[ str, List[ Dict[ str, Any]]], section: str, name: str) → Dict[ str, Any] | None View on GitHub

+

make_headers(_token: str | None = None, **kwargs: Any) → None View on GitHub

+

pool_config_from_file_or_data(_config: Dict[ str, str], file_key_name: str, pool_key_name: str) → None View on GitHub

+

_read_token_file() → str View on GitHub

+

set_token(_token: str) → None View on GitHub

+

property _headers: Dict[ str, str]_

+

load_incluster_config(ca_certs: str = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt', token_refresh_interval: timedelta = datetime.timedelta(seconds=60)) → None View on GitHub

+

load_kube_config(context: str | None = None) → None View on GitHub

+

property _server: str_
_exception _patroni.dcs.kubernetes.K8sConnectionFailed View on GitHub

Bases: K8sException

_exception _patroni.dcs.kubernetes.K8sException View on GitHub

Bases: Exception

class _patroni.dcs.kubernetes.K8sObject(_kwargs: Dict[ str, Any]) View on GitHub

Bases: object +

__init\\__(kwargs: Dict[ str, Any]) → None View on GitHub

+

classmethod \\__wrap(_parent: str | None, value: Any) → Any View on GitHub

+

get(name: str, default: Any | None = None) → Any | None View on GitHub

+

to_dict() → Dict[ str, Any] View on GitHub
class _patroni.dcs.kubernetes.Kubernetes(_config: Dict[ str, Any], mpp: AbstractMPP) View on GitHub

Bases: AbstractDCS +

__init\\__(config: Dict[ str, Any], mpp: AbstractMPP) → None View on GitHub

Prepare DCS paths, MPP object, initial values for state information and processing dependencies. +

Variables

configdict, reference to config section of selected DCS. i.e.: zookeeper for zookeeper, etcd for etcd, etc… +

__load_cluster(_group: str | None_, loader: Callable[[ Dict[ str, Any]], Cluster | Dict[ int, Cluster]]) → Cluster | Dict[ int, Cluster]

+

__target_ref(_leader_ip: str_, latest_subsets: List[K8sObject], pod: K8sObject) → K8sObject

+

abc_impl = <_abc._abc_data object>_

+

cluster_from_nodes(_group: str, nodes: Dict[ str, K8sObject], pods: Collection[K8sObject]) → Cluster View on GitHub

+

property \\__config_resource_version: str | None_

+

_create_config_service() → None View on GitHub

+

delete_leader(_leader: Leader) → bool View on GitHub

Unused +

load_cluster(_path: str, loader: Callable[[ Any], Cluster | Dict[ int, Cluster]]) → Cluster | Dict[ int, Cluster] View on GitHub

Main abstract method that implements the loading of Cluster instance. + Note

  Internally this method should call the _loader_ method that will build `+Cluster+` object which represents current state and topology of the cluster in DCS. This method supposed to be called only by the `+get_cluster()+` method.
  +
  Parameters:::
  Raise:::
    `+DCSError+` in case of communication problems with DCS. If the current node was running as a primary and exception raised, instance would be demoted.
+
map_subsets(_endpoints: Dict[ str, Any], ips: List[ str]) → None View on GitHub

+

mpp_cluster_loader(_path: Dict[ str, Any]) → Dict[ int, Cluster] View on GitHub

Load and build all PostgreSQL clusters from a single MPP cluster. +

Parameters

path – the path in DCS where to load Cluster(s) from.

Returns

all MPP groups as dict, with group IDs as keys and Cluster objects as values. +

patch_or_create(_name: str, annotations: Dict[ str, Any], resource_version: str | None = None, patch: bool = False, retry: Callable[[…​], Any] | None = None, ips: List[ str] | None = None) → K8sObject View on GitHub

Patch or create K8s object, Endpoint or ConfigMap. +

Parameters
Returns

the new V1Endpoints or V1ConfigMap object, that was created or updated. +

postgresql_cluster_loader(_path: Dict[ str, Any]) → Cluster View on GitHub

Load and build the Cluster object from DCS, which represents a single PostgreSQL cluster. +

Parameters

path – the path in DCS where to load Cluster from.

Returns

Cluster instance. +

update_leader(_leader: Leader) → bool View on GitHub

Unused +

update_leader_with_retry(_annotations: Dict[ str, Any], resource_version: str | None, ips: List[ str]) → bool View on GitHub

+

wait_caches(_stop_time: float) → None View on GitHub

+

write_failsafe(_value: str) → bool View on GitHub

Unused +

write_leader_optime(_last_lsn: str) → bool View on GitHub

Unused +

write_status(_value: str) → bool View on GitHub

Unused +

attempt_to_acquire_leader() → bool View on GitHub

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 View on GitHub

Removes the initialize key for a cluster. +

Returns

True if successfully committed to DCS. +

client_path(path: str) → str View on GitHub

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: K8sObject, p2: K8sObject) → bool View on GitHub

+

delete_cluster(*args: Any, **kwargs: Any) → Any View on GitHub

Delete cluster from DCS. +

Returns

True if successfully committed to DCS. +

delete_leader(leader: Leader | None, last_lsn: int | None = None) → bool View on GitHub

Update optime/leader and voluntarily remove leader key from DCS. + This method should remove leader key if current instance is the leader. +

Parameters
Returns

boolean result of called abstract _delete_leader(). +

delete_sync_state(version: str | None = None) → bool View on GitHub

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_mpp_coordinator() → Cluster | None View on GitHub

Load the PostgreSQL cluster for the MPP Coordinator. + Note

  This method is only executed on the worker nodes to find the coordinator.
  +
  Returns:::
    Select `+Cluster+` instance associated with the MPP Coordinator group ID.
+
initialize(create_new: bool = True, sysid: str = '') → bool View on GitHub

Race for cluster initialization. + This method should atomically create initialize key and return True, otherwise it should return False. +

Parameters
Returns

True if key has been created successfully. +

property _leader_path: str_

Get the client path for leader. +

manual_failover(leader: str | None, candidate: str | None, scheduled_at: datetime | None = None, version: str | None = None) → bool View on GitHub

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

Parameters
Returns

True if successfully committed to DCS. +

static _member(_pod: K8sObject) → Member View on GitHub

+

patch_or_create(*args: Any, **kwargs: Any) → Any View on GitHub

+

patch_or_create_config(annotations: Dict[ str, Any], resource_version: str | None = None, patch: bool = False, retry: bool = True) → bool View on GitHub

+

reload_config(config: Config | Dict[ str, Any]) → None View on GitHub

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 View on GitHub

+

set_config_value(value: str, version: str | None = None) → bool View on GitHub

Create or update /config key in DCS. +

Parameters
Returns

True if successfully committed to DCS. +

set_failover_value(value: str, version: str | None = None) → bool View on GitHub

Unused +

set_history_value(value: str) → bool View on GitHub

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 View on GitHub

Set the new value for retry_timeout. +

set_sync_state_value(value: str, version: str | None = None) → bool View on GitHub

Unused +

set_ttl(ttl: int) → bool | None View on GitHub

Set the new ttl value for DCS keys. +

static _subsets_changed(_last_observed_subsets: List[K8sObject], ip: str, ports: List[K8sObject]) → bool View on GitHub
>>> 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 View on GitHub

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 View on GitHub

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: Leader, last_lsn: int | None, slots: Dict[ str, int] | None = None, failsafe: Dict[ str, str] | None = None) → bool View on GitHub

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

Parameters
Returns

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

watch(leader_version: str | None, timeout: float) → bool View on GitHub

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

Parameters
Returns

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

write_leader_optime(last_lsn: int) → None View on GitHub

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

Parameters

last_lsn – absolute WAL LSN in bytes. +

write_sync_state(leader: str | None, sync_standby: Collection[ str] | None, version: str | None = None) → SyncState | None View on GitHub

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

Parameters
Returns

the new SyncState object or None

exception _patroni.dcs.kubernetes.KubernetesError(_value: Any) View on GitHub

Bases: DCSError

exception _patroni.dcs.kubernetes.KubernetesRetriableException(_orig: ApiException) View on GitHub

Bases: ApiException +

__init\\__(orig: ApiException) → None View on GitHub

+

property _sleeptime: int | None_
class _patroni.dcs.kubernetes.ObjectCache(_dcs: Kubernetes, func: Callable[[…​], Any], retry: Retry, condition: Condition, name: str | None = None) View on GitHub

Bases: Thread +

__init\\__(dcs: Kubernetes, func: Callable[[…​], Any], retry: Retry, condition: Condition, name: str | None = None) → None View on GitHub

This constructor should always be called with keyword arguments. Arguments are:
group should be None; reserved for future extension when a ThreadGroup class is implemented.
target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.
args is a list or tuple of arguments for the target invocation. Defaults to ().
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to \{}.
If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init\\__()) before doing anything else to the thread. +

_build_cache() → None View on GitHub

+

do_watch(_resource_version: str) → None View on GitHub

+

static \\__finish_response(_response: HTTPResponse) → None View on GitHub

+

_list() → K8sObject View on GitHub

+

process_event(_event: Dict[ str, Any | Dict[ str, Dict[ str, Any] | Any]]) → None View on GitHub

+

watch(_resource_version: str) → HTTPResponse View on GitHub

+

copy() → Dict[ str, K8sObject] View on GitHub

+

delete(name: str, resource_version: str) → Tuple[ bool, K8sObject | None] View on GitHub

+

get(name: str) → K8sObject | None View on GitHub

+

is_ready() → bool View on GitHub

Must be called only when holding the lock on _condition +

kill_stream() → None View on GitHub

+

run() → None View on GitHub

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: K8sObject) → Tuple[ bool, K8sObject | None] View on GitHub
patroni.dcs.kubernetes._cleanup_temp_files() → None View on GitHub
patroni.dcs.kubernetes.create_temp_file(_content: bytes) → str View on GitHub
patroni.dcs.kubernetes.run_and_handle_exceptions(_method: Callable[[…​], Any], *args: Any, **kwargs: Any) → Any View on GitHub
patroni.dcs.kubernetes.catch_kubernetes_errors(func: Callable[[…​], Any]) → Callable[[…​], Any] View on GitHub
patroni.dcs.kubernetes.to_camel_case(value: str) → str View on GitHub

Previous Next


© Copyright 2015 Compose, Zalando SE. Revision 9d231aee.

Built with Sphinx using a theme provided by Read the Docs.

Read the Docs v: latest

+ Builds