patroni.dcs.kubernetes module¶
-
class
patroni.dcs.kubernetes.CoreV1ApiProxy(use_endpoints: Optional[bool] = False, bypass_api_service: Optional[bool] = False)¶ Bases:
objectProxy class to work with k8s_client.CoreV1Api() object
-
_DEFAULT_RETRIABLE_HTTP_CODES= frozenset({500, 503, 504})¶
-
__init__(use_endpoints: Optional[bool] = False, bypass_api_service: Optional[bool] = False) → None¶ Initialize self. See help(type(self)) for accurate signature.
-
property
use_endpoints¶
-
-
class
patroni.dcs.kubernetes.K8sClient¶ Bases:
object-
class
ApiClient(bypass_api_service: Optional[bool] = False)¶ Bases:
object-
_API_URL_PREFIX= '/api/v1/namespaces/'¶
-
__init__(bypass_api_service: Optional[bool] = False) → None¶ Initialize self. See help(type(self)) for accurate signature.
-
_calculate_timeouts(api_servers: int, timeout: Optional[float] = None) → Tuple[int, float, int]¶ 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: Optional[patroni.utils.Retry], api_servers_cache: List[str], method: str, path: str, **kwargs: Any) → urllib3.response.HTTPResponse¶
-
static
_handle_server_response(response: urllib3.response.HTTPResponse, _preload_content: bool) → Union[urllib3.response.HTTPResponse, patroni.dcs.kubernetes.K8sObject]¶
-
property
api_servers_cache¶
-
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]¶
-
-
class
CoreV1Api(api_client: Optional[patroni.dcs.kubernetes.K8sClient.ApiClient] = None)¶ Bases:
object-
__init__(api_client: Optional[patroni.dcs.kubernetes.K8sClient.ApiClient] = None) → None¶ Initialize self. See help(type(self)) for accurate signature.
-
-
class
_K8sObjectTemplate(**kwargs: Any)¶ Bases:
patroni.dcs.kubernetes.K8sObjectThe template for objects which we create locally, e.g. k8s_client.V1ObjectMeta & co
-
class
-
class
patroni.dcs.kubernetes.K8sConfig¶ Bases:
object-
static
_get_by_name(config: Dict[str, List[Dict[str, Any]]], section: str, name: str) → Optional[Dict[str, Any]]¶
-
_pool_config_from_file_or_data(config: Dict[str, str], file_key_name: str, pool_key_name: str) → None¶
-
property
headers¶
-
load_incluster_config(ca_certs: str = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt', token_refresh_interval: datetime.timedelta = datetime.timedelta(seconds=60)) → None¶
-
property
server¶
-
static
-
exception
patroni.dcs.kubernetes.K8sConnectionFailed¶
-
class
patroni.dcs.kubernetes.K8sObject(kwargs: Dict[str, Any])¶ Bases:
object
-
class
patroni.dcs.kubernetes.Kubernetes(config: Dict[str, Any], mpp: patroni.postgresql.mpp.AbstractMPP)¶ Bases:
patroni.dcs.AbstractDCS-
__init__(config: Dict[str, Any], mpp: patroni.postgresql.mpp.AbstractMPP) → None¶ Prepare DCS paths, MPP object, initial values for state information and processing dependencies.
- Parameters
config –
dict, reference to config section of selected DCS. i.e.:zookeeperfor zookeeper,etcdfor etcd, etc…mpp – an object implementing
AbstractMPPinterface.
-
__load_cluster(group: Optional[str], loader: Callable[[Dict[str, Any]], Union[patroni.dcs.Cluster, Dict[int, patroni.dcs.Cluster]]]) → Union[patroni.dcs.Cluster, Dict[int, patroni.dcs.Cluster]]¶
-
__target_ref(leader_ip: str, latest_subsets: List[patroni.dcs.kubernetes.K8sObject], pod: patroni.dcs.kubernetes.K8sObject) → patroni.dcs.kubernetes.K8sObject¶
-
_abc_impl= <_abc._abc_data object>¶
-
_cluster: Optional[patroni.dcs.Cluster]¶
-
_cluster_from_nodes(group: str, nodes: Dict[str, patroni.dcs.kubernetes.K8sObject], pods: Collection[patroni.dcs.kubernetes.K8sObject]) → patroni.dcs.Cluster¶
-
property
_config_resource_version¶
-
_delete_leader(leader: patroni.dcs.Leader) → bool¶ Unused
-
_load_cluster(path: str, loader: Callable[[Any], Union[patroni.dcs.Cluster, Dict[int, patroni.dcs.Cluster]]]) → Union[patroni.dcs.Cluster, Dict[int, patroni.dcs.Cluster]]¶ Main abstract method that implements the loading of
Clusterinstance.Note
Internally this method should call the loader method that will build
Clusterobject which represents current state and topology of the cluster in DCS. This method supposed to be called only by theget_cluster()method.- Parameters
path – the path in DCS where to load Cluster(s) from.
loader – one of
_postgresql_cluster_loader()or_mpp_cluster_loader().
- Raise
DCSErrorin case of communication problems with DCS. If the current node was running as a primary and exception raised, instance would be demoted.
-
_mpp_cluster_loader(path: Dict[str, Any]) → Dict[int, patroni.dcs.Cluster]¶ 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 andClusterobjects as values.
-
_patch_or_create(name: str, annotations: Dict[str, Any], resource_version: Optional[str] = None, patch: bool = False, retry: Optional[Callable[[…], Any]] = None, ips: Optional[List[str]] = None) → patroni.dcs.kubernetes.K8sObject¶ Patch or create K8s object, Endpoint or ConfigMap.
- Parameters
name – the name of the object.
annotations – mapping of annotations that we want to create/update.
resource_version – object should be updated only if the
resource_versionmatches provided value.patch –
Trueif we know in advance that the object already exists and we should patch it.retry – a callable that will take care of retries
ips –
IP address that we want to put to the subsets of the endpoint. Could have following values:
None- when we don’t need to touch subset;[]- to set subsets to the empty list, whendelete_leader()method is called;['ip.add.re.ss']- when we want to make sure that the subsets of the leader endpoint contains the IP address of the leader, that we get from thekubernetes.pod_ip;['']- when we want to make sure that the subsets of the leader endpoint contains the IP address of the leader, butkubernetes.pod_ipconfiguration is missing. In this case we will try to take the IP address of the Pod which name matchesnamefrom the config file.
- Returns
the new
V1EndpointsorV1ConfigMapobject, that was created or updated.
-
_postgresql_cluster_loader(path: Dict[str, Any]) → patroni.dcs.Cluster¶ Load and build the
Clusterobject from DCS, which represents a single PostgreSQL cluster.- Parameters
path – the path in DCS where to load
Clusterfrom.- Returns
Clusterinstance.
-
_update_leader(leader: patroni.dcs.Leader) → bool¶ Unused
-
_update_leader_with_retry(annotations: Dict[str, Any], resource_version: Optional[str], ips: List[str]) → bool¶
-
attempt_to_acquire_leader() → bool¶ Attempt to acquire leader lock.
Note
This method should create
/leaderkey with the value_name.The key must be created atomically. In case the key already exists it should not be overwritten and
Falsemust be returned.If key creation fails due to DCS not being accessible or because it is not able to process requests (hopefully temporary), the
DCSErrorexception should be raised.- Returns
Trueif key has been created successfully.
-
cancel_initialization() → bool¶ Removes the
initializekey for a cluster.- Returns
Trueif 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
Trueif successfully committed to DCS.
-
delete_leader(leader: Optional[patroni.dcs.Leader], last_lsn: Optional[int] = None) → bool¶ Update
optime/leaderand voluntarily remove leader key from DCS.This method should remove leader key if current instance is the leader.
- Parameters
leader –
Leaderobject with information about the leader.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_mpp_coordinator() → Optional[patroni.dcs.Cluster]¶ Load the PostgreSQL cluster for the MPP Coordinator.
Note
This method is only executed on the worker nodes to find the coordinator.
- Returns
Select
Clusterinstance associated with the MPP Coordinator group ID.
-
initialize(create_new: bool = True, sysid: str = '') → bool¶ Race for cluster initialization.
This method should atomically create
initializekey and returnTrue, otherwise it should returnFalse.- Parameters
create_new –
Falseif 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
Trueif key has been created successfully.
-
property
leader_path¶ 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
/failoverkey 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
Trueif 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
/configkey in DCS.- Parameters
value – new value to set in the
configkey.version – for conditional update of the key/object.
- Returns
Trueif successfully committed to DCS.
-
set_history_value(value: str) → bool¶ Set value for
historyin DCS.- Parameters
value – new value of
historykey/object.- Returns
Trueif successfully committed to DCS.
-
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
_nameandttlofttl.Since it could be called only on initial cluster bootstrap it could create this key regardless, overwriting the key if necessary.
- Returns
Trueif 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/+_nameand the value of data in a given DCS.- Parameters
data – information about an instance (including connection strings).
- Returns
Trueif successfully committed to DCS.
-
property
ttl¶ Get current
ttlvalue.
-
update_leader(cluster: patroni.dcs.Cluster, last_lsn: Optional[int], slots: Optional[Dict[str, int]] = None, failsafe: Optional[Dict[str, str]] = None) → bool¶ Update
leaderkey (or session) ttl,/status, and/failsafekeys.- Parameters
cluster –
Clusterobject with information about the current cluster state.last_lsn – absolute WAL LSN in bytes.
slots – dictionary with permanent slots
confirmed_flush_lsn.failsafe – if defined dictionary passed to
write_failsafe().
- Returns
Trueifleaderkey (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
Truethis will reschedule the next run of the HA cycle.
-
write_leader_optime(last_lsn: int) → None¶ Write value for WAL LSN to
optimeannotation of the leader object.- Parameters
last_lsn – absolute WAL LSN in bytes.
-
write_sync_state(leader: Optional[str], sync_standby: Optional[Collection[str]], quorum: Optional[int], 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
quorum – if the node from sync_standby list is doing a leader race it should see at least quorum other nodes from the sync_standby + leader list
version – last known resource_version for conditional update of the object
- Returns
the new
SyncStateobject 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-
__init__(orig: patroni.dcs.kubernetes.K8sClient.rest.ApiException) → None¶ Initialize self. See help(type(self)) for accurate signature.
-
property
sleeptime¶
-
-
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-
__init__(dcs: patroni.dcs.kubernetes.Kubernetes, func: Callable[[…], Any], retry: patroni.utils.Retry, condition: threading.Condition, name: Optional[str] = None) → None¶ 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 the argument tuple 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.
-
_list() → patroni.dcs.kubernetes.K8sObject¶
-
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]¶
-
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._run_and_handle_exceptions(method: Callable[[…], Any], *args: Any, **kwargs: Any) → Any¶
-
patroni.dcs.kubernetes.catch_kubernetes_errors(func: Callable[[…], Any]) → Callable[[…], Any]¶
-
patroni.dcs.kubernetes.k8s_client¶