signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def polling_loop(timeout, interval=<NUM_LIT:1>):
start_time = time.time()<EOL>iteration = <NUM_LIT:0><EOL>end_time = start_time + timeout<EOL>while time.time() < end_time:<EOL><INDENT>yield iteration<EOL>iteration += <NUM_LIT:1><EOL>time.sleep(interval)<EOL><DEDENT>
Returns an iterator that returns values until timeout has passed. Timeout is measured from start of iteration.
f12581:m7
def __init__(self, max_tries=<NUM_LIT:1>, delay=<NUM_LIT:0.1>, backoff=<NUM_LIT:2>, max_jitter=<NUM_LIT>, max_delay=<NUM_LIT>,<EOL>sleep_func=_sleep, deadline=None, retry_exceptions=PatroniException):
self.max_tries = max_tries<EOL>self.delay = delay<EOL>self.backoff = backoff<EOL>self.max_jitter = int(max_jitter * <NUM_LIT:100>)<EOL>self.max_delay = float(max_delay)<EOL>self._attempts = <NUM_LIT:0><EOL>self._cur_delay = delay<EOL>self.deadline = deadline<EOL>self._cur_stoptime = None<EOL>self.sleep_func = sleep_fun...
Create a :class:`Retry` instance for retrying function calls :param max_tries: How many times to retry the command. -1 means infinite tries. :param delay: Initial delay between retry attempts. :param backoff: Backoff multiplier between retry attempts. Defaults to 2 for exponential backoff. ...
f12581:c1:m0
def reset(self):
self._attempts = <NUM_LIT:0><EOL>self._cur_delay = self.delay<EOL>self._cur_stoptime = None<EOL>
Reset the attempt counter
f12581:c1:m1
def copy(self):
return Retry(max_tries=self.max_tries, delay=self.delay, backoff=self.backoff,<EOL>max_jitter=self.max_jitter / <NUM_LIT>, max_delay=self.max_delay, sleep_func=self.sleep_func,<EOL>deadline=self.deadline, retry_exceptions=self.retry_exceptions)<EOL>
Return a clone of this retry manager
f12581:c1:m2
def __call__(self, func, *args, **kwargs):
self.reset()<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>if self.deadline is not None and self._cur_stoptime is None:<EOL><INDENT>self._cur_stoptime = time.time() + self.deadline<EOL><DEDENT>return func(*args, **kwargs)<EOL><DEDENT>except self.retry_exceptions:<EOL><INDENT>if self._attempts == self.max_tries:<EOL><IND...
Call a function with arguments until it completes without throwing a `retry_exceptions` :param func: Function to call :param args: Positional arguments to call the function with :params kwargs: Keyword arguments to call the function with The function will be called until it doesn't thr...
f12581:c1:m3
@synchronized<EOL><INDENT>def activate(self):<DEDENT>
self.active = True<EOL>return self._activate()<EOL>
Activates the watchdog device with suitable timeouts. While watchdog is active keepalive needs to be called every time loop_wait expires. :returns False if a safe watchdog could not be configured, but is required.
f12582:c1:m2
@property<EOL><INDENT>def is_running(self):<DEDENT>
return False<EOL>
Returns True when watchdog is activated and capable of performing it's task.
f12582:c2:m0
@property<EOL><INDENT>def is_healthy(self):<DEDENT>
return False<EOL>
Returns False when calling open() is known to fail.
f12582:c2:m1
@property<EOL><INDENT>def can_be_disabled(self):<DEDENT>
return True<EOL>
Returns True when watchdog will be disabled by calling close(). Some watchdog devices will keep running no matter what once activated. May raise WatchdogError if called without calling open() first.
f12582:c2:m2
@abc.abstractmethod<EOL><INDENT>def open(self):<DEDENT>
Open watchdog device. When watchdog is opened keepalive must be called. Returns nothing on success or raises WatchdogError if the device could not be opened.
f12582:c2:m3
@abc.abstractmethod<EOL><INDENT>def close(self):<DEDENT>
Gracefully close watchdog device.
f12582:c2:m4
@abc.abstractmethod<EOL><INDENT>def keepalive(self):<DEDENT>
Resets the watchdog timer. Watchdog must be open when keepalive is called.
f12582:c2:m5
@abc.abstractmethod<EOL><INDENT>def get_timeout(self):<DEDENT>
Returns the current keepalive timeout in effect.
f12582:c2:m6
@staticmethod<EOL><INDENT>def has_set_timeout():<DEDENT>
return False<EOL>
Returns True if setting a timeout is supported.
f12582:c2:m7
def set_timeout(self, timeout):
raise WatchdogError("<STR_LIT>".format(self.describe()))<EOL>
Set the watchdog timer timeout. :param timeout: watchdog timeout in seconds
f12582:c2:m8
def describe(self):
return self.__class__.__name__<EOL>
Human readable name for this device
f12582:c2:m9
def __getattr__(self, name):
if name.startswith('<STR_LIT>') and name[<NUM_LIT:4>:] in WDIOF:<EOL><INDENT>return bool(self.options & WDIOF[name[<NUM_LIT:4>:]])<EOL><DEDENT>raise AttributeError("<STR_LIT>".format(name))<EOL>
Convenience has_XYZ attributes for checking WDIOF bits in options
f12584:c1:m0
def _ioctl(self, func, arg):
if self._fd is None:<EOL><INDENT>raise WatchdogError("<STR_LIT>")<EOL><DEDENT>if os.name != '<STR_LIT>':<EOL><INDENT>import fcntl<EOL>fcntl.ioctl(self._fd, func, arg, True)<EOL><DEDENT>
Runs the specified ioctl on the underlying fd. Raises WatchdogError if the device is closed. Raises OSError or IOError (Python 2) when the ioctl fails.
f12584:c2:m7
def has_set_timeout(self):
return self.get_support().has_SETTIMEOUT<EOL>
Returns True if setting a timeout is supported.
f12584:c2:m11
def check_auth(func):
def wrapper(handler, *args, **kwargs):<EOL><INDENT>if handler.check_auth_header():<EOL><INDENT>return func(handler, *args, **kwargs)<EOL><DEDENT><DEDENT>return wrapper<EOL>
Decorator function to check authorization header. Usage example: @check_auth def do_PUT_foo(): pass
f12585:m0
def do_GET(self, write_status_code_only=False):
path = '<STR_LIT>' if self.path == '<STR_LIT:/>' else self.path<EOL>response = self.get_postgresql_status()<EOL>patroni = self.server.patroni<EOL>cluster = patroni.dcs.cluster<EOL>if not cluster and patroni.ha.is_paused():<EOL><INDENT>primary_status_code = <NUM_LIT:200> if response['<STR_LIT>'] == '<STR_LIT>' else <NUM...
Default method for processing all GET requests which can not be routed to other methods
f12585:c0:m5
@staticmethod<EOL><INDENT>def parse_schedule(schedule, action):<DEDENT>
error = None<EOL>scheduled_at = None<EOL>try:<EOL><INDENT>scheduled_at = dateutil.parser.parse(schedule)<EOL>if scheduled_at.tzinfo is None:<EOL><INDENT>error = '<STR_LIT>'.format(action)<EOL>status_code = <NUM_LIT><EOL><DEDENT>elif scheduled_at < datetime.datetime.now(tzutc):<EOL><INDENT>error = '<STR_LIT>'.format(act...
parses the given schedule and validates at
f12585:c0:m13
def parse_request(self):
ret = BaseHTTPRequestHandler.parse_request(self)<EOL>if ret:<EOL><INDENT>mname = self.path.lstrip('<STR_LIT:/>').split('<STR_LIT:/>')[<NUM_LIT:0>]<EOL>mname = self.command + ('<STR_LIT:_>' + mname if mname else '<STR_LIT>')<EOL>if hasattr(self, '<STR_LIT>' + mname):<EOL><INDENT>self.command = mname<EOL><DEDENT><DEDENT>...
Override parse_request method to enrich basic functionality of `BaseHTTPRequestHandler` class Original class can only invoke do_GET, do_POST, do_PUT, etc method implementations if they are defined. But we would like to have at least some simple routing mechanism, i.e.: GET /uri1/part2 request s...
f12585:c0:m21
@staticmethod<EOL><INDENT>def _read_postmaster_pidfile(data_dir):<DEDENT>
pid_line_names = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:port>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>try:<EOL><INDENT>with open(os.path.join(data_dir, '<STR_LIT>')) as f:<EOL><INDENT>return {name: line.rstrip('<STR_LIT:\n>') for name, line in zip(pid_line_names, f)}<EOL><DEDENT><DEDENT>except IOError:<...
Reads and parses postmaster.pid from the data directory :returns dictionary of values if successful, empty dictionary otherwise
f12586:c0:m1
def signal_stop(self, mode):
if self.is_single_user:<EOL><INDENT>logger.warning("<STR_LIT>".format(self.pid))<EOL>return False<EOL><DEDENT>try:<EOL><INDENT>self.send_signal(STOP_SIGNALS[mode])<EOL><DEDENT>except psutil.NoSuchProcess:<EOL><INDENT>return True<EOL><DEDENT>except psutil.AccessDenied as e:<EOL><INDENT>logger.warning("<STR_LIT>".format(...
Signal postmaster process to stop :returns None if signaled, True if process is already gone, False if error
f12586:c0:m6
def __str__(self):
return repr(self.value)<EOL>
>>> str(PatroniException('foo')) "'foo'"
f12587:c0:m1
def _tag_ebs(self, conn, role):
tags = {'<STR_LIT:Name>': '<STR_LIT>' + self.cluster_name, '<STR_LIT>': role, '<STR_LIT>': self.instance_id}<EOL>volumes = conn.get_all_volumes(filters={'<STR_LIT>': self.instance_id})<EOL>conn.create_tags([v.id for v in volumes], tags)<EOL>
set tags, carrying the cluster name, instance role and instance id for the EBS storage
f12588:c0:m3
def _tag_ec2(self, conn, role):
tags = {'<STR_LIT>': role}<EOL>conn.create_tags([self.instance_id], tags)<EOL>
tag the current EC2 instance with a cluster role
f12588:c0:m4
def repr_size(n_bytes):
if n_bytes < <NUM_LIT>:<EOL><INDENT>return '<STR_LIT>'.format(n_bytes)<EOL><DEDENT>i = -<NUM_LIT:1><EOL>while n_bytes > <NUM_LIT>:<EOL><INDENT>n_bytes /= <NUM_LIT><EOL>i += <NUM_LIT:1><EOL><DEDENT>return '<STR_LIT>'.format(round(n_bytes, <NUM_LIT:1>), si_prefixes[i])<EOL>
>>> repr_size(1000) '1000 Bytes' >>> repr_size(8257332324597) '7.5 TiB'
f12589:m1
def size_as_bytes(size_, prefix):
prefix = prefix.upper()<EOL>assert prefix in si_prefixes<EOL>exponent = si_prefixes.index(prefix) + <NUM_LIT:1><EOL>return int(size_ * (<NUM_LIT> ** exponent))<EOL>
>>> size_as_bytes(7.5, 'T') 8246337208320
f12589:m2
def run(self):
if self.init_error:<EOL><INDENT>logger.error('<STR_LIT>',<EOL>self.wal_e.env_dir)<EOL>return ExitCode.FAIL<EOL><DEDENT>try:<EOL><INDENT>should_use_s3 = self.should_use_s3_to_create_replica()<EOL>if should_use_s3 is None: <EOL><INDENT>return ExitCode.RETRY_LATER<EOL><DEDENT>elif should_use_s3:<EOL><INDENT>return self.c...
Creates a new replica using WAL-E Returns ------- ExitCode 0 = Success 1 = Error, try again 2 = Error, don't try again
f12589:c0:m1
def should_use_s3_to_create_replica(self):
threshold_megabytes = self.wal_e.threshold_mb<EOL>threshold_percent = self.wal_e.threshold_pct<EOL>try:<EOL><INDENT>cmd = self.wal_e.cmd + ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>logger.debug('<STR_LIT>', cmd)<EOL>wale_output = subprocess.check_output(cmd)<EOL>reader = csv.DictReader(wale_output.decode('<STR_LIT:ut...
determine whether it makes sense to use S3 and not pg_basebackup
f12589:c0:m2
def failover_limitation(self):
if not self.reachable:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if self.tags.get('<STR_LIT>', False):<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if self.watchdog_failed:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return None<EOL>
Returns reason why this node can't promote or None if everything is ok.
f12590:c0:m2
def get_effective_tags(self):
tags = self.patroni.tags.copy()<EOL>if self._disable_sync > <NUM_LIT:0>:<EOL><INDENT>tags['<STR_LIT>'] = True<EOL><DEDENT>return tags<EOL>
Return configuration tags merged with dynamically applied tags.
f12590:c1:m13
def bootstrap_standby_leader(self):
clone_source = self.get_remote_master()<EOL>msg = '<STR_LIT>'.format(clone_source.conn_url)<EOL>result = self.clone(clone_source, msg)<EOL>self._post_bootstrap_task.complete(result)<EOL>if result:<EOL><INDENT>self.state_handler.set_role('<STR_LIT>')<EOL><DEDENT>return result<EOL>
If we found 'standby' key in the configuration, we need to bootstrap not a real master, but a 'standby leader', that will take base backup from a remote master and start follow it.
f12590:c1:m17
def process_sync_replication(self):
if self.is_synchronous_mode():<EOL><INDENT>current = self.cluster.sync.leader and self.cluster.sync.sync_standby<EOL>picked, allow_promote = self.state_handler.pick_synchronous_standby(self.cluster)<EOL>if picked != current:<EOL><INDENT>if current:<EOL><INDENT>logger.info("<STR_LIT>", current)<EOL>if not self.dcs.write...
Process synchronous standby beahvior. Synchronous standbys are registered in two places postgresql.conf and DCS. The order of updating them must be right. The invariant that should be kept is that if a node is master and sync_standby is set in DCS, then that node must have synchronous_standby s...
f12590:c1:m24
def while_not_sync_standby(self, func):
if not self.is_synchronous_mode() or self.patroni.nosync:<EOL><INDENT>return func()<EOL><DEDENT>with self._member_state_lock:<EOL><INDENT>self._disable_sync += <NUM_LIT:1><EOL><DEDENT>try:<EOL><INDENT>if self.touch_member():<EOL><INDENT>for _ in polling_loop(timeout=self.dcs.loop_wait*<NUM_LIT:2>, interval=<NUM_LIT:2>)...
Runs specified action while trying to make sure that the node is not assigned synchronous standby status. Tags us as not allowed to be a sync standby as we are going to go away, if we currently are wait for leader to notice and pick an alternative one or if the leader changes or goes away we are also f...
f12590:c1:m26
@staticmethod<EOL><INDENT>def fetch_node_status(member):<DEDENT>
try:<EOL><INDENT>response = requests.get(member.api_url, timeout=<NUM_LIT:2>, verify=False)<EOL>logger.info('<STR_LIT>', member.name, member.api_url, response.content)<EOL>return _MemberStatus.from_api_response(member, response.json())<EOL><DEDENT>except Exception as e:<EOL><INDENT>logger.warning("<STR_LIT>", member.na...
This function perform http get request on member.api_url and fetches its status :returns: `_MemberStatus` object
f12590:c1:m30
def is_lagging(self, wal_position):
lag = (self.cluster.last_leader_operation or <NUM_LIT:0>) - wal_position<EOL>return lag > self.patroni.config.get('<STR_LIT>', <NUM_LIT:0>)<EOL>
Returns if instance with an wal should consider itself unhealthy to be promoted due to replication lag. :param wal_position: Current wal position. :returns True when node is lagging
f12590:c1:m32
def _is_healthiest_node(self, members, check_replication_lag=True):
_, my_wal_position = self.state_handler.timeline_wal_position()<EOL>if check_replication_lag and self.is_lagging(my_wal_position):<EOL><INDENT>logger.info('<STR_LIT>')<EOL>return False <EOL><DEDENT>if not self.is_standby_cluster() and self.check_timeline():<EOL><INDENT>cluster_timeline = self.cluster.timeline<EOL>my_t...
This method tries to determine whether I am healthy enough to became a new leader candidate or not.
f12590:c1:m33
def demote(self, mode):
mode_control = {<EOL>'<STR_LIT>': dict(stop='<STR_LIT>', checkpoint=False, release=False, offline=True, async_req=False),<EOL>'<STR_LIT>': dict(stop='<STR_LIT>', checkpoint=True, release=True, offline=False, async_req=False),<EOL>'<STR_LIT>': dict(stop='<STR_LIT>', checkpoint=False, release=True...
Demote PostgreSQL running as master. :param mode: One of offline, graceful or immediate. offline is used when connection to DCS is not available. graceful is used when failing over to another node due to user request. May only be called running async. immediate is used when ...
f12590:c1:m39
def process_manual_failover_from_leader(self):
failover = self.cluster.failover<EOL>if not failover or (self.is_paused() and not self.state_handler.is_leader()):<EOL><INDENT>return<EOL><DEDENT>if (failover.scheduled_at and not<EOL>self.should_run_scheduled_action("<STR_LIT>", failover.scheduled_at, lambda:<EOL>self.dcs.manual_failover('<STR_LIT>', '<STR_LIT>', inde...
Checks if manual failover is requested and takes action if appropriate. Cleans up failover key if failover conditions are not matched. :returns: action message if demote was initiated, None if no action was taken
f12590:c1:m41
def process_unhealthy_cluster(self):
if self.is_healthiest_node():<EOL><INDENT>if self.acquire_lock():<EOL><INDENT>failover = self.cluster.failover<EOL>if failover:<EOL><INDENT>if self.is_paused() and failover.leader and failover.candidate:<EOL><INDENT>logger.info('<STR_LIT>')<EOL>self.dcs.manual_failover('<STR_LIT>', failover.candidate, failover.schedule...
Cluster has no leader key
f12590:c1:m42
def restart(self, restart_data, run_async=False):
assert isinstance(restart_data, dict)<EOL>if (not self.restart_matches(restart_data.get('<STR_LIT>'),<EOL>restart_data.get('<STR_LIT>'),<EOL>('<STR_LIT>' in restart_data))):<EOL><INDENT>return (False, "<STR_LIT>")<EOL><DEDENT>with self._async_executor:<EOL><INDENT>prev = self._async_executor.schedule('<STR_LIT>')<EOL>i...
conditional and unconditional restart
f12590:c1:m50
def handle_starting_instance(self):
<EOL>if not self.state_handler.check_for_startup() or self.is_paused():<EOL><INDENT>self.set_start_timeout(None)<EOL>if self.is_paused():<EOL><INDENT>self.state_handler.set_state(self.state_handler.is_running() and '<STR_LIT>' or '<STR_LIT>')<EOL><DEDENT>return None<EOL><DEDENT>if self.has_lock():<EOL><INDENT>if not se...
Starting up PostgreSQL may take a long time. In case we are the leader we may want to fail over to.
f12590:c1:m58
def set_start_timeout(self, value):
self._start_timeout = value<EOL>
Sets timeout for starting as master before eligible for failover. Must be called when async_executor is busy or in the main thread.
f12590:c1:m59
def wakeup(self):
self.dcs.event.set()<EOL>
Call of this method will trigger the next run of HA loop if there is no "active" leader watch request in progress. This usually happens on the master or if the node is running async action
f12590:c1:m64
def get_remote_member(self, member=None):
cluster_params = self.get_standby_cluster_config()<EOL>if cluster_params:<EOL><INDENT>name = member.name if member else '<STR_LIT>'.format(uuid.uuid1())<EOL>data = {k: v for k, v in cluster_params.items() if k in RemoteMember.allowed_keys()}<EOL>data['<STR_LIT>'] = '<STR_LIT>' not in cluster_params<EOL>conn_kwargs = me...
In case of standby cluster this will tel us from which remote master to stream. Config can be both patroni config or cluster.config.data
f12590:c1:m65
def quote_ident(value):
return value if sync_standby_name_re.match(value) else '<STR_LIT:">' + value + '<STR_LIT:">'<EOL>
Very simplified version of quote_ident
f12591:m0
def _pgcommand(self, cmd):
return os.path.join(self._bin_dir, cmd)<EOL>
Returns path to the specified PostgreSQL command
f12591:c0:m13
def pg_ctl(self, cmd, *args, **kwargs):
pg_ctl = [self._pgcommand('<STR_LIT>'), cmd]<EOL>return subprocess.call(pg_ctl + ['<STR_LIT>', self._data_dir] + list(args), **kwargs) == <NUM_LIT:0><EOL>
Builds and executes pg_ctl command :returns: `!True` when return_code == 0, otherwise `!False`
f12591:c0:m14
def pg_isready(self):
cmd = [self._pgcommand('<STR_LIT>'), '<STR_LIT>', self._local_address['<STR_LIT:port>'], '<STR_LIT>', self._database]<EOL>if '<STR_LIT:host>' in self._local_address:<EOL><INDENT>cmd.extend(['<STR_LIT>', self._local_address['<STR_LIT:host>']])<EOL><DEDENT>if '<STR_LIT:username>' in self._superuser:<EOL><INDENT>cmd.exten...
Runs pg_isready to see if PostgreSQL is accepting connections. :returns: 'ok' if PostgreSQL is up, 'reject' if starting up, 'no_resopnse' if not up.
f12591:c0:m15
@property<EOL><INDENT>def can_rewind(self):<DEDENT>
<EOL>if not self.config.get('<STR_LIT>'):<EOL><INDENT>return False<EOL><DEDENT>cmd = [self._pgcommand('<STR_LIT>'), '<STR_LIT>']<EOL>try:<EOL><INDENT>ret = subprocess.call(cmd, stdout=open(os.devnull, '<STR_LIT:w>'), stderr=subprocess.STDOUT)<EOL>if ret != <NUM_LIT:0>: <EOL><INDENT>return False<EOL><DEDENT><DEDENT>exc...
check if pg_rewind executable is there and that pg_controldata indicates we have either wal_log_hints or checksums turned on
f12591:c0:m19
def _query(self, sql, *params):
cursor = None<EOL>try:<EOL><INDENT>cursor = self._cursor()<EOL>cursor.execute(sql, params)<EOL>return cursor<EOL><DEDENT>except psycopg2.Error as e:<EOL><INDENT>if cursor and cursor.connection.closed == <NUM_LIT:0>:<EOL><INDENT>if isinstance(e, psycopg2.OperationalError):<EOL><INDENT>self.close_connection()<EOL><DEDENT...
We are always using the same cursor, therefore this method is not thread-safe!!! You can call it from different threads only if you are holding explicit `AsyncExecutor` lock, because the main thread is always holding this lock when running HA cycle.
f12591:c0:m29
def run_bootstrap_post_init(self, config):
cmd = config.get('<STR_LIT>') or config.get('<STR_LIT>')<EOL>if cmd:<EOL><INDENT>r = self._local_connect_kwargs<EOL>if '<STR_LIT:host>' in r:<EOL><INDENT>host = quote_plus(r['<STR_LIT:host>']) if r['<STR_LIT:host>'].startswith('<STR_LIT:/>') else r['<STR_LIT:host>']<EOL><DEDENT>else:<EOL><INDENT>host = '<STR_LIT>'<EOL>...
runs a script after initdb or custom bootstrap script is called and waits until completion.
f12591:c0:m35
def can_create_replica_without_replication_connection(self):
replica_methods = self._create_replica_methods<EOL>return any(self.replica_method_can_work_without_replication_connection(method) for method in replica_methods)<EOL>
go through the replication methods to see if there are ones that does not require a working replication connection.
f12591:c0:m39
def create_replica(self, clone_member):
self.set_state('<STR_LIT>')<EOL>self._sysid = None<EOL>is_remote_master = isinstance(clone_member, RemoteMember)<EOL>create_replica_methods = is_remote_master and clone_member.create_replica_methods<EOL>replica_methods = (<EOL>create_replica_methods<EOL>or self._create_replica_methods<EOL>or ['<STR_LIT>']<EOL>)<EOL>if ...
create the replica according to the replica_method defined by the user. this is a list, so we need to loop through all methods the user supplies
f12591:c0:m40
def is_running(self):
if self._postmaster_proc:<EOL><INDENT>if self._postmaster_proc.is_running():<EOL><INDENT>return self._postmaster_proc<EOL><DEDENT>self._postmaster_proc = None<EOL><DEDENT>self._schedule_load_slots = self.use_slots<EOL>self._postmaster_proc = PostmasterProcess.from_pidfile(self._data_dir)<EOL>return self._postmaster_pro...
Returns PostmasterProcess if one is running on the data directory or None. If most recently seen process is running updates the cached process based on pid file.
f12591:c0:m44
def call_nowait(self, cb_name):
if self.bootstrapping:<EOL><INDENT>return<EOL><DEDENT>if cb_name in (ACTION_ON_START, ACTION_ON_STOP, ACTION_ON_RESTART, ACTION_ON_ROLE_CHANGE):<EOL><INDENT>self.__cb_called = True<EOL><DEDENT>if self.callback and cb_name in self.callback:<EOL><INDENT>cmd = self.callback[cb_name]<EOL>try:<EOL><INDENT>cmd = shlex.split(...
pick a callback command and call it without waiting for it to finish
f12591:c0:m46
def wait_for_port_open(self, postmaster, timeout):
for _ in polling_loop(timeout):<EOL><INDENT>with self._cancellable_lock:<EOL><INDENT>if self._is_cancelled:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>if not postmaster.is_running():<EOL><INDENT>logger.error('<STR_LIT>')<EOL>self.set_state('<STR_LIT>')<EOL>return False<EOL><DEDENT>isready = self.pg_isready()<EOL>if i...
Waits until PostgreSQL opens ports.
f12591:c0:m53
def _build_effective_configuration(self):
OPTIONS_MAPPING = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>if self._major_version >= <NUM_LIT>:<EOL><INDENT>OPTIONS_MAPPING['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>data = self.controldata()<EOL>effective_configuration = self._server_parameters.copy()<EOL>for na...
It might happen that the current value of one (or more) below parameters stored in the controldata is higher than the value stored in the global cluster configuration. Example: max_connections in global configuration is 100, but in controldata `Current max_connections setting: 200`. If we try t...
f12591:c0:m54
def start(self, timeout=None, task=None, block_callbacks=False, role=None):
<EOL>self.close_connection()<EOL>if self.is_running():<EOL><INDENT>logger.error('<STR_LIT>')<EOL>self.set_state('<STR_LIT>')<EOL>return True<EOL><DEDENT>if not block_callbacks:<EOL><INDENT>self.__cb_pending = ACTION_ON_START<EOL><DEDENT>self.set_role(role or self.get_postgres_role_from_data_directory())<EOL>self.set_st...
Start PostgreSQL Waits for postmaster to open ports or terminate so pg_isready can be used to check startup completion or failure. :returns: True if start was initiated and postmaster ports are open, False if start failed
f12591:c0:m55
def stop(self, mode='<STR_LIT>', block_callbacks=False, checkpoint=None, on_safepoint=None):
if checkpoint is None:<EOL><INDENT>checkpoint = False if mode == '<STR_LIT>' else True<EOL><DEDENT>success, pg_signaled = self._do_stop(mode, block_callbacks, checkpoint, on_safepoint)<EOL>if success:<EOL><INDENT>if not block_callbacks:<EOL><INDENT>self.set_state('<STR_LIT>')<EOL>if pg_signaled:<EOL><INDENT>self.call_n...
Stop PostgreSQL Supports a callback when a safepoint is reached. A safepoint is when no user backend can return a successful commit to users. Currently this means we wait for user backends to close. But in the future alternate mechanisms could be added. :param on_safepoint: This callba...
f12591:c0:m57
@staticmethod<EOL><INDENT>def terminate_starting_postmaster(postmaster):<DEDENT>
postmaster.signal_stop('<STR_LIT>')<EOL>postmaster.wait()<EOL>
Terminates a postmaster that has not yet opened ports or possibly even written a pid file. Blocks until the process goes away.
f12591:c0:m59
def check_for_startup(self):
return self.is_starting() and not self.check_startup_state_changed()<EOL>
Checks PostgreSQL status and returns if PostgreSQL is in the middle of startup.
f12591:c0:m62
def check_startup_state_changed(self):
ready = self.pg_isready()<EOL>if ready == STATE_REJECT:<EOL><INDENT>return False<EOL><DEDENT>elif ready == STATE_NO_RESPONSE:<EOL><INDENT>self.set_state('<STR_LIT>')<EOL>self._schedule_load_slots = False <EOL>if not self._running_custom_bootstrap:<EOL><INDENT>self.save_configuration_files() <EOL><DEDENT>return True<E...
Checks if PostgreSQL has completed starting up or failed or still starting. Should only be called when state == 'starting' :returns: True if state was changed from 'starting'
f12591:c0:m63
def wait_for_startup(self, timeout=None):
if not self.is_starting():<EOL><INDENT>logger.warning("<STR_LIT>")<EOL><DEDENT>while not self.check_startup_state_changed():<EOL><INDENT>with self._cancellable_lock:<EOL><INDENT>if self._is_cancelled:<EOL><INDENT>return None<EOL><DEDENT><DEDENT>if timeout and self.time_in_state() > timeout:<EOL><INDENT>return None<EOL>...
Waits for PostgreSQL startup to complete or fail. :returns: True if start was successful, False otherwise
f12591:c0:m64
def restart(self, timeout=None, task=None, block_callbacks=False, role=None):
self.set_state('<STR_LIT>')<EOL>if not block_callbacks:<EOL><INDENT>self.__cb_pending = ACTION_ON_RESTART<EOL><DEDENT>ret = self.stop(block_callbacks=True) and self.start(timeout, task, True, role)<EOL>if not ret and not self.is_starting():<EOL><INDENT>self.set_state('<STR_LIT>'.format(self.state))<EOL><DEDENT>return r...
Restarts PostgreSQL. When timeout parameter is set the call will block either until PostgreSQL has started, failed to start or timeout arrives. :returns: True when restart was successful and timeout did not expire when waiting.
f12591:c0:m65
def _replace_pg_hba(self):
<EOL>if self._running_custom_bootstrap:<EOL><INDENT>addresses = {'<STR_LIT>': '<STR_LIT>'}<EOL>if '<STR_LIT:host>' in self._local_address and not self._local_address['<STR_LIT:host>'].startswith('<STR_LIT:/>'):<EOL><INDENT>for _, _, _, _, sa in socket.getaddrinfo(self._local_address['<STR_LIT:host>'], self._local_addre...
Replace pg_hba.conf content in the PGDATA if hba_file is not defined in the `postgresql.parameters` and pg_hba is defined in `postgresql` configuration section. :returns: True if pg_hba.conf was rewritten.
f12591:c0:m69
def _replace_pg_ident(self):
if not self._server_parameters.get('<STR_LIT>') and self.config.get('<STR_LIT>'):<EOL><INDENT>with open(self._pg_ident_conf, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(self._CONFIG_WARNING_HEADER)<EOL>for line in self.config['<STR_LIT>']:<EOL><INDENT>f.write('<STR_LIT>'.format(line))<EOL><DEDENT><DEDENT>return True<EOL><...
Replace pg_ident.conf content in the PGDATA if ident_file is not defined in the `postgresql.parameters` and pg_ident is defined in the `postgresql` section. :returns: True if pg_ident.conf was rewritten.
f12591:c0:m70
def controldata(self):
result = {}<EOL>if self._version_file_exists() and self.state != '<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>env = {'<STR_LIT>': '<STR_LIT:C>', '<STR_LIT>': '<STR_LIT:C>', '<STR_LIT>': os.getenv('<STR_LIT>')}<EOL>if os.getenv('<STR_LIT>') is not None:<EOL><INDENT>env['<STR_LIT>'] = os.getenv('<STR_LIT>')<EOL><DEDENT>data...
return the contents of pg_controldata, or non-True value if pg_controldata call failed
f12591:c0:m75
def save_configuration_files(self):
try:<EOL><INDENT>for f in self._configuration_to_save:<EOL><INDENT>config_file = os.path.join(self._config_dir, f)<EOL>backup_file = os.path.join(self._data_dir, f + '<STR_LIT>')<EOL>if os.path.isfile(config_file):<EOL><INDENT>shutil.copy(config_file, backup_file)<EOL><DEDENT><DEDENT><DEDENT>except IOError:<EOL><INDENT...
copy postgresql.conf to postgresql.conf.backup to be able to retrive configuration files - originally stored as symlinks, those are normally skipped by pg_basebackup - in case of WAL-E basebackup (see http://comments.gmane.org/gmane.comp.db.postgresql.wal-e/239)
f12591:c0:m96
def restore_configuration_files(self):
try:<EOL><INDENT>for f in self._configuration_to_save:<EOL><INDENT>config_file = os.path.join(self._config_dir, f)<EOL>backup_file = os.path.join(self._data_dir, f + '<STR_LIT>')<EOL>if not os.path.isfile(config_file):<EOL><INDENT>if os.path.isfile(backup_file):<EOL><INDENT>shutil.copy(backup_file, config_file)<EOL><DE...
restore a previously saved postgresql.conf
f12591:c0:m97
def clone(self, clone_member):
self._rewind_state = REWIND_STATUS.INITIAL<EOL>ret = self.create_replica(clone_member) == <NUM_LIT:0><EOL>if ret:<EOL><INDENT>self._post_restore()<EOL>self._configure_server_parameters()<EOL><DEDENT>return ret<EOL>
- initialize the replica from an existing member (master or replica) - initialize the replica using the replica creation method that works without the replication connection (i.e. restore from on-disk base backup)
f12591:c0:m110
def bootstrap(self, config):
pg_hba = config.get('<STR_LIT>', [])<EOL>method = config.get('<STR_LIT>') or '<STR_LIT>'<EOL>self._running_custom_bootstrap = method != '<STR_LIT>' and method in config and '<STR_LIT>' in config[method]<EOL>if self._running_custom_bootstrap:<EOL><INDENT>do_initialize = self._custom_bootstrap<EOL>config = config[method]...
Initialize a new node from scratch and start it.
f12591:c0:m111
def pick_synchronous_standby(self, cluster):
current = cluster.sync.sync_standby<EOL>current = current.lower() if current else current<EOL>members = {m.name.lower(): m for m in cluster.members}<EOL>candidates = []<EOL>for app_name, state, sync_state in self.query(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(self.lsn_name)):<EOL><INDENT>member = members...
Finds the best candidate to be the synchronous standby. Current synchronous standby is always preferred, unless it has disconnected or does not want to be a synchronous standby any longer. :returns tuple of candidate name or None, and bool showing if the member is the active synchronous standb...
f12591:c0:m116
def set_synchronous_standby(self, name):
if name and name != '<STR_LIT:*>':<EOL><INDENT>name = quote_ident(name)<EOL><DEDENT>if name != self._synchronous_standby_names:<EOL><INDENT>if name is None:<EOL><INDENT>self._server_parameters.pop('<STR_LIT>', None)<EOL><DEDENT>else:<EOL><INDENT>self._server_parameters['<STR_LIT>'] = name<EOL><DEDENT>self._synchronous_...
Sets a node to be synchronous standby and if changed does a reload for PostgreSQL.
f12591:c0:m117
@staticmethod<EOL><INDENT>def postgres_version_to_int(pg_version):<DEDENT>
try:<EOL><INDENT>components = list(map(int, pg_version.split('<STR_LIT:.>')))<EOL><DEDENT>except ValueError:<EOL><INDENT>raise PostgresException('<STR_LIT>'.format(pg_version))<EOL><DEDENT>if len(components) < <NUM_LIT:2> or len(components) == <NUM_LIT:2> and components[<NUM_LIT:0>] < <NUM_LIT:10> or len(components) > ...
Convert the server_version to integer >>> Postgresql.postgres_version_to_int('9.5.3') 90503 >>> Postgresql.postgres_version_to_int('9.3.13') 90313 >>> Postgresql.postgres_version_to_int('10.1') 100001 >>> Postgresql.postgres_version_to_int('10') # doctest: +IGNO...
f12591:c0:m118
@staticmethod<EOL><INDENT>def postgres_major_version_to_int(pg_version):<DEDENT>
return Postgresql.postgres_version_to_int(pg_version + '<STR_LIT>')<EOL>
>>> Postgresql.postgres_major_version_to_int('10') 100000 >>> Postgresql.postgres_major_version_to_int('9.6') 90600
f12591:c0:m119
def read_postmaster_opts(self):
result = {}<EOL>try:<EOL><INDENT>with open(os.path.join(self._data_dir, '<STR_LIT>')) as f:<EOL><INDENT>data = f.read()<EOL>for opt in data.split('<STR_LIT>'):<EOL><INDENT>if '<STR_LIT:=>' in opt and opt.startswith('<STR_LIT>'):<EOL><INDENT>name, val = opt.split('<STR_LIT:=>', <NUM_LIT:1>)<EOL>result[name.strip('<STR_L...
returns the list of option names/values from postgres.opts, Empty dict if read failed or no file
f12591:c0:m120
def single_user_mode(self, command=None, options=None):
cmd = [self._pgcommand('<STR_LIT>'), '<STR_LIT>', '<STR_LIT>', self._data_dir]<EOL>for opt, val in sorted((options or {}).items()):<EOL><INDENT>cmd.extend(['<STR_LIT:-c>', '<STR_LIT>'.format(opt, val)])<EOL><DEDENT>cmd.append(self._database)<EOL>return self.cancellable_subprocess_call(cmd, communicate_input=command)<EO...
run a given command in a single-user mode. If the command is empty - then just start and stop
f12591:c0:m121
def schedule_sanity_checks_after_pause(self):
self._schedule_load_slots = self.use_slots<EOL>self._sysid = None<EOL>
After coming out of pause we have to: 1. sync replication slots, because it might happen that slots were removed 2. get new 'Database system identifier' to make sure that it wasn't changed
f12591:c0:m127
def polling_loop(timeout, interval=<NUM_LIT:1>):
start_time = time.time()<EOL>iteration = <NUM_LIT:0><EOL>end_time = start_time + timeout<EOL>while time.time() < end_time:<EOL><INDENT>yield iteration<EOL>iteration += <NUM_LIT:1><EOL>time.sleep(interval)<EOL><DEDENT>
Returns an iterator that returns values until timeout has passed. Timeout is measured from start of iteration.
f12616:m0
def before_feature(context, feature):
context.pctl.create_and_set_output_directory(feature.name)<EOL>
create per-feature output directory to collect Patroni and PostgreSQL logs
f12620:m2
def after_feature(context, feature):
context.pctl.stop_all()<EOL>shutil.rmtree(os.path.join(context.pctl.patroni_path, '<STR_LIT:data>'))<EOL>context.dcs_ctl.cleanup_service_tree()<EOL>if feature.status == '<STR_LIT>':<EOL><INDENT>shutil.copytree(context.pctl.output_dir, context.pctl.output_dir + '<STR_LIT>')<EOL><DEDENT>
stop all Patronis, remove their data directory and cleanup the keys in etcd
f12620:m3
@abc.abstractmethod<EOL><INDENT>def _is_accessible(self):<DEDENT>
process is accessible for queries
f12620:c0:m3
@abc.abstractmethod<EOL><INDENT>def _start(self):<DEDENT>
start process
f12620:c0:m4
def stop(self, kill=False, timeout=<NUM_LIT:15>):
super(AbstractDcsController, self).stop(kill=kill, timeout=timeout)<EOL>if self._work_directory:<EOL><INDENT>shutil.rmtree(self._work_directory)<EOL><DEDENT>
terminate process and wipe out the temp work directory, but only if we actually started it
f12620:c3:m2
@abc.abstractmethod<EOL><INDENT>def query(self, key, scope='<STR_LIT>'):<DEDENT>
query for a value of a given key
f12620:c3:m4
@abc.abstractmethod<EOL><INDENT>def cleanup_service_tree(self):<DEDENT>
clean all contents stored in the tree used for the tests
f12620:c3:m5
def main():
query = '<STR_LIT:U+0020>'.join(sys.stdin.readlines())<EOL>sys.stdout.write(pretty_print_graphql(query))<EOL>
Read a GraphQL query from standard input, and output it pretty-printed to standard output.
f12622:m0
def get_comparable_location_types(query_metadata_table):
return {<EOL>location: location_info.type.name<EOL>for location, location_info in query_metadata_table.registered_locations<EOL>}<EOL>
Return the dict of location -> GraphQL type name for each location in the query.
f12626:m1
def get_comparable_child_locations(query_metadata_table):
all_locations_with_possible_children = {<EOL>location: set(query_metadata_table.get_child_locations(location))<EOL>for location, _ in query_metadata_table.registered_locations<EOL>}<EOL>return {<EOL>location: child_locations<EOL>for location, child_locations in six.iteritems(all_locations_with_possible_children)<EOL>if...
Return the dict of location -> set of child locations for each location in the query.
f12626:m2
def get_comparable_revisits(query_metadata_table):
revisit_origins = {<EOL>query_metadata_table.get_revisit_origin(location)<EOL>for location, _ in query_metadata_table.registered_locations<EOL>}<EOL>intermediate_result = {<EOL>location: set(query_metadata_table.get_all_revisits(location))<EOL>for location in revisit_origins<EOL>}<EOL>return {<EOL>location: revisits<EO...
Return a dict location -> set of revisit locations for that starting location.
f12626:m3
def compute_child_and_revisit_locations(ir_blocks):
if not ir_blocks:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'.format(ir_blocks))<EOL><DEDENT>first_block = ir_blocks[<NUM_LIT:0>]<EOL>if not isinstance(first_block, blocks.QueryRoot):<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>.format(first_block, ir_blocks))<EOL><DEDENT>no_op_block_types = (<EOL>blocks.Filter...
Return dicts describing the parent-child and revisit relationships for all query locations. Args: ir_blocks: list of IR blocks describing the given query Returns: tuple of: dict mapping parent location -> set of child locations (guaranteed to be non-empty) dict mapping ...
f12626:m4
def setUp(self):
self.maxDiff = None<EOL>self.schema = get_schema()<EOL>
Initialize the test schema once for all tests, and disable max diff limits.
f12626:c0:m0
def setUp(self):
self.maxDiff = None<EOL>self.schema = get_schema()<EOL>
Disable max diff limits for all tests.
f12627:c0:m0
def setUp(self):
self.maxDiff = None<EOL>
Disable max diff limits for all tests.
f12627:c1:m0
def setUp(self):
self.maxDiff = None<EOL>
Disable max diff limits for all tests.
f12627:c2:m0
def setUp(self):
self.maxDiff = None<EOL>self.schema = get_schema()<EOL>
Initialize the test schema once for all tests, and disable max diff limits.
f12628:c0:m0