desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Retrieves operation status. Args: project_id: A string specifying a project ID. operation_id: A string specifying an operation ID.'
def get(self, project_id, operation_id):
self.authenticate() try: operation = operations[operation_id] except KeyError: raise CustomHTTPError(HTTPCodes.NOT_FOUND, message='Operation not found.') self.write(json_encode(operation.rest_repr()))
'Creates a new CreateVersionOperation. Args: project_id: A string specifying a project ID. service_id: A string specifying a service ID. version: A dictionary containing verision details.'
def __init__(self, project_id, service_id, version):
self.project_id = project_id self.service_id = service_id self.version = version self.id = str(uuid.uuid4()) self.start_time = datetime.datetime.utcnow() self.done = False self.response = None self.error = None self.method = None
'Marks the operation as failed. Args: message: A string specifying the reason the operation failed.'
def set_error(self, message):
self.done = True self.error = {'message': message}
'Formats the operation for a REST API response. Returns: A dictionary containing operation details.'
def rest_repr(self):
output = {'name': 'apps/{}/operations/{}'.format(self.project_id, self.id), 'metadata': {'@type': Types.OPERATION_METADATA, 'method': self.method, 'insertTime': (self.start_time.isoformat() + 'Z'), 'target': 'apps/{}/services/{}/versions/{}'.format(self.project_id, self.service_id, self.version['id'])}, 'done': sel...
'Creates a new CreateVersionOperation. Args: project_id: A string specifying a project ID. service_id: A string specifying a service ID. version: A dictionary containing verision details.'
def __init__(self, project_id, service_id, version):
super(CreateVersionOperation, self).__init__(project_id, service_id, version) self.method = Methods.CREATE_VERSION
'Marks the operation as completed. Args: url: A string specifying the location of the version.'
def finish(self, url):
create_time = datetime.datetime.utcnow() self.response = {'@type': Types.VERSION, 'name': 'apps/{}/services/{}/versions/{}'.format(self.project_id, self.service_id, self.version['id']), 'id': self.version['id'], 'runtime': self.version['runtime'], 'servingStatus': ServingStatus.SERVING, 'createTime': (create_ti...
'Creates a new CreateVersionOperation. Args: project_id: A string specifying a project ID. service_id: A string specifying a service ID. version: A dictionary containing verision details.'
def __init__(self, project_id, service_id, version):
super(DeleteVersionOperation, self).__init__(project_id, service_id, version) self.method = Methods.DELETE_VERSION
'Marks the operation as completed.'
def finish(self):
self.response = {'@type': Types.EMPTY} self.done = True
'Creates a new UpdateVersionOperation. Args: project_id: A string specifying a project ID. service_id: A string specifying a service ID. version: A dictionary containing verision details.'
def __init__(self, project_id, service_id, version):
super(UpdateVersionOperation, self).__init__(project_id, service_id, version) self.method = Methods.UPDATE_VERSION
'Creates new OperationsCache. Args: size: An integer specifying the maximum size of the cache.'
def __init__(self, size=256):
super(OperationsCache, self).__init__() self.operations_list = [] self.max_size = size
'Adds a new operation to the cache. Args: key: A string specifying the operation ID. value: A dictionary containing the operation details.'
def __setitem__(self, key, value):
super(OperationsCache, self).__setitem__(key, value) self.operations_list.append(key) to_remove = (len(self) - self.max_size) for _ in range(to_remove): old_key = self.operations_list.pop(0) del self[old_key]
'Defines required resources to handle requests. Args: zk_client: A KazooClient.'
def initialize(self, zk_client):
self.zk_client = zk_client
'Handles UpdateQueues operations.'
def post(self):
self.authenticate() project_id = self.get_argument('app_id', None) if (project_id is None): raise CustomHTTPError(HTTPCodes.BAD_REQUEST, message='app_id parameter is required') try: payload = yaml.safe_load(self.request.body) except ParserError: raise InvalidQueueCon...
'Ensures requests are authenticated. Raises: CustomHTTPError if the secret is invalid.'
def authenticate(self):
if ('AppScale-Secret' not in self.request.headers): message = 'A required header is missing: AppScale-Secret' raise CustomHTTPError(HTTPCodes.UNAUTHORIZED, message=message) if (self.request.headers['AppScale-Secret'] != options.secret): raise CustomHTTPError(HTTPCodes.UNAU...
'Writes a custom JSON-based error message. Args: status_code: An integer specifying the HTTP error code.'
def write_error(self, status_code, **kwargs):
details = {'code': status_code} if ('exc_info' in kwargs): error = kwargs['exc_info'][1] try: details.update(error.kwargs) except AttributeError: pass self.finish(json_encode({'error': details}))
'Constructor. Args: datastore_batch: A reference to the batch datastore interface. zookeeper: A reference to the zookeeper interface.'
def __init__(self, datastore_batch, zookeeper=None, log_level=logging.INFO):
class_name = self.__class__.__name__ self.logger = logging.getLogger(class_name) self.logger.setLevel(log_level) assert datastore_batch.valid_data_version() self.logger.info('Starting {}'.format(class_name)) self.datastore_batch = datastore_batch self.zookeeper = zookeeper self.taskqu...
'Returns the limit that should be used for the given query. Args: query: A datastore_pb.Query. Returns: An int, the limit to be used when accessing the datastore.'
def get_limit(self, query):
limit = self._MAXIMUM_RESULTS if query.has_count(): limit = min(query.count(), self._MAXIMUM_RESULTS) if query.has_limit(): limit = min(query.limit(), limit) if query.has_offset(): limit = (limit + min(query.offset(), self._MAXIMUM_RESULTS)) if (limit <= 0): limit = 1...
'Takes an encoded string and converts it to a PropertyValue. Args: value: An encoded str. prop_value: PropertyValue to fill in.'
@staticmethod def __decode_index_str(value, prop_value):
value = str(value).replace('\x01\x01', '\x00').replace('\x01\x02', '\x01') decoded_value = sortable_pb_encoder.Decoder(array.array('B', str(value))) prop_value.Merge(decoded_value)
'Verify that this is the stub for app_id. Args: app_id: An application ID. Raises: AppScaleBadArg: If the application id is not set.'
@staticmethod def validate_app_id(app_id):
if (not app_id): raise dbconstants.AppScaleBadArg('Application name must be set')
'Validate this key by checking to see if it has a name or id. Args: key: entity_pb.Reference Raises: datastore_errors.BadRequestError: if the key is invalid TypeError: if key is not of entity_pb.Reference'
@staticmethod def validate_key(key):
if (not isinstance(key, entity_pb.Reference)): raise TypeError('Expected type Reference') DatastoreDistributed.validate_app_id(key.app()) for elem in key.path().element_list(): if (elem.has_id() and elem.has_name()): raise datastore_errors.BadRequestError('Each key pa...
'Returns the namespace prefix for a query. Args: data: An Entity, Key or Query PB, or an (app_id, ns) tuple. Returns: A valid table prefix.'
def get_table_prefix(self, data):
if isinstance(data, entity_pb.EntityProto): app_id = clean_app_id(data.key().app()) namespace = data.key().name_space() elif isinstance(data, tuple): app_id = data[0] namespace = data[1] else: app_id = clean_app_id(data.app()) namespace = data.name_space() ...
'Get the key string for the ancestor portion of a composite key. Args: ent_key: A string of the entire path of an entity. Returns: A str of the path of the ancestor.'
@staticmethod def get_ancestor_key_from_ent_key(ent_key):
ancestor = '' tokens = str(ent_key).split(dbconstants.KIND_SEPARATOR) for token in tokens[:(-2)]: ancestor += (token + dbconstants.KIND_SEPARATOR) return ancestor
'Creates a key to the composite index table for a given entity for a composite cursor. Keys are built as such: app_id/ns/composite_id/ancestor/valuevaluevalue..../entity_key Components explained: ns: The namespace of the entity. composite_id: The composite ID assigned to this index upon creation. ancestor: The root anc...
@staticmethod def get_composite_index_key(index, entity, position_list=None, filters=None):
composite_id = index.id() definition = index.definition() app_id = clean_app_id(entity.key().app()) name_space = entity.key().name_space() ent_key = encode_index_pb(entity.key().path()) pre_comp_index_key = '{0}{1}{2}{4}{3}{4}'.format(app_id, DatastoreDistributed._NAMESPACE_SEPARATOR, name_space...
'Creates composite indexes for a set of entities. Args: entities: A list entities. composite_indexes: A list of datastore_pb.CompositeIndex.'
def insert_composite_indexes(self, entities, composite_indexes):
if (not composite_indexes): return row_keys = [] row_values = {} for ent in entities: for index_def in composite_indexes: kind = get_entity_kind(ent.key()) if (index_def.definition().entity_type() != kind): continue prop_name_def_list =...
'Deletes a index for the given application identifier. Args: app_id: A string representing the application identifier. index: A entity_pb.CompositeIndex object.'
def delete_composite_index_metadata(self, app_id, index):
self.logger.info('Deleting composite index:\n{}'.format(index)) index_keys = [] composite_id = str(index.id()) index_keys.append(self._SEPARATOR.join([app_id, 'index', composite_id])) self.datastore_batch.batch_delete(dbconstants.METADATA_TABLE, index_keys, column_names=dbconstants.METADATA_TA...
'Stores a new index for the given application identifier. Args: app_id: A string representing the application identifier. index: A entity_pb.CompositeIndex object. Returns: A unique number representing the composite index ID.'
def create_composite_index(self, app_id, index):
rand = int((str(int(time.time())) + str(random.randint(0, 999999)))) index.set_id(rand) encoded_entity = index.Encode() row_key = self._SEPARATOR.join([app_id, 'index', str(rand)]) row_keys = [row_key] row_values = {} row_values[row_key] = {dbconstants.METADATA_SCHEMA[0]: encoded_entity} ...
'Updates an index for a given app ID. Args: app_id: A string containing the app ID. index: An entity_pb.CompositeIndex object.'
def update_composite_index(self, app_id, index):
self.logger.info('Updating index: {}'.format(index)) entries_updated = 0 entity_type = index.definition().entity_type() prefix = '{app}{delimiter}{entity_type}{kind_separator}'.format(app=app_id, delimiter=(self._SEPARATOR * 2), entity_type=entity_type, kind_separator=dbconstants.KIND_SEPARATOR) ...
'Allocates a block of IDs for a project. Args: project: A string specifying the project ID. size: An integer specifying the number of IDs to reserve. Returns: A tuple of integers specifying the start and end ID.'
def allocate_size(self, project, size):
allocator = EntityIDAllocator(self.datastore_batch.session, project) return allocator.allocate_size(size)
'Reserves all IDs up to the one given. Args: project: A string specifying the project ID. max_id: An integer specifying the maximum ID to allocated. Returns: A tuple of integers specifying the start and end ID.'
def allocate_max(self, project, max_id):
allocator = EntityIDAllocator(self.datastore_batch.session, project) return allocator.allocate_max(max_id)
'Updates indexes of existing entities, inserts new entities and indexes for them. Args: app: A string containing the application ID. entities: List of entities. composite_indexes: A list or tuple of CompositeIndex objects.'
def put_entities(self, app, entities, composite_indexes=()):
self.logger.debug('Inserting {} entities'.format(len(entities))) entity_keys = [] for entity in entities: prefix = self.get_table_prefix(entity) entity_keys.append(get_entity_key(prefix, entity.key().path())) current_values = self.datastore_batch.batch_get_entity(dbconstants.APP_EN...
'Deletes the entities and the indexes associated with them. Args: group: An entity group Reference object. txid: An integer specifying a transaction ID. keys: An interable containing entity Reference objects. composite_indexes: A list or tuple of CompositeIndex objects.'
def delete_entities(self, group, txid, keys, composite_indexes=()):
entity_keys = [] for key in keys: prefix = self.get_table_prefix(key) entity_keys.append(get_entity_key(prefix, key.path())) current_values = self.datastore_batch.batch_get_entity(dbconstants.APP_ENTITY_TABLE, entity_keys, APP_ENTITY_SCHEMA) for key in entity_keys: if (not curren...
'Stores and entity and its indexes in the datastore. Args: app_id: Application ID. put_request: Request with entities to store. put_response: The response sent back to the app server. Raises: ZKTransactionException: If we are unable to acquire/release ZooKeeper locks.'
def dynamic_put(self, app_id, put_request, put_response):
if (app_id not in self.scattered_allocators): self.scattered_allocators[app_id] = ScatteredAllocator(self.datastore_batch.session, app_id) allocator = self.scattered_allocators[app_id] entities = put_request.entity_list() for entity in entities: self.validate_key(entity.key()) fo...
'Extract the root key from an entity key. We remove any excess children from a string to get to the root key. Args: entity_key: A string or Key object representing a row key. Returns: The root key extracted from the row key. Raises: TypeError: If the type is not supported.'
def get_root_key_from_entity_key(self, entity_key):
if isinstance(entity_key, str): tokens = entity_key.split(dbconstants.KIND_SEPARATOR) return (tokens[0] + dbconstants.KIND_SEPARATOR) elif isinstance(entity_key, entity_pb.Reference): app_id = clean_app_id(entity_key.app()) path = entity_key.path() element_list = path.ele...
'Acquires locks for non-transaction operations. Acquires locks and transaction handlers for each entity group in the set of entities. It is possible that multiple entities share the same group, and hence they can use the same lock when being updated. The reason we get locks for puts in non-transactional puts is that i...
def acquire_locks_for_nontrans(self, app_id, entities, retries=0):
root_keys = [] txn_hash = {} if (not isinstance(entities, list)): raise TypeError('Expected a list and got {0}'.format(entities.__class__)) for ent in entities: if isinstance(ent, entity_pb.Reference): root_keys.append(self.get_root_key_from_entity_key(ent)) ...
'Gets the root key string from an ancestor listing. Args: app_id: The app ID of the listing. ns: The namespace of the entity. ancestor_list: The ancestry of a given entity. Returns: A string representing the root key of an entity.'
def get_root_key(self, app_id, ns, ancestor_list):
prefix = self.get_table_prefix((app_id, ns)) first_ent = ancestor_list[0] if first_ent.has_name(): key_id = first_ent.name() elif first_ent.has_id(): key_id = str(first_ent.id()).zfill(ID_KEY_LENGTH) return '{0}{1}{2}:{3}{4}'.format(prefix, self._NAMESPACE_SEPARATOR, first_ent.type()...
'A wrapper for isinstance for mocking purposes. Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object\'s type. Args: obj: The object to check. expected_type: A instance type we are comparing obj\'s type to. Returns: True if obj is ...
def is_instance_wrapper(self, obj, expected_type):
return isinstance(obj, expected_type)
'Acquires locks for entities for one particular entity group. Args: entities: A list of entities (entity_pb.EntityProto or entity_pb.Reference) for which are are getting a lock for. txnid: The transaction ID handler. Returns: A hash mapping root keys to transaction IDs. Raises: ZKTransactionException: If lock is not ob...
def acquire_locks_for_trans(self, entities, txnid):
root_keys = [] txn_hash = {} if (not self.is_instance_wrapper(entities, list)): raise TypeError('Expected a list and got {0}'.format(entities.__class__)) for ent in entities: if self.is_instance_wrapper(ent, entity_pb.Reference): root_keys.append(self.get_root_...
'Releases locks for non-transactional puts. Args: entities: List of entities for which we are releasing locks. Can be either entity_pb.EntityProto or entity_pb.Reference. txn_hash: A hash mapping root keys to transaction IDs. Raises: ZKTransactionException: If we are unable to release locks.'
def release_locks_for_nontrans(self, app_id, entities, txn_hash):
root_keys = [] for ent in entities: if isinstance(ent, entity_pb.EntityProto): ent = ent.key() root_keys.append(self.get_root_key_from_entity_key(ent)) root_keys = list(set(root_keys)) for root_key in root_keys: txnid = txn_hash[root_key] self.zookeeper.releas...
'Given a list of keys fetch the entities. Args: key_list: A list of keys to fetch. Returns: A tuple of entities from the datastore and key list.'
def fetch_keys(self, key_list):
row_keys = [] for key in key_list: self.validate_app_id(key.app()) index_key = str(encode_index_pb(key.path())) prefix = self.get_table_prefix(key) row_keys.append(self._SEPARATOR.join([prefix, index_key])) result = self.datastore_batch.batch_get_entity(dbconstants.APP_ENTITY...
'Fetch keys from the datastore. Args: app_id: The application ID. get_request: Request with list of keys. get_response: Response to application server. Raises: ZKTransactionException: If a lock was unable to get acquired.'
def dynamic_get(self, app_id, get_request, get_response):
keys = get_request.key_list() if (len(keys) < 5): self.logger.debug('Get:\n{}'.format(get_request)) else: self.logger.debug('Get: {} keys'.format(len(keys))) if get_request.has_transaction(): (results, row_keys) = self.fetch_keys(keys) fetched_groups = {group_for_ke...
'Deletes a set of rows. Args: app_id: The application ID. delete_request: Request with a list of keys.'
def dynamic_delete(self, app_id, delete_request):
keys = delete_request.key_list() if (not keys): return ent_kinds = [] for key in delete_request.key_list(): last_path = key.path().element_list()[(-1)] if (last_path.type() not in ent_kinds): ent_kinds.append(last_path.type()) composite_indexes = [] filtered_i...
'Transform a list of filters into a more usable form. Args: filters: A list of filter PBs. Returns: A dict mapping property names to lists of (op, value) tuples.'
def generate_filter_info(self, filters):
filter_info = {} for filt in filters: prop = filt.property(0) value = prop.value() if (prop.name() == '__key__'): value = reference_property_to_reference(value.referencevalue()) value = value.path() filter_info.setdefault(prop.name(), []).append((filt.op()...
'Transform a list of orders into a more usable form which is a tuple of properties and ordering directions. Args: orders: A list of order PBs. Returns: A list of (property, direction) tuples.'
def generate_order_info(self, orders):
orders = [(order.property(), order.direction()) for order in orders] if (orders and (orders[(-1)] == ('__key__', datastore_pb.Query_Order.ASCENDING))): orders.pop() return orders
'Builds the start key for cursor query. Args: prefix: The start key prefix (app id and namespace). prop_name: Property name of the filter. order: Sort order the query requires. last_result: Last result encoded in cursor. query: A datastore_pb.Query object. Raises: AppScaleDBError if unable to retrieve original entity o...
def __get_start_key(self, prefix, prop_name, order, last_result, query=None):
e = last_result path = str(encode_index_pb(e.key().path())) last_result_key = self._SEPARATOR.join([prefix, path]) if ((not prop_name) and (not order)): return last_result_key if e.property_list(): plist = e.property_list() else: ret = self.datastore_batch.batch_get_entit...
'Checks to see if the current query can be executed as a zigzag merge join. Args: query: A datastore_pb.Query. filter_info: dict of property names mapping to tuples of filter operators and values. order_info: tuple with property name and the sort order. Returns: True if it qualifies as a zigzag merge join, and false ot...
def is_zigzag_merge_join(self, query, filter_info, order_info):
filter_info = self.remove_exists_filters(filter_info) order_properties = [] for order in order_info: order_properties.append(order[0]) property_names = [] for property_name in filter_info: filt = filter_info[property_name] property_names.append(property_name) if (filt...
'Given a list of keys fetch the entities from the entity table. Args: rowkeys: A list of strings which are keys to the entitiy table. Returns: A list of entities.'
def __fetch_entities_from_row_list(self, rowkeys):
result = self.datastore_batch.batch_get_entity(dbconstants.APP_ENTITY_TABLE, rowkeys, APP_ENTITY_SCHEMA) entities = [] for key in rowkeys: if ((key in result) and (APP_ENTITY_SCHEMA[0] in result[key])): entities.append(result[key][APP_ENTITY_SCHEMA[0]]) return entities
'Extract the rowkeys to fetch from a list of references. Args: refs: key/value pairs where the values contain a reference to the entitiy table. Returns: A list of rowkeys.'
def __extract_rowkeys_from_refs(self, refs):
if (len(refs) == 0): return [] keys = [item.keys()[0] for item in refs] rowkeys = [] for (index, ent) in enumerate(refs): key = keys[index] ent = ent[key]['reference'] if (ent not in rowkeys): rowkeys.append(ent) return rowkeys
'Given a list of references, get the entities. Args: refs: key/value pairs where the values contain a reference to the entitiy table. Returns: A list of validated entities.'
def __fetch_entities(self, refs):
rowkeys = self.__extract_rowkeys_from_refs(refs) return self.__fetch_entities_from_row_list(rowkeys)
'Given a list of references, return the entities as a dictionary. Args: refs: key/value pairs where the values contain a reference to the entitiy table. Returns: A dictionary of validated entities.'
def __fetch_entities_dict(self, refs):
rowkeys = self.__extract_rowkeys_from_refs(refs) return self.__fetch_entities_dict_from_row_list(rowkeys)
'Given a list of rowkeys, return the entities as a dictionary. Args: rowkeys: A list of strings which are keys to the entitiy table. Returns: A dictionary of validated entities.'
def __fetch_entities_dict_from_row_list(self, rowkeys):
results = self.datastore_batch.batch_get_entity(dbconstants.APP_ENTITY_TABLE, rowkeys, APP_ENTITY_SCHEMA) clean_results = {} for key in rowkeys: if ((key in results) and (APP_ENTITY_SCHEMA[0] in results[key])): clean_results[key] = results[key][APP_ENTITY_SCHEMA[0]] return clean_resu...
'Fetch all the valid entities as needed from references. Args: index_dict: A dictionary containing a list of index entries for each reference. limit: An integer specifying the max number of entities needed. app_id: A string, the application identifier. direction: The direction of the index. Returns: A list of valid ent...
def __fetch_and_validate_entity_set(self, index_dict, limit, app_id, direction):
references = index_dict.keys() references.sort() offset = 0 results = [] to_fetch = limit added_padding = False while True: refs_to_fetch = references[offset:(offset + to_fetch)] if (len(refs_to_fetch) == 0): return results[:limit] entities = self.__fetch_...
'Given a result from a range query on the Entity table return a list of encoded entities. Args: kv: Key and values from a range query on the entity table. Returns: The extracted entities.'
def __extract_entities(self, kv):
keys = [item.keys()[0] for item in kv] results = [] for (index, entity) in enumerate(kv): key = keys[index] entity = entity[key][APP_ENTITY_SCHEMA[0]] results.append(entity) return results
'Performs an ordered ancestor query. It grabs all entities of a given ancestor and then orders in memory. Args: query: The query to run. filter_info: Tuple with filter operators and values order_info: Tuple with property name and the sort order. Returns: A list of entities. Raises: ZKTransactionException: If a lock cou...
def ordered_ancestor_query(self, query, filter_info, order_info):
ancestor = query.ancestor() prefix = self.get_table_prefix(query) path = (buffer((prefix + self._SEPARATOR)) + encode_index_pb(ancestor.path())) txn_id = 0 if query.has_transaction(): txn_id = query.transaction().handle() startrow = path endrow = (path + self._TERM_STRING) end_in...
'Performs ancestor queries which is where you select entities based on a particular root entitiy. Args: query: The query to run. filter_info: Tuple with filter operators and values. order_info: Tuple with property name and the sort order. Returns: A list of entities. Raises: ZKTransactionException: If a lock could not ...
def ancestor_query(self, query, filter_info, order_info):
ancestor = query.ancestor() prefix = self.get_table_prefix(query) path = (buffer((prefix + self._SEPARATOR)) + encode_index_pb(ancestor.path())) txn_id = 0 if query.has_transaction(): txn_id = query.transaction().handle() startrow = path endrow = (path + self._TERM_STRING) end_in...
'Fetches entities from the entity table given a query and a set of parameters. It will validate the results and remove tombstoned items. Args: startrow: The key from which we start a range query. endrow: The end key that terminates a range query. limit: The maximum number of items to return from a query. offset: The nu...
def fetch_from_entity_table(self, startrow, endrow, limit, offset, start_inclusive, end_inclusive, query, txn_id):
final_result = [] while 1: result = self.datastore_batch.range_query(dbconstants.APP_ENTITY_TABLE, APP_ENTITY_SCHEMA, startrow, endrow, limit, offset=0, start_inclusive=start_inclusive, end_inclusive=end_inclusive) prev_len = len(result) last_result = None if result: ...
'Performs kindless queries where queries are performed on the entity table and go across kinds. Args: query: The query to run. filter_info: Tuple with filter operators and values. Returns: Entities that match the query.'
def kindless_query(self, query, filter_info):
prefix = self.get_table_prefix(query) filters = [] if ('__key__' in filter_info): for filter in filter_info['__key__']: filters.append({'key': str(filter[1]), 'op': filter[0]}) order = None prop_name = None startrow = (prefix + self._SEPARATOR) endrow = ((prefix + self._S...
'Use this function for reversing the key ancestry order. Needed for kind queries. Args: key: A string key which needs reversing. Returns: A string key which can be used on the kind table.'
def reverse_path(self, key):
tokens = key.split(dbconstants.KIND_SEPARATOR) tokens.reverse() key = (dbconstants.KIND_SEPARATOR.join(tokens)[1:] + dbconstants.KIND_SEPARATOR) return key
'Gets start and end keys for kind queries, along with inclusivity of those keys. Args: query: The query to run. filter_info: __key__ filter. order_info: ordering for __key__. Returns: A tuple of the start row, end row, if its start inclusive, and if its end inclusive'
def kind_query_range(self, query, filter_info, order_info):
ancestor_filter = '' if query.has_ancestor(): ancestor = query.ancestor() ancestor_filter = encode_index_pb(ancestor.path()) end_inclusive = self._ENABLE_INCLUSIVITY start_inclusive = self._ENABLE_INCLUSIVITY prefix = self.get_table_prefix(query) startrow = ((((prefix + self._SEP...
'Returns the default namespace entry because the groomer does not generate it for each application. Returns: A entity proto of the default metadata.Namespace.'
def default_namespace(self):
default_namespace = Namespace(id=1) protobuf = db.model_to_protobuf(default_namespace) last_path = protobuf.key().path().element_list()[(-1)] last_path.set_id(1) return protobuf.Encode()
'Performs kind only queries, kind and ancestor, and ancestor queries https://developers.google.com/appengine/docs/python/datastore/queries. Args: query: The query to run. filter_info: tuple with filter operators and values. order_info: tuple with property name and the sort order. Returns: An ordered list of entities ma...
def __kind_query(self, query, filter_info, order_info):
self.logger.debug('Kind Query:\n{}'.format(query)) filter_info = self.remove_exists_filters(filter_info) for fi in filter_info: if (fi != '__key__'): return None if (query.has_ancestor() and (len(order_info) > 0)): return self.ordered_ancestor_query(query, filter_info, ord...
'Remove any filters that have EXISTS filters. Args: filter_info: dict of property names mapping to tuples of filter operators and values. Returns: A filter info dictionary without any EXIST filters.'
def remove_exists_filters(self, filter_info):
filtered = {} for key in filter_info.keys(): if (filter_info[key][0][0] == datastore_pb.Query_Filter.EXISTS): continue else: filtered[key] = filter_info[key] return filtered
'Keep only the first equality filter for a given property. Args: potential_filter_ops: A list of tuples in the form (operation, value). Returns: A filter_ops list with only one equality filter.'
def remove_extra_equality_filters(self, potential_filter_ops):
filter_ops = [] saw_equality_filter = False for (operation, value) in potential_filter_ops: if ((operation == datastore_pb.Query_Filter.EQUAL) and saw_equality_filter): continue if (operation == datastore_pb.Query_Filter.EQUAL): saw_equality_filter = True filt...
'Performs queries satisfiable by the Single_Property tables. Args: query: The query to run. filter_info: tuple with filter operators and values. order_info: tuple with property name and the sort order. Returns: List of entities retrieved from the given query.'
def __single_property_query(self, query, filter_info, order_info):
self.logger.debug('Single Property Query:\n{}'.format(query)) if (query.kind().startswith('__') and query.kind().endswith('__')): query.set_name_space('') filter_info = self.remove_exists_filters(filter_info) ancestor = None property_names = set(filter_info.keys()) property_names.u...
'Applies property filters in the query. Args: filter_ops: Tuple with property filter operator and value. order_info: Tuple with property name and sort order. kind: Kind of the entity. prefix: Prefix for the table. limit: Number of results. offset: Number of results to skip. startrow: Start key for the range scan. force...
def __apply_filters(self, filter_ops, order_info, property_name, kind, prefix, limit, offset, startrow, force_start_key_exclusive=False, ancestor=None, query=None, end_compiled_cursor=None):
ancestor_filter = None if ancestor: ancestor_filter = str(encode_index_pb(ancestor.path())) end_inclusive = True start_inclusive = True endrow = None column_names = dbconstants.PROPERTY_SCHEMA if (order_info and (order_info[0][0] == property_name)): direction = order_info[0][...
'Performs a composite query for queries which have multiple equality filters. Uses a varient of the zigzag join merge algorithm. This method is used if there are only equality filters present. If there are inequality filters, orders on properties which are not also apart of a filter, or ancestors, this method does not ...
def zigzag_merge_join(self, query, filter_info, order_info):
self.logger.debug('ZigZag Merge Join Query:\n{}'.format(query)) if (not self.is_zigzag_merge_join(query, filter_info, order_info)): return None kind = query.kind() prefix = self.get_table_prefix(query) limit = self.get_limit(query) app_id = clean_app_id(query.app()) directio...
'Checks to see if the query has a composite index that can implement the given query. Args: query: A datastore_pb.Query. Returns: True if the composite exists, False otherwise.'
def does_composite_index_exist(self, query):
return (query.composite_index_size() > 0)
'Gets the start and end key of a composite query. Args: query: A datastore_pb.Query object. filter_info: A dictionary mapping property names to tuples of filter operators and values. composite_id: An int, the composite index ID, Returns: A tuple of strings, the start and end key for the composite table.'
def get_range_composite_query(self, query, filter_info):
start_key = '' end_key = '' composite_index = query.composite_index_list()[0] index_id = composite_index.id() definition = composite_index.definition() app_id = clean_app_id(query.app()) name_space = '' if query.has_name_space(): name_space = query.name_space() pre_comp_index...
'Returns the start and end keys for a composite query which has multiple filters for a single property, and potentially multiple equality filters. Args: filter_ops: dictionary mapping the inequality filter to operators and values. equality_value: A string used for the start and end key which is derived from equality fi...
def composite_multiple_filter_prop(self, filter_ops, equality_value, pre_comp_index_key, direction):
oper1 = None oper2 = None value1 = None value2 = None start_key = '' end_key = '' if ((filter_ops[0][0] == datastore_pb.Query_Filter.GREATER_THAN) or (filter_ops[0][0] == datastore_pb.Query_Filter.GREATER_THAN_OR_EQUAL)): oper1 = filter_ops[0][0] oper2 = filter_ops[1][0] ...
'Performs composite queries using a range query against the composite table. Faster than in-memory filters, but requires indexes to be built upon each put. Args: query: The query to run. filter_info: dictionary mapping property names to tuples of filter operators and values. Returns: List of entities retrieved from the...
def composite_v2(self, query, filter_info):
self.logger.debug('Composite Query:\n{}'.format(query)) start_inclusive = True (startrow, endrow) = self.get_range_composite_query(query, filter_info) if (query.has_compiled_cursor() and query.compiled_cursor().position_size()): cursor = appscale_stub_util.ListCursor(query) last_resul...
'Returns filters from the query that contain multiple equality comparisons on repeated properties. Args: filter_list: A list of filters from the query. Returns: A dictionary that contains properties with multiple equality filters.'
def __get_multiple_equality_filters(self, filter_list):
equality_filters = {} for query_filter in filter_list: if (query_filter.op() != datastore_pb.Query_Filter.EQUAL): continue for prop in query_filter.property_list(): if (prop.name() not in equality_filters): equality_filters[prop.name()] = [] eq...
'Removes entities that do not meet the criteria defined by multiple equality filters. Args: entities: A list of entities that need filtering. filter_dict: A dictionary containing the relevant filters. Returns: A list of filtered entities.'
def __apply_multiple_equality_filters(self, entities, filter_dict):
filtered_entities = [] for entity in entities: entity_proto = entity_pb.EntityProto(entity) relevant_props_in_entity = {} for entity_prop in entity_proto.property_list(): if (entity_prop.name() not in filter_dict): continue if (entity_prop.name() n...
'Takes an index entry and returns the value of the property. This function is for single property indexes only. Args: index_entry: A dictionary containing an index entry. direction: The direction of the index. Returns: A property value.'
def __extract_value_from_index(self, index_entry, direction):
reference_key = index_entry.keys()[0] tokens = reference_key.split(self._SEPARATOR) value = self._SEPARATOR.join(tokens[4:(-1)]) if (direction == datastore_pb.Query_Order.DESCENDING): value = helper_functions.reverse_lex(value) entity = entity_pb.EntityProto() prop = entity.add_property(...
'Checks if an index entry is valid. Args: entry: A dictionary containing an index entry. entities: A dictionary of available valid entities. direction: The direction of the index. prop_name: A string containing the property name. Returns: A boolean indicating whether or not the entry is valid. Raises: AppScaleDBError: ...
def __valid_index_entry(self, entry, entities, direction, prop_name):
reference = entry[entry.keys()[0]]['reference'] if (reference not in entities): return False index_value = self.__extract_value_from_index(entry, direction) entity = entities[reference] entity_proto = entity_pb.EntityProto(entity) prop_found = False for prop in entity_proto.property_...
'Decodes entities, strips extra properties, and re-encodes them. Args: query: A datastore_pb.Query object. results: A list of encoded entities. Returns: A list of encoded entities.'
def remove_extra_props(self, query, results):
projected_props = query.property_name_list() cleaned_results = [] for result in results: entity = entity_pb.EntityProto(result) props_to_keep = [prop for prop in entity.property_list() if (prop.name() in projected_props)] if (not props_to_keep): continue entity.cl...
'Takes index values and creates partial entities out of them. This is required for projection queries where the query specifies certain properties which should be returned. Distinct queries are also handled here. A distinct query removes entities with duplicate index values. This will only return the first result for e...
def __extract_entities_from_composite_indexes(self, query, index_result):
definition = query.composite_index_list()[0].definition() prop_name_list = query.property_name_list() distinct_checker = [] entities = [] for index in index_result: entity = entity_pb.EntityProto() tokens = index.keys()[0].split(self._SEPARATOR) app_id = tokens.pop(0) ...
'Performs Composite queries which is a combination of multiple properties to query on. Args: query: The query to run. filter_info: dictionary mapping property names to tuples of filter operators and values. Returns: List of entities retrieved from the given query.'
def __composite_query(self, query, filter_info, _):
if self.does_composite_index_exist(query): return self.composite_v2(query, filter_info) self.logger.error('No composite ID was found for query:\n{}.'.format(query)) raise apiproxy_errors.ApplicationError(datastore_pb.Error.NEED_INDEX, 'No composite index provided')
'Takes results and applies ordering based on properties and whether it should be ascending or decending. Filters out any entities which do not match the given kind, if given. Args: result: unordered results. order_info: given ordering of properties. kind: The kind to filter on if given. Returns: A list of ordered entit...
def __multiorder_results(self, result, order_info, kind):
if (not result): return [] if ((not order_info) and (not kind)): return result vals = {} for e in result: key = self._SEPARATOR e = entity_pb.EntityProto(e) last_path = e.key().path().element_list()[(-1)] if (kind and (last_path.type() != kind)): ...
'Applies the strategy for the provided query. Args: query: A datastore_pb.Query protocol buffer. Returns: Result set.'
def __get_query_results(self, query):
if (query.has_transaction() and (not query.has_ancestor())): raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST, 'Only ancestor queries are allowed inside transactions.') num_components = (len(query.filter_list()) + len(query.order_list())) if query.has_ancestor(...
'Populates the query result and use that query result to encode a cursor. Args: query: The query to run. query_result: The response given to the application server.'
def _dynamic_run_query(self, query, query_result):
result = self.__get_query_results(query) last_entity = None count = 0 offset = query.offset() if result: query_result.set_skipped_results((len(result) - offset)) last_entity = result[(-1)] count = len(result) result = result[offset:] if query.has_limit(): ...
'Adds tasks to enqueue upon committing the transaction. Args: app_id: A string specifying the application ID. request: A protocol buffer AddActions request.'
def dynamic_add_actions(self, app_id, request):
txid = request.add_request(0).transaction().handle() existing_tasks = self.datastore_batch.transactional_tasks_count(app_id, txid) if (existing_tasks > _MAX_ACTIONS_PER_TXN): message = 'Only {} tasks can be added to a transaction'.format(_MAX_ACTIONS_PER_TXN) raise db...
'Gets a transaction ID for a new transaction. Args: app_id: The application for which we are getting a new transaction ID. is_xg: A bool that indicates if this transaction operates over multiple entity groups. Returns: A long representing a unique transaction ID.'
def setup_transaction(self, app_id, is_xg):
txid = self.zookeeper.get_transaction_id(app_id, is_xg) in_progress = self.zookeeper.get_current_transactions(app_id) self.datastore_batch.start_transaction(app_id, txid, is_xg, in_progress) return txid
'Send a BulkAdd request to the taskqueue service. Args: app: A string specifying an application ID. task_ops: A list of tasks.'
def enqueue_transactional_tasks(self, app, tasks):
if (app not in self.taskqueue_stubs): self.taskqueue_stubs[app] = TaskQueueServiceStub(app, '') bulk_request = taskqueue_service_pb.TaskQueueBulkAddRequest() bulk_response = taskqueue_service_pb.TaskQueueBulkAddResponse() for task in tasks: bulk_request.add_add_request().CopyFrom(task) ...
'Apply all operations in transaction table in a single batch. Args: app: A string containing an application ID. txn: An integer specifying a transaction ID.'
def apply_txn_changes(self, app, txn):
metadata = self.datastore_batch.get_transaction_metadata(app, txn) if ('start' not in metadata): raise dbconstants.TxTimeoutException('Unable to find transaction') tx_duration = (datetime.datetime.utcnow() - metadata['start']) if (tx_duration > datetime.timedelta(seconds=MAX_TX_DURATION...
'Handles the commit phase of a transaction. Args: app_id: The application ID requesting the transaction commit. http_request_data: The encoded request of datastore_pb.Transaction. Returns: An encoded protocol buffer commit response.'
def commit_transaction(self, app_id, http_request_data):
commitres_pb = datastore_pb.CommitResponse() transaction_pb = datastore_pb.Transaction(http_request_data) txn_id = transaction_pb.handle() try: self.apply_txn_changes(app_id, txn_id) except dbconstants.TxTimeoutException as timeout: return (commitres_pb.Encode(), datastore_pb.Error.T...
'Handles the rollback phase of a transaction. Args: app_id: The application ID requesting the rollback. http_request_data: The encoded request, a datstore_pb.Transaction. Returns: An encoded protocol buffer void response.'
def rollback_transaction(self, app_id, http_request_data):
txn = datastore_pb.Transaction(http_request_data) self.logger.info('Doing a rollback on transaction {} for {}'.format(txn.handle(), app_id)) try: self.zookeeper.notify_failed_transaction(app_id, txn.handle()) return (api_base_pb.VoidProto().Encode(), 0, '') except zk...
'Initializes an UnprocessedQueryResult object. Args: contents: An optional string to initialize a QueryResult object.'
def __init__(self, contents=None):
datastore_pb.QueryResult.__init__(self, contents=contents) self.binary_results_ = []
'Returns a reference to the stored list of results. Unlike the original function, this returns the binary results instead of the decoded results.'
def result_list(self):
return self.binary_results_
'Encodes QueryResult object and outputs it to a buffer object. This is called during the Encode process. The only difference from the original function is outputting the binary results instead of encoding result objects. Args: out: A buffer object to store the output.'
def OutputUnchecked(self, out):
if self.has_cursor_: out.putVarInt32(10) out.putVarInt32(self.cursor_.ByteSize()) self.cursor_.OutputUnchecked(out) for i in xrange(len(self.binary_results_)): out.putVarInt32(18) out.putVarInt32(len(self.binary_results_[i])) out.buf.fromstring(self.binary_results...
'Initializes an UnprocessedQueryCursor object. Args: query: A query protocol buffer object. binary_results: A list of strings that contain encoded protocol buffer results. last_entity: A string that contains the last entity. It is used to generate the cursor, and it can be defined even if there are no results.'
def __init__(self, query, binary_results, last_entity):
self.__binary_results = binary_results self.__query = query self.__last_ent = last_entity if (len(binary_results) > 0): results = [entity_pb.EntityProto(binary_results[(-1)])] else: results = [] super(UnprocessedQueryCursor, self).__init__(query, results, last_entity)
'Populates a QueryResult object with results the QueryCursor has been storing. Args: count: The number of results requested in the query. offset: The number of results to skip. result: A QueryResult object to populate.'
def PopulateQueryResult(self, count, offset, result):
result.set_skipped_results(min(count, offset)) result_list = result.result_list() if self.__binary_results: if self.__query.keys_only(): for binary_result in self.__binary_results: entity = entity_pb.EntityProto(binary_result) entity.clear_property() ...
'Constructor function for the backup service.'
def __init__(self):
log_format = logging.Formatter('%(asctime)s %(levelname)s %(filename)s: %(lineno)s %(message)s') logging.getLogger().handlers[0].setFormatter(log_format) self.__cassandra_backup_lock = threading.Lock()
'Returns the default bad request json string. Args: reason: The reason the request is bad. Returns: The default message to return on a bad request.'
@classmethod def bad_request(cls, reason):
return json.dumps({'success': False, 'reason': reason})
'Handles remote requests with serialized JSON. Args: request_data: A str, the serialized JSON request. Returns: A str, serialized JSON.'
def remote_request(self, request_data):
try: request = json.loads(request_data) logging.info('Request received: {0}'.format(request)) except (TypeError, ValueError) as error: logging.exception(error) return self.bad_request('Unable to parse request. Exception: {0}'.format(error)) request_type =...
'Top level function for doing source code backups. Args: storage: A str, one of the StorageTypes class members. path: A str, the name of the backup file to be created. Returns: A JSON string to return to the client.'
def do_app_backup(self, storage, path):
if (not backup_recovery_helper.app_backup(storage, path)): return self.bad_request('Source code backup failed!') logging.info('Successful source code backup!') return json.dumps({'success': True, 'reason': ''})
'Top level function for restoring source code. Args: storage: A str, one of the StorageTypes class members. path: A str, the name of the backup file to be created. Returns: A JSON string to return to the client.'
def do_app_restore(self, storage, path):
if (not backup_recovery_helper.app_restore(storage, path)): return self.bad_request('Source code restore failed!') logging.info('Successful source code restore!') return json.dumps({'success': True, 'reason': ''})
'Top level function for doing Cassandra backups. Args: storage: A str, one of the StorageTypes class members. path: A str, the name of the backup file to be created. Returns: A JSON string to return to the client.'
def do_cassandra_backup(self, storage, path):
success = True reason = 'success' try: logging.info('Acquiring lock for db backup.') self.__cassandra_backup_lock.acquire(True) logging.info('Got the lock for db backup.') if (not cassandra_backup.backup_data(storage, path)): return self...
'Top level function for doing Cassandra restores. Args: storage: A str, one of the StorageTypes class members. path: A str, the name of the backup file to be created. Returns: A JSON string to return to the client.'
def do_cassandra_restore(self, storage, path):
success = True reason = 'success' try: logging.info('Acquiring lock for db restore.') self.__cassandra_backup_lock.acquire(True) logging.info('Got the lock for db restore.') if (not cassandra_backup.restore_data(storage, path)): return s...
'Constructor. Args: app_id: A str, the application ID. backup_dir: A str, the location of the backup file. zoo_keeper: A ZooKeeper client. table_name: The database used (e.g. cassandra).'
def __init__(self, app_id, backup_dir, zoo_keeper, table_name):
multiprocessing.Process.__init__(self) self.app_id = app_id self.backup_dir = backup_dir self.zoo_keeper = zoo_keeper self.table = table_name self.entities_restored = 0 self.indexes = [] self.ds_distributed = None
'Stops the restore process.'
def stop(self):
pass
'Starts the main loop of the restore thread.'
def run(self):
datastore_batch = appscale_datastore_batch.DatastoreFactory.getDatastore(self.table) self.ds_distributed = DatastoreDistributed(datastore_batch, zookeeper=self.zoo_keeper) while True: logging.debug('Trying to get restore lock.') if self.get_restore_lock(): logging.inf...