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), item.data, <NUM_LIT>)<EOL>p.str = item.str<EOL>self.run_hooks(p)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if table.table_name == "<STR_LIT>":<EOL><INDENT>self.combat_log_names = dict(enumerate(<EOL>(item.str for item in table.items)))<EOL><DEDENT><DEDENT>
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>" % (ge, ))<EOL>self.run_hooks(ge)<EOL><DEDENT>
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 = StringIO(f.read())<EOL>frame = <NUM_LIT:0><EOL>more = True<EOL>while more and reader.remaining > <NUM_LIT:0>:<EOL><INDENT>cmd = reader.read_vint32()<EOL>tick = reader.read_vint32()<EOL>compressed = False<EOL>if cmd & demo_pb2.DEM_IsCompressed:<EOL><INDENT>compressed = True<EOL>cmd = cmd & ~demo_pb2.DEM_IsCompressed<EOL><DEDENT>if cmd not in messages.MESSAGE_TYPES:<EOL><INDENT>raise KeyError("<STR_LIT>")<EOL><DEDENT>message_type = messages.MESSAGE_TYPES[cmd]<EOL>message = reader.read_message(message_type, compressed)<EOL>self.info('<STR_LIT>' % (frame, message_type))<EOL>self.worthless(message)<EOL>self.run_hooks(message)<EOL>self.info('<STR_LIT>' % ('<STR_LIT:->' * <NUM_LIT>, ))<EOL>frame += <NUM_LIT:1><EOL>if self.frames and frame > self.frames:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>
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))<EOL><DEDENT>
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_expires = next_aegis[<NUM_LIT:0>] + <NUM_LIT> * <NUM_LIT:10> <EOL>self.indexed_players[active_aegis].aegises += <NUM_LIT:1><EOL>next_aegis = aegises.popleft() if aegises else None<EOL><DEDENT>elif aegis_expires and kill["<STR_LIT>"] > aegis_expires:<EOL><INDENT>active_aegis = None<EOL>aegis_expires = None<EOL><DEDENT>source = kill["<STR_LIT:source>"]<EOL>target = kill["<STR_LIT:target>"]<EOL>timestamp = kill["<STR_LIT>"]<EOL>if active_aegis == self.heroes[target].index:<EOL><INDENT>active_aegis = None<EOL>aegis_expires = None<EOL>self.heroes[target].aegis_deaths += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>real_kills.append(kill)<EOL>self.heroes[target].add_death(source, timestamp)<EOL>if target != source:<EOL><INDENT>self.heroes[source].add_kill(target, timestamp)<EOL><DEDENT><DEDENT><DEDENT>self.kills = real_kills<EOL>
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><INDENT>p = self.heroes[player.hero_name]<EOL>p.name = player.player_name<EOL>p.index = index<EOL>p.team = <NUM_LIT:0> if index < <NUM_LIT:5> else <NUM_LIT:1><EOL>self.indexed_players[index] = p<EOL>self.info["<STR_LIT>"][player.player_name] = p<EOL><DEDENT>
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>timestamp = ge.keys["<STR_LIT>"]<EOL>if (target.startswith("<STR_LIT>") and not<EOL>target_illusion):<EOL><INDENT>self.kills.append({<EOL>"<STR_LIT:target>": target,<EOL>"<STR_LIT:source>": source,<EOL>"<STR_LIT>": timestamp,<EOL>"<STR_LIT>": self.tick,<EOL>})<EOL><DEDENT>elif source.startswith("<STR_LIT>"):<EOL><INDENT>self.heroes[source].creep_kill(target, timestamp)<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>"""<STR_LIT>"""<EOL>pass<EOL><DEDENT><DEDENT><DEDENT>
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.encode("<STR_LIT:utf-8>")),<EOL>quote_plus(value.encode("<STR_LIT:utf-8>"))))<EOL><DEDENT><DEDENT>url += "<STR_LIT:&>".join(entries)<EOL>return str(url)<EOL>
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>": min_players,<EOL>"<STR_LIT>": tournament_games_only<EOL>}<EOL>return make_request("<STR_LIT>", params, **kwargs)<EOL>
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, version="<STR_LIT>",<EOL>base="<STR_LIT>", **kwargs)<EOL>
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, image_size)<EOL>
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>time.sleep(watch)<EOL>counter += <NUM_LIT:1><EOL>if clear:<EOL><INDENT>click.clear()<EOL><DEDENT>yield <NUM_LIT:0><EOL><DEDENT>
>>> 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><DEDENT>else:<EOL><INDENT>master = click.prompt('<STR_LIT>', type=str, default=cluster.leader.member.name)<EOL><DEDENT><DEDENT>if master is not None and cluster.leader and cluster.leader.member.name != master:<EOL><INDENT>raise PatroniCtlException('<STR_LIT>'.format(master, cluster_name))<EOL><DEDENT>candidate_names = [str(m.name) for m in cluster.members if m.name != master and not m.nofailover]<EOL>candidate_names.sort()<EOL>if not candidate_names:<EOL><INDENT>raise PatroniCtlException('<STR_LIT>'.format(action))<EOL><DEDENT>if candidate is None and not force:<EOL><INDENT>candidate = click.prompt('<STR_LIT>' + str(candidate_names), type=str, default='<STR_LIT>')<EOL><DEDENT>if action == '<STR_LIT>' and not candidate:<EOL><INDENT>raise PatroniCtlException('<STR_LIT>')<EOL><DEDENT>if candidate == master:<EOL><INDENT>raise PatroniCtlException(action.title() + '<STR_LIT>')<EOL><DEDENT>if candidate and candidate not in candidate_names:<EOL><INDENT>raise PatroniCtlException('<STR_LIT>'.format(candidate, cluster_name))<EOL><DEDENT>scheduled_at_str = None<EOL>scheduled_at = None<EOL>if action == '<STR_LIT>':<EOL><INDENT>if scheduled is None and not force:<EOL><INDENT>scheduled = click.prompt('<STR_LIT>',<EOL>type=str, default='<STR_LIT>')<EOL><DEDENT>scheduled_at = parse_scheduled(scheduled)<EOL>if scheduled_at:<EOL><INDENT>if cluster.is_paused():<EOL><INDENT>raise PatroniCtlException("<STR_LIT>")<EOL><DEDENT>scheduled_at_str = scheduled_at.isoformat()<EOL><DEDENT><DEDENT>failover_value = {'<STR_LIT>': master, '<STR_LIT>': candidate, '<STR_LIT>': scheduled_at_str}<EOL>logging.debug(failover_value)<EOL>click.echo('<STR_LIT>')<EOL>output_members(dcs.get_cluster(), cluster_name)<EOL>if not force:<EOL><INDENT>demote_msg = '<STR_LIT>' + master if master else '<STR_LIT>'<EOL>if not click.confirm('<STR_LIT>'.format(action, cluster_name, demote_msg)):<EOL><INDENT>raise PatroniCtlException('<STR_LIT>' + action)<EOL><DEDENT><DEDENT>r = None<EOL>try:<EOL><INDENT>member = cluster.leader.member if cluster.leader else cluster.get_member(candidate, False)<EOL>r = request_patroni(member, '<STR_LIT>', action, failover_value, auth_header(obj))<EOL>if r.status_code == <NUM_LIT> and action == '<STR_LIT>' and '<STR_LIT>' in r.text:<EOL><INDENT>r = request_patroni(member, '<STR_LIT>', '<STR_LIT>', failover_value, auth_header(obj))<EOL><DEDENT>if r.status_code in (<NUM_LIT:200>, <NUM_LIT>):<EOL><INDENT>logging.debug(r)<EOL>cluster = dcs.get_cluster()<EOL>logging.debug(cluster)<EOL>click.echo('<STR_LIT>'.format(timestamp(), r.text))<EOL><DEDENT>else:<EOL><INDENT>click.echo('<STR_LIT>'.format(action.title(), r.status_code, r.text))<EOL>return<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>logging.exception(r)<EOL>logging.warning('<STR_LIT>')<EOL>click.echo('<STR_LIT>'.format(timestamp(), action))<EOL>dcs.manual_failover(master, candidate, scheduled_at=scheduled_at)<EOL><DEDENT>output_members(cluster, cluster_name)<EOL>
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>'.format(protocol, connect_address or listen)<EOL><DEDENT>data = {<EOL>'<STR_LIT>': p.connection_string,<EOL>'<STR_LIT>': restapi_connection_string(config['<STR_LIT>']),<EOL>'<STR_LIT:state>': p.state,<EOL>'<STR_LIT>': p.role<EOL>}<EOL>return dcs.touch_member(data, permanent=True)<EOL>
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['<STR_LIT>']['<STR_LIT>'] and config['<STR_LIT>']['<STR_LIT>'] or '<STR_LIT>'<EOL>
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>buf.write(text_type(line))<EOL><DEDENT>buf.seek(<NUM_LIT:0>)<EOL>class opts:<EOL><INDENT>side_by_side = False<EOL>width = <NUM_LIT><EOL>tab_width = <NUM_LIT:8><EOL><DEDENT>cdiff.markup_to_pager(cdiff.PatchStream(buf), opts)<EOL><DEDENT>else:<EOL><INDENT>for line in unified_diff:<EOL><INDENT>click.echo(line.rstrip('<STR_LIT:\n>'))<EOL><DEDENT><DEDENT>
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, None)<EOL><DEDENT>else:<EOL><INDENT>config[key] = value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not isinstance(config.get(key), dict):<EOL><INDENT>config[key] = {}<EOL><DEDENT>set_path_value(config[key], path[<NUM_LIT:1>:], value, prefix + (key,))<EOL>if config[key] == {}:<EOL><INDENT>del config[key]<EOL><DEDENT><DEDENT><DEDENT>for pair in kvpairs:<EOL><INDENT>if not pair or "<STR_LIT:=>" not in pair:<EOL><INDENT>raise PatroniCtlException("<STR_LIT>".format(pair))<EOL><DEDENT>key_path, value = pair.split("<STR_LIT:=>", <NUM_LIT:1>)<EOL>set_path_value(changed_data, key_path.strip().split("<STR_LIT:.>"), yaml.safe_load(value))<EOL><DEDENT>return format_config_for_editing(changed_data), changed_data<EOL>
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 YAML values. :param before_editing: human representation before editing :param data: configuration datastructure :param kvpairs: list of strings containing key value pairs separated by = :returns tuple of human readable and parsed datastructure after changes
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(changed_data), changed_data<EOL>
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_cmd, tmpfile])<EOL>if ret:<EOL><INDENT>raise PatroniCtlException("<STR_LIT>".format(ret))<EOL><DEDENT>with codecs.open(tmpfile, encoding='<STR_LIT:utf-8>') as fd:<EOL><INDENT>after_editing = fd.read()<EOL><DEDENT>return after_editing, yaml.safe_load(after_editing)<EOL><DEDENT>
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>].ip orlen(last_observed_subsets[<NUM_LIT:0>].ports) != len(subsets[<NUM_LIT:0>].ports):<EOL><INDENT>return True<EOL><DEDENT>if len(subsets[<NUM_LIT:0>].ports) == <NUM_LIT:1>:<EOL><INDENT>return not Kubernetes.compare_ports(last_observed_subsets[<NUM_LIT:0>].ports[<NUM_LIT:0>], subsets[<NUM_LIT:0>].ports[<NUM_LIT:0>])<EOL><DEDENT>observed_ports = {p.name: p for p in last_observed_subsets[<NUM_LIT:0>].ports}<EOL>for p in subsets[<NUM_LIT:0>].ports:<EOL><INDENT>if p.name not in observed_ports or not Kubernetes.compare_ports(p, observed_ports.pop(p.name)):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
>>> 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')])] >>> Kubernetes.subsets_changed(s1, s2) True >>> a = [k8s_client.V1EndpointAddress(ip='1.2.3.4')] >>> s1 = [k8s_client.V1EndpointSubset(addresses=a, ports=[k8s_client.V1EndpointPort(protocol='TCP', port=1)])] >>> s2 = [k8s_client.V1EndpointSubset(addresses=a, ports=[k8s_client.V1EndpointPort(port=5432)])] >>> Kubernetes.subsets_changed(s1, s2) True >>> p1 = k8s_client.V1EndpointPort(name='port1', port=1) >>> p2 = k8s_client.V1EndpointPort(name='port2', port=2) >>> p3 = k8s_client.V1EndpointPort(name='port3', port=3) >>> s1 = [k8s_client.V1EndpointSubset(addresses=a, ports=[p1, p2])] >>> s2 = [k8s_client.V1EndpointSubset(addresses=a, ports=[p2, p3])] >>> Kubernetes.subsets_changed(s1, s2) True >>> s2 = [k8s_client.V1EndpointSubset(addresses=a, ports=[p2, p1])] >>> Kubernetes.subsets_changed(s1, s2) False
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 ret:<EOL><INDENT>try:<EOL><INDENT>self._session = self._client.session.create(name=self._scope + '<STR_LIT:->' + self._name,<EOL>checks=self.__session_checks,<EOL>lock_delay=<NUM_LIT>, behavior='<STR_LIT>')<EOL><DEDENT>except InvalidSessionTTL:<EOL><INDENT>logger.exception('<STR_LIT>')<EOL>self.adjust_ttl()<EOL>raise<EOL><DEDENT><DEDENT>self._last_session_refresh = time.time()<EOL>return ret<EOL>
: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 are encoded as their unicode codepoint. Name is truncated to 64 characters. Multiple different member names may map to a single slot name.
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. In order to not introduce new keys and be compatible with original Governor we decided to extend original connection string in a following way: postgres://{username}:{password}@{connect_address}/postgres?application_name={api_url} This way original Governor could use such connection string as it is, because of feature of `libpq` library. This method is able to split connection string stored in DCS into two parts, `conn_url` and `api_url`
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>]<EOL><DEDENT>else:<EOL><INDENT>return [module_prefix + name for _, name, is_pkg in pkgutil.iter_modules([dcs_dirname]) if not is_pkg]<EOL><DEDENT>
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 through `toc`, which contains list of all "frozen" resources.
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 Member(index, name, session, data)<EOL>
>>> 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><DEDENT>return SyncState(index, data.get('<STR_LIT>'), data.get('<STR_LIT>'))<EOL>
>>> 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, {"leader": "leader"}).leader == "leader" True
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 <NUM_LIT:1><EOL><DEDENT><DEDENT>return <NUM_LIT:0><EOL>
>>> 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._cluster = None<EOL>self._cluster_valid_till = <NUM_LIT:0><EOL>self._cluster_thread_lock = Lock()<EOL>self._last_leader_operation = '<STR_LIT>'<EOL>self.event = Event()<EOL>
: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 was running as a master and exception raised, instance would be demoted.
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 etcd `prevValue` parameter must be used.
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 created atomically. In case if key already exists it should not be overwritten and `!False` must be returned
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.member_ttl will be used` :param permanent: if set to `!True`, the member key will never expire. Used in patronictl for the external master. :returns: `!True` on success otherwise `!False`
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 method should create atomically initialize key and return `!True` otherwise it should return `!False`
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('<STR_LIT:U+002C>') if m.strip()]<EOL>logger.debug("<STR_LIT>", machines)<EOL>if not machines:<EOL><INDENT>raise etcd.EtcdException<EOL><DEDENT>random.shuffle(machines)<EOL>for url in machines:<EOL><INDENT>r = urlparse(url)<EOL>port = r.port or (<NUM_LIT> if r.scheme == '<STR_LIT>' else <NUM_LIT>)<EOL>self._dns_resolver.resolve_async(r.hostname, port)<EOL><DEDENT>return machines<EOL><DEDENT>except Exception as e:<EOL><INDENT>logger.error("<STR_LIT>", self._base_uri, self.version_prefix, e)<EOL>if self._machines_cache:<EOL><INDENT>self._base_uri = self._machines_cache.pop(<NUM_LIT:0>)<EOL>logger.info("<STR_LIT>", self._base_uri)<EOL><DEDENT>elif self._update_machines_cache:<EOL><INDENT>raise etcd.EtcdException("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT><DEDENT><DEDENT>
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 then get new topology of etcd cluster. So we will catch this exception and return empty list of machines. Later, during next `api_execute` call we will forcefully update machines_cache. Also this method implements the same timeout-retry logic as `api_execute`, because the original method was retrying 2 times with the `read_timeout` on each node.
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><INDENT>url = uri(protocol, host, port, endpoint)<EOL>if endpoint:<EOL><INDENT>try:<EOL><INDENT>response = requests.get(url, timeout=self.read_timeout, verify=False)<EOL>if response.ok:<EOL><INDENT>for member in response.json():<EOL><INDENT>ret.extend(member['<STR_LIT>'])<EOL><DEDENT>break<EOL><DEDENT><DEDENT>except RequestException:<EOL><INDENT>logger.exception('<STR_LIT>', url)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ret.append(url)<EOL><DEDENT><DEDENT>if ret:<EOL><INDENT>self._protocol = protocol<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>logger.warning('<STR_LIT>', srv)<EOL><DEDENT>return list(set(ret))<EOL>
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><INDENT>return list(set(ret))<EOL><DEDENT><DEDENT>return [uri(self.protocol, host, port)]<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 etcd.EtcdException<EOL><DEDENT>self._base_uri = self._next_server()<EOL>self._refresh_machines_cache()<EOL>self._update_machines_cache = False<EOL>self._machines_cache_updated = time.time()<EOL>
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>] = max(self._connect_timeout, args[<NUM_LIT:1>]/<NUM_LIT>)<EOL><DEDENT>return super(PatroniSequentialThreadingHandler, self).create_connection(*args, **kwargs)<EOL>
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 smaller connect_timeout), he have to override `create_connection` method in the `SequentialThreadingHandler` class (which is used by `kazoo.Client`). :param args: always contains `tuple(host, port)` as the first element and could contain `connect_timeout` (negotiated session timeout) as the second element.
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) to figure out that connection was dead and we had only small time for reconnect and retry. This method is needed to return different value of read_timeout, which is not calculated from negotiated session timeout but from value of `loop_wait`. And it is 2 sec smaller than loop_wait, because we can spend up to 2 seconds when calling `touch_member()` and `write_leader_optime()` methods, which also may hang...
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(obj2[key]):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
>>> 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_config(config[name], value):<EOL><INDENT>is_changed = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>config[name] = value<EOL>is_changed = True<EOL><DEDENT><DEDENT>elif str(config[name]) != str(value):<EOL><INDENT>config[name] = value<EOL>is_changed = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>config[name] = value<EOL>is_changed = True<EOL><DEDENT><DEDENT>return is_changed<EOL>
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>', '<STR_LIT:X>'): <EOL><INDENT>base = <NUM_LIT:16><EOL>i += <NUM_LIT:1><EOL><DEDENT>else: <EOL><INDENT>base = <NUM_LIT:8><EOL><DEDENT><DEDENT>else: <EOL><INDENT>base = <NUM_LIT:10><EOL><DEDENT>ret = None<EOL>while i <= ln:<EOL><INDENT>try: <EOL><INDENT>i += <NUM_LIT:1> <EOL>ret = int(value[:i], base)<EOL><DEDENT>except ValueError: <EOL><INDENT>i -= <NUM_LIT:1><EOL>break<EOL><DEDENT><DEDENT>if ret is not None: <EOL><INDENT>return ret, value[i:].strip() <EOL><DEDENT><DEDENT>return (None if strict else <NUM_LIT:1>), value.strip()<EOL>
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') == (-56, 'd') True >>> strtol(' d ') == (None, 'd') True >>> strtol('9s', False) == (9, 's') True >>> strtol(' s ', False) == (1, 's') True
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_LIT> * <NUM_LIT>, '<STR_LIT:d>': <NUM_LIT:1000> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT>},<EOL>'<STR_LIT:s>': {'<STR_LIT>': -<NUM_LIT:1000>, '<STR_LIT:s>': <NUM_LIT:1>, '<STR_LIT>': <NUM_LIT>, '<STR_LIT:h>': <NUM_LIT> * <NUM_LIT>, '<STR_LIT:d>': <NUM_LIT> * <NUM_LIT> * <NUM_LIT>},<EOL>'<STR_LIT>': {'<STR_LIT>': -<NUM_LIT:1000> * <NUM_LIT>, '<STR_LIT:s>': -<NUM_LIT>, '<STR_LIT>': <NUM_LIT:1>, '<STR_LIT:h>': <NUM_LIT>, '<STR_LIT:d>': <NUM_LIT> * <NUM_LIT>}<EOL>}<EOL>value, unit = strtol(value)<EOL>if value is not None:<EOL><INDENT>if not unit:<EOL><INDENT>return value<EOL><DEDENT>if base_unit and base_unit not in convert:<EOL><INDENT>base_value, base_unit = strtol(base_unit, False)<EOL><DEDENT>else:<EOL><INDENT>base_value = <NUM_LIT:1><EOL><DEDENT>if base_unit in convert and unit in convert[base_unit]:<EOL><INDENT>multiplier = convert[base_unit][unit]<EOL>if multiplier < <NUM_LIT:0>:<EOL><INDENT>value /= -multiplier<EOL><DEDENT>else:<EOL><INDENT>value *= multiplier<EOL><DEDENT>return int(value/base_value)<EOL><DEDENT><DEDENT>
>>> 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_value).lower() == str(new_value).lower()<EOL><DEDENT>else: <EOL><INDENT>return str(old_value) == str(new_value)<EOL><DEDENT>return old_value is not None and new_value is not None and old_value == new_value<EOL>
>>> compare_values('enum', None, 'remote_write', 'REMOTE_WRITE') True >>> compare_values('real', None, '1.23', 1.23) True
f12581:m5