code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self.remove_partition(partition)
broker_destination.add_partition(partition) | def move_partition(self, partition, broker_destination) | Move partition to destination broker and adjust replicas. | 4.111706 | 3.822608 | 1.075628 |
return sum(1 for p in topic.partitions if p in self.partitions) | def count_partitions(self, topic) | Return count of partitions for given topic. | 8.705226 | 8.228855 | 1.05789 |
# Only partitions not having replica in broker are valid
# Get best fit partition, based on avoiding partition from same topic
# and partition with least siblings in destination-broker.
eligible_partitions = self.partitions - broker.partitions
if eligible_partitions:
... | def get_preferred_partition(self, broker, sibling_distance) | The preferred partition belongs to the topic with the minimum
(also negative) distance between destination and source.
:param broker: Destination broker
:param sibling_distance: dict {topic: distance} negative distance should
mean that destination broker has got less partition of a... | 8.980957 | 7.796546 | 1.151915 |
# Possible partitions which can grant leadership to broker
owned_partitions = list(filter(
lambda p: self is not p.leader and len(p.replicas) > 1,
self.partitions,
))
for partition in owned_partitions:
# Partition not available to grant leader... | def request_leadership(self, opt_count, skip_brokers, skip_partitions) | Under-balanced broker requests leadership from current leader, on the
pretext that it recursively can maintain its leadership count as optimal.
:key_terms:
leader-balanced: Count of brokers as leader is at least opt-count
Algorithm:
=========
Step-1: Broker will request... | 5.180735 | 4.732226 | 1.094778 |
owned_partitions = list(filter(
lambda p: self is p.leader and len(p.replicas) > 1,
self.partitions,
))
for partition in owned_partitions:
# Skip using same partition with broker if already used before
potential_new_leaders = list(filter(
... | def donate_leadership(self, opt_count, skip_brokers, used_edges) | Over-loaded brokers tries to donate their leadership to one of their
followers recursively until they become balanced.
:key_terms:
used_edges: Represent list of tuple/edges (partition, prev-leader, new-leader),
which have already been used for donating leadership from
... | 3.60097 | 3.140564 | 1.1466 |
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host)
return ssh | def ssh_client(host) | Start an ssh client.
:param host: the host
:type host: str
:returns: ssh client
:rtype: Paramiko client | 1.602154 | 2.213729 | 0.723735 |
if minutes:
return FIND_MINUTES_COMMAND.format(
data_path=data_path,
minutes=minutes,
)
if start_time:
if end_time:
return FIND_RANGE_COMMAND.format(
data_path=data_path,
start_time=start_time,
end_t... | def find_files_cmd(data_path, minutes, start_time, end_time) | Find the log files depending on their modification time.
:param data_path: the path to the Kafka data directory
:type data_path: str
:param minutes: check the files modified in the last N minutes
:type minutes: int
:param start_time: check the files modified after start_time
:type start_time: s... | 1.67188 | 1.78112 | 0.938668 |
files_str = ",".join(files)
check_command = CHECK_COMMAND.format(
ionice=IONICE,
java_home=java_home,
files=files_str,
)
# One line per message can generate several MB/s of data
# Use pre-filtering on the server side to reduce it
command = "{check_command} | {reduce_... | def check_corrupted_files_cmd(java_home, files) | Check the file corruption of the specified files.
:param java_home: the JAVA_HOME
:type java_home: string
:param files: list of files to be checked
:type files: list of string | 6.350274 | 7.226776 | 0.878715 |
with closing(ssh_client(host)) as ssh:
_, stdout, stderr = ssh.exec_command(command)
lines = stdout.read().splitlines()
report_stderr(host, stderr)
return lines | def get_output_lines_from_command(host, command) | Execute a command on the specified host, returning a list of
output lines.
:param host: the host name
:type host: str
:param command: the command
:type commmand: str | 3.201391 | 4.623378 | 0.692435 |
command = find_files_cmd(data_path, minutes, start_time, end_time)
pool = Pool(len(brokers))
result = pool.map(
partial(get_output_lines_from_command, command=command),
[host for broker, host in brokers])
return [(broker, host, files)
for (broker, host), files
... | def find_files(data_path, brokers, minutes, start_time, end_time) | Find all the Kafka log files on the broker that have been modified
in the speficied time range.
start_time and end_time should be in the format specified
by TIME_FORMAT_REGEX.
:param data_path: the path to the lof files on the broker
:type data_path: str
:param brokers: the brokers
:type b... | 3.792179 | 3.680805 | 1.030258 |
current_file = None
for line in output.readlines():
file_name_search = FILE_PATH_REGEX.search(line)
if file_name_search:
current_file = file_name_search.group(1)
continue
if INVALID_MESSAGE_REGEX.match(line) or INVALID_BYTES_REGEX.match(line):
pri... | def parse_output(host, output) | Parse the output of the dump tool and print warnings or error messages
accordingly.
:param host: the source
:type host: str
:param output: the output of the script on host
:type output: list of str | 3.641162 | 3.541606 | 1.02811 |
print(
"{ltype} Host: {host}, File: {path}".format(
ltype=line_type,
host=host,
path=path,
)
)
print("{ltype} Output: {line}".format(ltype=line_type, line=line)) | def print_line(host, path, line, line_type) | Print a dump tool line to stdout.
:param host: the source host
:type host: str
:param path: the path to the file that is being analyzed
:type path: str
:param line: the line to be printed
:type line: str
:param line_type: a header for the line
:type line_type: str | 2.698772 | 2.960062 | 0.911728 |
with closing(ssh_client(host)) as ssh:
for i, batch in enumerate(chunks(files, batch_size)):
command = check_corrupted_files_cmd(java_home, batch)
_, stdout, stderr = ssh.exec_command(command)
report_stderr(host, stderr)
print(
" {host}: ... | def check_files_on_host(java_home, host, files, batch_size) | Check the files on the host. Files are grouped together in groups
of batch_size files. The dump class will be executed on each batch,
sequentially.
:param java_home: the JAVA_HOME of the broker
:type java_home: str
:param host: the host where the tool will be executed
:type host: str
:param... | 3.868195 | 4.308304 | 0.897846 |
client = KafkaClient(cluster_config.broker_list)
result = {}
for topic, topic_data in six.iteritems(client.topic_partitions):
for partition, p_data in six.iteritems(topic_data):
topic_partition = topic + "-" + str(partition)
result[topic_partition] = p_data.leader
re... | def get_partition_leaders(cluster_config) | Return the current leaders of all partitions. Partitions are
returned as a "topic-partition" string.
:param cluster_config: the cluster
:type cluster_config: kafka_utils.utils.config.ClusterConfig
:returns: leaders for partitions
:rtype: map of ("topic-partition", broker_id) pairs | 3.027911 | 2.989364 | 1.012895 |
match = TP_FROM_FILE_REGEX.match(file_path)
if not match:
print("File path is not valid: " + file_path)
sys.exit(1)
return match.group(1) | def get_tp_from_file(file_path) | Return the name of the topic-partition given the path to the file.
:param file_path: the path to the log file
:type file_path: str
:returns: the name of the topic-partition, ex. "topic_name-0"
:rtype: str | 3.058046 | 3.365763 | 0.908574 |
print("Filtering leaders")
leader_of = get_partition_leaders(cluster_config)
result = []
for broker, host, files in broker_files:
filtered = []
for file_path in files:
tp = get_tp_from_file(file_path)
if tp not in leader_of or leader_of[tp] == broker:
... | def filter_leader_files(cluster_config, broker_files) | Given a list of broker files, filters out all the files that
are in the replicas.
:param cluster_config: the cluster
:type cluster_config: kafka_utils.utils.config.ClusterConfig
:param broker_files: the broker files
:type broker_files: list of (b_id, host, [file_path, file_path ...]) tuples
:re... | 3.398989 | 3.177786 | 1.069609 |
brokers = get_broker_list(cluster_config)
broker_files = find_files(data_path, brokers, minutes, start_time, end_time)
if not check_replicas: # remove replicas
broker_files = filter_leader_files(cluster_config, broker_files)
processes = []
print("Starting {n} parallel processes".format... | def check_cluster(
cluster_config,
data_path,
java_home,
check_replicas,
batch_size,
minutes,
start_time,
end_time,
) | Check the integrity of the Kafka log files in a cluster.
start_time and end_time should be in the format specified
by TIME_FORMAT_REGEX.
:param data_path: the path to the log folder on the broker
:type data_path: str
:param java_home: the JAVA_HOME of the broker
:type java_home: str
:param... | 3.175158 | 3.160804 | 1.004541 |
if not args.minutes and not args.start_time:
print("Error: missing --minutes or --start-time")
return False
if args.minutes and args.start_time:
print("Error: --minutes shouldn't be specified if --start-time is used")
return False
if args.end_time and not args.start_time... | def validate_args(args) | Basic option validation. Returns False if the options are not valid,
True otherwise.
:param args: the command line options
:type args: map
:param brokers_num: the number of brokers | 1.793859 | 1.880198 | 0.95408 |
if self.args.topic in ct.topics:
topic = ct.topics[self.args.topic]
else:
self.log.error(
"Topic {topic} not found. Exiting."
.format(topic=self.args.topic),
)
sys.exit(1)
if topic.replication_factor == sel... | def run_command(self, ct, cluster_balancer) | Get executable proposed plan(if any) for display or execution. | 2.276392 | 2.305141 | 0.987528 |
optimum, extra = compute_optimum(len(groups), total)
over_loaded, under_loaded, optimal = [], [], []
for group in sorted(groups, key=key, reverse=True):
n_elements = key(group)
additional_element = 1 if extra else 0
if n_elements > optimum + additional_element:
over_... | def _smart_separate_groups(groups, key, total) | Given a list of group objects, and a function to extract the number of
elements for each of them, return the list of groups that have an excessive
number of elements (when compared to a uniform distribution), a list of
groups with insufficient elements, and a list of groups that already have
the optimal... | 3.049587 | 3.106089 | 0.981809 |
optimum, extra = compute_optimum(len(groups), total)
over_loaded, under_loaded, optimal = _smart_separate_groups(groups, key, total)
# If every group is optimal return
if not extra:
return over_loaded, under_loaded
# Some groups in optimal may have a number of elements that is optimum +... | def separate_groups(groups, key, total) | Separate the group into overloaded and under-loaded groups.
The revised over-loaded groups increases the choice space for future
selection of most suitable group based on search criteria.
For example:
Given the groups (a:4, b:4, c:3, d:2) where the number represents the number
of elements for each... | 3.954417 | 3.39817 | 1.16369 |
return {
broker
for broker in self._brokers
if not broker.inactive and not broker.decommissioned
} | def active_brokers(self) | Return set of brokers that are not inactive or decommissioned. | 6.391566 | 3.142921 | 2.033638 |
if broker not in self._brokers:
self._brokers.add(broker)
else:
self.log.warning(
'Broker {broker_id} already present in '
'replication-group {rg_id}'.format(
broker_id=broker.id,
rg_id=self._id,
... | def add_broker(self, broker) | Add broker to current broker-list. | 3.103616 | 2.931509 | 1.058709 |
return sum(1 for b in partition.replicas if b in self.brokers) | def count_replica(self, partition) | Return count of replicas of given partition. | 10.475706 | 10.157993 | 1.031277 |
broker_dest = self._elect_dest_broker(partition)
if not broker_dest:
raise NotEligibleGroupError(
"No eligible brokers to accept partition {p}".format(p=partition),
)
source_broker.move_partition(partition, broker_dest) | def acquire_partition(self, partition, source_broker) | Move a partition from a broker to any of the eligible brokers
of the replication group.
:param partition: Partition to move
:param source_broker: Broker the partition currently belongs to | 5.234447 | 5.199403 | 1.00674 |
# Select best-fit source and destination brokers for partition
# Best-fit is based on partition-count and presence/absence of
# Same topic-partition over brokers
broker_source, broker_destination = self._select_broker_pair(
rg_destination,
victim_partitio... | def move_partition(self, rg_destination, victim_partition) | Move partition(victim) from current replication-group to destination
replication-group.
Step 1: Evaluate source and destination broker
Step 2: Move partition from source-broker to destination-broker | 4.543132 | 4.390528 | 1.034758 |
broker_source = self._elect_source_broker(victim_partition)
broker_destination = rg_destination._elect_dest_broker(victim_partition)
return broker_source, broker_destination | def _select_broker_pair(self, rg_destination, victim_partition) | Select best-fit source and destination brokers based on partition
count and presence of partition over the broker.
* Get overloaded and underloaded brokers
Best-fit Selection Criteria:
Source broker: Select broker containing the victim-partition with
maximum partitions.
... | 3.352439 | 3.971857 | 0.844048 |
broker_subset = broker_subset or self._brokers
over_loaded_brokers = sorted(
[
broker
for broker in broker_subset
if victim_partition in broker.partitions and not broker.inactive
],
key=lambda b: len(b.partition... | def _elect_source_broker(self, victim_partition, broker_subset=None) | Select first over loaded broker having victim_partition.
Note: The broker with maximum siblings of victim-partitions (same topic)
is selected to reduce topic-partition imbalance. | 2.819059 | 2.531123 | 1.113758 |
under_loaded_brokers = sorted(
[
broker
for broker in self._brokers
if (victim_partition not in broker.partitions and
not broker.inactive and
not broker.decommissioned)
],
key=lam... | def _elect_dest_broker(self, victim_partition) | Select first under loaded brokers preferring not having
partition of same topic as victim partition. | 3.041257 | 2.647006 | 1.148942 |
total_partitions = sum(len(b.partitions) for b in self.brokers)
blacklist = set(b for b in self.brokers if b.decommissioned)
active_brokers = self.get_active_brokers() - blacklist
if not active_brokers:
raise EmptyReplicationGroupError("No active brokers in %s", self... | def rebalance_brokers(self) | Rebalance partition-count across brokers. | 3.035851 | 2.939831 | 1.032662 |
# Sort given brokers to ensure determinism
over_loaded_brokers = sorted(
over_loaded_brokers,
key=lambda b: len(b.partitions),
reverse=True,
)
under_loaded_brokers = sorted(
under_loaded_brokers,
key=lambda b: len(b.par... | def _get_target_brokers(self, over_loaded_brokers, under_loaded_brokers, sibling_distance) | Pick best-suitable source-broker, destination-broker and partition to
balance partition-count over brokers in given replication-group. | 4.301038 | 4.081126 | 1.053885 |
sibling_distance = defaultdict(lambda: defaultdict(dict))
topics = {p.topic for p in self.partitions}
for source in self.brokers:
for dest in self.brokers:
if source != dest:
for topic in topics:
sibling_distance[de... | def generate_sibling_distance(self) | Generate a dict containing the distance computed as difference in
in number of partitions of each topic from under_loaded_brokers
to over_loaded_brokers.
Negative distance means that the destination broker has got less
partitions of a certain topic than the source broker.
retur... | 3.575705 | 2.462251 | 1.45221 |
for source in six.iterkeys(sibling_distance[dest]):
sibling_distance[dest][source][topic] = \
dest.count_partitions(topic) - \
source.count_partitions(topic)
return sibling_distance | def update_sibling_distance(self, sibling_distance, dest, topic) | Update the sibling distance for topic and destination broker. | 4.559264 | 4.269051 | 1.067981 |
# Evaluate possible source and destination-broker
source_broker, dest_broker = self._get_eligible_broker_pair(
under_loaded_rg,
eligible_partition,
)
if source_broker and dest_broker:
self.log.debug(
'Moving partition {p_name} ... | def move_partition_replica(self, under_loaded_rg, eligible_partition) | Move partition to under-loaded replication-group if possible. | 3.328475 | 3.095031 | 1.075425 |
under_brokers = list(filter(
lambda b: eligible_partition not in b.partitions,
under_loaded_rg.brokers,
))
over_brokers = list(filter(
lambda b: eligible_partition in b.partitions,
self.brokers,
))
# Get source and destina... | def _get_eligible_broker_pair(self, under_loaded_rg, eligible_partition) | Evaluate and return source and destination broker-pair from over-loaded
and under-loaded replication-group if possible, return None otherwise.
Return source broker with maximum partitions and destination broker with
minimum partitions based on following conditions:-
1) At-least one brok... | 2.172642 | 2.246031 | 0.967325 |
if not isinstance(res, dict):
raise ValueError('Value should be of dict type')
result = set([])
for _, v in res.items():
for value in v:
result.add(value)
return list(result) | def merge_result(res) | Merge all items in `res` into a list.
This command is used when sending a command to multiple nodes
and they result from each node should be merged into a single list. | 3.958463 | 4.463309 | 0.88689 |
if not isinstance(res, dict):
raise ValueError('Value should be of dict type')
if len(res.keys()) != 1:
raise RedisClusterException("More then 1 result from command")
return list(res.values())[0] | def first_key(res) | Returns the first result for the given command.
If more then 1 result is returned then a `RedisClusterException` is raised. | 5.537674 | 3.45085 | 1.604728 |
@wraps(func)
async def inner(*args, **kwargs):
for _ in range(0, 3):
try:
return await func(*args, **kwargs)
except ClusterDownError:
# Try again with the new cluster setup. All other errors
# should be raised.
... | def clusterdown_wrapper(func) | Wrapper for CLUSTERDOWN error handling.
If the cluster reports it is down it is assumed that:
- connection_pool was disconnected
- connection_pool was reseted
- refereh_table_asap set to True
It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail. | 5.347635 | 4.722602 | 1.132349 |
"Parse the results of Redis's DEBUG OBJECT command into a Python dict"
# The 'type' of the object is the first item in the response, but isn't
# prefixed with a name
response = nativestr(response)
response = 'type:' + response
response = dict([kv.split(':') for kv in response.split()])
# pa... | def parse_debug_object(response) | Parse the results of Redis's DEBUG OBJECT command into a Python dict | 8.036768 | 7.003501 | 1.147536 |
"Parse the result of Redis's INFO command into a Python dict"
info = {}
response = nativestr(response)
def get_value(value):
if ',' not in value or '=' not in value:
try:
if '.' in value:
return float(value)
else:
... | def parse_info(response) | Parse the result of Redis's INFO command into a Python dict | 2.584528 | 2.362947 | 1.093774 |
if host is None and port is None:
return await self.execute_command('SLAVEOF', b('NO'), b('ONE'))
return await self.execute_command('SLAVEOF', host, port) | async def slaveof(self, host=None, port=None) | Set the server to be a replicated slave of the instance identified
by the ``host`` and ``port``. If called without arguments, the
instance is promoted to a master instead. | 3.484951 | 3.536935 | 0.985302 |
args = ['SLOWLOG GET']
if num is not None:
args.append(num)
return await self.execute_command(*args) | async def slowlog_get(self, num=None) | Get the entries from the slowlog. If ``num`` is specified, get the
most recent ``num`` items. | 3.404099 | 3.057128 | 1.113496 |
return cache_class(self, app=name,
identity_generator_class=identity_generator_class,
compressor_class=compressor_class,
serializer_class=serializer_class,
*args, **kwargs) | def cache(self, name, cache_class=Cache,
identity_generator_class=IdentityGenerator,
compressor_class=Compressor,
serializer_class=Serializer, *args, **kwargs) | Return a cache object using default identity generator,
serializer and compressor.
``name`` is used to identify the series of your cache
``cache_class`` Cache is for normal use and HerdCache
is used in case of Thundering Herd Problem
``identity_generator_class`` is the class use... | 2.100146 | 2.585481 | 0.812284 |
if lock_class is None:
if self._use_lua_lock is None:
# the first time .lock() is called, determine if we can use
# Lua by attempting to register the necessary scripts
try:
LuaLock.register_scripts(self)
... | def lock(self, name, timeout=None, sleep=0.1, blocking_timeout=None,
lock_class=None, thread_local=True) | Return a new Lock object using key ``name`` that mimics
the behavior of threading.Lock.
If specified, ``timeout`` indicates a maximum life for the lock.
By default, it will remain locked until release() is called.
``sleep`` indicates the amount of time to sleep per loop iteration
... | 2.880691 | 2.949513 | 0.976667 |
"Increment the value of ``key`` in hash ``name`` by ``amount``"
return await self.execute_command('HINCRBY', name, key, amount) | async def hincrby(self, name, key, amount=1) | Increment the value of ``key`` in hash ``name`` by ``amount`` | 3.45937 | 3.371952 | 1.025925 |
return await self.execute_command('HINCRBYFLOAT', name, key, amount) | async def hincrbyfloat(self, name, key, amount=1.0) | Increment the value of ``key`` in hash ``name`` by floating ``amount`` | 3.028424 | 3.049209 | 0.993183 |
return await self.execute_command('HSET', name, key, value) | async def hset(self, name, key, value) | Set ``key`` to ``value`` within hash ``name``
Returns 1 if HSET created a new field, otherwise 0 | 3.799948 | 3.678545 | 1.033003 |
return await self.execute_command('HSETNX', name, key, value) | async def hsetnx(self, name, key, value) | Set ``key`` to ``value`` within hash ``name`` if ``key`` does not
exist. Returns 1 if HSETNX created a field, otherwise 0. | 3.319169 | 3.557925 | 0.932895 |
if not mapping:
raise DataError("'hmset' with 'mapping' of length 0")
items = []
for pair in iteritems(mapping):
items.extend(pair)
return await self.execute_command('HMSET', name, *items) | async def hmset(self, name, mapping) | Set key to value within hash ``name`` for each corresponding
key and value from the ``mapping`` dict. | 4.103167 | 3.811265 | 1.076589 |
pieces = [name, cursor]
if match is not None:
pieces.extend([b('MATCH'), match])
if count is not None:
pieces.extend([b('COUNT'), count])
return await self.execute_command('HSCAN', *pieces) | async def hscan(self, name, cursor=0, match=None, count=None) | Incrementally return key/value slices in a hash. Also return a cursor
indicating the scan position.
``match`` allows for filtering the keys by pattern
``count`` allows for hint the minimum number of returns | 2.235106 | 2.927555 | 0.763472 |
shard_hint = kwargs.pop('shard_hint', None)
value_from_callable = kwargs.pop('value_from_callable', False)
watch_delay = kwargs.pop('watch_delay', None)
async with await self.pipeline(True, shard_hint) as pipe:
while True:
try:
if ... | async def transaction(self, func, *watches, **kwargs) | Convenience method for executing the callable `func` as a transaction
while watching all keys specified in `watches`. The 'func' callable
should expect a single argument which is a Pipeline object. | 2.824443 | 2.599499 | 1.086534 |
if isinstance(value, bytes):
return value
elif isinstance(value, int):
value = b(str(value))
elif isinstance(value, float):
value = b(repr(value))
elif not isinstance(value, str):
value = str(value)
if isinstance(value, str... | def encode(self, value) | Return a bytestring representation of the value | 2.205032 | 2.118421 | 1.040885 |
nodes_cache = {}
tmp_slots = {}
all_slots_covered = False
disagreements = []
startup_nodes_reachable = False
nodes = self.orig_startup_nodes
# With this option the client will attempt to connect to any of the previous set of nodes instead of the origin... | async def initialize(self) | Init the slots cache by asking all startup nodes what the current cluster configuration is
TODO: Currently the last node will have the last say about how the configuration is setup.
Maybe it should stop to try after it have correctly covered all slots or when one node is reached
and it could ex... | 3.859036 | 3.719038 | 1.037644 |
nodes = nodes_cache or self.nodes
async def node_require_full_coverage(node):
r_node = self.get_redis_link(host=node['host'], port=node['port'])
node_config = await r_node.config_get('cluster-require-full-coverage')
return 'yes' in node_config.values()
... | async def cluster_require_full_coverage(self, nodes_cache) | if exists 'cluster-require-full-coverage no' config on redis servers,
then even all slots are not covered, cluster still will be able to
respond | 3.513776 | 3.156761 | 1.113095 |
node_name = "{0}:{1}".format(host, port)
node = {
'host': host,
'port': port,
'name': node_name,
'server_type': server_type
}
self.nodes[node_name] = node
return node | def set_node(self, host, port, server_type=None) | Update data for a node. | 2.153079 | 2.138736 | 1.006706 |
for item in self.startup_nodes:
self.set_node_name(item)
for n in self.nodes.values():
if n not in self.startup_nodes:
self.startup_nodes.append(n)
# freeze it so we can set() it
uniq = {frozenset(node.items()) for node in self.startup_n... | def populate_startup_nodes(self) | Do something with all startup nodes and filters out any duplicates | 4.604838 | 4.208447 | 1.094189 |
url = urlparse(url)
qs = url.query
url_options = {}
for name, value in iter(parse_qs(qs).items()):
if value and len(value) > 0:
parser = URL_QUERY_ARGUMENT_PARSERS.get(name)
if parser:
try:
... | def from_url(cls, url, db=None, decode_components=False, **kwargs) | Return a connection pool configured from the given URL.
For example::
redis://[:password]@localhost:6379/0
rediss://[:password]@localhost:6379/0
unix://[:password]@/path/to/socket.sock?db=0
Three URL schemes are supported:
- ```redis://``
<http://www.iana.org/... | 2.552052 | 2.319511 | 1.100254 |
"Get a connection from the pool"
self._checkpid()
try:
connection = self._available_connections.pop()
except IndexError:
connection = self.make_connection()
self._in_use_connections.add(connection)
return connection | def get_connection(self, *args, **kwargs) | Get a connection from the pool | 4.282482 | 4.009662 | 1.068041 |
"Releases the connection back to the pool"
self._checkpid()
if connection.pid != self.pid:
return
self._in_use_connections.remove(connection)
# discard connection with unread response
if connection.awaiting_response:
connection.disconnect()
... | def release(self, connection) | Releases the connection back to the pool | 6.582651 | 6.526232 | 1.008645 |
self.pid = os.getpid()
self._created_connections = 0
self._created_connections_per_node = {} # Dict(Node, Int)
self._available_connections = {} # Dict(Node, List)
self._in_use_connections = {} # Dict(Node, Set)
self._check_lock = threading.Lock()
self.... | def reset(self) | Resets the connection pool back to a clean state. | 4.762676 | 3.937428 | 1.20959 |
if self.count_all_num_connections(node) >= self.max_connections:
if self.max_connections_per_node:
raise RedisClusterException("Too many connection ({0}) for node: {1}"
.format(self.count_all_num_connections(node),
... | def make_connection(self, node) | Create a new connection | 3.694745 | 3.703476 | 0.997642 |
self._checkpid()
if connection.pid != self.pid:
return
# Remove the current connection from _in_use_connection and add it back to the available pool
# There is cases where the connection is to be removed but it will not exist and there
# must be a safe way t... | def release(self, connection) | Releases the connection back to the pool | 6.340268 | 6.049544 | 1.048057 |
all_conns = chain(
self._available_connections.values(),
self._in_use_connections.values(),
)
for node_connections in all_conns:
for connection in node_connections:
connection.disconnect() | def disconnect(self) | Nothing that requires any overwrite. | 4.557483 | 4.37768 | 1.041073 |
if self._available_connections:
node_name = random.choice(list(self._available_connections.keys()))
conn_list = self._available_connections[node_name]
# check it in case of empty connection list
if conn_list:
return conn_list.pop()
... | def get_random_connection(self) | Open new connection to random redis server. | 5.122038 | 4.826889 | 1.061147 |
self._checkpid()
try:
return self.get_connection_by_node(self.get_node_by_slot(slot))
except KeyError:
return self.get_random_connection() | def get_connection_by_slot(self, slot) | Determine what server a specific slot belongs to and return a redis object that is connected | 4.81204 | 4.735545 | 1.016153 |
self._checkpid()
self.nodes.set_node_name(node)
try:
# Try to get connection from existing pool
connection = self._available_connections.get(node["name"], []).pop()
except IndexError:
connection = self.make_connection(node)
self._in_... | def get_connection_by_node(self, node) | get a connection by node | 5.534763 | 5.31499 | 1.04135 |
"Re-subscribe to any channels and patterns previously subscribed to"
# NOTE: for python3, we can't pass bytestrings as keyword arguments
# so we need to decode channel/pattern names back to str strings
# before passing them to [p]subscribe.
if self.channels:
channels ... | async def on_connect(self, connection) | Re-subscribe to any channels and patterns previously subscribed to | 3.965583 | 3.413245 | 1.161822 |
if self.decode_responses and isinstance(value, bytes):
value = value.decode(self.encoding)
elif not self.decode_responses and isinstance(value, str):
value = value.encode(self.encoding)
return value | def encode(self, value) | Encode the value so that it's identical to what we'll
read off the connection | 2.590276 | 2.499807 | 1.036191 |
"Parse the response from a publish/subscribe command"
connection = self.connection
if connection is None:
raise RuntimeError(
'pubsub connection not set: '
'did you forget to call subscribe() or psubscribe()?')
coro = self._execute(connection, ... | async def parse_response(self, block=True, timeout=0) | Parse the response from a publish/subscribe command | 4.892583 | 4.011367 | 1.21968 |
if args:
args = list_or_args(args[0], args[1:])
new_patterns = {}
new_patterns.update(dict.fromkeys(map(self.encode, args)))
for pattern, handler in iteritems(kwargs):
new_patterns[self.encode(pattern)] = handler
ret_val = await self.execute_comma... | async def psubscribe(self, *args, **kwargs) | Subscribe to channel patterns. Patterns supplied as keyword arguments
expect a pattern name as the key and a callable as the value. A
pattern's callable will be invoked automatically when a message is
received on that pattern rather than producing a message via
``listen()``. | 4.833466 | 4.514008 | 1.07077 |
if args:
args = list_or_args(args[0], args[1:])
return await self.execute_command('PUNSUBSCRIBE', *args) | async def punsubscribe(self, *args) | Unsubscribe from the supplied patterns. If empy, unsubscribe from
all patterns. | 4.262028 | 4.509888 | 0.945041 |
if args:
args = list_or_args(args[0], args[1:])
new_channels = {}
new_channels.update(dict.fromkeys(map(self.encode, args)))
for channel, handler in iteritems(kwargs):
new_channels[self.encode(channel)] = handler
ret_val = await self.execute_comma... | async def subscribe(self, *args, **kwargs) | Subscribe to channels. Channels supplied as keyword arguments expect
a channel name as the key and a callable as the value. A channel's
callable will be invoked automatically when a message is received on
that channel rather than producing a message via ``listen()`` or
``get_message()``. | 5.080337 | 4.619475 | 1.099765 |
if args:
args = list_or_args(args[0], args[1:])
return await self.execute_command('UNSUBSCRIBE', *args) | async def unsubscribe(self, *args) | Unsubscribe from the supplied channels. If empty, unsubscribe from
all channels | 4.527956 | 5.006832 | 0.904355 |
"Listen for messages on channels this client has been subscribed to"
if self.subscribed:
return self.handle_message(await self.parse_response(block=True)) | async def listen(self) | Listen for messages on channels this client has been subscribed to | 16.728565 | 9.574595 | 1.747182 |
response = await self.parse_response(block=False, timeout=timeout)
if response:
return self.handle_message(response, ignore_subscribe_messages)
return None | async def get_message(self, ignore_subscribe_messages=False, timeout=0) | Get the next message if one is available, otherwise None.
If timeout is specified, the system will wait for `timeout` seconds
before returning. Timeout should be specified as a floating point
number. | 4.459537 | 4.740153 | 0.9408 |
message_type = nativestr(response[0])
if message_type == 'pmessage':
message = {
'type': message_type,
'pattern': response[1],
'channel': response[2],
'data': response[3]
}
else:
message ... | def handle_message(self, response, ignore_subscribe_messages=False) | Parses a pub/sub message. If the channel or pattern was subscribed to
with a message handler, the handler is invoked instead of a parsed
message being returned. | 2.271947 | 2.090447 | 1.086823 |
# NOTE: don't parse the response in this function -- it could pull a
# legitimate message off the stack if the connection is already
# subscribed to one or more channels
await self.connection_pool.initialize()
if self.connection is None:
self.connection = se... | async def execute_command(self, *args, **kwargs) | Execute a publish/subscribe command.
Taken code from redis-py and tweak to make it work within a cluster. | 6.947853 | 6.245548 | 1.112449 |
if self.identity_generator and param is not None:
if self.serializer:
param = self.serializer.serialize(param)
if self.compressor:
param = self.compressor.compress(param)
identity = self.identity_generator.generate(key, param)
... | def _gen_identity(self, key, param=None) | generate identity according to key and param given | 2.777943 | 2.629824 | 1.056323 |
if self.serializer:
content = self.serializer.serialize(content)
if self.compressor:
content = self.compressor.compress(content)
return content | def _pack(self, content) | pack the content using serializer and compressor | 3.109745 | 1.925532 | 1.615005 |
if self.compressor:
try:
content = self.compressor.decompress(content)
except CompressError:
pass
if self.serializer:
content = self.serializer.deserialize(content)
return content | def _unpack(self, content) | unpack cache using serializer and compressor | 3.309193 | 2.278605 | 1.452289 |
identity = self._gen_identity(key, param)
return await self.client.delete(identity) | async def delete(self, key, param=None) | delete cache corresponding to identity
generated from key and param | 7.798144 | 4.568682 | 1.70687 |
cursor = '0'
count_deleted = 0
while cursor != 0:
cursor, identities = await self.client.scan(
cursor=cursor, match=pattern, count=count
)
count_deleted += await self.client.delete(*identities)
return count_deleted | async def delete_pattern(self, pattern, count=None) | delete cache according to pattern in redis,
delete `count` keys each time | 4.342268 | 3.27694 | 1.325099 |
identity = self._gen_identity(key, param)
return await self.client.exists(identity) | async def exist(self, key, param=None) | see if specific identity exists | 7.152221 | 4.743013 | 1.507949 |
identity = self._gen_identity(key, param)
return await self.client.ttl(identity) | async def ttl(self, key, param=None) | get time to live of a specific identity | 8.371465 | 5.625719 | 1.48807 |
identity = self._gen_identity(key, param)
expected_expired_ts = int(time.time())
if expire_time:
expected_expired_ts += expire_time
expected_expired_ts += herd_timeout or self.default_herd_timeout
value = self._pack([value, expected_expired_ts])
retur... | async def set(self, key, value, param=None, expire_time=None, herd_timeout=None) | Use key and param to generate identity and pack the content,
expire the key within real_timeout if expire_time is given.
real_timeout is equal to the sum of expire_time and herd_time.
The content is cached with expire_time. | 3.577266 | 3.100489 | 1.153774 |
identity = self._gen_identity(key, param)
res = await self.client.get(identity)
if res:
res, timeout = self._unpack(res)
now = int(time.time())
if timeout <= now:
extend_timeout = extend_herd_timeout or self.extend_herd_timeout
... | async def get(self, key, param=None, extend_herd_timeout=None) | Use key or identity generate from key and param to
get cached content and expire time.
Compare expire time with time.now(), return None and
set cache with extended timeout if cache is expired,
else, return unpacked content | 3.659912 | 3.115328 | 1.174808 |
aggregate = options.get('aggregate', True)
if not aggregate:
return res
return merge_result(res) | def parse_cluster_pubsub_channels(res, **options) | Result callback, handles different return types
switchable by the `aggregate` flag. | 6.805108 | 5.865212 | 1.160249 |
aggregate = options.get('aggregate', True)
if not aggregate:
return res
numpat = 0
for node, node_numpat in res.items():
numpat += node_numpat
return numpat | def parse_cluster_pubsub_numpat(res, **options) | Result callback, handles different return types
switchable by the `aggregate` flag. | 3.526815 | 3.387479 | 1.041133 |
aggregate = options.get('aggregate', True)
if not aggregate:
return res
numsub_d = dict()
for _, numsub_tups in res.items():
for channel, numsubbed in numsub_tups:
try:
numsub_d[channel] += numsubbed
except KeyError:
numsub_d[... | def parse_cluster_pubsub_numsub(res, **options) | Result callback, handles different return types
switchable by the `aggregate` flag. | 2.550853 | 2.500206 | 1.020257 |
pieces = []
if max_len is not None:
if not isinstance(max_len, int) or max_len < 1:
raise RedisError("XADD maxlen must be a positive integer")
pieces.append('MAXLEN')
if approximate:
pieces.append('~')
pieces.append... | async def xadd(self, name: str, entry: dict,
max_len=None, stream_id='*',
approximate=True) -> str | Appends the specified stream entry to the stream at the specified key.
If the key does not exist, as a side effect of running
this command the key is created with a stream value.
Available since 5.0.0.
Time complexity: O(log(N)) with N being the number of items already into the stream.
... | 2.538614 | 2.642344 | 0.960743 |
pieces = [start, end]
if count is not None:
if not isinstance(count, int) or count < 1:
raise RedisError("XRANGE count must be a positive integer")
pieces.append("COUNT")
pieces.append(str(count))
return await self.execute_command('XR... | async def xrange(self, name: str, start='-', end='+', count=None) -> list | Read stream values within an interval.
Available since 5.0.0.
Time complexity: O(log(N)+M) with N being the number of elements in the stream and M the number
of elements being returned. If M is constant (e.g. always asking for the first 10 elements with COUNT),
you can consider it O(log... | 2.920508 | 3.268617 | 0.8935 |
pieces = []
if block is not None:
if not isinstance(block, int) or block < 1:
raise RedisError("XREAD block must be a positive integer")
pieces.append("BLOCK")
pieces.append(str(block))
if count is not None:
if not isinstan... | async def xread(self, count=None, block=None, **streams) -> dict | Available since 5.0.0.
Time complexity:
For each stream mentioned: O(log(N)+M) with N being the number
of elements in the stream and M the number of elements being returned.
If M is constant (e.g. always asking for the first 10 elements with COUNT),
you can consider it O(log(N))... | 1.957179 | 1.894178 | 1.03326 |
pieces = ['GROUP', group, consumer_id]
if block is not None:
if not isinstance(block, int) or block < 1:
raise RedisError("XREAD block must be a positive integer")
pieces.append("BLOCK")
pieces.append(str(block))
if count is not None:
... | async def xreadgroup(self, group: str, consumer_id: str,
count=None, block=None, **streams) | Available since 5.0.0.
Time complexity:
For each stream mentioned: O(log(N)+M) with N being the number of elements
in the stream and M the number of elements being returned.
If M is constant (e.g. always asking for the first 10 elements with COUNT),
you can consider it O(log(N))... | 1.981914 | 2.077243 | 0.954108 |
pieces = [name, group]
if count is not None:
pieces.extend([start, end, count])
if consumer is not None:
pieces.append(str(consumer))
# todo: may there be a parse function
return await self.execute_command('XPENDING', *pieces) | async def xpending(self, name: str, group: str,
start='-', end='+', count=None, consumer=None) -> list | Available since 5.0.0.
Time complexity:
O(log(N)+M) with N being the number of elements in the consumer
group pending entries list, and M the number of elements being returned.
When the command returns just the summary it runs in O(1)
time assuming the list of consumers is small... | 4.864145 | 5.757152 | 0.844887 |
pieces = ['MAXLEN']
if approximate:
pieces.append('~')
pieces.append(max_len)
return await self.execute_command('XTRIM', name, *pieces) | async def xtrim(self, name: str, max_len: int, approximate=True) -> int | [NOTICE] Not officially released yet
XTRIM is designed to accept different trimming strategies,
even if currently only MAXLEN is implemented.
:param name: name of the stream
:param max_len: max length of the stream after being trimmed
:param approximate: whether redis will limi... | 5.652356 | 5.536719 | 1.020886 |
return await self.execute_command('XDEL', name, stream_id) | async def xdel(self, name: str, stream_id: str) -> int | [NOTICE] Not officially released yet
[NOTICE] In the current implementation, memory is not
really reclaimed until a macro node is completely empty,
so you should not abuse this feature.
remove items from the middle of a stream, just by ID.
:param name: name of the stream
... | 5.210691 | 5.791314 | 0.899743 |
return await self.execute_command('XINFO CONSUMERS', name, group) | async def xinfo_consumers(self, name: str, group: str) -> list | [NOTICE] Not officially released yet
XINFO command is an observability interface that can be used
with sub-commands in order to get information
about streams or consumer groups.
:param name: name of the stream
:param group: name of the consumer group | 5.522385 | 7.666241 | 0.720351 |
return await self.execute_command('XACK', name, group, stream_id) | async def xack(self, name: str, group: str, stream_id: str) -> int | [NOTICE] Not officially released yet
XACK is the command that allows a consumer to mark a pending message as correctly processed.
:param name: name of the stream
:param group: name of the consumer group
:param stream_id: id of the entry the consumer wants to mark
:return: numbe... | 4.150182 | 5.905117 | 0.702811 |
return await self.execute_command('XCLAIM', name, group, consumer, min_idle_time, *stream_ids) | async def xclaim(self, name: str, group: str, consumer: str, min_idle_time: int, *stream_ids) | [NOTICE] Not officially released yet
Gets ownership of one or multiple messages in the Pending Entries List of a given stream consumer group.
:param name: name of the stream
:param group: name of the consumer group
:param consumer: name of the consumer
:param min_idle_time: ms
... | 2.592645 | 2.846649 | 0.910771 |
return await self.execute_command('XGROUP CREATE', name, group, stream_id) | async def xgroup_create(self, name: str, group: str, stream_id='$') -> bool | [NOTICE] Not officially released yet
XGROUP is used in order to create, destroy and manage consumer groups.
:param name: name of the stream
:param group: name of the consumer group
:param stream_id:
If we provide $ as we did, then only new messages arriving
in the... | 4.619023 | 5.313025 | 0.869377 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.