desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Tries to acquire the lock for a datastore restore.
Returns:
True on success, False otherwise.'
| def get_restore_lock(self):
| return self.zoo_keeper.get_lock_with_path(zk.DS_RESTORE_LOCK_PATH)
|
'Stores the given entity batch.
Args:
entity_batch: A list of entities to store.
Returns:
True on success, False otherwise.'
| def store_entity_batch(self, entity_batch):
| logging.debug('Entity batch to process: {0}'.format(entity_batch))
new_entities_encoded = []
ent_protos = []
for entity in entity_batch:
ent_proto = entity_pb.EntityProto()
ent_proto.ParseFromString(entity)
ent_proto.key().set_app(self.app_id)
ent_protos.appen... |
'Reads entities from backup file and stores them in the datastore.
Args:
backup_file: A str, the backup file location to restore from.'
| def read_from_file_and_restore(self, backup_file):
| entities_to_store = []
with open(backup_file, 'rb') as file_object:
while True:
try:
entity = cPickle.load(file_object)
entities_to_store.append(entity)
if (len(entities_to_store) == self.BATCH_SIZE):
logging.info('Storing ... |
'Runs the restore process. Reads the backup file and stores entities
in batches.'
| def run_restore(self):
| logging.info('Restore started')
start = time.time()
for backup_file in glob.glob('{0}/*{1}'.format(self.backup_dir, DatastoreBackup.BACKUP_FILE_SUFFIX)):
if backup_file.endswith('.backup'):
logging.info('Restoring "{0}" data from: {1}'.format(self.app_id, backup_file))
... |
'Constructor.
Args:
app_id: The application ID.
zk: ZooKeeper client.
table_name: The database used (e.g. cassandra).
source_code: True when a backup of the source code is requested,
False otherwise.
skip_list: A list of Kinds to be skipped during backup; empty list if
none.'
| def __init__(self, app_id, zoo_keeper, table_name, source_code=False, skip_list=()):
| multiprocessing.Process.__init__(self)
self.app_id = app_id
self.zoo_keeper = zoo_keeper
self.table = table_name
self.source_code = source_code
self.skip_kinds = skip_list
self.last_key = ((self.app_id + '\x00') + dbconstants.TERMINATING_STRING)
self.backup_timestamp = time.strftime('%Y%... |
'Stops the backup thread.'
| def stop(self):
| pass
|
'Creates a new backup filename. Also creates the backup folder if it
doesn\'t exist.
Returns:
True on success, False otherwise.'
| def set_filename(self):
| if (not self.backup_dir):
self.backup_dir = '{0}{1}-{2}/'.format(self.BACKUP_FILE_LOCATION, self.app_id, self.backup_timestamp)
try:
os.makedirs(self.backup_dir)
logging.info('Backup dir created: {0}'.format(self.backup_dir))
except OSError as os_error:
... |
'Copies the source code of the app into the backup directory.
Skips this step if the file is not found.'
| def backup_source_code(self):
| sourcefile = '{0}{1}.tar.gz'.format(_SOURCE_LOCATION, self.app_id)
if os.path.isfile(sourcefile):
try:
shutil.copy(sourcefile, self.backup_dir)
logging.info('Source code has been successfully backed up.')
except shutil.Error as error:
logging... |
'Starts the main loop of the backup thread.'
| def run(self):
| while True:
logging.debug('Trying to get backup lock.')
if self.get_backup_lock():
logging.info('Got the backup lock.')
self.db_access = appscale_datastore_batch.DatastoreFactory.getDatastore(self.table)
self.set_filename()
if self... |
'Tries to acquire the lock for a datastore backup.
Returns:
True on success, False otherwise.'
| def get_backup_lock(self):
| return self.zoo_keeper.get_lock_with_path(zk.DS_BACKUP_LOCK_PATH)
|
'Gets a batch of entities to operate on.
Args:
first_key: The last key from a previous query.
batch_size: The number of entities to fetch.
start_inclusive: True if first row should be included, False otherwise.
Returns:
A list of entities.'
| def get_entity_batch(self, first_key, batch_size, start_inclusive):
| batch = self.db_access.range_query(dbconstants.APP_ENTITY_TABLE, dbconstants.APP_ENTITY_SCHEMA, first_key, self.last_key, batch_size, start_inclusive=start_inclusive)
if batch:
logging.debug('Retrieved entities from {0} to {1}'.format(batch[0].keys()[0], batch[(-1)].keys()[0]))
return... |
'Verify that the entity is not blacklisted.
Args:
key: The key to the entity table.
txn_id: An int, a transaction ID.
Returns:
True on success, False otherwise.'
| def verify_entity(self, key, txn_id):
| app_id = key.split(dbconstants.KEY_DELIMITER)[0]
try:
if self.zoo_keeper.is_blacklisted(app_id, txn_id):
logging.warn('Found a blacklisted item for version {0} on key {1}'.format(txn_id, key))
return False
except zk.ZKTransactionException as zk_exce... |
'Dumps the entity content into a backup file.
Args:
entity: The entity to be backed up.
Returns:
True on success, False otherwise.'
| def dump_entity(self, entity):
| if ((self.current_file_size + len(entity)) > self.MAX_FILE_SIZE):
self.current_fileno += 1
self.set_filename()
self.current_file_size = 0
try:
with open(self.filename, 'ab+') as file_object:
cPickle.dump(entity, file_object, cPickle.HIGHEST_PROTOCOL)
self.enti... |
'Verifies entity, fetches from journal if necessary and calls
dump_entity.
Args:
entity: The entity to be backed up.
Returns:
True on success, False otherwise.'
| def process_entity(self, entity):
| key = entity.keys()[0]
kind = entity_utils.get_kind_from_entity_key(key)
if (re.match(self.PROTECTED_KINDS, kind) or re.match(self.PRIVATE_KINDS, kind)):
if ((not re.match(self.BLOB_CHUNK_REGEX, kind)) and (not re.match(self.BLOB_INFO_REGEX, kind))):
logging.debug('Skipping key: {0... |
'Runs the backup process. Loops on the entire dataset and dumps it into
a file.'
| def run_backup(self):
| logging.info('Backup started')
start = time.time()
first_key = '{0}\x00'.format(self.app_id)
start_inclusive = True
entities_remaining = []
while True:
try:
entities = (entities_remaining + self.get_entity_batch(first_key, self.BATCH_SIZE, start_inclusive))
log... |
'Accessor for getting all the supported storage types.'
| def get_storage_types(self):
| return [self.LOCAL_FS, self.GCS]
|
'Class for initializing backup/recovery web handler.'
| def initialize(self, backup_recovery_service):
| self.backup_recovery_service = backup_recovery_service
|
'A GET handler for requests to this server.'
| def get(self):
| self.write(json.dumps({'status': 'up'}))
|
'A POST handler for request to this server.'
| @tornado.web.asynchronous
def post(self):
| request = self.request
http_request_data = request.body
response = self.backup_recovery_service.remote_request(http_request_data)
request.connection.write_headers(tornado.httputil.ResponseStartLine('HTTP/1.1', HTTP_OK, 'OK'), tornado.httputil.HTTPHeaders({'Content-Length': str(len(response))}))
requ... |
'Handles POST requests for clearing datastore server stats.'
| @tornado.web.asynchronous
def post(self):
| global STATS
STATS = {}
self.write({'message': 'Statistics for this server cleared.'})
self.finish()
|
'Handle requests to turn read-only mode on or off.'
| @tornado.web.asynchronous
def post(self):
| global READ_ONLY
payload = self.request.body
data = json.loads(payload)
if ('readOnly' not in data):
self.set_status(dbconstants.HTTP_BAD_REQUEST)
if data['readOnly']:
READ_ONLY = True
message = 'Write operations now disabled.'
else:
READ_ONLY = False
... |
'Function which handles unknown protocol buffers.
Args:
app_id: Name of the application.
http_request_data: Stores the protocol buffer request from the AppServer
Raises:
Raises exception.'
| def unknown_request(self, app_id, http_request_data, pb_type):
| raise NotImplementedError('Unknown request of operation {0}'.format(pb_type))
|
'Function which handles POST requests. Data of the request is
the request from the AppServer in an encoded protocol buffer
format.'
| @tornado.web.asynchronous
def post(self):
| request = self.request
http_request_data = request.body
pb_type = request.headers['protocolbuffertype']
app_data = request.headers['appdata']
app_data = app_data.split(':')
if (len(app_data) == 4):
(app_id, user_email, nick_name, auth_domain) = app_data
os.environ['AUTH_DOMAIN'] ... |
'Handles get request for the web server. Returns that it is currently
up in json.'
| @tornado.web.asynchronous
def get(self):
| self.write(json.dumps(STATS))
self.finish()
|
'Receives a remote request to which it should give the correct
response. The http_request_data holds an encoded protocol buffer
of a certain type. Each type has a particular response type.
Args:
app_id: The application ID that is sending this request.
http_request_data: Encoded protocol buffer.'
| def remote_request(self, app_id, http_request_data):
| apirequest = remote_api_pb.Request()
apirequest.ParseFromString(http_request_data)
apiresponse = remote_api_pb.Response()
response = None
errcode = 0
errdetail = ''
apperror_pb = None
if (not apirequest.has_method()):
errcode = datastore_pb.Error.BAD_REQUEST
errdetail = '... |
'Handles the intial request to start a transaction. Replies with
a unique identifier to handle this transaction in future requests.
Args:
app_id: The application ID requesting the transaction.
http_request_data: The encoded request.
Returns:
An encoded transaction protocol buffer with a unique handler.'
| def begin_transaction_request(self, app_id, http_request_data):
| global datastore_access
begin_transaction_req_pb = datastore_pb.BeginTransactionRequest(http_request_data)
multiple_eg = False
if begin_transaction_req_pb.has_allow_multiple_eg():
multiple_eg = bool(begin_transaction_req_pb.allow_multiple_eg())
handle = None
transaction_pb = datastore_pb... |
'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_request(self, app_id, http_request_data):
| global datastore_access
if READ_ONLY:
commitres_pb = datastore_pb.CommitResponse()
transaction_pb = datastore_pb.Transaction(http_request_data)
logger.warning('Unable to commit in read-only mode: {}'.format(transaction_pb))
return (commitres_pb.Encode(), datasto... |
'Handles the rollback phase of a transaction.
Args:
app_id: The application ID requesting the rollback.
http_request_data: The encoded request.
Returns:
An encoded protocol buffer void response.'
| def rollback_transaction_request(self, app_id, http_request_data):
| global datastore_access
response = api_base_pb.VoidProto()
if READ_ONLY:
logger.warning('Unable to rollback in read-only mode: {}'.format(http_request_data))
return (response.Encode(), datastore_pb.Error.CAPABILITY_DISABLED, 'Datastore is in read-only mode.')
... |
'High level function for running queries.
Args:
http_request_data: Stores the protocol buffer request from the AppServer.
Returns:
Returns an encoded query response.'
| def run_query(self, http_request_data):
| global datastore_access
query = datastore_pb.Query(http_request_data)
clone_qr_pb = UnprocessedQueryResult()
try:
datastore_access._dynamic_run_query(query, clone_qr_pb)
except zktransaction.ZKBadRequest as zkie:
logger.exception('Illegal arguments in transaction during ... |
'High level function for creating composite indexes.
Args:
app_id: Name of the application.
http_request_data: Stores the protocol buffer request from the
AppServer.
Returns:
Returns an encoded response.'
| def create_index_request(self, app_id, http_request_data):
| global datastore_access
request = entity_pb.CompositeIndex(http_request_data)
response = api_base_pb.Integer64Proto()
if READ_ONLY:
logger.warning('Unable to create in read-only mode: {}'.format(request))
return (response.Encode(), datastore_pb.Error.CAPABILITY_DISABLED... |
'High level function for updating a composite index.
Args:
app_id: A string containing the application ID.
http_request_data: A string containing the protocol buffer request
from the AppServer.
Returns:
A tuple containing an encoded response, error code, and error details.'
| def update_index_request(self, app_id, http_request_data):
| global datastore_access
index = entity_pb.CompositeIndex(http_request_data)
response = api_base_pb.VoidProto()
if READ_ONLY:
logger.warning('Unable to update in read-only mode: {}'.format(index))
return (response.Encode(), datastore_pb.Error.CAPABILITY_DISABLED, 'Datast... |
'Deletes a composite index for a given application.
Args:
app_id: Name of the application.
http_request_data: A serialized CompositeIndices item
Returns:
A Tuple of an encoded entity_pb.VoidProto, error code, and
error explanation.'
| def delete_index_request(self, app_id, http_request_data):
| global datastore_access
request = entity_pb.CompositeIndex(http_request_data)
response = api_base_pb.VoidProto()
if READ_ONLY:
logger.warning('Unable to delete in read-only mode: {}'.format(request))
return (response.Encode(), datastore_pb.Error.CAPABILITY_DISABLED, 'Da... |
'Gets the indices of the given application.
Args:
app_id: Name of the application.
http_request_data: Stores the protocol buffer request from the
AppServer.
Returns:
A Tuple of an encoded response, error code, and error explanation.'
| def get_indices_request(self, app_id):
| global datastore_access
response = datastore_pb.CompositeIndices()
try:
indices = datastore_access.datastore_batch.get_indices(app_id)
except dbconstants.AppScaleDBConnectionError:
logger.exception('DB connection error while fetching indices for {}'.format(app_id))
... |
'High level function for getting unique identifiers for entities.
Args:
app_id: Name of the application.
http_request_data: Stores the protocol buffer request from the
AppServer.
Returns:
Returns an encoded response.
Raises:
NotImplementedError: when requesting a max id.'
| def allocate_ids_request(self, app_id, http_request_data):
| request = datastore_pb.AllocateIdsRequest(http_request_data)
response = datastore_pb.AllocateIdsResponse()
if (request.has_max() and request.has_size()):
return (response.Encode(), datastore_pb.Error.BAD_REQUEST, 'Both size and max cannot be set.')
if (not (request.has_max() or... |
'High level function for doing puts.
Args:
app_id: Name of the application.
http_request_data: Stores the protocol buffer request from the AppServer.
Returns:
Returns an encoded put response.'
| def put_request(self, app_id, http_request_data):
| global datastore_access
putreq_pb = datastore_pb.PutRequest(http_request_data)
putresp_pb = datastore_pb.PutResponse()
if READ_ONLY:
logger.warning('Unable to put in read-only mode: {}'.format(putreq_pb))
return (putresp_pb.Encode(), datastore_pb.Error.CAPABILITY_DISABL... |
'High level function for doing gets.
Args:
app_id: Name of the application.
http_request_data: Stores the protocol buffer request from the AppServer.
Returns:
An encoded get response.'
| def get_request(self, app_id, http_request_data):
| global datastore_access
getreq_pb = datastore_pb.GetRequest(http_request_data)
getresp_pb = datastore_pb.GetResponse()
try:
datastore_access.dynamic_get(app_id, getreq_pb, getresp_pb)
except zktransaction.ZKBadRequest as zkie:
logger.exception('Illegal argument during {}'.fo... |
'High level function for doing deletes.
Args:
app_id: Name of the application.
http_request_data: Stores the protocol buffer request from the AppServer.
Returns:
An encoded delete response.'
| def delete_request(self, app_id, http_request_data):
| global datastore_access
delreq_pb = datastore_pb.DeleteRequest(http_request_data)
delresp_pb = api_base_pb.VoidProto()
if READ_ONLY:
logger.warning('Unable to delete in read-only mode: {}'.format(delreq_pb))
return (delresp_pb.Encode(), datastore_pb.Error.CAPABILITY_DIS... |
'High level function for adding transactional tasks.
Args:
app_id: Name of the application.
http_request_data: Stores the protocol buffer request from the AppServer.
Returns:
An encoded AddActions response.'
| def add_actions_request(self, app_id, http_request_data):
| global datastore_access
req_pb = taskqueue_service_pb.TaskQueueBulkAddRequest(http_request_data)
resp_pb = taskqueue_service_pb.TaskQueueBulkAddResponse()
if READ_ONLY:
logger.warning('Unable to add transactional tasks in read-only mode')
return (resp_pb.Encode(), da... |
'Constructor.'
| def __init__(self, boundary):
| self.form_fields = []
self.files = []
if (not boundary):
self.boundary = mimetools.choose_boundary()
else:
self.boundary = boundary
return
|
'Get the content type to use.'
| def get_content_type(self):
| return ('multipart/form-data; boundary=%s' % self.boundary)
|
'Add a simple field to the form data.'
| def add_field(self, name, value):
| self.form_fields.append((name, value))
return
|
'Add a file to be uploaded.'
| def add_file(self, fieldname, filename, fileHandle, blob_key, access_type, size, creation):
| body = fileHandle.read()
mimetype = ('message/external-body; blob-key="%s"; access-type="%s"' % (blob_key, access_type))
self.files.append((fieldname, filename, mimetype, body, size, creation))
return
|
'Return a string representing the form data, including attached files.'
| def __str__(self):
| parts = []
part_boundary = ('--' + self.boundary)
parts.extend(([part_boundary, ('Content-Disposition: form-data; name="%s"' % name), '', value] for (name, value) in self.form_fields))
parts.extend(([part_boundary, ('Content-Type: %s' % content_type), 'MIME-Version: 1.0', ('Content-Dispositi... |
'Constructor.'
| def __init__(self):
| handlers = [('/_ah/upload/(.*)/(.*)', UploadHandler), ('/', HealthCheck)]
tornado.web.Application.__init__(self, handlers)
|
'Stubbed out to do nothing since we do not follow redirects.'
| def http_error_301(self, req, fp, code, msg, headers):
| return None
|
'Stubbed out to do nothing since we do not follow redirects.'
| def http_error_302(self, req, fp, code, msg, headers):
| return None
|
'This path is called to make sure the server is up and running.'
| def get(self):
| self.finish('Hello')
|
'Handler a post request from a user uploading a blob.
Args:
app_id: The application triggering the upload.
session_id: Authentication token to validate the upload.'
| def post(self, app_id='blob', session_id='session'):
| global datastore_path
db = datastore_distributed.DatastoreDistributed(app_id, datastore_path, require_indexes=False)
apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', db)
os.environ['APPLICATION_ID'] = app_id
blob_session = get_session(session_id)
if (not blob_session):
self.finish... |
'Returns a reference for the datastore.
Args:
d_type: The name of the datastore (ex: cassandra)
log_level: The logging level to use.'
| @classmethod
def getDatastore(cls, d_type, log_level=logging.INFO):
| db_module = importlib.import_module('appscale.datastore.{0}_env.{0}_interface'.format(d_type))
return db_module.DatastoreProxy(log_level=log_level)
|
'Returns a list of directories where the datastore code is
Returns: Directory list'
| @classmethod
def valid_datastores(cls):
| datastore_package_dir = os.path.dirname(appscale.datastore.__file__)
return [pkg.replace('_env', '') for (_, pkg, ispkg) in pkgutil.iter_modules([datastore_package_dir]) if (ispkg and pkg.endswith('_env'))]
|
'Constructor.
Args:
zk: ZooKeeper client.
table_name: The database used (ie, cassandra)
ds_path: The connection path to the datastore_server.'
| def __init__(self, zoo_keeper, table_name, ds_path):
| logging.info('Logging started')
threading.Thread.__init__(self)
self.zoo_keeper = zoo_keeper
self.table_name = table_name
self.db_access = None
self.ds_access = None
self.datastore_path = ds_path
self.stats = {}
self.namespace_info = {}
self.num_deletes = 0
self.composite_... |
'Stops the groomer thread.'
| def stop(self):
| self.zoo_keeper.close()
|
'Starts the main loop of the groomer thread.'
| def run(self):
| while True:
logging.debug('Trying to get groomer lock.')
if self.get_groomer_lock():
logging.info('Got the groomer lock.')
self.run_groomer()
try:
self.zoo_keeper.release_lock_with_path(zk.DS_GROOM_LOCK_PATH)
except... |
'Tries to acquire the lock to the datastore groomer.
Returns:
True on success, False otherwise.'
| def get_groomer_lock(self):
| return self.zoo_keeper.get_lock_with_path(zk.DS_GROOM_LOCK_PATH)
|
'Gets a batch of entites to operate on.
Args:
last_key: The last key from a previous query.
Returns:
A list of entities.'
| def get_entity_batch(self, last_key):
| return self.db_access.range_query(dbconstants.APP_ENTITY_TABLE, dbconstants.APP_ENTITY_SCHEMA, last_key, '', self.BATCH_SIZE, start_inclusive=False)
|
'Reinitializes statistics.'
| def reset_statistics(self):
| self.stats = {}
self.namespace_info = {}
self.num_deletes = 0
self.journal_entries_cleaned = 0
|
'Does a hard delete on a given row key to the entity
table.
Args:
row_key: A str representing the row key to delete.
Returns:
True on success, False otherwise.'
| def hard_delete_row(self, row_key):
| try:
self.db_access.batch_delete(dbconstants.APP_ENTITY_TABLE, [row_key])
except dbconstants.AppScaleDBConnectionError as db_error:
logging.error('Error hard deleting key {0}-->{1}'.format(row_key, db_error))
return False
except Exception as exception:
logging.err... |
'Load the composite index cache for an application ID.
Args:
app_id: A str, the application ID.
Returns:
True if the application has composites. False otherwise.'
| def load_composite_cache(self, app_id):
| start_key = dbconstants.KEY_DELIMITER.join([app_id, 'index', ''])
end_key = dbconstants.KEY_DELIMITER.join([app_id, 'index', dbconstants.TERMINATING_STRING])
results = self.db_access.range_query(dbconstants.METADATA_TABLE, dbconstants.METADATA_TABLE, start_key, end_key, dbconstants.MAX_NUMBER_OF_COMPOSITE_I... |
'Acquires a lock for a given entity key.
Args:
app_id: The application ID.
key: A string containing an entity key.
retries: An integer specifying the number of times to retry.
retry_time: How many seconds to wait before each retry.
Returns:
A transaction ID.
Raises:
ZKTransactionException if unable to acquire a lock fr... | def acquire_lock_for_key(self, app_id, key, retries, retry_time):
| root_key = key.split(dbconstants.KIND_SEPARATOR)[0]
root_key += dbconstants.KIND_SEPARATOR
txn_id = self.zoo_keeper.get_transaction_id(app_id, is_xg=False)
try:
self.zoo_keeper.acquire_lock(app_id, txn_id, root_key)
except zk.ZKTransactionException as zkte:
logging.warning('Concurren... |
'Releases a lock for a given entity key.
Args:
app_id: The application ID.
key: A string containing an entity key.
txn_id: A transaction ID.
retries: An integer specifying the number of times to retry.
retry_time: How many seconds to wait before each retry.'
| def release_lock_for_key(self, app_id, key, txn_id, retries, retry_time):
| root_key = key.split(dbconstants.KIND_SEPARATOR)[0]
root_key += dbconstants.KIND_SEPARATOR
try:
self.zoo_keeper.release_lock(app_id, txn_id)
except zk.ZKTransactionException as zkte:
logging.warning(str(zkte))
if (retries > 0):
logging.info('Trying again to r... |
'Fetches a dictionary of valid entities for a list of references.
Args:
references: A list of index references to entities.
Returns:
A dictionary of validated entities.'
| def fetch_entity_dict_for_references(self, references):
| keys = []
for item in references:
keys.append(item.values()[0][self.ds_access.INDEX_REFERENCE_COLUMN])
keys = list(set(keys))
entities = self.db_access.batch_get_entity(dbconstants.APP_ENTITY_TABLE, keys, dbconstants.APP_ENTITY_SCHEMA)
entities_by_app = {}
for key in entities:
ap... |
'For a list of index entries that have the same entity, lock the entity
and delete the indexes.
Since another process can update an entity after we\'ve determined that
an index entry is invalid, we need to re-check the index entries after
locking their entity key.
Args:
references: A list of references to an entity.
di... | def lock_and_delete_indexes(self, references, direction, entity_key):
| if (direction == datastore_pb.Query_Order.ASCENDING):
table_name = dbconstants.ASC_PROPERTY_TABLE
else:
table_name = dbconstants.DSC_PROPERTY_TABLE
app = entity_key.split(self.ds_access._SEPARATOR)[0]
try:
txn_id = self.acquire_lock_for_key(app_id=app, key=entity_key, retries=sel... |
'For a list of index entries that have the same entity, lock the entity
and delete the indexes.
Since another process can update an entity after we\'ve determined that
an index entry is invalid, we need to re-check the index entries after
locking their entity key.
Args:
reference: A dictionary containing a kind referen... | def lock_and_delete_kind_index(self, reference):
| table_name = dbconstants.APP_KIND_TABLE
entity_key = reference.values()[0].values()[0]
app = entity_key.split(self.ds_access._SEPARATOR)[0]
try:
txn_id = self.acquire_lock_for_key(app_id=app, key=entity_key, retries=self.ds_access.NON_TRANS_LOCK_RETRY_COUNT, retry_time=self.ds_access.LOCK_RETRY_... |
'Deletes invalid single property index entries.
This is needed because we do not delete index entries when updating or
deleting entities. With time, this results in queries taking an increasing
amount of time.
Args:
direction: The direction of the index.'
| def clean_up_indexes(self, direction):
| if (direction == datastore_pb.Query_Order.ASCENDING):
table_name = dbconstants.ASC_PROPERTY_TABLE
task_id = self.CLEAN_ASC_INDICES_TASK
else:
table_name = dbconstants.DSC_PROPERTY_TABLE
task_id = self.CLEAN_DSC_INDICES_TASK
if ((len(self.groomer_state) > 1) and (self.groomer_... |
'Deletes invalid kind index entries.
This is needed because the datastore does not delete kind index entries
when deleting entities.'
| def clean_up_kind_indices(self):
| table_name = dbconstants.APP_KIND_TABLE
task_id = self.CLEAN_KIND_INDICES_TASK
start_key = ''
end_key = dbconstants.TERMINATING_STRING
if (len(self.groomer_state) > 1):
start_key = self.groomer_state[1]
while True:
references = self.db_access.range_query(table_name=table_name, co... |
'Deletes old composite indexes and bad references.
Returns:
True on success, False otherwise.'
| def clean_up_composite_indexes(self):
| return True
|
'Fetches the composite indexes for a kind.
Args:
app_id: The application ID.
kind: A string, the kind for which we need composite indexes.
Returns:
A list of composite indexes.'
| def get_composite_indexes(self, app_id, kind):
| if (not kind):
return []
if (app_id in self.composite_index_cache):
if (self.composite_index_cache[app_id] == self.NO_COMPOSITES):
return []
elif (kind in self.composite_index_cache[app_id]):
return self.composite_index_cache[app_id][kind]
else:
... |
'Deletes indexes for a given entity.
Args:
entity: An EntityProto.'
| def delete_indexes(self, entity):
| return
|
'Deletes composite indexes for an entity.
Args:
entity: An EntityProto.
composites: A list of datastore_pb.CompositeIndexes composite indexes.'
| def delete_composite_indexes(self, entity, composites):
| row_keys = get_composite_indexes_rows([entity], composites)
self.db_access.batch_delete(dbconstants.COMPOSITE_TABLE, row_keys, column_names=dbconstants.COMPOSITE_SCHEMA)
|
'Puts a kind into the statistics object if
it does not already exist.
Args:
app_id: The application ID.
kind: A string representing an entity kind.'
| def initialize_kind(self, app_id, kind):
| if (app_id not in self.stats):
self.stats[app_id] = {kind: {'size': 0, 'number': 0}}
if (kind not in self.stats[app_id]):
self.stats[app_id][kind] = {'size': 0, 'number': 0}
|
'Puts a namespace into the namespace object if
it does not already exist.
Args:
app_id: The application ID.
namespace: A string representing a namespace.'
| def initialize_namespace(self, app_id, namespace):
| if (app_id not in self.namespace_info):
self.namespace_info[app_id] = {namespace: {'size': 0, 'number': 0}}
if (namespace not in self.namespace_info[app_id]):
self.namespace_info[app_id] = {namespace: {'size': 0, 'number': 0}}
if (namespace not in self.namespace_info[app_id]):
self.s... |
'Processes an entity and adds to the global statistics.
Args:
key: The key to the entity table.
entity: EntityProto entity.
size: A int of the size of the entity.
Returns:
True on success, False otherwise.'
| def process_statistics(self, key, entity, size):
| kind = utils.get_entity_kind(entity.key())
namespace = entity.key().name_space()
if (not kind):
logging.warning('Entity did not have a kind {0}'.format(entity))
return False
if re.match(self.PROTECTED_KINDS, kind):
return True
if re.match(self.PRIVATE_KINDS,... |
'Clean up old transactions and removed unused references
to reap storage.
Returns:
True on success, False otherwise.'
| def txn_blacklist_cleanup(self):
| return True
|
'Processes an entity by updating statistics, indexes, and removes
tombstones.
Args:
entity: The entity to operate on.
Returns:
True on success, False otherwise.'
| def process_entity(self, entity):
| logging.debug('Process entity {0}'.format(str(entity)))
key = entity.keys()[0]
one_entity = entity[key][dbconstants.APP_ENTITY_SCHEMA[0]]
logging.debug('Entity value: {0}'.format(entity))
ent_proto = entity_pb.EntityProto()
ent_proto.ParseFromString(one_entity)
self.process_stati... |
'Puts a namespace into the datastore.
Args:
namespace: A string, the namespace.
size: An int representing the number of bytes taken by a namespace.
number: The total number of entities in a namespace.
timestamp: A datetime.datetime object.
Returns:
True on success, False otherwise.'
| def create_namespace_entry(self, namespace, size, number, timestamp):
| entities_to_write = []
namespace_stat = stats.NamespaceStat(subject_namespace=namespace, bytes=size, count=number, timestamp=timestamp)
entities_to_write.append(namespace_stat)
if (namespace != ''):
namespace_entry = metadata.Namespace(key_name=namespace)
entities_to_write.append(namespa... |
'Puts a kind statistic into the datastore.
Args:
kind: The entity kind.
size: An int representing the number of bytes taken by entity kind.
number: The total number of entities.
timestamp: A datetime.datetime object.
Returns:
True on success, False otherwise.'
| def create_kind_stat_entry(self, kind, size, number, timestamp):
| kind_stat = stats.KindStat(kind_name=kind, bytes=size, count=number, timestamp=timestamp)
kind_entry = metadata.Kind(key_name=kind)
entities_to_write = [kind_stat, kind_entry]
try:
db.put(entities_to_write)
except datastore_errors.InternalError as internal_error:
logging.error('Error... |
'Puts a global statistic into the datastore.
Args:
app_id: The application identifier.
size: The number of bytes of all entities.
number: The total number of entities of an application.
timestamp: A datetime.datetime object.
Returns:
True on success, False otherwise.'
| def create_global_stat_entry(self, app_id, size, number, timestamp):
| global_stat = stats.GlobalStat(key_name=app_id, bytes=size, count=number, timestamp=timestamp)
try:
db.put(global_stat)
except datastore_errors.InternalError as internal_error:
logging.error('Error inserting global stat: {0}.'.format(internal_error))
return False
logg... |
'Queries for old tasks and removes the entity which tells
use whether a named task was enqueued.
Returns:
True on success.'
| def remove_old_tasks_entities(self):
| if ((len(self.groomer_state) > 1) and (self.groomer_state[0] == self.CLEAN_TASKS_TASK)):
last_cursor = Cursor(self.groomer_state[1])
else:
last_cursor = None
self.register_db_accessor(constants.DASHBOARD_APP_ID)
timeout = (datetime.datetime.utcnow() - datetime.timedelta(seconds=self.TASK... |
'Gets a distributed datastore object to interact with
the datastore for a certain application.
Args:
app_id: The application ID.
Returns:
A distributed_datastore.DatastoreDistributed object.'
| def register_db_accessor(self, app_id):
| ds_distributed = datastore_distributed.DatastoreDistributed(app_id, self.datastore_path, require_indexes=False)
apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', ds_distributed)
apiproxy_stub_map.apiproxy.RegisterStub('memcache', memcache_distributed.MemcacheService())
os.environ['APPLICATION_ID']... |
'Removes old logs.
Args:
log_timeout: The timeout value in seconds.
Returns:
True on success, False otherwise.'
| def remove_old_logs(self, log_timeout):
| if ((len(self.groomer_state) > 1) and (self.groomer_state[0] == self.CLEAN_LOGS_TASK)):
last_cursor = Cursor(self.groomer_state[1])
else:
last_cursor = None
self.register_db_accessor(constants.DASHBOARD_APP_ID)
if log_timeout:
timeout = (datetime.datetime.utcnow() - datetime.time... |
'Does a range query on the current batch of statistics and
deletes them.'
| def remove_old_statistics(self):
| for app_id in self.stats.keys():
self.register_db_accessor(app_id)
query = stats.KindStat.all()
entities = query.run()
logging.debug('Result from kind stat query: {0}'.format(str(entities)))
for entity in entities:
logging.debug('Removing kind ... |
'Puts the namespace information into the datastore for applications to
access.
Args:
timestamp: A datetime time stamp to know which stat items belong
together.
Returns:
True if there were no errors, False otherwise.'
| def update_namespaces(self, timestamp):
| for app_id in self.namespace_info.keys():
ds_distributed = self.register_db_accessor(app_id)
namespaces = self.namespace_info[app_id].keys()
for namespace in namespaces:
size = self.namespace_info[app_id][namespace]['size']
number = self.namespace_info[app_id][namespa... |
'Puts the statistics into the datastore for applications
to access.
Args:
timestamp: A datetime time stamp to know which stat items belong
together.
Returns:
True if there were no errors, False otherwise.'
| def update_statistics(self, timestamp):
| for app_id in self.stats.keys():
ds_distributed = self.register_db_accessor(app_id)
total_size = 0
total_number = 0
kinds = self.stats[app_id].keys()
for kind in kinds:
size = self.stats[app_id][kind]['size']
number = self.stats[app_id][kind]['number']... |
'Updates the groomer\'s internal state and persists the state to
ZooKeeper.
Args:
state: A list of strings representing the ID of the task to resume along
with any additional data about the task.'
| def update_groomer_state(self, state):
| zk_data = self.GROOMER_STATE_DELIMITER.join(state)
try:
self.zoo_keeper.update_node(self.GROOMER_STATE_PATH, zk_data)
except zk.ZKInternalException as zkie:
logging.exception(zkie)
self.groomer_state = state
|
'Runs the grooming process. Loops on the entire dataset sequentially
and updates stats, indexes, and transactions.'
| def run_groomer(self):
| self.db_access = appscale_datastore_batch.DatastoreFactory.getDatastore(self.table_name)
self.ds_access = DatastoreDistributed(datastore_batch=self.db_access, zookeeper=self.zoo_keeper)
logging.info('Groomer started')
start = time.time()
self.reset_statistics()
self.composite_index_cache = {}... |
'Create a new LargeBatch object.
Args:
session: A cassandra-driver session.
project: A string specifying a project ID.
txid: An integer specifying a transaction ID.'
| def __init__(self, session, project, txid):
| self.session = session
self.project = project
self.txid = txid
self.op_id = uuid.uuid4()
self.read_op_id = None
self.applied = False
|
'Fetch the status of the batch.
Args:
retries: The number of times to retry after failures.
Returns:
A boolean indicating whether or not the batch has been applied.
Raises:
BatchNotFound if the batch cannot be found.
BatchNotOwned if a different process owns the batch.'
| def is_applied(self, retries=5):
| get_status = '\n SELECT applied, op_id FROM batch_status\n WHERE txid_hash = %(txid_hash)s\n '
query = SimpleStatement(get_status, retry_policy=BASIC_RETRIES, consistency_level=ConsistencyLevel.SERIAL)
parameters = {'txid_hash... |
'Mark the batch as being in progress.
Args:
retries: The number of times to retry after failures.
Raises:
FailedBatch if the batch cannot be marked as being started.'
| def start(self, retries=5):
| if (retries < 0):
raise FailedBatch('Retries exhausted while starting batch')
insert = SimpleStatement('\n INSERT INTO batch_status (txid_hash, applied, op_id)\n VALUES (%(txid_hash)s, False, %(op_id)s)\n ... |
'Mark the batch as being applied.
Args:
retries: The number of times to retry after failures.
Raises:
FailedBatch if the batch cannot be marked as applied.'
| def set_applied(self, retries=5):
| if (retries < 0):
raise FailedBatch('Retries exhausted while updating batch')
update_status = SimpleStatement('\n UPDATE batch_status\n SET applied = True\n WHERE txid_hash = %(txid_hash)s\n ... |
'Clean up the batch status entry.
Args:
retries: The number of times to retry after failures.
Raises:
FailedBatch if the batch cannot be marked as applied.'
| def cleanup(self, retries=5):
| if (retries < 0):
raise FailedBatch('Retries exhausted while cleaning up batch')
clear_status = SimpleStatement('\n DELETE FROM batch_status\n WHERE txid_hash = %(txid_hash)s\n IF op_id = %(op_id)... |
'Claim a batch so that other processes don\'t work on it.
Raises:
FailedBatch if the batch cannot be claimed.'
| def claim(self):
| try:
if self.is_applied():
self.applied = True
except TRANSIENT_CASSANDRA_ERRORS as error:
raise FailedBatch(str(error))
except BatchNotOwned:
pass
except BatchNotFound:
return self.start()
update_id = SimpleStatement('\n UPDATE b... |
'Fetch a list of values for the given columns in a table.
Args:
table_name: A string containing the name of the table.
column_names: A list of column names to retrieve values for.
Returns:
A list containing a status marker followed by the values.
Note: The response does not contain any row keys or column names.'
| def get_table(self, table_name, column_names):
| response = [ERROR_DEFAULT]
statement = 'SELECT * FROM "{table}"'.format(table=table_name)
query = SimpleStatement(statement, retry_policy=BASIC_RETRIES)
try:
results = self.session.execute(query)
except dbconstants.TRANSIENT_CASSANDRA_ERRORS:
response[0] += 'Unable to ... |
'This is called when a ReadTimeout occurs.
Args:
query: A statement that timed out.
consistency: The consistency level of the statement.
required_responses: The number of responses required.
received_responses: The number of responses received.
data_retrieved: Indicates whether any responses contained data.
retry_num: ... | def on_read_timeout(self, query, consistency, required_responses, received_responses, data_retrieved, retry_num):
| if (retry_num >= BASIC_RETRY_COUNT):
return (self.RETHROW, None)
else:
return (self.RETRY, consistency)
|
'This is called when a WriteTimeout occurs.
Args:
query: A statement that timed out.
consistency: The consistency level of the statement.
required_responses: The number of responses required.
received_responses: The number of responses received.
data_retrieved: Indicates whether any responses contained data.
retry_num:... | def on_write_timeout(self, query, consistency, write_type, required_responses, received_responses, retry_num):
| if (retry_num >= BASIC_RETRY_COUNT):
return (self.RETHROW, None)
else:
return (self.RETRY, consistency)
|
'Constructor.'
| def __init__(self, log_level=logging.INFO, hosts=None):
| class_name = self.__class__.__name__
self.logger = logging.getLogger(class_name)
self.logger.setLevel(log_level)
self.logger.info('Starting {}'.format(class_name))
if (hosts is not None):
self.hosts = hosts
else:
self.hosts = appscale_info.get_db_ips()
remaining_retries = ... |
'Close all sessions and connections to Cassandra.'
| def close(self):
| self.cluster.shutdown()
|
'Takes in batches of keys and retrieves their corresponding rows.
Args:
table_name: The table to access
row_keys: A list of keys to access
column_names: A list of columns to access
Returns:
A dictionary of rows and columns/values of those rows. The format
looks like such: {key:{column_name:value,...}}
Raises:
TypeError... | def batch_get_entity(self, table_name, row_keys, column_names):
| if (not isinstance(table_name, str)):
raise TypeError('Expected a str')
if (not isinstance(column_names, list)):
raise TypeError('Expected a list')
if (not isinstance(row_keys, list)):
raise TypeError('Expected a list')
row_keys_bytes = [bytearray(row_key) for r... |
'Allows callers to store multiple rows with a single call. A row can
have multiple columns and values with them. We refer to each row as
an entity.
Args:
table_name: The table to mutate
row_keys: A list of keys to store on
column_names: A list of columns to mutate
cell_values: A dict of key/value pairs
ttl: The number ... | def batch_put_entity(self, table_name, row_keys, column_names, cell_values, ttl=None):
| if (not isinstance(table_name, str)):
raise TypeError('Expected a str')
if (not isinstance(column_names, list)):
raise TypeError('Expected a list')
if (not isinstance(row_keys, list)):
raise TypeError('Expected a list')
if (not isinstance(cell_values, dict)):
... |
'Prepare an insert statement.
Args:
table: A string containing the table name.
Returns:
A PreparedStatement object.'
| def prepare_insert(self, table):
| statement = '\n INSERT INTO "{table}" ({key}, {column}, {value})\n VALUES (?, ?, ?)\n USING TIMESTAMP ?\n '.format(table=table, key=ThriftColumn.KEY, column=ThriftColumn.COLUMN_NAME, value=ThriftColumn.... |
'Prepare a delete statement.
Args:
table: A string containing the table name.
Returns:
A PreparedStatement object.'
| def prepare_delete(self, table):
| statement = '\n DELETE FROM "{table}"\n USING TIMESTAMP ?\n WHERE {key} = ?\n '.format(table=table, key=ThriftColumn.KEY)
if (statement not in self.prepared_statements):
self.prepared_statements[stat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.