desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Use Cassandra\'s native batch statement to apply mutations atomically.
Args:
mutations: A list of dictionaries representing mutations.
txid: An integer specifying a transaction ID.'
| def _normal_batch(self, mutations, txid):
| self.logger.debug('Normal batch: {} mutations'.format(len(mutations)))
batch = BatchStatement(consistency_level=ConsistencyLevel.QUORUM, retry_policy=BASIC_RETRIES)
prepared_statements = {'insert': {}, 'delete': {}}
for mutation in mutations:
table = mutation['table']
if (table ... |
'Apply mutations across tables.
Args:
mutations: A list of dictionaries representing mutations.
txid: An integer specifying a transaction ID.'
| def apply_mutations(self, mutations, txid):
| prepared_statements = {'insert': {}, 'delete': {}}
statements_and_params = []
for mutation in mutations:
table = mutation['table']
if (table == 'group_updates'):
key = mutation['key']
insert = '\n INSERT INTO group_updates ... |
'Insert or delete multiple rows across tables in an atomic statement.
Args:
app: A string containing the application ID.
mutations: A list of dictionaries representing mutations.
entity_changes: A list of changes at the entity level.
txn: A transaction ID handler.
Raises:
FailedBatch if a concurrent process modifies th... | def _large_batch(self, app, mutations, entity_changes, txn):
| self.logger.debug('Large batch: transaction {}, {} mutations'.format(txn, len(mutations)))
large_batch = LargeBatch(self.session, app, txn)
try:
large_batch.start()
except FailedBatch as batch_error:
raise AppScaleDBConnectionError(str(batch_error))
insert_item = '\n ... |
'Insert or delete multiple rows across tables in an atomic statement.
Args:
app: A string containing the application ID.
mutations: A list of dictionaries representing mutations.
entity_changes: A list of changes at the entity level.
txn: A transaction ID handler.'
| def batch_mutate(self, app, mutations, entity_changes, txn):
| size = batch_size(mutations)
if (size > LARGE_BATCH_THRESHOLD):
self._large_batch(app, mutations, entity_changes, txn)
else:
self._normal_batch(mutations, txn)
|
'Remove a set of rows corresponding to a set of keys.
Args:
table_name: Table to delete rows from
row_keys: A list of keys to remove
column_names: Not used
Raises:
TypeError: If an argument passed in was not of the expected type.
AppScaleDBConnectionError: If the batch_delete could not be performed due
to an error with... | def batch_delete(self, table_name, row_keys, column_names=()):
| if (not isinstance(table_name, str)):
raise TypeError('Expected a str')
if (not isinstance(row_keys, list)):
raise TypeError('Expected a list')
row_keys_bytes = [bytearray(row_key) for row_key in row_keys]
statement = 'DELETE FROM "{table}" WHERE {key} IN %s... |
'Drops a given table (aka column family in Cassandra)
Args:
table_name: A string name of the table to drop
Raises:
TypeError: If an argument passed in was not of the expected type.
AppScaleDBConnectionError: If the delete_table could not be performed due
to an error with Cassandra.'
| def delete_table(self, table_name):
| if (not isinstance(table_name, str)):
raise TypeError('Expected a str')
statement = 'DROP TABLE IF EXISTS "{table}"'.format(table=table_name)
query = SimpleStatement(statement, retry_policy=BASIC_RETRIES)
try:
self.session.execute(query)
except dbconstants.TRANSIENT... |
'Creates a table if it doesn\'t already exist.
Args:
table_name: The column family name
column_names: Not used but here to match the interface
Raises:
TypeError: If an argument passed in was not of the expected type.
AppScaleDBConnectionError: If the create_table could not be performed due
to an error with Cassandra.'
| def create_table(self, table_name, column_names):
| if (not isinstance(table_name, str)):
raise TypeError('Expected a str')
if (not isinstance(column_names, list)):
raise TypeError('Expected a list')
statement = 'CREATE TABLE IF NOT EXISTS "{table}" ({key} blob,{column} text,{value} blob,PRIMARY KEY ... |
'Gets a dense range ordered by keys. Returns an ordered list of
a dictionary of [key:{column1:value1, column2:value2},...]
or a list of keys if keys only.
Args:
table_name: Name of table to access
column_names: Columns which get returned within the key range
start_key: String for which the query starts at
end_key: Stri... | def range_query(self, table_name, column_names, start_key, end_key, limit, offset=0, start_inclusive=True, end_inclusive=True, keys_only=False):
| if (not isinstance(table_name, str)):
raise TypeError('table_name must be a string')
if (not isinstance(column_names, list)):
raise TypeError('column_names must be a list')
if (not isinstance(start_key, str)):
raise TypeError('start_key must be a s... |
'Retrieve a value from the datastore metadata table.
Args:
key: A string containing the key to fetch.
Returns:
A string containing the value or None if the key is not present.'
| def get_metadata(self, key):
| statement = '\n SELECT {value} FROM "{table}"\n WHERE {key} = %s\n AND {column} = %s\n '.format(value=ThriftColumn.VALUE, table=dbconstants.DATASTORE_METADATA_TABLE, key=ThriftColumn.KEY, column=ThriftColu... |
'Set a datastore metadata value.
Args:
key: A string containing the key to set.
value: A string containing the value to set.'
| def set_metadata(self, key, value):
| if (not isinstance(key, str)):
raise TypeError('key should be a string')
if (not isinstance(value, str)):
raise TypeError('value should be a string')
statement = '\n INSERT INTO "{table}" ({key}, {column}, {value})\n ... |
'Gets the indices of the given application.
Args:
app_id: Name of the application.
Returns:
Returns a list of encoded entity_pb.CompositeIndex objects.'
| def get_indices(self, app_id):
| start_key = dbconstants.KEY_DELIMITER.join([app_id, 'index', ''])
end_key = dbconstants.KEY_DELIMITER.join([app_id, 'index', dbconstants.TERMINATING_STRING])
result = self.range_query(dbconstants.METADATA_TABLE, dbconstants.METADATA_SCHEMA, start_key, end_key, dbconstants.MAX_NUMBER_OF_COMPOSITE_INDEXES, of... |
'Checks whether or not the data layout can be used.
Returns:
A boolean.'
| def valid_data_version(self):
| try:
version = self.get_metadata(VERSION_INFO_KEY)
except cassandra.InvalidRequest:
return False
return ((version is not None) and (float(version) == EXPECTED_DATA_VERSION))
|
'Fetch the latest transaction IDs for each group.
Args:
groups: An interable containing encoded Reference objects.
Returns:
A set of integers specifying transaction IDs.'
| def group_updates(self, groups):
| futures = []
for group in groups:
query = 'SELECT * FROM group_updates WHERE group=%s'
futures.append(self.session.execute_async(query, [bytearray(group)]))
updates = set()
for future in futures:
rows = future.result()
try:
result = rows[0]
... |
'Persist transaction metadata.
Args:
app: A string containing an application ID.
txid: An integer specifying the transaction ID.
is_xg: A boolean specifying that the transaction is cross-group.
in_progress: An iterable containing transaction IDs.'
| def start_transaction(self, app, txid, is_xg, in_progress):
| if in_progress:
in_progress_bin = bytearray(struct.pack(('q' * len(in_progress)), *in_progress))
else:
in_progress_bin = None
insert = '\n INSERT INTO transactions (txid_hash, operation, namespace, path,\n ... |
'Update transaction metadata with new put operations.
Args:
app: A string containing an application ID.
txid: An integer specifying the transaction ID.
entities: A list of entities that will be put upon commit.'
| def put_entities_tx(self, app, txid, entities):
| batch = BatchStatement(consistency_level=ConsistencyLevel.QUORUM, retry_policy=BASIC_RETRIES)
insert = self.session.prepare('\n INSERT INTO transactions (txid_hash, operation, namespace, path, entity)\n VALUES (?, ?, ?, ?, ?)\n ... |
'Update transaction metadata with new delete operations.
Args:
app: A string containing an application ID.
txid: An integer specifying the transaction ID.
entity_keys: A list of entity keys that will be deleted upon commit.'
| def delete_entities_tx(self, app, txid, entity_keys):
| batch = BatchStatement(consistency_level=ConsistencyLevel.QUORUM, retry_policy=BASIC_RETRIES)
insert = self.session.prepare('\n INSERT INTO transactions (txid_hash, operation, namespace, path, entity)\n VALUES (?, ?, ?, ?, ?)\n ... |
'Count the number of existing tasks associated with the transaction.
Args:
app: A string specifying an application ID.
txid: An integer specifying a transaction ID.
Returns:
An integer specifying the number of existing tasks.'
| def transactional_tasks_count(self, app, txid):
| select = '\n SELECT count(*) FROM transactions\n WHERE txid_hash = %(txid_hash)s\n AND operation = %(operation)s\n '
parameters = {'txid_hash': tx_partition(app, txid), 'operation': TxnActions.ENQUEUE_... |
'Add tasks to be enqueued upon the completion of a transaction.
Args:
app: A string specifying an application ID.
txid: An integer specifying a transaction ID.
tasks: A list of TaskQueueAddRequest objects.'
| def add_transactional_tasks(self, app, txid, tasks):
| batch = BatchStatement(consistency_level=ConsistencyLevel.QUORUM, retry_policy=BASIC_RETRIES)
insert = self.session.prepare('\n INSERT INTO transactions (txid_hash, operation, namespace, path, task)\n VALUES (?, ?, ?, ?, ?)\n ... |
'Keep track of which entity groups were read in a transaction.
Args:
app: A string specifying an application ID.
txid: An integer specifying a transaction ID.
group_keys: An iterable containing Reference objects.'
| def record_reads(self, app, txid, group_keys):
| batch = BatchStatement(consistency_level=ConsistencyLevel.QUORUM, retry_policy=BASIC_RETRIES)
insert = self.session.prepare('\n INSERT INTO transactions (txid_hash, operation, namespace, path)\n VALUES (?, ?, ?, ?)\n ... |
'Fetch transaction state.
Args:
app: A string specifying an application ID.
txid: An integer specifying a transaction ID.
Returns:
A dictionary containing transaction state.'
| def get_transaction_metadata(self, app, txid):
| select = '\n SELECT namespace, operation, path, start_time, is_xg, in_progress,\n entity, task\n FROM transactions\n WHERE txid_hash = %(txid_hash)s\n ... |
'Creates a new EntityIDAllocator object.
Args:
session: A cassandra-drivers session object.
project: A string specifying a project ID.'
| def __init__(self, session, project, scattered=False):
| self.project = project
self.session = session
self.scattered = scattered
if scattered:
self.max_allowed = _MAX_SCATTERED_COUNTER
else:
self.max_allowed = _MAX_SEQUENTIAL_COUNTER
|
'Ensures an entry exists for a reservation.
Args:
retries: The number of times to retry the insert.
Raises:
AllocationFailed if the insert is tried too many times.'
| def _ensure_entry(self, retries=5):
| if (retries < 0):
raise AppScaleDBConnectionError('Unable to create reserved_ids entry')
logger.debug('Creating reserved_ids entry for {}'.format(self.project))
insert = SimpleStatement('\n INSERT INTO reserved_ids (project, scattered, la... |
'Retrieves the last entity ID that was reserved.
Returns:
An integer specifying an entity ID.'
| def _get_last_reserved(self):
| get_reserved = SimpleStatement('\n SELECT last_reserved\n FROM reserved_ids\n WHERE project = %(project)s\n AND scattered = %(scattered)s\n ', consistency_level=ConsistencyLevel.SERIAL)... |
'Retrieve the op_id that was last written during a reservation.
Returns:
A UUID4 containing the latest op_id.'
| def _get_last_op_id(self):
| get_op_id = SimpleStatement('\n SELECT op_id\n FROM reserved_ids\n WHERE project = %(project)s\n AND scattered = %(scattered)s\n ', consistency_level=ConsistencyLevel.SERIAL)
parame... |
'Update the last reserved value to allocate that block.
Args:
last_reserved: An integer specifying the last reserved value.
new_reserved: An integer specifying the new reserved value.
Raises:
ReservationFailed if the update statement fails.'
| def _set_reserved(self, last_reserved, new_reserved):
| op_id = uuid.uuid4()
set_reserved = SimpleStatement('\n UPDATE reserved_ids\n SET last_reserved = %(new_reserved)s,\n op_id = %(op_id)s\n WHERE project = %(project)s\n ... |
'Reserve a block of IDs for this project.
Args:
size: The number of IDs to reserve.
retries: The number of times to retry the reservation.
Returns:
A tuple of integers specifying the start and end ID.
Raises:
AppScaleDBConnectionError if the reservation is tried too many times.
AppScaleBadArg if the ID space has been e... | def allocate_size(self, size, retries=5):
| if (retries < 0):
raise AppScaleDBConnectionError('Unable to reserve new block')
try:
last_reserved = self._get_last_reserved()
except TRANSIENT_CASSANDRA_ERRORS:
raise AppScaleDBConnectionError('Unable to get last reserved ID')
new_reserved = (last_res... |
'Reserves all IDs up to the one given.
Args:
max_id: An integer specifying the maximum ID to allocated.
retries: The number of times to retry the reservation.
Returns:
A tuple of integers specifying the start and end ID.
Raises:
AppScaleDBConnectionError if the reservation is tried too many times.
AppScaleBadArg if the... | def allocate_max(self, max_id, retries=5):
| if (retries < 0):
raise AppScaleDBConnectionError('Unable to reserve new block')
if (max_id > self.max_allowed):
raise AppScaleBadArg('Exceeded maximum allocated IDs')
try:
last_reserved = self._get_last_reserved()
except TRANSIENT_CASSANDRA_ERRORS:
r... |
'Creates a new ScatteredAllocator instance. Each project should just
have one instance since it reserves a large block of IDs at a time.
Args:
session: A cassandra-driver session.
project: A string specifying a project ID.'
| def __init__(self, session, project):
| super(ScatteredAllocator, self).__init__(session, project, scattered=True)
self.start_id = None
self.end_id = None
|
'Returns a new iterator object.'
| def __iter__(self):
| return self
|
'Generates a new entity ID.
Returns:
An integer specifying an entity ID.'
| def next(self):
| if ((self.start_id is None) or (self.start_id > self.end_id)):
(self.start_id, self.end_id) = self.allocate_size(DEFAULT_RESERVATION_SIZE)
next_id = ToScatteredId(self.start_id)
self.start_id += 1
return next_id
|
'Create an entity lock.
Args:
client: A kazoo client.
keys: A list of entity Reference objects.
txid: An integer specifying the transaction ID.'
| def __init__(self, client, keys, txid=None):
| self.client = client
self.paths = [zk_group_path(key) for key in keys]
self.data = str((txid or ''))
self.wake_event = client.handler.event_object()
self.prefix = (uuid.uuid4().hex + self._NODE_NAME)
self.create_paths = [((path + '/') + self.prefix) for path in self.paths]
self.create_tried ... |
'Make sure the ZooKeeper lock paths have been created.'
| def _ensure_path(self):
| for path in self.paths:
self.client.ensure_path(path)
|
'Cancel a pending lock acquire.'
| def cancel(self):
| self.cancelled = True
self.wake_event.set()
|
'Acquire the lock. By default blocks and waits forever.
Returns:
A boolean indicating whether or not the lock was acquired.'
| def acquire(self):
| def _acquire_lock():
' Acquire a kazoo thread lock. '
got_it = self._lock.acquire(False)
if (not got_it):
raise ForceRetryError()
return True
retry = self._retry.copy()
retry.deadline = LOCK_TIMEOUT
locked = self._lock.acquire(False)
if (... |
'A callback function for handling connection state changes.
Args:
state: The new connection state.'
| def _watch_session(self, state):
| self.wake_event.set()
return True
|
'Check if there are any concurrent cross-group locks.
Args:
children_list: A list of current transactions for each group.'
| def _resolve_deadlocks(self, children_list):
| current_txid = int(self.data)
for (index, children) in enumerate(children_list):
our_index = children.index(self.nodes[index])
if (our_index == 0):
continue
for child in children[:(our_index - 1)]:
try:
(data, _) = self.client.get(((self.paths[inde... |
'Create contender node(s) and wait until the lock is acquired.'
| def _inner_acquire(self):
| self._ensure_path()
nodes = [None for _ in self.paths]
if self.create_tried:
nodes = self._find_nodes()
else:
self.create_tried = True
for (index, node) in enumerate(nodes):
if (node is not None):
continue
try_num = 0
while True:
try:
... |
'A callback function for handling contender deletions.
Args:
event: A ZooKeeper event.'
| def _watch_predecessor(self, event):
| self.wake_event.set()
|
'Retrieve a list of sorted contenders for each group.
Returns:
A list of contenders for each group.'
| def _get_sorted_children(self):
| children = []
for path in self.paths:
try:
children.append(self.client.get_children(path))
except NoNodeError:
children.append([])
lockname = self._NODE_NAME
for child_list in children:
child_list.sort(key=(lambda c: c[(c.find(lockname) + len(lockname)):])... |
'Retrieve a list of paths this lock has created.
Returns:
A list of ZooKeeper paths.'
| def _find_nodes(self):
| nodes = []
for path in self.paths:
try:
children = self.client.get_children(path)
except NoNodeError:
children = []
node = None
for child in children:
if child.startswith(self.prefix):
node = child
nodes.append(node)
... |
'Remove ZooKeeper nodes.
Args:
nodes: A list of nodes to delete.'
| def _delete_nodes(self, nodes):
| for (index, node) in enumerate(nodes):
if (node is None):
continue
self.client.delete(((self.paths[index] + '/') + node))
|
'Attempt to delete nodes that this lock has created.'
| def _best_effort_cleanup(self):
| try:
nodes = self._find_nodes()
self._delete_nodes(nodes)
except KazooException:
pass
|
'Release the lock immediately.'
| def release(self):
| self.client.retry(self._inner_release)
for path in self.paths:
try:
self.client.delete(path)
except (NotEmptyError, NoNodeError):
pass
return
|
'Release the lock by removing created nodes.'
| def _inner_release(self):
| if (not self.is_acquired):
return False
try:
self._delete_nodes(self.nodes)
except NoNodeError:
pass
self.is_acquired = False
self.nodes = [None for _ in self.paths]
return True
|
'Creates a new ZKTransaction, which will communicate with Zookeeper
on the given host.
Args:
host: A str that indicates which machine runs the Zookeeper service.
start_gc: A bool that indicates if we should start the garbage collector
for timed out transactions.
db_access: A DatastoreProxy instance.
log_level: A loggin... | def __init__(self, host=DEFAULT_HOST, start_gc=False, db_access=None, log_level=logging.INFO):
| retry_policy = KazooRetry(max_tries=5)
class_name = self.__class__.__name__
self.logger = logging.getLogger(class_name)
self.logger.setLevel(log_level)
self.logger.info('Starting {}'.format(class_name))
self.host = host
self.handle = kazoo.client.KazooClient(hosts=host, connection_retry=Z... |
'Starts a new thread that cleans up failed transactions.
If called when the GC thread is already started, this causes the GC thread
to reload its GC settings.'
| def start_gc(self):
| self.logger.info('Starting GC thread')
with self.gc_cv:
if self.gc_running:
self.gc_cv.notifyAll()
else:
self.gc_running = True
self.gcthread = threading.Thread(target=self.gc_runner)
self.gcthread.daemon = True
self.gcthread.star... |
'Stops the thread that cleans up failed transactions.'
| def stop_gc(self):
| self.logger.info('Stopping GC thread')
if self.gc_running:
with self.gc_cv:
self.gc_running = False
self.gc_cv.notifyAll()
self.gcthread.join()
self.logger.info('GC is done')
|
'Stops the thread that cleans up failed transactions and closes its
connection to Zookeeper.'
| def close(self):
| self.logger.info('Closing ZK connection')
self.stop_gc()
self.handle.stop()
self.handle.close()
|
'Increment a counter atomically.
Args:
path: A str of unique path to the counter.
value: An int of how much to increment the counter by.
Returns:
A tuple (int, int) of the previous value and the new value.
Raises:
ZKTransactionException: If it could not increment the counter.'
| def increment_and_get_counter(self, path, value):
| if (path not in self.__counter_cache):
self.__counter_cache[path] = InspectableCounter(self.handle, path)
counter = self.__counter_cache[path]
try:
new_value = (counter + value)
return ((new_value - value), new_value)
except kazoo.exceptions.ZookeeperError as zoo_exception:
... |
'Fetch the ZooKeeper node at the given path.
Args:
path: A PATH_SEPARATOR-separated str that represents the node whose value
should be updated.
retries: The number of times to retry fetching the node.
Returns:
The value of the node.
Raises:
ZKInternalException: If there was an error trying to fetch the node.'
| def get_node(self, path, retries=5):
| try:
return self.run_with_retry(self.handle.get, path)
except kazoo.exceptions.NoNodeError:
return False
except kazoo.exceptions.ZookeeperError as zoo_exception:
self.logger.exception(zoo_exception)
if (retries > 0):
self.logger.info('Trying again to fetc... |
'Sets the ZooKeeper node at path to value, creating the node if it
doesn\'t exist.
Args:
path: A PATH_SEPARATOR-separated str that represents the node whose value
should be updated.
value: A str representing the value that should be associated with the
updated node.'
| def update_node(self, path, value):
| self.logger.debug('Updating node at {}, with new value {}'.format(path, value))
try:
self.run_with_retry(self.handle.set, path, str(value))
except kazoo.exceptions.NoNodeError:
self.run_with_retry(self.handle.create, path, str(value), ZOO_ACL_OPEN, makepath=True)
|
'Deletes the ZooKeeper node at path, and any child nodes it may have.
Args:
path: A PATH_SEPARATOR-separated str that represents the node to delete.'
| def delete_recursive(self, path):
| try:
children = self.run_with_retry(self.handle.get_children, path)
for child in children:
self.delete_recursive(PATH_SEPARATOR.join([path, child]))
self.run_with_retry(self.handle.delete, path)
except kazoo.exceptions.NoNodeError:
pass
|
'Prints information about the given ZooKeeper node and its children.
Args:
path: A PATH_SEPARATOR-separated str that represents the node to print
info about.'
| def dump_tree(self, path):
| try:
value = self.run_with_retry(self.handle.get, path)[0]
self.logger.info('{0} = "{1}"'.format(path, value))
children = self.run_with_retry(self.handle.get_children, path)
for child in children:
self.dump_tree(PATH_SEPARATOR.join([path, child]))
except kazoo.e... |
'Returns the ZooKeeper path that holds all information for the given
application.
Args:
app_id: A str that represents the application we wish to get the root
path for.
Returns:
A str that represents a ZooKeeper node, whose immediate children are
the transaction prefix path and the locks prefix path.'
| def get_app_root_path(self, app_id):
| return PATH_SEPARATOR.join([APPS_PATH, urllib.quote_plus(app_id)])
|
'Returns the location of the ZooKeeper node who contains all transactions
in progress for the given application.
Args:
app_id: A str that represents the application we wish to get all
transaction information for.
Returns:
A str that represents a ZooKeeper node, whose immediate children are all
of the transactions curre... | def get_transaction_prefix_path(self, app_id):
| return PATH_SEPARATOR.join([self.get_app_root_path(app_id), APP_TX_PATH])
|
'Returns a path that callers can use to get new transaction IDs from
ZooKeeper, which are given as sequence nodes.
Args:
app_id: A str that represents the application we wish to build a new
transaction path for.
Returns: A str that can be used to create new transactions.'
| def get_txn_path_before_getting_id(self, app_id):
| return PATH_SEPARATOR.join([self.get_transaction_prefix_path(app_id), APP_TX_PREFIX])
|
'Returns the location of the ZooKeeper node who contains all information
for a transaction, and is the parent of the transaction lock list and
registered keys for the transaction.
Args:
app_id: A str that represents the application we wish to get the prefix
path for.
txid: An int that represents the transaction ID whos... | def get_transaction_path(self, app_id, txid):
| txstr = (APP_TX_PREFIX + ('%010d' % txid))
return PATH_SEPARATOR.join([self.get_app_root_path(app_id), APP_TX_PATH, txstr])
|
'Returns the location of the ZooKeeper node whose value is a
XG_LIST-separated str, representing all of the locks that have been acquired
for the given transaction ID.
Args:
app_id: A str that represents the application we wish to get the
transaction information about.
txid: A str that represents the transaction ID we ... | def get_transaction_lock_list_path(self, app_id, txid):
| return PATH_SEPARATOR.join([self.get_transaction_path(app_id, txid), TX_LOCK_PATH])
|
'Returns the location of the ZooKeeper node whose children are
all of the blacklisted transaction IDs for the given application ID.
Args:
app_id: A str corresponding to the application who we want to get
blacklisted transaction IDs for.
Returns:
A str corresponding to the ZooKeeper node whose children are blacklisted
t... | def get_blacklist_root_path(self, app_id):
| return PATH_SEPARATOR.join([self.get_transaction_prefix_path(app_id), TX_BLACKLIST_PATH])
|
'Returns the location of the ZooKeeper node whose children are
all of the valid transaction IDs for the given application ID.
Args:
app_id: A str corresponding to the application who we want to get
valid transaction IDs for.
Returns:
A str corresponding to the ZooKeeper node whose children are valid
transaction IDs.'
| def get_valid_transaction_root_path(self, app_id):
| return PATH_SEPARATOR.join([self.get_transaction_prefix_path(app_id), TX_VALIDLIST_PATH])
|
'Gets the valid transaction path with the entity key.
Args:
app_id: The application ID.
entity_key: The entity within the path.
Returns:
A str representing the transaction path.'
| def get_valid_transaction_path(self, app_id, entity_key):
| return PATH_SEPARATOR.join([self.get_valid_transaction_root_path(app_id), urllib.quote_plus(entity_key)])
|
'Gets the root path of the lock for a particular app.
Args:
app_id: The application ID.
key: The key for which we\'re getting the root path lock.
Returns:
A str of the root lock path.'
| def get_lock_root_path(self, app_id, key):
| return PATH_SEPARATOR.join([self.get_app_root_path(app_id), APP_LOCK_PATH, urllib.quote_plus(key)])
|
'Gets the XG path for a transaction.
Args:
app_id: The application ID whose XG path we want.
tx_id: The transaction ID whose XG path we want.
Returns:
A str representing the XG path for the given transaction.'
| def get_xg_path(self, app_id, tx_id):
| txstr = (APP_TX_PREFIX + ('%010d' % tx_id))
return PATH_SEPARATOR.join([self.get_app_root_path(app_id), APP_TX_PATH, txstr, XG_PREFIX])
|
'Creates a new node in ZooKeeper, with the given value.
Args:
path: The path to create the node at.
value: The value that we should store in the node.
Raises:
ZKTransactionException: If the sequence node couldn\'t be created.'
| def create_node(self, path, value):
| try:
self.run_with_retry(self.handle.create, path, value=str(value), acl=ZOO_ACL_OPEN, ephemeral=False, sequence=False, makepath=True)
except kazoo.exceptions.KazooException as kazoo_exception:
self.logger.exception(kazoo_exception)
raise ZKTransactionException("Couldn't create pat... |
'Creates a new sequence node in ZooKeeper, with a non-zero initial ID.
We avoid using zero as the initial ID because Google App Engine apps can
use a zero ID as a sentinel value, to indicate that an ID should be
allocated for them.
Args:
path: The prefix to create the sequence node at. For example, a prefix
of \'/abc\'... | def create_sequence_node(self, path, value):
| try:
txn_id_path = self.run_with_retry(self.handle.create, path, value=str(value), acl=ZOO_ACL_OPEN, ephemeral=False, sequence=True, makepath=True)
if txn_id_path:
txn_id = long(txn_id_path.split(PATH_SEPARATOR)[(-1)].lstrip(APP_TX_PREFIX))
if (txn_id == 0):
s... |
'Acquires a new id for an upcoming transaction.
Note that the caller must lock particular root entities using acquire_lock,
and that the transaction ID expires after a constant amount of time.
Args:
app_id: A str representing the application we want to perform a
transaction on.
is_xg: A bool that indicates if this tran... | def get_transaction_id(self, app_id, is_xg=False):
| timestamp = str(time.time())
app_path = self.get_txn_path_before_getting_id(app_id)
txn_id = self.create_sequence_node(app_path, timestamp)
if is_xg:
xg_path = self.get_xg_path(app_id, txn_id)
self.create_node(xg_path, timestamp)
return txn_id
|
'Gets the status of the given transaction.
Args:
app_id: A str representing the application whose transaction we wish to
query.
txid: An int that indicates the transaction ID we should query.
Returns:
True if the transaction is in progress.
Raises:
ZKTransactionException: If the transaction is not in progress, or it
ha... | def check_transaction(self, app_id, txid):
| txpath = self.get_transaction_path(app_id, txid)
try:
if self.is_blacklisted(app_id, txid):
raise ZKTransactionException('Transaction {0} timed out.'.format(txid))
except ZKInternalException as zk_exception:
self.logger.exception(zk_exception)
raise ZKTransaction... |
'Checks to see if the named transaction is currently running.
Args:
app_id: A str representing the application whose transaction we wish to
query.
txid: An int that indicates the transaction ID we should query.
Returns:
True if the transaction is in progress, and False otherwise.
Raises:
ZKTransactionException: If the ... | def is_in_transaction(self, app_id, txid, retries=5):
| tx_lock_path = self.get_transaction_lock_list_path(app_id, txid)
if self.is_blacklisted(app_id, txid):
raise ZKTransactionException('Transaction {} is blacklisted'.format(txid))
try:
if (not self.run_with_retry(self.handle.exists, tx_lock_path)):
return False
ret... |
'Checks to see if a lock does not have a transaction linked.
If the groomer misses to unlock a lock for whatever reason, we need
to make sure the lock is eventually released.
Args:
tx_lockpath: A str, the path to the transaction using the lock.
Returns:
True if the lock is an orphan, and False otherwise.'
| def is_orphan_lock(self, tx_lockpath):
| try:
self.handle.get(tx_lockpath)
return False
except kazoo.exceptions.NoNodeError:
return True
|
'Acquire an additional lock for a cross group transaction.
Args:
app_id: A str representing the application ID.
txid: The transaction ID you are acquiring a lock for. Built into
the path.
entity_key: Used to get the root path.
create: A bool that indicates if we should create a new Zookeeper node
to store the lock info... | def acquire_additional_lock(self, app_id, txid, entity_key, create):
| txpath = self.get_transaction_path(app_id, txid)
lockrootpath = self.get_lock_root_path(app_id, entity_key)
lockpath = None
try:
lockpath = self.run_with_retry(self.handle.create, lockrootpath, value=str(txpath), acl=ZOO_ACL_OPEN, ephemeral=False, sequence=False, makepath=True)
except kazoo.... |
'Checks to see if the transaction can operate over multiple entity
groups.
Args:
app_id: The application ID that the transaction operates over.
tx_id: The transaction ID that may or may not be XG.
Returns:
True if the transaction is XG, False otherwise.
Raises:
ZKTransactionException: on ZooKeeper exceptions.
ZKInterna... | def is_xg(self, app_id, tx_id):
| try:
return self.run_with_retry(self.handle.exists, self.get_xg_path(app_id, tx_id))
except kazoo.exceptions.ZookeeperError as zk_exception:
raise ZKTransactionException('ZooKeeper exception:{0}'.format(zk_exception))
except kazoo.exceptions.KazooException as kazoo_exception:
self... |
'Acquire lock for transaction. It will acquire additional locks
if the transactions is XG.
You must call get_transaction_id() first to obtain transaction ID.
You could call this method anytime if the root entity key is same,
or different in the case of it being XG.
Args:
app_id: The application ID to acquire a lock for... | def acquire_lock(self, app_id, txid, entity_key):
| lockrootpath = self.get_lock_root_path(app_id, entity_key)
try:
if self.is_in_transaction(app_id, txid):
transaction_lock_path = self.get_transaction_lock_list_path(app_id, txid)
prelockpath = self.run_with_retry(self.handle.get, transaction_lock_path)[0]
lock_list = ... |
'Gets a list of keys updated in this transaction.
Args:
app_id: A str corresponding to the application ID whose transaction we
wish to query.
txid: The transaction ID that we want to get a list of updated keys for.
Returns:
A list of (keys, txn_id) that have been updated in this transaction.
Raises:
ZKTransactionExcept... | def get_updated_key_list(self, app_id, txid):
| txpath = self.get_transaction_path(app_id, txid)
try:
child_list = self.run_with_retry(self.handle.get_children, txpath)
keylist = []
for item in child_list:
if re.match(('^' + TX_UPDATEDKEY_PREFIX), item):
keyandtx = self.run_with_retry(self.handle.get, PATH_... |
'Remove a transaction\'s sequence node.
Args:
app_id: A string specifying an application ID.
txid: An integer specifying a transaction ID.'
| def remove_tx_node(self, app_id, txid):
| txpath = self.get_transaction_path(app_id, txid)
try:
self.run_with_retry(self.handle.delete, txpath, (-1), True)
except NoNodeError:
return
except RetryFailedError:
raise ZKInternalException('Unable to remove transaction for {}'.format(txid))
|
'Releases all locks acquired during this transaction.
Callers must call acquire_lock before calling release_lock. Upon calling
release_lock, the given transaction ID is no longer valid.
Args:
app_id: The application ID we are releasing a lock for.
txid: The transaction ID we are releasing a lock for.
Returns:
True if t... | def release_lock(self, app_id, txid):
| self.check_transaction(app_id, txid)
txpath = self.get_transaction_path(app_id, txid)
transaction_lock_path = self.get_transaction_lock_list_path(app_id, txid)
try:
lock_list_str = self.run_with_retry(self.handle.get, transaction_lock_path)[0]
lock_list = lock_list_str.split(LOCK_LIST_SE... |
'Checks to see if the given transaction ID has been blacklisted (that is,
if it is no longer considered to be a valid transaction).
Args:
app_id: The application ID whose transaction ID we want to validate.
txid: The transaction ID that we want to validate.
Returns:
True if the transaction is blacklisted, False otherwi... | def is_blacklisted(self, app_id, txid, retries=5):
| try:
blacklist_root = self.get_blacklist_root_path(app_id)
blacklist_txn = PATH_SEPARATOR.join([blacklist_root, str(txid)])
return self.run_with_retry(self.handle.exists, blacklist_txn)
except kazoo.exceptions.KazooException as kazoo_exception:
self.logger.exception(kazoo_excepti... |
'This returns valid transaction id for the entity key.
Args:
app_id: A str representing the application ID.
target_txid: The transaction id that we want to check for validness.
entity_key: The entity that the transaction operates over.
Returns:
A long containing the latest valid transaction id, or zero if there is
none... | def get_valid_transaction_id(self, app_id, target_txid, entity_key):
| try:
if self.is_in_transaction(app_id, target_txid):
key_list = self.get_updated_key_list(app_id, target_txid)
for (key, txn_id) in key_list:
if (entity_key == key):
return long(txn_id)
except ZKTransactionException as zk_exception:
vtx... |
'Registers a key which is a part of a transaction. This is to know
what journal version we must rollback to upon failure.
Args:
app_id: A str representing the application ID.
current_txid: The current transaction ID for which we\'ll rollback to upon
failure.
target_txid: A long transaction ID we are rolling forward to.... | def register_updated_key(self, app_id, current_txid, target_txid, entity_key):
| vtxpath = self.get_valid_transaction_path(app_id, entity_key)
try:
if self.run_with_retry(self.handle.exists, vtxpath):
self.run_with_retry(self.handle.set_async, vtxpath, str(target_txid))
else:
value = PATH_SEPARATOR.join([urllib.quote_plus(entity_key), str(target_txid)... |
'Marks the given transaction as failed, invalidating its use by future
callers.
This function also cleans up successful transactions that have expired.
Args:
app_id: The application ID whose transaction we wish to invalidate.
txid: An int representing the transaction ID we wish to invalidate.
Returns:
True if the trans... | def notify_failed_transaction(self, app_id, txid):
| self.logger.debug('notify_failed_trasnsaction: app={}, txid={}'.format(app_id, txid))
lockpath = None
lock_list = []
txpath = self.get_transaction_path(app_id, txid)
try:
lockpath = self.run_with_retry(self.handle.get, PATH_SEPARATOR.join([txpath, TX_LOCK_PATH]))[0]
lock_list =... |
'Transaction ID garbage collection (GC) runner.
Note: This must be running as separate thread.'
| def gc_runner(self):
| self.logger.debug('Starting GC thread.')
while self.gc_running:
try:
app_list = self.run_with_retry(self.handle.get_children, APPS_PATH)
for app in app_list:
app_id = urllib.unquote_plus(app)
app_path = PATH_SEPARATOR.join([APPS_PATH, app])
... |
'Try to garbage collect timed out transactions.
Args:
app_id: The application ID.
app_path: The application path for which we\'re garbage collecting.
Returns:
True if the garbage collector ran, False otherwise.'
| def try_garbage_collection(self, app_id, app_path):
| last_time = 0
gc_time_path = PATH_SEPARATOR.join([app_path, GC_TIME_PATH])
try:
val = self.run_with_retry(self.handle.get, gc_time_path)[0]
last_time = float(val)
except kazoo.exceptions.NoNodeError:
last_time = 0
except (ZookeeperError, KazooException):
self.logger.e... |
'Tries to get the lock based on path.
Args:
path: A str, the lock path.
Returns:
True if the lock was obtained, False otherwise.'
| def get_lock_with_path(self, path):
| try:
now = str(time.time())
self.run_with_retry(self.handle.create, path, value=now, acl=ZOO_ACL_OPEN, ephemeral=True)
except kazoo.exceptions.NoNodeError:
self.logger.error('Unable to create {}'.format(path))
return False
except kazoo.exceptions.NodeExistsError:
... |
'Releases lock based on path.
Args:
path: A str, the lock path.
Returns:
True on success, False on system failures.
Raises:
ZKTransactionException: If the lock could not be released.'
| def release_lock_with_path(self, path):
| try:
self.run_with_retry(self.handle.delete, path)
except kazoo.exceptions.NoNodeError:
raise ZKTransactionException('Unable to delete lock: {0}'.format(path))
except (kazoo.exceptions.SystemZookeeperError, KazooException, SystemError):
self.logger.exception('Unable to... |
'Clean up temporary batch data.
Args:
app: A string containing the application ID.
transaction: An integer containing the transaction ID.'
| def clean_up_batch(self, app, transaction):
| self.logger.debug('Cleaning up batch: app={}, transaction={}'.format(app, transaction))
clear_batch = '\n DELETE FROM batches\n WHERE app = %(app)s AND transaction = %(transaction)s\n '
parameters = {'app': a... |
'Write the batch to the entities table.
Args:
app: a string specifying the application ID.
txid: An integer specifying the transaction ID.'
| def _write_batch(self, app, txid):
| composite_indices = [entity_pb.CompositeIndex(index) for index in self.db_access.get_indices(str(app))]
self.logger.debug('Applying batch: app={}, transaction={}'.format(app, txid))
select_mutations = '\n SELECT old_value, new_value FROM batches\n ... |
'Check if batch completed and apply mutations if necessary.
Args:
app: A string containing the application ID.
transaction: An integer containing the transaction ID.'
| def resolve_batch(self, app, transaction):
| session = self.db_access.session
large_batch = LargeBatch(session, app, transaction)
large_batch.claim()
if large_batch.applied:
self._write_batch(app, transaction)
self.clean_up_batch(app, transaction)
large_batch.cleanup()
|
'Execute garbage collection for an application.
Args:
app_id: The application ID.
app_path: The application path.'
| def execute_garbage_collection(self, app_id, app_path):
| start = time.time()
txrootpath = PATH_SEPARATOR.join([app_path, APP_TX_PATH])
try:
txlist = self.run_with_retry(self.handle.get_children, txrootpath)
except kazoo.exceptions.NoNodeError:
return
except (ZookeeperError, KazooException):
self.logger.exception('Unable to ge... |
'Fetch a list of open transactions for a given project.
Args:
project: A string containing a project ID.
Returns:
A list of integers specifying transaction IDs.'
| def get_current_transactions(self, project):
| project_path = PATH_SEPARATOR.join([APPS_PATH, project])
txrootpath = PATH_SEPARATOR.join([project_path, APP_TX_PATH])
try:
txlist = self.run_with_retry(self.handle.get_children, txrootpath)
except kazoo.exceptions.NoNodeError:
return []
return [int(txid.lstrip(APP_TX_PREFIX)) for tx... |
'Create an InspectableCounter.
Args:
client: A KazooClient object.
path: A string containing the ZooKeeper path to use for the counter.
default: An integer containing the default counter value.'
| def __init__(self, client, path, default=0):
| self.client = client
self.path = path
self.default = default
self.default_type = type(default)
self._ensured_path = False
|
'Make sure the ZooKeeper path that stores the counter value exists.'
| def _ensure_node(self):
| if (not self._ensured_path):
self.client.ensure_path(self.path)
self._ensured_path = True
|
'Retrieve the current value and node version from ZooKeeper.
Returns:
A tuple consisting of the current count and node version.'
| def _value(self):
| self._ensure_node()
(old, stat) = self.client.get(self.path)
old = (old.decode('ascii') if (old != '') else self.default)
version = stat.version
data = self.default_type(old)
return (data, version)
|
'Retrieve the current value from ZooKeeper.
Returns:
An integer containing the current count.'
| @property
def value(self):
| return self._value()[0]
|
'Add a value to the counter.
Args:
value: An integer specifying how much to add.
Returns:
An integer indicating the new count after the change.'
| def _change(self, value):
| if (not isinstance(value, self.default_type)):
raise TypeError('Invalid type for value change')
return self.client.retry(self._inner_change, value)
|
'Add a value to the counter.
Args:
value: An integer specifying how much to add.
Returns:
An integer indicating the new count after the change.'
| def _inner_change(self, value):
| (data, version) = self._value()
new_value = (data + value)
new_data = repr(new_value).encode('ascii')
try:
self.client.set(self.path, new_data, version=version)
return new_value
except BadVersionError:
raise ForceRetryError()
|
'Add value to counter.
Returns:
An integer indicating the new count after the change.'
| def __add__(self, value):
| return self._change(value)
|
'Subtract value from counter.
Returns:
An integer indicating the new count after the change.'
| def __sub__(self, value):
| return self._change((- value))
|
'Create a Queue object.
Args:
queue_info: A dictionary containing queue info.
app: A string containing the application ID.'
| def __init__(self, queue_info, app):
| self.app = app
if ('name' not in queue_info):
raise InvalidQueueConfiguration('Queue requires a name: {}'.format(queue_info))
self.name = queue_info['name']
self.task_retry_limit = self.DEFAULT_RETRY_LIMIT
if ('retry_parameters' in queue_info):
retry_params = queue_info['... |
'Ensures all of the Queue\'s attributes are valid.
Raises:
InvalidQueueConfiguration if there is an invalid attribute.'
| def validate_config(self):
| for (attribute, rule) in QUEUE_ATTRIBUTE_RULES.iteritems():
try:
value = getattr(self, attribute)
except AttributeError:
continue
if (not rule(value)):
message = 'Invalid queue configuration for {queue}.{param}: {value}'.format(queue=self.na... |
'Checks if this Queue is equivalent to another.
Returns:
A boolean indicating whether or not the two Queues are equal.'
| def __eq__(self, other):
| if (not isinstance(other, self.__class__)):
return False
if ((self.app != other.app) or (self.name != other.name)):
return False
for attribute in self.OPTIONAL_ATTRS:
if hasattr(self, attribute):
if (not hasattr(other, attribute)):
return False
... |
'Checks if this Queue is different than another.
Returns:
A boolean indicating whether or not the two Queues are different.'
| def __ne__(self, other):
| return (not self.__eq__(other))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.