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_func<EOL>self.retry_exceptions = retry_exceptions<EOL> | 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.
:param max_jitter: Additional max jitter period to wait between retry attempts to avoid slamming the server.
:param max_delay: Maximum delay in seconds, regardless of other backoff settings. Defaults to one hour.
:param retry_exceptions: single exception or tuple | 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><INDENT>raise RetryFailedError("<STR_LIT>")<EOL><DEDENT>self._attempts += <NUM_LIT:1><EOL>sleeptime = self._cur_delay + (random.randint(<NUM_LIT:0>, self.max_jitter) / <NUM_LIT>)<EOL>if self._cur_stoptime is not None and time.time() + sleeptime >= self._cur_stoptime:<EOL><INDENT>raise RetryFailedError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>self.sleep_func(sleeptime)<EOL><DEDENT>self._cur_delay = min(self._cur_delay * self.backoff, self.max_delay)<EOL><DEDENT><DEDENT> | 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 throw one of the retryable exceptions | 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_LIT><EOL><DEDENT>else:<EOL><INDENT>primary_status_code = <NUM_LIT:200> if patroni.ha.is_leader() else <NUM_LIT><EOL><DEDENT>replica_status_code = <NUM_LIT:200> if not patroni.noloadbalance and response.get('<STR_LIT>') == '<STR_LIT>' else <NUM_LIT><EOL>status_code = <NUM_LIT><EOL>if patroni.ha.is_standby_cluster() and ('<STR_LIT>' in path or '<STR_LIT>' in path):<EOL><INDENT>status_code = <NUM_LIT:200> if patroni.ha.is_leader() else <NUM_LIT><EOL><DEDENT>elif '<STR_LIT>' in path or '<STR_LIT>' in path or '<STR_LIT>' in path or '<STR_LIT>' in path:<EOL><INDENT>status_code = primary_status_code<EOL><DEDENT>elif '<STR_LIT>' in path:<EOL><INDENT>status_code = replica_status_code<EOL><DEDENT>elif '<STR_LIT>' in path:<EOL><INDENT>status_code = <NUM_LIT:200> if primary_status_code == <NUM_LIT:200> else replica_status_code<EOL><DEDENT>elif cluster: <EOL><INDENT>is_synchronous = cluster.is_synchronous_mode() and cluster.syncand cluster.sync.sync_standby == patroni.postgresql.name<EOL>if path in ('<STR_LIT>', '<STR_LIT>') and is_synchronous:<EOL><INDENT>status_code = replica_status_code<EOL><DEDENT>elif path in ('<STR_LIT>', '<STR_LIT>') and not is_synchronous:<EOL><INDENT>status_code = replica_status_code<EOL><DEDENT><DEDENT>if write_status_code_only: <EOL><INDENT>message = self.responses[status_code][<NUM_LIT:0>]<EOL>self.wfile.write('<STR_LIT>'.format(self.protocol_version, status_code, message).encode('<STR_LIT:utf-8>'))<EOL><DEDENT>else:<EOL><INDENT>self._write_status_response(status_code, response)<EOL><DEDENT> | 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(action)<EOL>status_code = <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>status_code = None<EOL><DEDENT><DEDENT>except (ValueError, TypeError):<EOL><INDENT>logger.exception('<STR_LIT>', action, schedule)<EOL>error = '<STR_LIT>'<EOL>status_code = <NUM_LIT><EOL><DEDENT>return (status_code, error, scheduled_at)<EOL> | 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>return ret<EOL> | 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 should invoke `do_GET_uri1()`
POST /other should invoke `do_POST_other()`
If the `do_<REQUEST_METHOD>_<first_part_url>` method does not exists we'll fallback to original behavior. | 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:<EOL><INDENT>return {}<EOL><DEDENT> | 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(e))<EOL>return False<EOL><DEDENT>return None<EOL> | 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.create_replica_with_s3()<EOL><DEDENT>elif not should_use_s3:<EOL><INDENT>return ExitCode.FAIL<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>logger.exception("<STR_LIT>")<EOL><DEDENT>return ExitCode.FAIL<EOL> | 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:utf-8>').splitlines(),<EOL>dialect='<STR_LIT>')<EOL>rows = list(reader)<EOL>if not len(rows):<EOL><INDENT>logger.warning('<STR_LIT>')<EOL>return False<EOL><DEDENT>if len(rows) > <NUM_LIT:1>:<EOL><INDENT>logger.warning(<EOL>'<STR_LIT>',<EOL>rows)<EOL>return False<EOL><DEDENT>backup_info = rows[<NUM_LIT:0>]<EOL><DEDENT>except subprocess.CalledProcessError:<EOL><INDENT>logger.exception("<STR_LIT>")<EOL>return None<EOL><DEDENT>try:<EOL><INDENT>backup_size = int(backup_info['<STR_LIT>'])<EOL>backup_start_segment = backup_info['<STR_LIT>']<EOL>backup_start_offset = backup_info['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>logger.exception("<STR_LIT>")<EOL>return None<EOL><DEDENT>lsn_segment = backup_start_segment[<NUM_LIT:8>:<NUM_LIT:16>]<EOL>lsn_offset = hex((int(backup_start_segment[<NUM_LIT:16>:<NUM_LIT:32>], <NUM_LIT:16>) << <NUM_LIT>) + int(backup_start_offset))[<NUM_LIT:2>:-<NUM_LIT:1>]<EOL>backup_start_lsn = '<STR_LIT>'.format(lsn_segment, lsn_offset)<EOL>diff_in_bytes = backup_size<EOL>attempts_no = <NUM_LIT:0><EOL>while True:<EOL><INDENT>if self.master_connection:<EOL><INDENT>try:<EOL><INDENT>with psycopg2.connect(self.master_connection) as con:<EOL><INDENT>if con.server_version >= <NUM_LIT>:<EOL><INDENT>wal_name = '<STR_LIT>'<EOL>lsn_name = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>wal_name = '<STR_LIT>'<EOL>lsn_name = '<STR_LIT:location>'<EOL><DEDENT>con.autocommit = True<EOL>with con.cursor() as cur:<EOL><INDENT>cur.execute(("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>").format(wal_name, lsn_name),<EOL>(backup_start_lsn, backup_start_lsn, backup_start_lsn))<EOL>diff_in_bytes = int(cur.fetchone()[<NUM_LIT:0>])<EOL><DEDENT><DEDENT><DEDENT>except psycopg2.Error:<EOL><INDENT>logger.exception('<STR_LIT>')<EOL>if attempts_no < self.retries: <EOL><INDENT>attempts_no = attempts_no + <NUM_LIT:1><EOL>time.sleep(RETRY_SLEEP_INTERVAL)<EOL>continue<EOL><DEDENT>else:<EOL><INDENT>if not self.no_master:<EOL><INDENT>return False <EOL><DEDENT>logger.info("<STR_LIT>")<EOL>diff_in_bytes = <NUM_LIT:0><EOL>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>diff_in_bytes = <NUM_LIT:0><EOL><DEDENT>break<EOL><DEDENT>is_size_thresh_ok = diff_in_bytes < int(threshold_megabytes) * <NUM_LIT><EOL>threshold_pct_bytes = backup_size * threshold_percent / <NUM_LIT><EOL>is_percentage_thresh_ok = float(diff_in_bytes) < int(threshold_pct_bytes)<EOL>are_thresholds_ok = is_size_thresh_ok and is_percentage_thresh_ok<EOL>class Size(object):<EOL><INDENT>def __init__(self, n_bytes, prefix=None):<EOL><INDENT>self.n_bytes = n_bytes<EOL>self.prefix = prefix<EOL><DEDENT>def __repr__(self):<EOL><INDENT>if self.prefix is not None:<EOL><INDENT>n_bytes = size_as_bytes(self.n_bytes, self.prefix)<EOL><DEDENT>else:<EOL><INDENT>n_bytes = self.n_bytes<EOL><DEDENT>return repr_size(n_bytes)<EOL><DEDENT><DEDENT>class HumanContext(object):<EOL><INDENT>def __init__(self, items):<EOL><INDENT>self.items = items<EOL><DEDENT>def __repr__(self):<EOL><INDENT>return '<STR_LIT:U+002CU+0020>'.join('<STR_LIT>'.format(key, value)<EOL>for key, value in self.items)<EOL><DEDENT><DEDENT>human_context = repr(HumanContext([<EOL>('<STR_LIT>', Size(threshold_megabytes, '<STR_LIT:M>')),<EOL>('<STR_LIT>', threshold_percent),<EOL>('<STR_LIT>', Size(threshold_pct_bytes)),<EOL>('<STR_LIT>', Size(backup_size)),<EOL>('<STR_LIT>', Size(diff_in_bytes)),<EOL>('<STR_LIT>', is_size_thresh_ok),<EOL>('<STR_LIT>', is_percentage_thresh_ok),<EOL>]))<EOL>if not are_thresholds_ok:<EOL><INDENT>logger.info('<STR_LIT>'<EOL>'<STR_LIT>', human_context)<EOL><DEDENT>else:<EOL><INDENT>logger.info('<STR_LIT>', human_context)<EOL><DEDENT>return are_thresholds_ok<EOL> | 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_sync_state(self.state_handler.name, None, index=self.cluster.sync.index):<EOL><INDENT>logger.info('<STR_LIT>')<EOL>return<EOL><DEDENT><DEDENT>if self.is_synchronous_mode_strict() and picked is None:<EOL><INDENT>picked = '<STR_LIT:*>'<EOL>logger.warning("<STR_LIT>")<EOL><DEDENT>logger.info("<STR_LIT>", picked)<EOL>self.state_handler.set_synchronous_standby(picked)<EOL>if picked and picked != '<STR_LIT:*>' and not allow_promote:<EOL><INDENT>time.sleep(<NUM_LIT:2>)<EOL>picked, allow_promote = self.state_handler.pick_synchronous_standby(self.cluster)<EOL><DEDENT>if allow_promote:<EOL><INDENT>try:<EOL><INDENT>cluster = self.dcs.get_cluster()<EOL><DEDENT>except DCSError:<EOL><INDENT>return logger.warning("<STR_LIT>")<EOL><DEDENT>if cluster.sync.leader and cluster.sync.leader != self.state_handler.name:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return<EOL><DEDENT>if not self.dcs.write_sync_state(self.state_handler.name, picked, index=cluster.sync.index):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return<EOL><DEDENT>logger.info("<STR_LIT>", picked)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if self.cluster.sync.leader and self.dcs.delete_sync_state(index=self.cluster.sync.index):<EOL><INDENT>logger.info("<STR_LIT>")<EOL><DEDENT>self.state_handler.set_synchronous_standby(None)<EOL><DEDENT> | 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 set to that value. Or more simple, first set in postgresql.conf
and then in DCS. When removing, first remove in DCS, then in postgresql.conf. This is so we only consider
promoting standbys that were guaranteed to be replicating synchronously. | 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>):<EOL><INDENT>try:<EOL><INDENT>if not self.is_sync_standby(self.dcs.get_cluster()):<EOL><INDENT>break<EOL><DEDENT><DEDENT>except DCSError:<EOL><INDENT>logger.warning("<STR_LIT>")<EOL>break<EOL><DEDENT>logger.info("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.warning("<STR_LIT>")<EOL><DEDENT>return func()<EOL><DEDENT>finally:<EOL><INDENT>with self._member_state_lock:<EOL><INDENT>self._disable_sync -= <NUM_LIT:1><EOL><DEDENT><DEDENT> | 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 free.
If the connection to DCS fails we run the action anyway, as this is only a hint.
There is a small race window where this function runs between a master picking us the sync standby and
publishing it to the DCS. As the window is rather tiny consequences are holding up commits for one cycle
period we don't worry about it here. | 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.name, member.api_url, e)<EOL><DEDENT>return _MemberStatus.unknown(member)<EOL> | 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_timeline = self.state_handler.replica_cached_timeline(cluster_timeline)<EOL>if my_timeline < cluster_timeline:<EOL><INDENT>logger.info('<STR_LIT>', my_timeline, cluster_timeline)<EOL>return False<EOL><DEDENT><DEDENT>members = [m for m in members if m.name != self.state_handler.name and not m.nofailover and m.api_url]<EOL>if members:<EOL><INDENT>for st in self.fetch_nodes_statuses(members):<EOL><INDENT>if st.failover_limitation() is None:<EOL><INDENT>if not st.in_recovery:<EOL><INDENT>logger.warning('<STR_LIT>', st.member.name)<EOL>return False<EOL><DEDENT>if my_wal_position < st.wal_position:<EOL><INDENT>logger.info('<STR_LIT>', st.member.name)<EOL>return False<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return True<EOL> | 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, offline=False, async_req=True),<EOL>'<STR_LIT>': dict(stop='<STR_LIT>', checkpoint=False, release=False, offline=False, async_req=True),<EOL>}[mode]<EOL>self.state_handler.trigger_check_diverged_lsn()<EOL>self.state_handler.stop(mode_control['<STR_LIT>'], checkpoint=mode_control['<STR_LIT>'],<EOL>on_safepoint=self.watchdog.disable if self.watchdog.is_running else None)<EOL>self.state_handler.set_role('<STR_LIT>')<EOL>self.set_is_leader(False)<EOL>if mode_control['<STR_LIT>']:<EOL><INDENT>with self._async_executor:<EOL><INDENT>self.release_leader_key_voluntarily()<EOL><DEDENT>time.sleep(<NUM_LIT:2>) <EOL><DEDENT>if mode_control['<STR_LIT>']:<EOL><INDENT>node_to_follow, leader = None, None<EOL><DEDENT>else:<EOL><INDENT>cluster = self.dcs.get_cluster()<EOL>node_to_follow, leader = self._get_node_to_follow(cluster), cluster.leader<EOL><DEDENT>if mode_control['<STR_LIT>']:<EOL><INDENT>self._async_executor.schedule('<STR_LIT>')<EOL>self._async_executor.run_async(self.state_handler.follow, (node_to_follow,))<EOL><DEDENT>else:<EOL><INDENT>if self.is_synchronous_mode():<EOL><INDENT>self.state_handler.set_synchronous_standby(None)<EOL><DEDENT>if self.state_handler.rewind_or_reinitialize_needed_and_possible(leader):<EOL><INDENT>return False <EOL><DEDENT>self.state_handler.follow(node_to_follow)<EOL><DEDENT> | 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 we determine that we are not suitable for master and want to failover quickly
without regard for data durability. May only be called synchronously.
immediate-nolock is used when find out that we have lost the lock to be master. Need to bring down
PostgreSQL as quickly as possible without regard for data durability. May only be called synchronously. | 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>', index=failover.index))):<EOL><INDENT>return<EOL><DEDENT>if not failover.leader or failover.leader == self.state_handler.name:<EOL><INDENT>if not failover.candidate or failover.candidate != self.state_handler.name:<EOL><INDENT>if not failover.candidate and self.is_paused():<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if self.is_synchronous_mode():<EOL><INDENT>if failover.candidate and not self.cluster.sync.matches(failover.candidate):<EOL><INDENT>logger.warning('<STR_LIT>',<EOL>failover.candidate, self.cluster.sync.sync_standby)<EOL>members = []<EOL><DEDENT>else:<EOL><INDENT>members = [m for m in self.cluster.members if self.cluster.sync.matches(m.name)]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>members = [m for m in self.cluster.members<EOL>if not failover.candidate or m.name == failover.candidate]<EOL><DEDENT>if self.is_failover_possible(members): <EOL><INDENT>self._async_executor.schedule('<STR_LIT>')<EOL>self._async_executor.run_async(self.demote, ('<STR_LIT>',))<EOL>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>',<EOL>failover.leader, self.state_handler.name)<EOL><DEDENT>logger.info('<STR_LIT>')<EOL>self.dcs.manual_failover('<STR_LIT>', '<STR_LIT>', index=failover.index)<EOL> | 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.scheduled_at, failover.index)<EOL><DEDENT>else:<EOL><INDENT>logger.info('<STR_LIT>')<EOL>self.dcs.manual_failover('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT><DEDENT>self.load_cluster_from_dcs()<EOL>if self.is_standby_cluster():<EOL><INDENT>msg = '<STR_LIT>'<EOL>return self.enforce_follow_remote_master(msg)<EOL><DEDENT>else:<EOL><INDENT>return self.enforce_master_role(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return self.follow('<STR_LIT>',<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if bool(self.cluster.failover) or self.patroni.nofailover:<EOL><INDENT>self.state_handler.trigger_check_diverged_lsn()<EOL>time.sleep(<NUM_LIT:2>) <EOL><DEDENT>if self.patroni.nofailover:<EOL><INDENT>return self.follow('<STR_LIT>',<EOL>'<STR_LIT>')<EOL><DEDENT>return self.follow('<STR_LIT>',<EOL>'<STR_LIT>')<EOL><DEDENT> | 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>if prev is not None:<EOL><INDENT>return (False, prev + '<STR_LIT>')<EOL><DEDENT>self.recovering = True<EOL><DEDENT>timeout = restart_data.get('<STR_LIT>', self.patroni.config['<STR_LIT>'])<EOL>self.set_start_timeout(timeout)<EOL>do_restart = functools.partial(self.state_handler.restart, timeout, self._async_executor.critical_task)<EOL>if self.is_synchronous_mode() and not self.has_lock():<EOL><INDENT>do_restart = functools.partial(self.while_not_sync_standby, do_restart)<EOL><DEDENT>if run_async:<EOL><INDENT>self._async_executor.run_async(do_restart)<EOL>return (True, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>res = self._async_executor.run(do_restart)<EOL>if res:<EOL><INDENT>return (True, '<STR_LIT>')<EOL><DEDENT>elif res is None:<EOL><INDENT>return (False, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return (False, '<STR_LIT>')<EOL><DEDENT><DEDENT> | 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 self.update_lock():<EOL><INDENT>logger.info("<STR_LIT>")<EOL>self.demote('<STR_LIT>')<EOL>return '<STR_LIT>'<EOL><DEDENT>timeout = self._start_timeout or self.patroni.config['<STR_LIT>']<EOL>time_left = timeout - self.state_handler.time_in_state()<EOL>if time_left <= <NUM_LIT:0>:<EOL><INDENT>if self.is_failover_possible(self.cluster.members):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>self.demote('<STR_LIT>')<EOL>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>msg = self.process_manual_failover_from_leader()<EOL>if msg is not None:<EOL><INDENT>return msg<EOL><DEDENT>return '<STR_LIT>'.format(time_left)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return None<EOL><DEDENT> | 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 = member.conn_kwargs() if member else{k: cluster_params[k] for k in ('<STR_LIT:host>', '<STR_LIT:port>') if k in cluster_params}<EOL>if conn_kwargs:<EOL><INDENT>data['<STR_LIT>'] = conn_kwargs<EOL><DEDENT>return RemoteMember(name, data)<EOL><DEDENT> | 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.extend(['<STR_LIT>', self._superuser['<STR_LIT:username>']])<EOL><DEDENT>ret = subprocess.call(cmd)<EOL>return_codes = {<NUM_LIT:0>: STATE_RUNNING,<EOL><NUM_LIT:1>: STATE_REJECT,<EOL><NUM_LIT:2>: STATE_NO_RESPONSE,<EOL><NUM_LIT:3>: STATE_UNKNOWN}<EOL>return return_codes.get(ret, STATE_UNKNOWN)<EOL> | 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>except OSError:<EOL><INDENT>return False<EOL><DEDENT>return self.configuration_allows_rewind(self.controldata())<EOL> | 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>else:<EOL><INDENT>raise e<EOL><DEDENT><DEDENT>if self.state == '<STR_LIT>':<EOL><INDENT>raise RetryFailedError('<STR_LIT>')<EOL><DEDENT>raise PostgresConnectionException('<STR_LIT>')<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>r['<STR_LIT:host>'] = '<STR_LIT:localhost>' <EOL><DEDENT>if '<STR_LIT:user>' in r:<EOL><INDENT>user = r['<STR_LIT:user>'] + '<STR_LIT:@>'<EOL><DEDENT>else:<EOL><INDENT>user = '<STR_LIT>'<EOL>if '<STR_LIT:password>' in r:<EOL><INDENT>import getpass<EOL>r.setdefault('<STR_LIT:user>', os.environ.get('<STR_LIT>', getpass.getuser()))<EOL><DEDENT><DEDENT>connstring = '<STR_LIT>'.format(user, host, r['<STR_LIT:port>'], r['<STR_LIT>'])<EOL>env = self.write_pgpass(r) if '<STR_LIT:password>' in r else None<EOL>try:<EOL><INDENT>ret = self.cancellable_subprocess_call(shlex.split(cmd) + [connstring], env=env)<EOL><DEDENT>except OSError:<EOL><INDENT>logger.error('<STR_LIT>', cmd)<EOL>return False<EOL><DEDENT>if ret != <NUM_LIT:0>:<EOL><INDENT>logger.error('<STR_LIT>', cmd, ret)<EOL>return False<EOL><DEDENT><DEDENT>return True<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 clone_member and clone_member.conn_url:<EOL><INDENT>r = clone_member.conn_kwargs(self._replication)<EOL>connstring = '<STR_LIT>'.format(**r)<EOL>env = self.write_pgpass(r)<EOL><DEDENT>else:<EOL><INDENT>connstring = '<STR_LIT>'<EOL>env = os.environ.copy()<EOL>replica_methods =[r for r in replica_methods if self.replica_method_can_work_without_replication_connection(r)]<EOL><DEDENT>ret = <NUM_LIT:1><EOL>for replica_method in replica_methods:<EOL><INDENT>with self._cancellable_lock:<EOL><INDENT>if self._is_cancelled:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if replica_method == "<STR_LIT>":<EOL><INDENT>ret = self.basebackup(connstring, env, self.config.get(replica_method, {}))<EOL>if ret == <NUM_LIT:0>:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not self.data_directory_empty():<EOL><INDENT>if self.config.get(replica_method, {}).get('<STR_LIT>', False):<EOL><INDENT>logger.info('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self.remove_data_directory()<EOL><DEDENT><DEDENT>cmd = replica_method<EOL>method_config = {}<EOL>if self.config.get(replica_method, {}):<EOL><INDENT>method_config = self.config[replica_method].copy()<EOL>cmd = method_config.pop('<STR_LIT>', cmd)<EOL><DEDENT>if not method_config.get('<STR_LIT>', False):<EOL><INDENT>method_config.update({"<STR_LIT>": self.scope,<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": self._data_dir,<EOL>"<STR_LIT>": connstring})<EOL><DEDENT>else:<EOL><INDENT>for param in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>method_config.pop(param, None)<EOL><DEDENT><DEDENT>params = ["<STR_LIT>".format(arg, val) for arg, val in method_config.items()]<EOL>try:<EOL><INDENT>ret = self.cancellable_subprocess_call(shlex.split(cmd) + params, env=env)<EOL>if ret == <NUM_LIT:0>:<EOL><INDENT>logger.info('<STR_LIT>', replica_method)<EOL>break<EOL><DEDENT>else:<EOL><INDENT>logger.error('<STR_LIT>',<EOL>replica_method, cmd, ret)<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>logger.exception('<STR_LIT>', replica_method)<EOL>ret = <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>self.set_state('<STR_LIT>')<EOL>return ret<EOL> | 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_proc<EOL> | 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(self.callback[cb_name]) + [cb_name, self.role, self.scope]<EOL>self._callback_executor.call(cmd)<EOL><DEDENT>except Exception:<EOL><INDENT>logger.exception('<STR_LIT>', cmd, cb_name, self.role, self.scope)<EOL><DEDENT><DEDENT> | 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 isready != STATE_NO_RESPONSE:<EOL><INDENT>if isready not in [STATE_REJECT, STATE_RUNNING]:<EOL><INDENT>logger.warning("<STR_LIT>")<EOL><DEDENT>return True<EOL><DEDENT><DEDENT>logger.warning("<STR_LIT>")<EOL>return False<EOL> | 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 name, cname in OPTIONS_MAPPING.items():<EOL><INDENT>value = parse_int(effective_configuration[name])<EOL>cvalue = parse_int(data[cname])<EOL>if cvalue > value:<EOL><INDENT>effective_configuration[name] = cvalue<EOL>self._pending_restart = True<EOL><DEDENT><DEDENT>return effective_configuration<EOL> | 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 to start postgres with
max_connections=100, it will immediately exit.
As a workaround we will start it with the values from controldata and set `pending_restart`
to true as an indicator that current values of parameters are not matching expectations. | 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_state('<STR_LIT>')<EOL>self._pending_restart = False<EOL>configuration = self._server_parameters if self.role == '<STR_LIT>' else self._build_effective_configuration()<EOL>self._write_postgresql_conf(configuration)<EOL>self.resolve_connection_addresses()<EOL>self._replace_pg_hba()<EOL>self._replace_pg_ident()<EOL>options = ['<STR_LIT>'.format(p, configuration[p]) for p in self.CMDLINE_OPTIONS<EOL>if p in configuration and p != '<STR_LIT>']<EOL>with self._cancellable_lock:<EOL><INDENT>if self._is_cancelled:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>with task or null_context():<EOL><INDENT>if task and task.is_cancelled:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>return False<EOL><DEDENT>self._postmaster_proc = PostmasterProcess.start(self._pgcommand('<STR_LIT>'),<EOL>self._data_dir,<EOL>self._postgresql_conf,<EOL>options)<EOL>if task:<EOL><INDENT>task.complete(self._postmaster_proc)<EOL><DEDENT><DEDENT>start_timeout = timeout<EOL>if not start_timeout:<EOL><INDENT>try:<EOL><INDENT>start_timeout = float(self.config.get('<STR_LIT>', <NUM_LIT>))<EOL><DEDENT>except ValueError:<EOL><INDENT>start_timeout = <NUM_LIT><EOL><DEDENT><DEDENT>if not self._postmaster_proc or not self.wait_for_port_open(self._postmaster_proc, start_timeout):<EOL><INDENT>return False<EOL><DEDENT>ret = self.wait_for_startup(start_timeout)<EOL>if ret is not None:<EOL><INDENT>return ret<EOL><DEDENT>elif timeout is not None:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT> | 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_nowait(ACTION_ON_STOP)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>')<EOL>self.set_state('<STR_LIT>')<EOL><DEDENT>return success<EOL> | 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 callback is called when no user backends are running. | 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<EOL><DEDENT>else:<EOL><INDENT>if ready != STATE_RUNNING:<EOL><INDENT>logger.warning("<STR_LIT>",<EOL>"<STR_LIT>" if ready == STATE_UNKNOWN else "<STR_LIT>")<EOL><DEDENT>self.set_state('<STR_LIT>')<EOL>self._schedule_load_slots = self.use_slots<EOL>if not self._running_custom_bootstrap:<EOL><INDENT>self.save_configuration_files()<EOL><DEDENT>action = self.__cb_pending or ACTION_ON_START<EOL>self.call_nowait(action)<EOL>self.__cb_pending = None<EOL>return True<EOL><DEDENT> | 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><DEDENT>time.sleep(<NUM_LIT:1>)<EOL><DEDENT>return self.state == '<STR_LIT>'<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 ret<EOL> | 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_address['<STR_LIT:port>'],<EOL><NUM_LIT:0>, socket.SOCK_STREAM, socket.IPPROTO_TCP):<EOL><INDENT>addresses[sa[<NUM_LIT:0>] + '<STR_LIT>'] = '<STR_LIT:host>'<EOL><DEDENT><DEDENT>with open(self._pg_hba_conf, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(self._CONFIG_WARNING_HEADER)<EOL>for address, t in addresses.items():<EOL><INDENT>f.write((<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>).format(t, self._replication['<STR_LIT:username>'], self._superuser.get('<STR_LIT:username>') or '<STR_LIT:all>', address))<EOL><DEDENT><DEDENT><DEDENT>elif not self._server_parameters.get('<STR_LIT>') and self.config.get('<STR_LIT>'):<EOL><INDENT>with open(self._pg_hba_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><DEDENT> | 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><DEDENT> | 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 = subprocess.check_output([self._pgcommand('<STR_LIT>'), self._data_dir], env=env)<EOL>if data:<EOL><INDENT>data = data.decode('<STR_LIT:utf-8>').splitlines()<EOL>result = {l.split('<STR_LIT::>')[<NUM_LIT:0>].replace('<STR_LIT>', '<STR_LIT>', <NUM_LIT:1>): l.split('<STR_LIT::>', <NUM_LIT:1>)[<NUM_LIT:1>].strip() for l in data<EOL>if l and '<STR_LIT::>' in l}<EOL><DEDENT><DEDENT>except subprocess.CalledProcessError:<EOL><INDENT>logger.exception("<STR_LIT>")<EOL><DEDENT><DEDENT>return result<EOL> | 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>logger.exception('<STR_LIT>')<EOL><DEDENT>return True<EOL> | 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><DEDENT>elif f == '<STR_LIT>':<EOL><INDENT>open(config_file, '<STR_LIT:w>').close()<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except IOError:<EOL><INDENT>logger.exception('<STR_LIT>')<EOL><DEDENT> | 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]<EOL><DEDENT>else:<EOL><INDENT>do_initialize = self._initdb<EOL><DEDENT>return do_initialize(config) and self.append_pg_hba(pg_hba) and self.save_configuration_files()and self._configure_server_parameters() and self.start()<EOL> | 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.get(app_name)<EOL>if state != '<STR_LIT>' or not member or member.tags.get('<STR_LIT>', False):<EOL><INDENT>continue<EOL><DEDENT>if sync_state == '<STR_LIT>':<EOL><INDENT>return app_name, True<EOL><DEDENT>if sync_state == '<STR_LIT>' and app_name == current:<EOL><INDENT>return current, False<EOL><DEDENT>if sync_state in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>candidates.append(app_name)<EOL><DEDENT><DEDENT>if candidates:<EOL><INDENT>return candidates[<NUM_LIT:0>], False<EOL><DEDENT>return None, False<EOL> | 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 standby. | 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_standby_names = name<EOL>if self.state == '<STR_LIT>':<EOL><INDENT>self._write_postgresql_conf()<EOL>self.reload()<EOL><DEDENT><DEDENT> | 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) > <NUM_LIT:3>:<EOL><INDENT>raise PostgresException('<STR_LIT>'<EOL>.format(pg_version))<EOL><DEDENT>if len(components) == <NUM_LIT:2>:<EOL><INDENT>components.insert(<NUM_LIT:1>, <NUM_LIT:0>)<EOL><DEDENT>return int('<STR_LIT>'.join('<STR_LIT>'.format(c) for c in components))<EOL> | 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: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
PostgresException: 'Invalid PostgreSQL version format: X.Y or X.Y.Z is accepted: 10'
>>> Postgresql.postgres_version_to_int('9.6') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
PostgresException: 'Invalid PostgreSQL version format: X.Y or X.Y.Z is accepted: 9.6'
>>> Postgresql.postgres_version_to_int('a.b.c') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
PostgresException: 'Invalid PostgreSQL version: a.b.c' | 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_LIT:->')] = val.rstrip('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except IOError:<EOL><INDENT>logger.exception('<STR_LIT>')<EOL><DEDENT>return result<EOL> | 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)<EOL> | 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 child_locations<EOL>}<EOL> | 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<EOL>for location, revisits in six.iteritems(intermediate_result)<EOL>if revisits<EOL>}<EOL> | 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,<EOL>blocks.ConstructResult,<EOL>blocks.EndOptional,<EOL>blocks.OutputSource,<EOL>blocks.CoerceType,<EOL>)<EOL>current_location = None<EOL>traversed_or_recursed_or_folded = False<EOL>fold_started_at = None<EOL>top_level_locations = set()<EOL>parent_location = dict() <EOL>child_locations = dict() <EOL>revisits = dict() <EOL>query_path_to_revisit_origin = dict() <EOL>for block in ir_blocks[<NUM_LIT:1>:]:<EOL><INDENT>if isinstance(block, (blocks.Traverse, blocks.Fold, blocks.Recurse)):<EOL><INDENT>traversed_or_recursed_or_folded = True<EOL>if isinstance(block, blocks.Fold):<EOL><INDENT>fold_started_at = current_location<EOL><DEDENT><DEDENT>elif isinstance(block, blocks.Unfold):<EOL><INDENT>current_location = fold_started_at<EOL><DEDENT>elif isinstance(block, blocks.MarkLocation):<EOL><INDENT>if traversed_or_recursed_or_folded:<EOL><INDENT>block_parent_location = current_location<EOL><DEDENT>else:<EOL><INDENT>block_parent_location = parent_location.get(current_location, None)<EOL><DEDENT>if block_parent_location is not None:<EOL><INDENT>parent_location[block.location] = block_parent_location<EOL>child_locations.setdefault(block_parent_location, set()).add(block.location)<EOL><DEDENT>else:<EOL><INDENT>top_level_locations.add(current_location)<EOL><DEDENT>current_location = block.location<EOL>if isinstance(current_location, helpers.FoldScopeLocation):<EOL><INDENT>revisit_origin = None<EOL><DEDENT>elif isinstance(current_location, helpers.Location):<EOL><INDENT>if current_location.query_path not in query_path_to_revisit_origin:<EOL><INDENT>query_path_to_revisit_origin[current_location.query_path] = current_location<EOL>revisit_origin = None<EOL><DEDENT>else:<EOL><INDENT>revisit_origin = query_path_to_revisit_origin[current_location.query_path]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>.format(current_location, ir_blocks))<EOL><DEDENT>if revisit_origin is not None:<EOL><INDENT>revisits.setdefault(revisit_origin, set()).add(current_location)<EOL><DEDENT>traversed_or_recursed_or_folded = False<EOL><DEDENT>elif isinstance(block, blocks.Backtrack):<EOL><INDENT>current_location = block.location<EOL><DEDENT>elif isinstance(block, blocks.GlobalOperationsStart):<EOL><INDENT>current_location = None<EOL><DEDENT>elif isinstance(block, no_op_block_types):<EOL><INDENT>pass<EOL><DEDENT>elif isinstance(block, blocks.QueryRoot):<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>u'<STR_LIT>'.format(block, ir_blocks))<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError(u'<STR_LIT>'<EOL>.format(block, ir_blocks))<EOL><DEDENT><DEDENT>return child_locations, revisits<EOL> | 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 revisit origin -> set of revisits (possibly empty) | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.