signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def parse_string_table(self, tables): | self.info("<STR_LIT>" % (tables.tables, ))<EOL>for table in tables.tables:<EOL><INDENT>if table.table_name == "<STR_LIT>":<EOL><INDENT>for item in table.items:<EOL><INDENT>if len(item.data) > <NUM_LIT:0>:<EOL><INDENT>if len(item.data) == <NUM_LIT>:<EOL><INDENT>p = PlayerInfo()<EOL>ctypes.memmove(ctypes.addressof(p), it... | Need to pull out player information from string table | f12550:c3:m5 |
def parse_game_event(self, event): | if event.eventid in self.event_lookup:<EOL><INDENT>event_type = self.event_lookup[event.eventid]<EOL>ge = GameEvent(event_type.name)<EOL>for i, key in enumerate(event.keys):<EOL><INDENT>key_type = event_type.keys[i]<EOL>ge.keys[key_type.name] = getattr(key,<EOL>KEY_DATA_TYPES[key.type])<EOL><DEDENT>self.debug("<STR_LIT... | So CSVCMsg_GameEventList is a list of all events that can happen.
A game event has an eventid which maps to a type of event that happened | f12550:c3:m9 |
def parse(self): | self.important("<STR_LIT>" % (self.filename, ))<EOL>with open(self.filename, '<STR_LIT:rb>') as f:<EOL><INDENT>reader = Reader(StringIO(f.read()))<EOL>filestamp = reader.read(<NUM_LIT:8>)<EOL>offset = reader.read_int32()<EOL>if filestamp != "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>buff = Strin... | Parse a replay | f12550:c3:m10 |
def json_twisted_response(f): | def wrapper(*args, **kwargs):<EOL><INDENT>response = f(*args, **kwargs)<EOL>response.addCallback(lambda x: json.loads(x))<EOL>return response<EOL><DEDENT>wrapper.func = f<EOL>wrapper = util.mergeFunctionMetadata(f.func, wrapper)<EOL>return wrapper<EOL> | Parse the JSON from an API response. We do this in a decorator so that our
Twisted library can reuse the underlying functions | f12558:m0 |
def debug_dump(message, file_prefix="<STR_LIT>"): | global index<EOL>index += <NUM_LIT:1><EOL>with open("<STR_LIT>" % (file_prefix, index), '<STR_LIT:w>') as f:<EOL><INDENT>f.write(message.SerializeToString())<EOL>f.close()<EOL><DEDENT> | Utility while developing to dump message data to play with in the
interpreter | f12559:m0 |
def get_side_attr(attr, invert, player): | t = player.team<EOL>if invert:<EOL><INDENT>t = not player.team<EOL><DEDENT>return getattr(player, "<STR_LIT>" % ("<STR_LIT>" if t else "<STR_LIT>", attr))<EOL> | Get a player attribute that depends on which side the player is on.
A creep kill for a radiant hero is a badguy_kill, while a creep kill
for a dire hero is a goodguy_kill. | f12559:m1 |
def creep_kill(self, target, timestamp): | self.creep_kill_types[target] += <NUM_LIT:1><EOL>matched = False<EOL>for k, v in self.creep_types.iteritems():<EOL><INDENT>if target.startswith(k):<EOL><INDENT>matched = True<EOL>setattr(self, v, getattr(self, v) + <NUM_LIT:1>)<EOL>break<EOL><DEDENT><DEDENT>if not matched:<EOL><INDENT>print('<STR_LIT>'.format(target))<... | A creep was tragically killed. Need to split this into radiant/dire
and neutrals | f12559:c0:m3 |
def add_trigger(self, tick, fn): | self.triggers[tick].append(fn)<EOL> | When our tick count gets to <tick> then run fn | f12559:c1:m1 |
def calculate_kills(self): | aegises = deque(self.aegis)<EOL>next_aegis = aegises.popleft() if aegises else None<EOL>aegis_expires = None<EOL>active_aegis = None<EOL>real_kills = []<EOL>for kill in self.kills:<EOL><INDENT>if next_aegis and next_aegis[<NUM_LIT:0>] < kill["<STR_LIT>"]:<EOL><INDENT>active_aegis = next_aegis[<NUM_LIT:1>]<EOL>aegis_exp... | At the end of the game calculate kills/deaths, taking aegis into account
This has to be done at the end when we have a playerid : hero map | f12559:c1:m3 |
def parse_say_text(self, event): | if event.chat and event.format == "<STR_LIT>":<EOL><INDENT>self.chatlog.append((event.prefix, event.text))<EOL><DEDENT> | All chat | f12559:c1:m5 |
def parse_dota_um(self, event): | if event.type == dota_usermessages_pb2.CHAT_MESSAGE_AEGIS:<EOL><INDENT>self.aegis.append((self.tick, event.playerid_1))<EOL><DEDENT> | The chat messages that arrive when certain events occur.
The most useful ones are CHAT_MESSAGE_RUNE_PICKUP,
CHAT_MESSAGE_RUNE_BOTTLE, CHAT_MESSAGE_GLYPH_USED,
CHAT_MESSAGE_TOWER_KILL | f12559:c1:m7 |
def parse_user_message(self, user_message): | <EOL> | The combat summaries come through as CUserMsg_TextMsg objects | f12559:c1:m8 |
def parse_player_info(self, player): | if not player.ishltv:<EOL><INDENT>self.player_info[player.name] = {<EOL>"<STR_LIT>": player.userID,<EOL>"<STR_LIT>": player.guid,<EOL>"<STR_LIT>": player.fakeplayer,<EOL>}<EOL><DEDENT> | Parse a PlayerInfo struct. This arrives before a FileInfo message | f12559:c1:m9 |
def parse_file_info(self, file_info): | self.info["<STR_LIT>"] = file_info.playback_time<EOL>self.info["<STR_LIT>"] = file_info.game_info.dota.match_id<EOL>self.info["<STR_LIT>"] = file_info.game_info.dota.game_mode<EOL>self.info["<STR_LIT>"] = file_info.game_info.dota.game_winner<EOL>for index, player in enumerate(file_info.game_info.dota.player_info):<EOL>... | The CDemoFileInfo contains our winners as well as the length of the
demo | f12559:c1:m10 |
def parse_game_event(self, ge): | if ge.name == "<STR_LIT>":<EOL><INDENT>if ge.keys["<STR_LIT:type>"] == <NUM_LIT:4>:<EOL><INDENT>try:<EOL><INDENT>source = self.dp.combat_log_names.get(ge.keys["<STR_LIT>"],<EOL>"<STR_LIT>")<EOL>target = self.dp.combat_log_names.get(ge.keys["<STR_LIT>"],<EOL>"<STR_LIT>")<EOL>target_illusion = ge.keys["<STR_LIT>"]<EOL>ti... | Game events contain the combat log as well as 'chase_hero' events which
could be interesting | f12559:c1:m11 |
def load_heroes(): | filename = os.path.join(os.path.dirname(__file__), "<STR_LIT:data>", "<STR_LIT>")<EOL>with open(filename) as f:<EOL><INDENT>heroes = json.loads(f.read())["<STR_LIT:result>"]["<STR_LIT>"]<EOL>for hero in heroes:<EOL><INDENT>HEROES_CACHE[hero["<STR_LIT:id>"]] = hero<EOL><DEDENT><DEDENT> | Load hero details from JSON file into memoy | f12560:m0 |
def load_items(): | filename = os.path.join(os.path.dirname(__file__), "<STR_LIT:data>", "<STR_LIT>")<EOL>with open(filename) as f:<EOL><INDENT>items = json.loads(f.read())["<STR_LIT:result>"]["<STR_LIT>"]<EOL>for item in items:<EOL><INDENT>ITEMS_CACHE[item["<STR_LIT:id>"]] = item<EOL><DEDENT><DEDENT> | Load item details fom JSON file into memory | f12560:m1 |
def get_hero_name(id): | if not HEROES_CACHE:<EOL><INDENT>load_heroes()<EOL><DEDENT>return HEROES_CACHE.get(id)<EOL> | Get hero details from a hero id | f12560:m2 |
def get_item_name(id): | if not ITEMS_CACHE:<EOL><INDENT>load_items()<EOL><DEDENT>return ITEMS_CACHE.get(id)<EOL> | Get item details fom an item id | f12560:m3 |
def get_steam_id_32(steamid_64): | return steamid_64 - <NUM_LIT><EOL> | Get the 32 bit steam id from the 64 bit version | f12560:m4 |
def get_steam_id_64(steamid_32): | return steamid_32 + <NUM_LIT><EOL> | Get the 64 bit steam id from the 32 bit version | f12560:m5 |
def set_api_key(key): | global API_KEY<EOL>API_KEY = key<EOL> | Set your API key for all further API queries | f12563:m0 |
def url_map(base, params): | url = base<EOL>if not params:<EOL><INDENT>url.rstrip("<STR_LIT>")<EOL><DEDENT>elif '<STR_LIT:?>' not in url:<EOL><INDENT>url += "<STR_LIT:?>"<EOL><DEDENT>entries = []<EOL>for key, value in params.items():<EOL><INDENT>if value is not None:<EOL><INDENT>value = str(value)<EOL>entries.append("<STR_LIT>" % (quote_plus(key.e... | Return a URL with get parameters based on the params passed in
This is more forgiving than urllib.urlencode and will attempt to coerce
non-string objects into strings and automatically UTF-8 encode strings.
@param params: HTTP GET parameters | f12563:m1 |
def get_page(url): | import requests<EOL>logger.debug('<STR_LIT>' % (url, ))<EOL>return requests.get(url)<EOL> | Fetch a page | f12563:m2 |
def make_request(name, params=None, version="<STR_LIT>", key=None, api_type="<STR_LIT>",<EOL>fetcher=get_page, base=None, language="<STR_LIT>"): | params = params or {}<EOL>params["<STR_LIT:key>"] = key or API_KEY<EOL>params["<STR_LIT>"] = language<EOL>if not params["<STR_LIT:key>"]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>url = url_map("<STR_LIT>" % (base or BASE_URL, name, version), params)<EOL>return fetcher(url)<EOL> | Make an API request | f12563:m3 |
def json_request_response(f): | @wraps(f)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>response = f(*args, **kwargs)<EOL>response.raise_for_status()<EOL>return json.loads(response.content.decode('<STR_LIT:utf-8>'))<EOL><DEDENT>API_FUNCTIONS[f.__name__] = f<EOL>return wrapper<EOL> | Parse the JSON from an API response. We do this in a decorator so that our
Twisted library can reuse the underlying functions | f12563:m4 |
@json_request_response<EOL>def get_match_history(start_at_match_id=None, player_name=None, hero_id=None,<EOL>skill=<NUM_LIT:0>, date_min=None, date_max=None, account_id=None,<EOL>league_id=None, matches_requested=None, game_mode=None,<EOL>min_players=None, tournament_games_only=None,<EOL>**kwargs): | params = {<EOL>"<STR_LIT>": start_at_match_id,<EOL>"<STR_LIT>": player_name,<EOL>"<STR_LIT>": hero_id,<EOL>"<STR_LIT>": skill,<EOL>"<STR_LIT>": date_min,<EOL>"<STR_LIT>": date_max,<EOL>"<STR_LIT>": account_id,<EOL>"<STR_LIT>": league_id,<EOL>"<STR_LIT>": matches_requested,<EOL>"<STR_LIT>": game_mode,<EOL>"<STR_LIT>": m... | List of most recent 25 matches before start_at_match_id | f12563:m5 |
@json_request_response<EOL>def get_match_history_by_sequence_num(start_at_match_seq_num,<EOL>matches_requested=None, **kwargs): | params = {<EOL>"<STR_LIT>": start_at_match_seq_num,<EOL>"<STR_LIT>": matches_requested<EOL>}<EOL>return make_request("<STR_LIT>", params,<EOL>**kwargs)<EOL> | Most recent matches ordered by sequence number | f12563:m6 |
@json_request_response<EOL>def get_match_details(match_id, **kwargs): | return make_request("<STR_LIT>", {"<STR_LIT>": match_id}, **kwargs)<EOL> | Detailed information about a match | f12563:m7 |
@json_request_response<EOL>def get_steam_id(vanityurl, **kwargs): | params = {"<STR_LIT>": vanityurl}<EOL>return make_request("<STR_LIT>", params, version="<STR_LIT>",<EOL>base="<STR_LIT>", **kwargs)<EOL> | Get a players steam id from their steam name/vanity url | f12563:m8 |
@json_request_response<EOL>def get_player_summaries(players, **kwargs): | if (isinstance(players, list)):<EOL><INDENT>params = {'<STR_LIT>': '<STR_LIT:U+002C>'.join(str(p) for p in players)}<EOL><DEDENT>elif (isinstance(players, int)):<EOL><INDENT>params = {'<STR_LIT>': players}<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return make_request("<STR_LIT>", params, v... | Get players steam profile from their steam ids | f12563:m9 |
@json_request_response<EOL>def get_heroes(**kwargs): | return make_request("<STR_LIT>",<EOL>base="<STR_LIT>", **kwargs)<EOL> | Get a list of hero identifiers | f12563:m10 |
def get_hero_image_url(hero_name, image_size="<STR_LIT>"): | if hero_name.startswith("<STR_LIT>"):<EOL><INDENT>hero_name = hero_name[len("<STR_LIT>"):]<EOL><DEDENT>valid_sizes = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if image_size not in valid_sizes:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return "<STR_LIT>".format(<EOL>hero_name, ima... | Get a hero image based on name and image size | f12563:m11 |
def get_item_image_url(item_name, image_size="<STR_LIT>"): | return "<STR_LIT>".format(<EOL>item_name, image_size)<EOL> | Get an item image based on name | f12563:m12 |
@json_request_response<EOL>def get_live_league_games(**kwargs): | return make_request("<STR_LIT>", **kwargs)<EOL> | Get a list of currently live league games | f12563:m13 |
@json_request_response<EOL>def get_league_listing(**kwargs): | return make_request("<STR_LIT>", **kwargs)<EOL> | Get a list of leagues | f12563:m14 |
@json_request_response<EOL>def get_scheduled_league_games(**kwargs): | return make_request("<STR_LIT>", **kwargs)<EOL> | Get a list of scheduled league games | f12563:m15 |
def _load_config_file(self): | with open(self._config_file) as f:<EOL><INDENT>config = yaml.safe_load(f)<EOL>patch_config(config, self.__environment_configuration)<EOL>return config<EOL><DEDENT> | Loads config.yaml from filesystem and applies some values which were set via ENV | f12568:c0:m4 |
def watching(w, watch, max_count=None, clear=True): | if w and not watch:<EOL><INDENT>watch = <NUM_LIT:2><EOL><DEDENT>if watch and clear:<EOL><INDENT>click.clear()<EOL><DEDENT>yield <NUM_LIT:0><EOL>if max_count is not None and max_count < <NUM_LIT:1>:<EOL><INDENT>return<EOL><DEDENT>counter = <NUM_LIT:1><EOL>while watch and counter <= (max_count or counter):<EOL><INDENT>ti... | >>> len(list(watching(True, 1, 0)))
1
>>> len(list(watching(True, 1, 1)))
2
>>> len(list(watching(True, None, 0)))
1 | f12570:m8 |
def _do_failover_or_switchover(obj, action, cluster_name, master, candidate, force, scheduled=None): | dcs = get_dcs(obj, cluster_name)<EOL>cluster = dcs.get_cluster()<EOL>if action == '<STR_LIT>' and cluster.leader is None:<EOL><INDENT>raise PatroniCtlException('<STR_LIT>')<EOL><DEDENT>if master is None:<EOL><INDENT>if force or action == '<STR_LIT>':<EOL><INDENT>master = cluster.leader and cluster.leader.name<EOL><DEDE... | We want to trigger a failover or switchover for the specified cluster name.
We verify that the cluster name, master name and candidate name are correct.
If so, we trigger an action and keep the client up to date. | f12570:m22 |
def touch_member(config, dcs): | p = Postgresql(config['<STR_LIT>'])<EOL>p.set_state('<STR_LIT>')<EOL>p.set_role('<STR_LIT>')<EOL>def restapi_connection_string(config):<EOL><INDENT>protocol = '<STR_LIT>' if config.get('<STR_LIT>') else '<STR_LIT:http>'<EOL>connect_address = config.get('<STR_LIT>')<EOL>listen = config['<STR_LIT>']<EOL>return '<STR_LIT>... | Rip-off of the ha.touch_member without inter-class dependencies | f12570:m29 |
def set_defaults(config, cluster_name): | config['<STR_LIT>'].setdefault('<STR_LIT:name>', cluster_name)<EOL>config['<STR_LIT>'].setdefault('<STR_LIT>', cluster_name)<EOL>config['<STR_LIT>'].setdefault('<STR_LIT>', '<STR_LIT:127.0.0.1>')<EOL>config['<STR_LIT>']['<STR_LIT>'] = {'<STR_LIT>': None}<EOL>config['<STR_LIT>']['<STR_LIT>'] = '<STR_LIT::>' in config['<... | fill-in some basic configuration parameters if config file is not set | f12570:m30 |
@contextmanager<EOL>def temporary_file(contents, suffix='<STR_LIT>', prefix='<STR_LIT>'): | tmp = tempfile.NamedTemporaryFile(suffix=suffix, prefix=prefix, delete=False)<EOL>with tmp:<EOL><INDENT>tmp.write(contents)<EOL><DEDENT>try:<EOL><INDENT>yield tmp.name<EOL><DEDENT>finally:<EOL><INDENT>os.unlink(tmp.name)<EOL><DEDENT> | Creates a temporary file with specified contents that persists for the context.
:param contents: binary string that will be written to the file.
:param prefix: will be prefixed to the filename.
:param suffix: will be appended to the filename.
:returns path of the created file. | f12570:m37 |
def show_diff(before_editing, after_editing): | def listify(string):<EOL><INDENT>return [l+'<STR_LIT:\n>' for l in string.rstrip('<STR_LIT:\n>').split('<STR_LIT:\n>')]<EOL><DEDENT>unified_diff = difflib.unified_diff(listify(before_editing), listify(after_editing))<EOL>if sys.stdout.isatty():<EOL><INDENT>buf = io.StringIO()<EOL>for line in unified_diff:<EOL><INDENT>b... | Shows a diff between two strings.
If the output is to a tty the diff will be colored. Inputs are expected to be unicode strings. | f12570:m38 |
def format_config_for_editing(data): | return yaml.safe_dump(data, default_flow_style=False, encoding=None, allow_unicode=True)<EOL> | Formats configuration as YAML for human consumption.
:param data: configuration as nested dictionaries
:returns unicode YAML of the configuration | f12570:m39 |
def apply_config_changes(before_editing, data, kvpairs): | changed_data = copy.deepcopy(data)<EOL>def set_path_value(config, path, value, prefix=()):<EOL><INDENT>if prefix == ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>path = ['<STR_LIT:.>'.join(path)]<EOL><DEDENT>key = path[<NUM_LIT:0>]<EOL>if len(path) == <NUM_LIT:1>:<EOL><INDENT>if value is None:<EOL><INDENT>config.pop(key, Non... | Applies config changes specified as a list of key-value pairs.
Keys are interpreted as dotted paths into the configuration data structure. Except for paths beginning with
`postgresql.parameters` where rest of the path is used directly to allow for PostgreSQL GUCs containing dots.
Values are interpreted as ... | f12570:m40 |
def apply_yaml_file(data, filename): | changed_data = copy.deepcopy(data)<EOL>if filename == '<STR_LIT:->':<EOL><INDENT>new_options = yaml.safe_load(sys.stdin)<EOL><DEDENT>else:<EOL><INDENT>with open(filename) as fd:<EOL><INDENT>new_options = yaml.safe_load(fd)<EOL><DEDENT><DEDENT>patch_config(changed_data, new_options)<EOL>return format_config_for_editing(... | Applies changes from a YAML file to configuration
:param data: configuration datastructure
:param filename: name of the YAML file, - is taken to mean standard input
:returns tuple of human readable and parsed datastructure after changes | f12570:m41 |
def invoke_editor(before_editing, cluster_name): | editor_cmd = os.environ.get('<STR_LIT>')<EOL>if not editor_cmd:<EOL><INDENT>raise PatroniCtlException('<STR_LIT>')<EOL><DEDENT>with temporary_file(contents=before_editing.encode('<STR_LIT:utf-8>'),<EOL>suffix='<STR_LIT>',<EOL>prefix='<STR_LIT>'.format(cluster_name)) as tmpfile:<EOL><INDENT>ret = subprocess.call([editor... | Starts editor command to edit configuration in human readable format
:param before_editing: human representation before editing
:returns tuple of human readable and parsed datastructure after changes | f12570:m42 |
def reset(self): | self.is_cancelled = False<EOL>self.result = None<EOL> | Must be called every time the background task is finished.
Must be called from async thread. Caller must hold lock on async executor when calling. | f12573:c0:m1 |
def cancel(self): | if self.result is not None:<EOL><INDENT>return False<EOL><DEDENT>self.is_cancelled = True<EOL>return True<EOL> | Tries to cancel the task, returns True if the task has already run.
Caller must hold lock on async executor and the task when calling. | f12573:c0:m2 |
def complete(self, result): | self.result = result<EOL> | Mark task as completed along with a result.
Must be called from async thread. Caller must hold lock on task when calling. | f12573:c0:m3 |
@staticmethod<EOL><INDENT>def subsets_changed(last_observed_subsets, subsets):<DEDENT> | if len(last_observed_subsets) != len(subsets):<EOL><INDENT>return True<EOL><DEDENT>if subsets == []:<EOL><INDENT>return False<EOL><DEDENT>if len(last_observed_subsets[<NUM_LIT:0>].addresses or []) != <NUM_LIT:1> orlast_observed_subsets[<NUM_LIT:0>].addresses[<NUM_LIT:0>].ip != subsets[<NUM_LIT:0>].addresses[<NUM_LIT:0>... | >>> Kubernetes.subsets_changed([], [])
False
>>> Kubernetes.subsets_changed([], [k8s_client.V1EndpointSubset()])
True
>>> s1 = [k8s_client.V1EndpointSubset(addresses=[k8s_client.V1EndpointAddress(ip='1.2.3.4')])]
>>> s2 = [k8s_client.V1EndpointSubset(addresses=[k8s_client.V1EndpointAddress(ip='1.2.3.5')])]
>>> Kubernet... | f12574:c3:m10 |
def _write_leader_optime(self, last_operation): | Unused | f12574:c3:m14 | |
def _update_leader(self): | Unused | f12574:c3:m15 | |
def set_failover_value(self, value, index=None): | Unused | f12574:c3:m19 | |
def set_sync_state_value(self, value, index=None): | Unused | f12574:c3:m28 | |
def service_name_from_scope_name(scope_name): | def replace_char(match):<EOL><INDENT>c = match.group(<NUM_LIT:0>)<EOL>return '<STR_LIT:->' if c in '<STR_LIT>' else "<STR_LIT>".format(ord(c))<EOL><DEDENT>service_name = re.sub(r'<STR_LIT>', replace_char, scope_name.lower())<EOL>return service_name[<NUM_LIT:0>:<NUM_LIT>]<EOL> | Translate scope name to service name which can be used in dns.
230 = 253 - len('replica.') - len('.service.consul') | f12575:m2 |
def _do_refresh_session(self): | if self._session and self._last_session_refresh + self._loop_wait > time.time():<EOL><INDENT>return False<EOL><DEDENT>if self._session:<EOL><INDENT>try:<EOL><INDENT>self._client.session.renew(self._session)<EOL><DEDENT>except NotFound:<EOL><INDENT>self._session = None<EOL><DEDENT><DEDENT>ret = not self._session<EOL>if ... | :returns: `!True` if it had to create new session | f12575:c6:m8 |
def slot_name_from_member_name(member_name): | def replace_char(match):<EOL><INDENT>c = match.group(<NUM_LIT:0>)<EOL>return '<STR_LIT:_>' if c in '<STR_LIT>' else "<STR_LIT>".format(ord(c))<EOL><DEDENT>slot_name = re.sub('<STR_LIT>', replace_char, member_name.lower())<EOL>return slot_name[<NUM_LIT:0>:<NUM_LIT>]<EOL> | Translate member name to valid PostgreSQL slot name.
PostgreSQL replication slot names must be valid PostgreSQL names. This function maps the wider space of
member names to valid PostgreSQL names. Names are lowercased, dashes and periods common in hostnames
are replaced with underscores, other characters a... | f12576:m0 |
def parse_connection_string(value): | scheme, netloc, path, params, query, fragment = urlparse(value)<EOL>conn_url = urlunparse((scheme, netloc, path, params, '<STR_LIT>', fragment))<EOL>api_url = ([v for n, v in parse_qsl(query) if n == '<STR_LIT>'] or [None])[<NUM_LIT:0>]<EOL>return conn_url, api_url<EOL> | Original Governor stores connection strings for each cluster members if a following format:
postgres://{username}:{password}@{connect_address}/postgres
Since each of our patroni instances provides own REST API endpoint it's good to store this information
in DCS among with postgresql connection string. I... | f12576:m1 |
def dcs_modules(): | dcs_dirname = os.path.dirname(__file__)<EOL>module_prefix = __package__ + '<STR_LIT:.>'<EOL>if getattr(sys, '<STR_LIT>', False):<EOL><INDENT>importer = pkgutil.get_importer(dcs_dirname)<EOL>return [module for module in list(importer.toc) if module.startswith(module_prefix) and module.count('<STR_LIT:.>') == <NUM_LIT:2>... | Get names of DCS modules, depending on execution environment. If being packaged with PyInstaller,
modules aren't discoverable dynamically by scanning source directory because `FrozenImporter` doesn't
implement `iter_modules` method. But it is still possible to find all potential DCS modules by
iterating thr... | f12576:m2 |
@staticmethod<EOL><INDENT>def from_node(index, name, session, data):<DEDENT> | if data.startswith('<STR_LIT>'):<EOL><INDENT>conn_url, api_url = parse_connection_string(data)<EOL>data = {'<STR_LIT>': conn_url, '<STR_LIT>': api_url}<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>data = json.loads(data)<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>data = {}<EOL><DEDENT><DEDENT>return Memb... | >>> Member.from_node(-1, '', '', '{"conn_url": "postgres://foo@bar/postgres"}') is not None
True
>>> Member.from_node(-1, '', '', '{')
Member(index=-1, name='', session='', data={}) | f12576:c0:m0 |
@staticmethod<EOL><INDENT>def from_node(index, data, modify_index=None):<DEDENT> | try:<EOL><INDENT>data = json.loads(data)<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>data = None<EOL>modify_index = <NUM_LIT:0><EOL><DEDENT>if not isinstance(data, dict):<EOL><INDENT>data = {}<EOL><DEDENT>return ClusterConfig(index, data, index if modify_index is None else modify_index)<EOL> | >>> ClusterConfig.from_node(1, '{') is None
False | f12576:c4:m0 |
@staticmethod<EOL><INDENT>def from_node(index, value):<DEDENT> | if isinstance(value, dict):<EOL><INDENT>data = value<EOL><DEDENT>elif value:<EOL><INDENT>try:<EOL><INDENT>data = json.loads(value)<EOL>if not isinstance(data, dict):<EOL><INDENT>data = {}<EOL><DEDENT><DEDENT>except (TypeError, ValueError):<EOL><INDENT>data = {}<EOL><DEDENT><DEDENT>else:<EOL><INDENT>data = {}<EOL><DEDEN... | >>> SyncState.from_node(1, None).leader is None
True
>>> SyncState.from_node(1, '{}').leader is None
True
>>> SyncState.from_node(1, '{').leader is None
True
>>> SyncState.from_node(1, '[]').leader is None
True
>>> SyncState.from_node(1, '{"leader": "leader"}').leader == "leader"
True
>>> SyncState.from_node(1, {"leade... | f12576:c5:m0 |
def matches(self, name): | return name is not None and name in (self.leader, self.sync_standby)<EOL> | Returns if a node name matches one of the nodes in the sync state
>>> s = SyncState(1, 'foo', 'bar')
>>> s.matches('foo')
True
>>> s.matches('bar')
True
>>> s.matches('baz')
False
>>> s.matches(None)
False
>>> SyncState(1, None, None).matches('foo')
False | f12576:c5:m1 |
@staticmethod<EOL><INDENT>def from_node(index, value):<DEDENT> | try:<EOL><INDENT>lines = json.loads(value)<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>lines = None<EOL><DEDENT>if not isinstance(lines, list):<EOL><INDENT>lines = []<EOL><DEDENT>return TimelineHistory(index, value, lines)<EOL> | >>> h = TimelineHistory.from_node(1, 2)
>>> h.lines
[] | f12576:c6:m0 |
@property<EOL><INDENT>def timeline(self):<DEDENT> | if self.history:<EOL><INDENT>if self.history.lines:<EOL><INDENT>try:<EOL><INDENT>return int(self.history.lines[-<NUM_LIT:1>][<NUM_LIT:0>]) + <NUM_LIT:1><EOL><DEDENT>except Exception:<EOL><INDENT>logger.error('<STR_LIT>', self.history.lines)<EOL><DEDENT><DEDENT>elif self.history.value == '<STR_LIT>':<EOL><INDENT>return ... | >>> Cluster(0, 0, 0, 0, 0, 0, 0, 0).timeline
0
>>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[]')).timeline
1
>>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[["a"]]')).timeline
0 | f12576:c7:m9 |
def __init__(self, config): | self._name = config['<STR_LIT:name>']<EOL>self._base_path = re.sub('<STR_LIT>', '<STR_LIT:/>', '<STR_LIT:/>'.join(['<STR_LIT>', config.get('<STR_LIT>', '<STR_LIT>'), config['<STR_LIT>']]))<EOL>self._set_loop_wait(config.get('<STR_LIT>', <NUM_LIT:10>))<EOL>self._ctl = bool(config.get('<STR_LIT>', False))<EOL>self._clust... | :param config: dict, reference to config section of selected DCS.
i.e.: `zookeeper` for zookeeper, `etcd` for etcd, etc... | f12576:c8:m0 |
@abc.abstractmethod<EOL><INDENT>def set_ttl(self, ttl):<DEDENT> | Set the new ttl value for leader key | f12576:c8:m11 | |
@abc.abstractmethod<EOL><INDENT>def ttl(self):<DEDENT> | Get new ttl value | f12576:c8:m12 | |
@abc.abstractmethod<EOL><INDENT>def set_retry_timeout(self, retry_timeout):<DEDENT> | Set the new value for retry_timeout | f12576:c8:m13 | |
@abc.abstractmethod<EOL><INDENT>def _load_cluster(self):<DEDENT> | Internally this method should build `Cluster` object which
represents current state and topology of the cluster in DCS.
this method supposed to be called only by `get_cluster` method.
raise `~DCSError` in case of communication or other problems with DCS.
If the current node... | f12576:c8:m17 | |
@abc.abstractmethod<EOL><INDENT>def _write_leader_optime(self, last_operation):<DEDENT> | write current xlog location into `/optime/leader` key in DCS
:param last_operation: absolute xlog location in bytes
:returns: `!True` on success. | f12576:c8:m21 | |
@abc.abstractmethod<EOL><INDENT>def _update_leader(self):<DEDENT> | Update leader key (or session) ttl
:returns: `!True` if leader key (or session) has been updated successfully.
If not, `!False` must be returned and current instance would be demoted.
You have to use CAS (Compare And Swap) operation in order to update leader key,
for example for et... | f12576:c8:m23 | |
def update_leader(self, last_operation, access_is_restricted=False): | ret = self._update_leader()<EOL>if ret and last_operation:<EOL><INDENT>self.write_leader_optime(last_operation)<EOL><DEDENT>return ret<EOL> | Update leader key (or session) ttl and optime/leader
:param last_operation: absolute xlog location in bytes
:returns: `!True` if leader key (or session) has been updated successfully.
If not, `!False` must be returned and current instance would be demoted. | f12576:c8:m24 |
@abc.abstractmethod<EOL><INDENT>def attempt_to_acquire_leader(self, permanent=False):<DEDENT> | Attempt to acquire leader lock
This method should create `/leader` key with value=`~self._name`
:param permanent: if set to `!True`, the leader key will never expire.
Used in patronictl for the external master
:returns: `!True` if key has been created successfully.
Key must be ... | f12576:c8:m25 | |
@abc.abstractmethod<EOL><INDENT>def set_failover_value(self, value, index=None):<DEDENT> | Create or update `/failover` key | f12576:c8:m26 | |
@abc.abstractmethod<EOL><INDENT>def set_config_value(self, value, index=None):<DEDENT> | Create or update `/config` key | f12576:c8:m28 | |
@abc.abstractmethod<EOL><INDENT>def touch_member(self, data, permanent=False):<DEDENT> | Update member key in DCS.
This method should create or update key with the name = '/members/' + `~self._name`
and value = data in a given DCS.
:param data: information about instance (including connection strings)
:param ttl: ttl for member key, optional parameter. If it is None `~self.... | f12576:c8:m29 | |
@abc.abstractmethod<EOL><INDENT>def take_leader(self):<DEDENT> | This method should create leader key with value = `~self._name` and ttl=`~self.ttl`
Since it could be called only on initial cluster bootstrap it could create this key regardless,
overwriting the key if necessary. | f12576:c8:m30 | |
@abc.abstractmethod<EOL><INDENT>def initialize(self, create_new=True, sysid="<STR_LIT>"):<DEDENT> | Race for cluster initialization.
:param create_new: False if the key should already exist (in the case we are setting the system_id)
:param sysid: PostgreSQL cluster system identifier, if specified, is written to the key
:returns: `!True` if key has been created successfully.
this meth... | f12576:c8:m31 | |
@abc.abstractmethod<EOL><INDENT>def delete_leader(self):<DEDENT> | Voluntarily remove leader key from DCS
This method should remove leader key if current instance is the leader | f12576:c8:m32 | |
@abc.abstractmethod<EOL><INDENT>def cancel_initialization(self):<DEDENT> | Removes the initialize key for a cluster | f12576:c8:m33 | |
@abc.abstractmethod<EOL><INDENT>def delete_cluster(self):<DEDENT> | Delete cluster from DCS | f12576:c8:m34 | |
@staticmethod<EOL><INDENT>def sync_state(leader, sync_standby):<DEDENT> | return {'<STR_LIT>': leader, '<STR_LIT>': sync_standby}<EOL> | Build sync_state dict | f12576:c8:m35 |
def watch(self, leader_index, timeout): | self.event.wait(timeout)<EOL>return self.event.isSet()<EOL> | If the current node is a master it should just sleep.
Any other node should watch for changes of leader key with a given timeout
:param leader_index: index of a leader key
:param timeout: timeout in seconds
:returns: `!True` if you would like to reschedule the next run of ha cycle | f12576:c8:m40 |
@property<EOL><INDENT>def machines(self):<DEDENT> | kwargs = self._build_request_parameters()<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>response = self.http.request(self._MGET, self._base_uri + self.version_prefix + '<STR_LIT>', **kwargs)<EOL>data = self._handle_server_response(response).data.decode('<STR_LIT:utf-8>')<EOL>machines = [m.strip() for m in data.split('<S... | Original `machines` method(property) of `etcd.Client` class raise exception
when it failed to get list of etcd cluster members. This method is being called
only when request failed on one of the etcd members during `api_execute` call.
For us it's more important to execute original request rather... | f12577:c2:m3 |
def _get_machines_cache_from_srv(self, srv): | ret = []<EOL>for r in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>protocol = '<STR_LIT>' if '<STR_LIT>' in r else '<STR_LIT:http>'<EOL>endpoint = '<STR_LIT>' if '<STR_LIT>' in r else '<STR_LIT>'<EOL>for host, port in self.get_srv_record('<STR_LIT>'.format(r, srv)):<EOL><I... | Fetch list of etcd-cluster member by resolving _etcd-server._tcp. SRV record.
This record should contain list of host and peer ports which could be used to run
'GET http://{host}:{port}/members' request (peer protocol) | f12577:c2:m8 |
def _get_machines_cache_from_dns(self, host, port): | if self.protocol == '<STR_LIT:http>':<EOL><INDENT>ret = []<EOL>for af, _, _, _, sa in self._dns_resolver.resolve(host, port):<EOL><INDENT>host, port = sa[:<NUM_LIT:2>]<EOL>if af == socket.AF_INET6:<EOL><INDENT>host = '<STR_LIT>'.format(host)<EOL><DEDENT>ret.append(uri(self.protocol, host, port))<EOL><DEDENT>if ret:<EOL... | One host might be resolved into multiple ip addresses. We will make list out of it | f12577:c2:m9 |
def _load_machines_cache(self): | self._update_machines_cache = True<EOL>if '<STR_LIT>' not in self._config and '<STR_LIT:host>' not in self._config and '<STR_LIT>' not in self._config:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>self._machines_cache = self._get_machines_cache_from_config()<EOL>if not self._machines_cache:<EOL><INDENT>raise et... | This method should fill up `_machines_cache` from scratch.
It could happen only in two cases:
1. During class initialization
2. When all etcd members failed | f12577:c2:m11 |
def create_connection(self, *args, **kwargs): | args = list(args)<EOL>if len(args) == <NUM_LIT:0>: <EOL><INDENT>kwargs['<STR_LIT>'] = max(self._connect_timeout, kwargs.get('<STR_LIT>', self._connect_timeout*<NUM_LIT:10>)/<NUM_LIT>)<EOL><DEDENT>elif len(args) == <NUM_LIT:1>:<EOL><INDENT>args.append(self._connect_timeout)<EOL><DEDENT>else:<EOL><INDENT>args[<NUM_LIT:1... | This method is trying to establish connection with one of the zookeeper nodes.
Somehow strategy "fail earlier and retry more often" works way better comparing to
the original strategy "try to connect with specified timeout".
Since we want to try connect to zookeeper more often (with the... | f12578:c1:m2 |
def select(self, *args, **kwargs): | try:<EOL><INDENT>return super(PatroniSequentialThreadingHandler, self).select(*args, **kwargs)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise select.error(<NUM_LIT:9>, str(e))<EOL><DEDENT> | Python3 raises `ValueError` if socket is closed, because fd == -1 | f12578:c1:m3 |
def _kazoo_connect(self, host, port): | ret = self._orig_kazoo_connect(host, port)<EOL>return max(self.loop_wait - <NUM_LIT:2>, <NUM_LIT:2>)*<NUM_LIT:1000>, ret[<NUM_LIT:1>]<EOL> | Kazoo is using Ping's to determine health of connection to zookeeper. If there is no
response on Ping after Ping interval (1/2 from read_timeout) it will consider current
connection dead and try to connect to another node. Without this "magic" it was taking
up to 2/3 from session timeout (ttl) t... | f12578:c2:m1 |
def set_ttl(self, ttl): | if self._client._session_timeout != ttl:<EOL><INDENT>self._client._session_timeout = ttl<EOL>self._client.restart()<EOL>return True<EOL><DEDENT> | It is not possible to change ttl (session_timeout) in zookeeper without
destroying old session and creating the new one. This method returns `!True`
if session_timeout has been changed (`restart()` has been called). | f12578:c2:m5 |
def deep_compare(obj1, obj2): | if set(list(obj1.keys())) != set(list(obj2.keys())): <EOL><INDENT>return False<EOL><DEDENT>for key, value in obj1.items():<EOL><INDENT>if isinstance(value, dict):<EOL><INDENT>if not (isinstance(obj2[key], dict) and deep_compare(value, obj2[key])):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>elif str(value) != str(obj... | >>> deep_compare({'1': None}, {})
False
>>> deep_compare({'1': {}}, {'1': None})
False
>>> deep_compare({'1': [1]}, {'1': [2]})
False
>>> deep_compare({'1': 2}, {'1': '2'})
True
>>> deep_compare({'1': {'2': [3, 4]}}, {'1': {'2': [3, 4]}})
True | f12581:m0 |
def patch_config(config, data): | is_changed = False<EOL>for name, value in data.items():<EOL><INDENT>if value is None:<EOL><INDENT>if config.pop(name, None) is not None:<EOL><INDENT>is_changed = True<EOL><DEDENT><DEDENT>elif name in config:<EOL><INDENT>if isinstance(value, dict):<EOL><INDENT>if isinstance(config[name], dict):<EOL><INDENT>if patch_conf... | recursively 'patch' `config` with `data`
:returns: `!True` if the `config` was changed | f12581:m1 |
def parse_bool(value): | value = str(value).lower()<EOL>if value in ('<STR_LIT>', '<STR_LIT:true>', '<STR_LIT:yes>', '<STR_LIT:1>'):<EOL><INDENT>return True<EOL><DEDENT>if value in ('<STR_LIT>', '<STR_LIT:false>', '<STR_LIT>', '<STR_LIT:0>'):<EOL><INDENT>return False<EOL><DEDENT> | >>> parse_bool(1)
True
>>> parse_bool('off')
False
>>> parse_bool('foo') | f12581:m2 |
def strtol(value, strict=True): | value = str(value).strip()<EOL>ln = len(value)<EOL>i = <NUM_LIT:0><EOL>if i < ln and value[i] in ('<STR_LIT:->', '<STR_LIT:+>'):<EOL><INDENT>i += <NUM_LIT:1><EOL><DEDENT>if i < ln and value[i].isdigit():<EOL><INDENT>if value[i] == '<STR_LIT:0>':<EOL><INDENT>i += <NUM_LIT:1><EOL>if i < ln and value[i] in ('<STR_LIT:x>',... | As most as possible close equivalent of strtol(3) function (with base=0),
used by postgres to parse parameter values.
>>> strtol(0) == (0, '')
True
>>> strtol(1) == (1, '')
True
>>> strtol(9) == (9, '')
True
>>> strtol(' +0x400MB') == (1024, 'MB')
True
>>> strtol(' -070d') == ... | f12581:m3 |
def parse_int(value, base_unit=None): | convert = {<EOL>'<STR_LIT>': {'<STR_LIT>': <NUM_LIT:1>, '<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT> * <NUM_LIT>, '<STR_LIT>': <NUM_LIT> * <NUM_LIT> * <NUM_LIT>},<EOL>'<STR_LIT>': {'<STR_LIT>': <NUM_LIT:1>, '<STR_LIT:s>': <NUM_LIT:1000>, '<STR_LIT>': <NUM_LIT:1000> * <NUM_LIT>, '<STR_LIT:h>': <NUM_LIT:1000> * <NUM_LI... | >>> parse_int('1') == 1
True
>>> parse_int(' 0x400 MB ', '16384kB') == 64
True
>>> parse_int('1MB', 'kB') == 1024
True
>>> parse_int('1000 ms', 's') == 1
True
>>> parse_int('1GB', 'MB') is None
True
>>> parse_int(0) == 0
True | f12581:m4 |
def compare_values(vartype, unit, old_value, new_value): | <EOL>if vartype == '<STR_LIT:bool>':<EOL><INDENT>old_value = parse_bool(old_value)<EOL>new_value = parse_bool(new_value)<EOL><DEDENT>elif vartype == '<STR_LIT>':<EOL><INDENT>old_value = parse_int(old_value)<EOL>new_value = parse_int(new_value, unit)<EOL><DEDENT>elif vartype == '<STR_LIT>':<EOL><INDENT>return str(old_va... | >>> compare_values('enum', None, 'remote_write', 'REMOTE_WRITE')
True
>>> compare_values('real', None, '1.23', 1.23)
True | f12581:m5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.