desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Decrement stats by another accounting object.'
def DecrementStatsFrom(self, accounting):
self.num_photos -= accounting.num_photos self.tn_size -= accounting.tn_size self.med_size -= accounting.med_size self.full_size -= accounting.full_size self.orig_size -= accounting.orig_size
'Return true if all stats match those in \'accounting\'.'
def StatsEqual(self, accounting):
return ((self.num_photos == accounting.num_photos) and (self.tn_size == accounting.tn_size) and (self.med_size == accounting.med_size) and (self.full_size == accounting.full_size) and (self.orig_size == accounting.orig_size))
'Check whether the \'op_id\' is in \'op_id_list_string\'. If it is, return true and leave the original list of op ids untouched. Otherwise, add the op_id to the list, trim it to a max length of _MAX_APPLIED_OP_IDS = 10 and return false.'
def IsOpDuplicate(self, op_id):
ids = (self.op_ids.split(',') if (self.op_ids is not None) else []) if (op_id in ids): return True ids.append(op_id) self.op_ids = ','.join(ids[(- self._MAX_APPLIED_OP_IDS):]) return False
'Create an accounting object (USER_SIZE:<user_id>, OWNED_BY).'
@classmethod def CreateUserOwnedBy(cls, user_id):
return Accounting(('%s:%d' % (Accounting.USER_SIZE, user_id)), Accounting.OWNED_BY)
'Create an accounting object (USER_SIZE:<user_id>, SHARED_BY).'
@classmethod def CreateUserSharedBy(cls, user_id):
return Accounting(('%s:%d' % (Accounting.USER_SIZE, user_id)), Accounting.SHARED_BY)
'Create an accounting object (USER_SIZE:<user_id>, VISIBLE_TO).'
@classmethod def CreateUserVisibleTo(cls, user_id):
return Accounting(('%s:%d' % (Accounting.USER_SIZE, user_id)), Accounting.VISIBLE_TO)
'Create an accounting object (VIEWPOINT_SIZE:<vp_id>, OWNED_BY:<user_id>).'
@classmethod def CreateViewpointOwnedBy(cls, viewpoint_id, user_id):
return Accounting(('%s:%s' % (Accounting.VIEWPOINT_SIZE, viewpoint_id)), ('%s:%d' % (Accounting.OWNED_BY, user_id)))
'Create an accounting object (VIEWPOINT_SIZE:<vp_id>, SHARED_BY:<user_id>).'
@classmethod def CreateViewpointSharedBy(cls, viewpoint_id, user_id):
return Accounting(('%s:%s' % (Accounting.VIEWPOINT_SIZE, viewpoint_id)), ('%s:%d' % (Accounting.SHARED_BY, user_id)))
'Create an accounting object (VIEWPOINT_SIZE:<vp_id>, VISIBLE_TO).'
@classmethod def CreateViewpointVisibleTo(cls, viewpoint_id):
return Accounting(('%s:%s' % (Accounting.VIEWPOINT_SIZE, viewpoint_id)), Accounting.VISIBLE_TO)
'Query for an accounting object (VIEWPOINT_SIZE:<vp_id>, SHARED_BY:<user_id>).'
@classmethod def QueryViewpointSharedBy(cls, client, viewpoint_id, user_id, callback, must_exist=True):
Accounting.Query(client, ((Accounting.VIEWPOINT_SIZE + ':') + viewpoint_id), (Accounting.SHARED_BY + (':%d' % user_id)), None, callback, must_exist=must_exist)
'Query for an accounting object (VIEWPOINT_SIZE:<vp_id>, VISIBLE_TO).'
@classmethod def QueryViewpointVisibleTo(cls, client, viewpoint_id, callback, must_exist=True):
Accounting.Query(client, ((Accounting.VIEWPOINT_SIZE + ':') + viewpoint_id), Accounting.VISIBLE_TO, None, callback, must_exist=must_exist)
'Query a single user\'s accounting entries. Returns an array of [owned_by, shared_by, visible_to] accounting entries, any of which may be None (eg: if data was not properly populated).'
@classmethod @gen.coroutine def QueryUserAccounting(cls, client, user_id):
user_hash = ('%s:%d' % (Accounting.USER_SIZE, user_id)) result = (yield [gen.Task(Accounting.Query, client, user_hash, Accounting.OWNED_BY, None, must_exist=False), gen.Task(Accounting.Query, client, user_hash, Accounting.SHARED_BY, None, must_exist=False), gen.Task(Accounting.Query, client, user_hash, Accounti...
'Apply an accounting object. This involves a query to fetch stats and applied op ids, check that this operation has not been applied, increment of values and Update.'
@classmethod def ApplyAccounting(cls, client, accounting, callback):
op_id = Operation.GetCurrent().operation_id assert (op_id is not None), 'accounting update outside an operation' def _OnException(accounting, type, value, traceback): Accounting.ApplyAccounting(client, accounting, callback) def _OnQueryAccounting(entry): if (entry is None): ...
'Initializes new AccountingAccumulator object.'
def __init__(self):
self.vp_ow_acc_dict = {} self.vp_vt_acc_dict = {} self.vp_sb_acc_dict = {} self.us_ow_acc_dict = {} self.us_vt_acc_dict = {} self.us_sb_acc_dict = {}
'Returns the viewpoint owned_by accounting object for the given viewpoint and user.'
def GetViewpointOwnedBy(self, viewpoint_id, user_id):
key = (viewpoint_id, user_id) if (key not in self.vp_ow_acc_dict): self.vp_ow_acc_dict[key] = Accounting.CreateViewpointOwnedBy(viewpoint_id, user_id) return self.vp_ow_acc_dict[key]
'Returns the viewpoint visible_to accounting for the given viewpoint.'
def GetViewpointVisibleTo(self, viewpoint_id):
key = viewpoint_id if (key not in self.vp_vt_acc_dict): self.vp_vt_acc_dict[key] = Accounting.CreateViewpointVisibleTo(viewpoint_id) return self.vp_vt_acc_dict[key]
'Returns the viewpoint shared_by accounting object for the given viewpoint and user.'
def GetViewpointSharedBy(self, viewpoint_id, user_id):
key = (viewpoint_id, user_id) if (key not in self.vp_sb_acc_dict): self.vp_sb_acc_dict[key] = Accounting.CreateViewpointSharedBy(viewpoint_id, user_id) return self.vp_sb_acc_dict[key]
'Returns the user owned_by accounting for the given user.'
def GetUserOwnedBy(self, user_id):
key = user_id if (key not in self.us_ow_acc_dict): self.us_ow_acc_dict[key] = Accounting.CreateUserOwnedBy(user_id) return self.us_ow_acc_dict[key]
'Returns the user visible_to accounting for the given user.'
def GetUserVisibleTo(self, user_id):
key = user_id if (key not in self.us_vt_acc_dict): self.us_vt_acc_dict[key] = Accounting.CreateUserVisibleTo(user_id) return self.us_vt_acc_dict[key]
'Returns the user shared_by accounting for the given user.'
def GetUserSharedBy(self, user_id):
key = user_id if (key not in self.us_sb_acc_dict): self.us_sb_acc_dict[key] = Accounting.CreateUserSharedBy(user_id) return self.us_sb_acc_dict[key]
'Add accounting changes caused by adding followers to a viewpoint. Each follower user has VISIBLE_TO incremented by the size of the viewpoint VISIBLE_TO.'
@gen.coroutine def AddFollowers(self, client, viewpoint_id, new_follower_ids):
if (len(new_follower_ids) > 0): vp_vt_acc = (yield gen.Task(Accounting.QueryViewpointVisibleTo, client, viewpoint_id, must_exist=False)) if (vp_vt_acc is not None): for follower_id in new_follower_ids: self.GetUserVisibleTo(follower_id).CopyStatsFrom(vp_vt_acc)
'Add accounting changes caused by adding the given user as a follower of the viewpoint as part of a merge accounts operation. Increments the target user\'s VISIBLE_TO by the size of the viewpoint VISIBLE_TO.'
@gen.coroutine def MergeAccounts(self, client, viewpoint_id, target_user_id):
vp_vt_acc = (yield gen.Task(Accounting.QueryViewpointVisibleTo, client, viewpoint_id, must_exist=False)) if (vp_vt_acc is not None): self.GetUserVisibleTo(target_user_id).IncrementStatsFrom(vp_vt_acc)
'Add accounting changes caused by removing photos from a user\'s default viewpoint. - photo_ids: list of photos that were removed (caller should exclude the ids of any photos that were already removed). We need to query all photos for size information. Creates the following entries: - (vs:<viewpoint>, ow:<user>): stats...
@gen.coroutine def RemovePhotos(self, client, user_id, viewpoint_id, photo_ids):
photo_keys = [DBKey(photo_id, None) for photo_id in photo_ids] photos = (yield gen.Task(Photo.BatchQuery, client, photo_keys, None)) self.GetViewpointOwnedBy(viewpoint_id, user_id).DecrementFromPhotos(photos) self.GetUserOwnedBy(user_id).CopyStatsFrom(self.GetViewpointOwnedBy(viewpoint_id, user_id))
'Generate and update accounting entries for a RemoveViewpoint event. The user will never be removed from their default viewpoint. This won\'t modify the viewpoint stats, but we will query them to determine how much to modify the user stats. Query: - (vs:<viewpoint_id>, vt) - (vs:<viewpoint_id>, sb:<user_id>) Creates th...
@gen.coroutine def RemoveViewpoint(self, client, user_id, viewpoint_id):
(vp_vt, vp_sb) = (yield [gen.Task(Accounting.QueryViewpointVisibleTo, client, viewpoint_id, must_exist=False), gen.Task(Accounting.QueryViewpointSharedBy, client, viewpoint_id, user_id, must_exist=False)]) if (vp_vt is not None): self.GetUserVisibleTo(user_id).DecrementStatsFrom(vp_vt) if (vp_sb is ...
'Add accounting changes caused by the revival of the given followers. These followers had removed the viewpoint (which freed up quota), but now have access to it again. Each follower has VISIBLE_TO incremented by the size of the viewpoint VISIBLE_TO, and SHARED_BY incremented by the size of the corresponding viewpoint ...
@gen.coroutine def ReviveFollowers(self, client, viewpoint_id, revive_follower_ids):
if (len(revive_follower_ids) > 0): (yield self.AddFollowers(client, viewpoint_id, revive_follower_ids)) vp_sb_acc_list = (yield [gen.Task(Accounting.QueryViewpointSharedBy, client, viewpoint_id, follower_id, must_exist=False) for follower_id in revive_follower_ids]) for (follower_id, vp_sb_a...
'Generate and update accounting entries for a SavePhotos event. - photo_ids: list of *new* photos that were added (caller should exclude the ids of any photos that already existed). We need to query all photos for size information. Creates the following entries: - (vs:<viewpoint>, ow:<user>): stats for user in default ...
@gen.coroutine def SavePhotos(self, client, user_id, viewpoint_id, photo_ids):
photo_keys = [DBKey(photo_id, None) for photo_id in photo_ids] photos = (yield gen.Task(Photo.BatchQuery, client, photo_keys, None)) self.GetViewpointOwnedBy(viewpoint_id, user_id).IncrementFromPhotos(photos) self.GetUserOwnedBy(user_id).CopyStatsFrom(self.GetViewpointOwnedBy(viewpoint_id, user_id))
'Generate and update accounting entries for a ShareNew or ShareExisting event. - photo_ids: list of *new* photos that were added (caller should exclude the ids of any photos that already existed). - follower_ids: list of ids of all followers of the viewpoint, *including* the sharer if it is not removed from the viewpoi...
@gen.coroutine def SharePhotos(self, client, sharer_id, viewpoint_id, photo_ids, follower_ids):
photo_keys = [DBKey(photo_id, None) for photo_id in photo_ids] photos = (yield gen.Task(Photo.BatchQuery, client, photo_keys, None)) acc = Accounting() acc.IncrementFromPhotos(photos) self.GetViewpointVisibleTo(viewpoint_id).IncrementStatsFrom(acc) if (sharer_id in follower_ids): self.Ge...
'Generate and update accounting entries for an Unshare event. Multiple episodes may be impacted and multiple photos per episode. - viewpoint: viewpoint that contains the episodes and photos in ep_dicts. - ep_dicts: dict containing episode and photos ids: {ep_id0: [ph_id0, ph_id1], ep_id1: [ph_id2]}. - followers: list o...
@gen.coroutine def Unshare(self, client, viewpoint, ep_dicts, followers):
from viewfinder.backend.db.episode import Episode episode_keys = [] photo_keys = [] for (episode_id, photo_ids) in ep_dicts.iteritems(): episode_keys.append(DBKey(episode_id, None)) for photo_id in photo_ids: photo_keys.append(DBKey(photo_id, None)) (episodes, photos) = (...
'Generate and update accounting entries for an UploadEpisode event. - ph_dicts: list of *new* photo dicts that were added (caller should exclude any photos that already existed). Creates the following entries: - (vs:<viewpoint>, ow:<user>): stats for user in default viewpoint. - (us:<user>, ow): overall stats for user....
@gen.coroutine def UploadEpisode(self, client, user_id, viewpoint_id, ph_dicts):
self.GetViewpointOwnedBy(viewpoint_id, user_id).IncrementFromPhotoDicts(ph_dicts) self.GetUserOwnedBy(user_id).CopyStatsFrom(self.GetViewpointOwnedBy(viewpoint_id, user_id))
'Applies all of the accounting deltas that have been collected in the accumulator.'
@gen.coroutine def Apply(self, client):
tasks = [] for us_ow_acc in self.us_ow_acc_dict.values(): tasks.append(gen.Task(Accounting.ApplyAccounting, client, us_ow_acc)) for us_vt_acc in self.us_vt_acc_dict.values(): tasks.append(gen.Task(Accounting.ApplyAccounting, client, us_vt_acc)) for us_sb_acc in self.us_sb_acc_dict.values...
'\'ups\' is measured either as read or write capacity units per second.'
def __init__(self, table_name, read_write, name, ups):
self._name = name self._ups = ups self._queue = [] self._last_rate_adjust = time.time() self._unavailable_rate = 0.0 self._need_adj = False qps_counter = backoff_counter = None if (table_name in kSaveMetricsFor): rw_str = ('write' if read_write else 'read') qps_counter = ...
'Adds \'req\', a DynDBRequest tuple, to the priority queue.'
def Push(self, req):
_requests_queued.increment() heapq.heappush(self._queue, (self._ComputePriority(req), req))
'Pops the highest priority request from the queue and returns it.'
def Pop(self):
self._ups_rate.Add(1.0) _requests_queued.decrement() return heapq.heappop(self._queue)[1]
'Returns True if the queue is empty, False otherwise.'
def IsEmpty(self):
return (len(self._queue) == 0)
'\'success\' specifies whether or not the request failed due to a provisioned throughput exceeded error. On success, we adjust self._ups_stat if units != 1, as in the case of an eventually consistent read (units=0.5), or an operation requiring more than 1 unit. On failure, set the _need_adj flag.'
def Report(self, success, units=1):
if (success and (units != 1.0)): logging.debug(('reported %.2f units for queue %s' % (units, self._name))) self._ups_rate.Add((units - 1.0)) if (not success): _throttles_per_min.increment() self._need_adj = True
'Adjust the unavailable qps if needed and it\'s been long enough since the last adjustment. Increase or decrease based on the _need_adj flag and current min/max.'
def RecomputeRate(self):
now = time.time() if ((now - self._last_rate_adjust) >= kMinRateAdjustmentPeriod): new_adj = None if (self._need_adj and (self._unavailable_rate < (self._ups * kMaxCapacityThrottleFraction))): new_adj = (self._ups * kPerThrottleLostCapacityFraction) elif ((not self._need_adj)...
'Ask the rate limiter for the number of seconds to sleep. We must sleep this long. We do not call RecomputeRate here since NeedsBackoff just did it.'
def GetBackoffSecs(self):
return self._ups_rate.ComputeBackoffSecs()
'Returns whether or not this queue needs to backoff. This calls a method on the rate limiter that does not increment the backoff counter. We first recompute the unavailable rate and adjust it if needed.'
def NeedsBackoff(self):
self.RecomputeRate() return self._ups_rate.NeedsBackoff()
'Clears any existing timeout registered on the ioloop for this queue. If there is a current backoff and the queue is not empty, sets a new timeout based on backoff.'
def ResetTimeout(self, callback):
def _OnTimeout(): self._timeout = None callback() if ((not self.IsEmpty()) and (self._timeout is None)): backoff_secs = self.GetBackoffSecs() self._timeout = ioloop.IOLoop.current().add_timeout((time.time() + backoff_secs), _OnTimeout) elif self.IsEmpty(): if self._ti...
'Computes the priority of \'req\'. First cut of this algorithm is to simply order by the time the request was (re)added to the queue.'
def _ComputePriority(self, req):
return time.time()
'Creates a DynamoDB request to API call \'method\' with JSON encoded arguments \'request\'. Invokes \'callback\' with JSON decoded response as an argument.'
def Schedule(self, method, request, callback):
if (method in ('ListTables', 'DescribeTable')): queue = self._cp_read_only_queue elif (method in ('CreateTable', 'DeleteTable')): queue = self._cp_mutate_queue elif (method in ('GetItem', 'Query', 'Scan')): queue = self._read_queues[request['TableName']] elif (method in ('BatchGe...
'Helper function to execute a DynamoDB request within the context in which is was scheduled. This way, if an unrecoverable exception is thrown during execution, it can be re-raised to the appropriate caller.'
def _ExecuteRequest(self, queue, dyn_req):
def _OnResponse(start_time, json_response): if (dyn_req.method in ('BatchGetItem',)): consumed_units = next(json_response.get('Responses').itervalues()).get('ConsumedCapacityUnits', 1) else: consumed_units = json_response.get('ConsumedCapacityUnits', 1) logging.debug(...
'If the queue is not empty and adequate provisioning is expected, sends the highest priority queue item(s) to DynamoDB. When all items have been sent, resets the queue processing timeout.'
def _ProcessQueue(self, queue):
if self._paused: return while ((not queue.IsEmpty()) and (not queue.NeedsBackoff())): dyn_req = queue.Pop() dyn_req.execute_cb(dyn_req) queue.ResetTimeout(partial(self._ProcessQueue, queue))
'Pauses all queue processing. No requests will be sent until _Resume() is invoked. NOTE: intended for testing.'
def _Pause(self):
self._paused = True
'Resume the scheduler if paused.'
def _Resume(self):
if self._paused: self._paused = False [self._ProcessQueue(q) for q in self._read_queues.values()] [self._ProcessQueue(q) for q in self._write_queues.values()] [self._ProcessQueue(q) for q in (self._cp_read_only_queue, self._cp_mutate_queue)]
'Uses single ConnectionManager instance of connection_manager is None.'
def __init__(self, schema, read_only=False):
self._schema = schema self._read_only = read_only self._scheduler = RequestScheduler(schema)
'See the header for DBClient.BatchGetItem for details. Note that currently items can only be requested from a single table at a time (though the interface supports multiple tables).'
@gen.engine def BatchGetItem(self, batch_dict, callback, must_exist=True):
assert (len(batch_dict) == 1), 'BatchGetItem currently supports only a single table' (table_name, (keys, attributes, consistent_read)) = next(batch_dict.iteritems()) table_def = self._schema.GetTable(table_name) key_result_dict = {key: None for key in keys} read_units = 0.0 whi...
'Invokes the specified callback after \'deadline_secs\'.'
def AddTimeout(self, deadline_secs, callback):
return ioloop.IOLoop.current().add_timeout((time.time() + deadline_secs), callback)
'Invokes the specified callback at time \'abs_timeout\'.'
def AddAbsoluteTimeout(self, abs_timeout, callback):
return ioloop.IOLoop.current().add_timeout(abs_timeout, callback)
'Removes an existing timeout.'
def RemoveTimeout(self, timeout):
ioloop.IOLoopcurrent().remove_timeout(timeout)
'Creates the base request structure for accessing a DynamoDB table by key.'
def _GetBaseRequest(self, table_def, key):
return {'TableName': table_def.name_in_db, 'Key': self._ToDynamoKey(table_def, key)}
'Converts a DynamoDB key into a DBKey named tuple, using the value types defined in the table key definition.'
def _FromDynamoKey(self, table_def, dyn_key):
if (dyn_key is None): return None (value_type, value) = dyn_key['HashKeyElement'].items()[0] hash_key = self._FromDynamoValue(table_def.hash_key_col, value_type, value) if table_def.range_key_col: (value_type, value) = dyn_key['RangeKeyElement'].items()[0] range_key = self._FromD...
'Converts from a DBKey named tuple into a DynamoDB key.'
def _ToDynamoKey(self, table_def, key):
dyn_key = {'HashKeyElement': self._ToDynamoValue(table_def.hash_key_col, key.hash_key)} if (key.range_key is not None): assert table_def.range_key_col dyn_key['RangeKeyElement'] = self._ToDynamoValue(table_def.range_key_col, key.range_key) return dyn_key
'Converts attributes as reported by DynamoDB into a dictionary of key/value pairs. This verifies at each step that the value types are in agreement, and converts from a list to a set for value types \'SS\' and \'NS\'.'
def _FromDynamoAttributes(self, table_def, dyn_attrs):
if (dyn_attrs is None): return None attrs = dict() for (k, v) in dyn_attrs.items(): (value_type, value) = v.items()[0] attrs[k] = self._FromDynamoValue(table_def.GetColumnByKey(k), value_type, value) return attrs
'Converts attributes from schema datamodel to a dictionary appropriate for use with DynamoDB JSON request protocol.'
def _ToDynamoAttributes(self, table_def, attrs):
dyn_attrs = dict() for (k, v) in attrs.items(): dyn_attrs[k] = self._ToDynamoValue(table_def.GetColumnByKey(k), v) return dyn_attrs
'Converts attribute updates from schema datamodel to a dictionary appropriate for use with DynamoDB JSON request protocol.'
def _ToDynamoAttributeUpdates(self, table_def, updates):
dyn_updates = dict() for (k, v) in updates.items(): dyn_updates[k] = {'Action': v.action} if (v.value is not None): dyn_updates[k]['Value'] = self._ToDynamoValue(table_def.GetColumnByKey(k), v.value) return dyn_updates
'Converts expected values from schema datamodel to a dictionary appropriate for use with DynamoDB JSON request protocol. If the value of an expected key is a boolean, it must be False, and is meant to specify that the attribute must not exist.'
def _ToDynamoExpected(self, table_def, expected):
dyn_exp = dict() for (k, v) in expected.items(): if isinstance(v, bool): assert (not v), 'if specifying a bool for an expected value, must be False' dyn_exp[k] = {'Exists': False} else: dyn_exp[k] = {'Value': self._ToDynamoValue(t...
'Converts a dynamo value to a python data structure for use with viewfinder schema.'
def _FromDynamoValue(self, col_def, dyn_type, dyn_value):
assert (col_def.value_type == dyn_type), ('%s != %s' % (col_def.value_type, dyn_type)) if (col_def.value_type == 'N'): return ConvertToNumber(dyn_value) elif (col_def.value_type == 'NS'): return set([ConvertToNumber(dv) for dv in dyn_value]) elif (col_def.value_type == 'SS'): ...
'Converts a value to a representation appropriate for passing as a JSON-encoded value to DynamoDB.'
def _ToDynamoValue(self, col_def, v):
if (col_def.value_type == 'N'): return {col_def.value_type: ConvertToString(v)} elif (col_def.value_type == 'NS'): return {col_def.value_type: [ConvertToString(v_el) for v_el in v]} elif (col_def.value_type == 'SS'): return {col_def.value_type: [v_el for v_el in v]} else: ...
'Builds a table schema namedtuple from a create or delete table request.'
def _GetTableSchema(self, name_in_db, desc):
assert (desc['TableName'] == name_in_db), ('%s != %s' % (desc['TableName'], name_in_db)) def _GetDBKeySchema(key): if (('KeySchema' in desc) and (key in desc['KeySchema'])): return DBKeySchema(name=desc['KeySchema'][key]['AttributeName'], value_type=desc['KeySchema'][key]['AttributeTyp...
'Begins the logic to get a new session token. Performs checks to ensure that only one request goes out at a time and that backoff is respected, so it can be called repeatedly with no ill effects. Set bypass_lock to True to override this behavior.'
def _update_session_token(self, callback, attempts=0, bypass_lock=False):
if ((self.provider.security_token == PENDING_SESSION_TOKEN_UPDATE) and (not bypass_lock)): return self.provider.security_token = PENDING_SESSION_TOKEN_UPDATE return self.sts.get_session_token(functools.partial(self._update_session_token_cb, callback=callback, attempts=attempts))
'Callback to use with `async_aws_sts`. The \'provider\' arg is a bit misleading, it is a relic from boto and should probably be left to its default. This will take the new Credentials obj from `async_aws_sts.get_session_token()` and use it to update self.provider, and then will clear the deque of pending requests. A ca...
def _update_session_token_cb(self, creds, provider='aws', callback=None, error=None, attempts=0):
def raise_error(): self.provider.security_token = None if callable(callback): return callback(error=error) else: logging.error(error) raise error if error: if isinstance(error, InvalidClientTokenIdError): raise_error() elif ...
'Make an asynchronous HTTP request to DynamoDB. Callback should operate on the decoded json response (with object hook applied, of course). It should also accept an error argument, which will be a boto.exception.DynamoDBResponseError. If there is not a valid session token, this method will ensure that a new one is fetc...
def make_request(self, action, body='', callback=None, object_hook=None):
this_request = functools.partial(self.make_request, action=action, body=body, callback=callback, object_hook=object_hook) if (self.authenticate_requests and (self.provider.security_token in [None, PENDING_SESSION_TOKEN_UPDATE])): self.pending_requests.appendleft(this_request) def cb_for_update(e...
'Check for errors and decode the json response (in the tornado response body), then pass on to orig callback. This method also contains some of the logic to handle reacquiring session tokens.'
def _finish_make_request(self, response, callback, orig_request, token_used, object_hook=None):
if (not response.body): assert response.error, ('How can there be no response body and no error? Response: %s' % response) raise DynamoDBResponseError(response.error.code, response.error.message, None) json_response = json.loads(response.body, object_hook=object_...
'A lock id is the concatenation of the resource type and resource id, separated by a colon. For example: op:123 vp:v--F'
@classmethod def ConstructLockId(cls, resource_type, resource_id):
assert (resource_type and (':' not in resource_type)), resource_type assert (resource_id and (':' not in resource_id)), resource_id return ((resource_type + ':') + resource_id)
'Returns the components of a lock identifier: (resource_type, resource_id)'
@classmethod def DeconstructLockId(cls, lock_id):
index = lock_id.find(':') assert (index != (-1)) return (lock_id[:index], lock_id[(index + 1):])
'Tries to acquire a lock on the specific resources instance, associating an optional "resource_data" string with the lock. Returns a tuple containing the lock object and a status value: (lock, status) The status value is one of: FAILED_TO_ACQUIRE_LOCK TryAcquire was unable to acquire the lock because another agent has ...
@classmethod def TryAcquire(cls, client, resource_type, resource_id, callback, resource_data=None, detect_abandonment=False, owner_id=None):
Lock._TryAcquire(client, resource_type, resource_id, callback, resource_data=resource_data, detect_abandonment=detect_abandonment, owner_id=owner_id)
'Acquires lock or fails with LockFailedError. Returns lock as only parameter to callback.'
@classmethod @gen.engine def Acquire(cls, client, resource_type, resource_id, owner_id, callback):
results = (yield gen.Task(Lock.TryAcquire, client, resource_type, resource_id, owner_id=owner_id)) (lock, status) = results.args if (status == Lock.FAILED_TO_ACQUIRE_LOCK): raise LockFailedError(('Cannot acquire lock "%s:%s", owner_id "%s" because another agent has acqu...
'Scans the Lock table for locks that have expired, and therefore are assumed to have been abandoned by their owners. Returns a tuple containing a list of abandoned locks and the key of the last lock that was scanned (or None if all locks have been scanned).'
@classmethod def ScanAbandoned(cls, client, callback, limit=None, excl_start_key=None):
assert (limit > 0), limit now = int(time.time()) Lock.Scan(client, None, callback, limit=limit, excl_start_key=excl_start_key, scan_filter={'expiration': db_client.ScanFilter([now], 'LE')})
'Returns true if this lock has been abandoned, which means that the process which acquired it failed and will never release it. Abandonment is assumed to have occurred if enough time has passed since the last renewal.'
def IsAbandoned(self):
return ((self.expiration is not None) and (self.expiration <= time.time()))
'Returns true if the lock is owned by the current instance.'
def AmOwner(self):
return (self._unique_id == self.owner_id)
'Returns true if the lock has been released via a call to "Release".'
def IsReleased(self):
return self._is_released
'Releases the lock so that it may be acquired by other agents. Deletes the lock from the Lock table. In addition, updates the "acquire_failures" attribute on the lock to the value in the database. This attribute allows the releasing owner to see whether any other agents tried to acquire the lock during the period in wh...
@gen.coroutine def Release(self, client):
assert (not self.IsAbandoned()), self assert self.AmOwner(), self assert (not self.IsReleased()), self self._StopRenewal() do_raise = False try: expected_acquire_failures = (False if (self.acquire_failures is None) else self.acquire_failures) (yield gen.Task(self.Delete, client, ...
'Marks the lock as abandoned by disabling renewal and expiring the lock. Other agents may acquire or release the lock, but must first be certain that the protected resource is in a consistent state.'
def Abandon(self, client, callback):
assert self.AmOwner(), self self._StopRenewal() self.expiration = 0 self.Update(client, expected={'owner_id': self.owner_id}, callback=callback)
'Helper method that makes "MAX_UPDATE_ATTEMPTS" to acquire the lock. If multiple agents are trying to acquire the lock, then one might be updating the lock in order to acquire it while another is querying the lock in order to see if it can be acquired. These race conditions are resolved by detecting changes and retryin...
@classmethod def _TryAcquire(cls, client, resource_type, resource_id, callback, resource_data=None, detect_abandonment=False, owner_id=None, attempts=0, test_hook=None):
def _OnUpdate(lock, status): 'If lock was acquired and abandonment needs to be detected,\n then starts renewal timer.\n ' if ((status != Lock.FAILED_TO_ACQUIRE_LOCK) and detect_abandonment): lock._Renew(cli...
'Stops renewing this lock\'s expiration on a periodic basis.'
def _StopRenewal(self):
if (self._timeout is not None): IOLoop.current().remove_timeout(self._timeout) self._timeout = None self._renewing = False
'Compares against Lock.owner_id.'
def _IsOwnedBy(self, owner_id):
assert (self.owner_id is not None) return (owner_id == self.owner_id)
'Set owner_id and asserts that owner_id argument is not None.'
def _SetOwnerId(self, owner_id):
assert (owner_id is not None) self._unique_id = owner_id self.owner_id = owner_id
'We matched expected owner_id to actual owner_id. Now, get _unique_id into sync with owner_id.'
def _SyncUniqueIdToOwnerId(self):
self._unique_id = self.owner_id
'Generates a random 48 bit number (converted to string) which is used as the owner id. This string is a decimal representation of a 48 bit random number and not 6 random bytes.'
def _GenerateOwnerId(self):
self._SetOwnerId(str(random.getrandbits(48)))
'Sets new owner on this lock and update expiration.'
def _TryTakeControl(self, client, detect_abandonment, callback):
former_owner_id = self.owner_id self._GenerateOwnerId() self.expiration = ((time.time() + Lock.ABANDONMENT_SECS) if detect_abandonment else None) self.Update(client, expected={'owner_id': former_owner_id}, callback=callback)
'Increments the "acquire_failures" attribute on the lock. Multiple agents may concurrently try to acquire the lock, so this operation must handle race conditions. Expecting the owner_id is a way to ensure that the lock hasn\'t been released by the owner before we update it here. Otherwise, our attempt to update a rele...
def _TryReportAcquireFailure(self, client, callback):
expected = {'owner_id': self.owner_id} if (self.acquire_failures is None): self.acquire_failures = 1 expected['acquire_failures'] = False else: self.acquire_failures += 1 expected['acquire_failures'] = (self.acquire_failures - 1) self.Update(client, expected=expected, cal...
'Continually renews the lock by updating its expiration on a regular interval. As long as the expiration is in the future, the lock is not considered to be abandoned.'
def _Renew(self, client):
def _OnException(type, value, tb): 'If failure occurs during renewal, just abandon the lock.' logging.error('failure trying to renew lock "%s"', exc_info=(type, value, tb)) def _OnRenewalTimeout(): self._timeout = None if (not self._renewing...
'Returns true if the photo has been hidden by the user so that it will not show in the personal library or conversation feed.'
def IsHidden(self):
return (UserPost.HIDDEN in self.labels)
'Returns true if the viewpoint is a default viewpoint.'
def IsDefault(self):
return (self.type == Viewpoint.DEFAULT)
'Returns true if the viewpoint is a system viewpoint (ex. welcome conversation).'
def IsSystem(self):
return (self.type == Viewpoint.SYSTEM)
'Returns a viewpoint id constructed from component parts. See "ConstructAssetId" for details of the encoding.'
@classmethod def ConstructViewpointId(cls, device_id, uniquifier):
return ConstructAssetId(IdPrefix.Viewpoint, device_id, uniquifier)
'Returns the components of a viewpoint id: device_id and uniquifier.'
@classmethod def DeconstructViewpointId(cls, viewpoint_id):
return DeconstructAssetId(IdPrefix.Viewpoint, viewpoint_id)
'Construct a cover_photo dict.'
@classmethod def ConstructCoverPhoto(cls, episode_id, photo_id):
assert (episode_id is not None), episode_id assert (photo_id is not None), photo_id return {'episode_id': episode_id, 'photo_id': photo_id}
'Ensures that a client-provided viewpoint id is valid according to the rules specified in VerifyAssetId.'
@classmethod @gen.coroutine def VerifyViewpointId(cls, client, user_id, device_id, viewpoint_id):
(yield VerifyAssetId(client, user_id, device_id, IdPrefix.Viewpoint, viewpoint_id, has_timestamp=False))
'Acquires a persistent global lock on the specified viewpoint.'
@classmethod @gen.engine def AcquireLock(cls, client, viewpoint_id, callback):
op = Operation.GetCurrent() lock = (yield gen.Task(Lock.Acquire, client, LockResourceType.Viewpoint, viewpoint_id, op.operation_id)) ViewpointLockTracker.AddViewpointId(viewpoint_id) callback(lock)
'Releases a previously acquired lock on the specified viewpoint.'
@classmethod @gen.engine def ReleaseLock(cls, client, viewpoint_id, lock, callback):
(yield gen.Task(lock.Release, client)) ViewpointLockTracker.RemoveViewpointId(viewpoint_id) callback()
'Asserts that a lock has been acquired on the specified viewpoint.'
@classmethod def AssertViewpointLockAcquired(cls, viewpoint_id):
assert ViewpointLockTracker.HasViewpointId(viewpoint_id), ("Lock for viewpoint, %s, should be acquired at this point but isn't." % viewpoint_id)
'The cover photo is consider set if it is a non empty dict.'
def IsCoverPhotoSet(self):
if (self.cover_photo is not None): assert (len(self.cover_photo) > 0), self return True return False
'Constructs a dictionary containing viewpoint metadata attributes, overridden by follower attributes where required (as viewed by the follower himself). The format conforms to VIEWPOINT_METADATA in json_schema.py.'
def MakeMetadataDict(self, follower):
vp_dict = self._asdict() foll_dict = follower.MakeMetadataDict() vp_dict.update(foll_dict) if follower.IsRemoved(): for attr_name in vp_dict.keys(): if (attr_name not in Viewpoint._IF_REMOVED_ATTRIBUTES): del vp_dict[attr_name] return vp_dict
'Adds the specified followers to this viewpoint, giving each follower CONTRIBUTE permission on the viewpoint. The caller is responsible for ensuring that the user adding the followers has permission to do so, and that the users to add are not yet followers. Returns the newly added followers.'
@gen.coroutine def AddFollowers(self, client, adding_user_id, existing_follower_ids, add_follower_ids, timestamp):
@gen.coroutine def _UpdateFollower(follower_id): 'Create a new follower of this viewpoint in the database.' follower = Follower(user_id=follower_id, viewpoint_id=self.viewpoint_id) follower.timestamp = timestamp follower.adding_user_id = adding_user_id ...
'Select a cover photo for this viewpoint. This is used to select a cover photo if the current cover photo gets unshared. The selection order here assumes that the order of episodes and photos in the activities reflects the intended order of selection. This won\'t be true of activities created before this change goes i...
@gen.engine def SelectCoverPhoto(self, client, exclude_posts_set, callback, activities_list=None, available_posts_dict=None):
from viewfinder.backend.db.post import Post batch_limit = 50 assert (not self.IsDefault()), self @gen.coroutine def _QueryAvailablePost(episode_id, photo_id): if (available_posts_dict is not None): post = available_posts_dict.get(Post.ConstructPostId(episode_id, photo_id), None) ...
'Select a cover photo from the ep_dicts argument. Selection assumes episodes and photos are ordered according to selection preference. Returns: Either None if no photos found, or a cover_photo dict with selected photo.'
@classmethod def SelectCoverPhotoFromEpDicts(cls, ep_dicts):
cover_photo = None for ep_dict in ep_dicts: if (len(ep_dict['photo_ids']) > 0): cover_photo = Viewpoint.ConstructCoverPhoto(ep_dict['episode_id'], ep_dict['photo_ids'][0]) break return cover_photo
'Confirm existence of specified cover_photo in ep_dicts. Return: True if specified cover_photo matches photo in ep_dicts. Otherwise, False.'
@classmethod def IsCoverPhotoContainedInEpDicts(cls, cover_episode_id, cover_photo_id, ep_dicts):
for ep_dict in ep_dicts: if (cover_episode_id == ep_dict['episode_id']): for photo_id in ep_dict['photo_ids']: if (cover_photo_id == photo_id): return True return False
'Creates and returns a new user\'s default viewpoint.'
@classmethod @gen.coroutine def CreateDefault(cls, client, user_id, device_id, timestamp):
from viewfinder.backend.db.user import User vp_dict = {'viewpoint_id': Viewpoint.ConstructViewpointId(device_id, User.DEFAULT_VP_ASSET_ID), 'user_id': user_id, 'timestamp': timestamp, 'type': Viewpoint.DEFAULT} (viewpoint, _) = (yield gen.Task(Viewpoint.CreateNew, client, **vp_dict)) raise gen.Return(vi...