desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Creates a new photo metadata object from the provided dictionary. Returns: new photo.'
@classmethod @gen.coroutine def CreateNew(cls, client, **ph_dict):
assert (('photo_id' in ph_dict) and ('user_id' in ph_dict) and ('episode_id' in ph_dict)), ph_dict photo = Photo.CreateFromKeywords(**ph_dict) (yield photo.Update(client)) raise gen.Return(photo)
'Updates existing photo metadata from the provided dictionary.'
@classmethod @gen.coroutine def UpdateExisting(cls, client, **ph_dict):
assert (('timestamp' not in ph_dict) and ('episode_id' not in ph_dict) and ('user_id' not in ph_dict)), ph_dict photo = Photo.CreateFromKeywords(**ph_dict) (yield photo.Update(client))
'For a photo that already exists, check that its attributes match. Return: photo, if it already exists.'
@classmethod @gen.coroutine def CheckCreate(cls, client, **ph_dict):
assert (('photo_id' in ph_dict) and ('user_id' in ph_dict)), ph_dict photo = (yield Photo.Query(client, ph_dict['photo_id'], None, must_exist=False)) if ((photo is not None) and photo.HasMismatchedValues(Photo.PHOTO_CREATE_ATTRIBUTE_UPDATE_ALLOWED_SET, **ph_dict)): logging.warning(('Photo.CheckCreat...
'Determines whether a photo\'s image data has been uploaded to S3 by using a HEAD request. If the image exists, then invokes callback with the Etag of the image. Otherwise, invokes the callback with None.'
@classmethod @gen.coroutine def IsImageUploaded(cls, obj_store, photo_id, suffix):
url = obj_store.GenerateUrl((photo_id + suffix), method='HEAD') http_client = httpclient.AsyncHTTPClient() try: response = (yield http_client.fetch(url, method='HEAD', validate_cert=options.options.validate_cert)) except httpclient.HTTPError as e: if (e.code == 404): raise ge...
'Updates photo to metadata object from the provided dictionary.'
@classmethod @gen.coroutine def UpdatePhoto(cls, client, act_dict, **ph_dict):
assert (('photo_id' in ph_dict) and ('user_id' in ph_dict)), ph_dict photo = (yield Photo._CheckUpdate(client, **ph_dict)) assert (photo is not None), ph_dict assert (photo.photo_id == ph_dict['photo_id']), (photo, ph_dict) assert (photo.user_id == ph_dict['user_id']), (photo, ph_dict) asset_key...
'Checks that the photo exists. Checks photo metadata object against the provided dictionary. Checks that the user_id in the dictionary matches the one on the photo. Returns: photo'
@classmethod @gen.coroutine def _CheckUpdate(cls, client, **ph_dict):
assert (('photo_id' in ph_dict) and ('user_id' in ph_dict)), ph_dict photo = (yield Photo.Query(client, ph_dict['photo_id'], None, must_exist=False)) if (photo is None): raise InvalidRequestError(('Photo "%s" does not exist and so cannot be updated.' % ph_dict['photo_id'])...
'Updates photo metadata.'
@classmethod @gen.coroutine def UpdateOperation(cls, client, act_dict, ph_dict):
assert (ph_dict['user_id'] == Operation.GetCurrent().user_id) (yield Photo.UpdatePhoto(client, act_dict=act_dict, **ph_dict))
'Create value for sort_key attribute. This is derived from timestamp and type.'
@classmethod def CreateSortKey(cls, timestamp, entry_type):
prefix = util.CreateSortKeyPrefix(timestamp, randomness=False) return (prefix + entry_type)
'Create a new analytics object with fields from \'analytics_dict\'. Sets timestamp if not specified. Payload may be empty.'
@classmethod def Create(cls, **analytics_dict):
create_dict = analytics_dict if ('timestamp' not in create_dict): create_dict['timestamp'] = util.GetCurrentTimestamp() entity = create_dict['entity'] entry_type = create_dict['type'] if entry_type.startswith('User.'): assert entity.startswith('us:'), ('Wrong entity string f...
'Return name of the asset that has the specified prefix.'
@staticmethod def GetAssetName(prefix):
if (not hasattr(IdPrefix, '_prefixes')): IdPrefix._prefixes = {} for slot in dir(IdPrefix): if (not slot.startswith('_')): prefix = getattr(IdPrefix, slot) if isinstance(prefix, str): assert (prefix not in IdPrefix._prefixes) ...
'Return true if "prefix" is a uniquely defined id prefix.'
@staticmethod def IsValid(prefix):
return (IdPrefix.GetAssetName(prefix) is not None)
'The base datastore object class manages columns according to the database schema as defined by the subclass\' schema table definition. However, derived classes can override the column set by specifying the "columns" argument. Columns of type IndexTermsColumn are ignored here. They will not create column values which c...
def __init__(self, columns=None):
self._columns = {} self._reindex = False columns = (columns or self._table.GetColumns()) for c in columns: if (not isinstance(c, schema.IndexTermsColumn)): self._columns[c.name] = c.NewInstance()
'Class decorator which adds properties for all columns defined in a table. The class must define a class attribute _table. Example: @DBObject.map_table_attributes class Foo(DBRangeObject): _table = DBObject._schema.GetTable(vf_schema.FOO)'
@staticmethod def map_table_attributes(cls):
assert issubclass(cls, DBObject) for c in cls._table.GetColumns(): if (not isinstance(c, schema.IndexTermsColumn)): fget = (lambda name: (lambda self: self.__GetProperty(name)))(c.name) fset = (lambda name: (lambda self, value: self.__SetProperty(name, value)))(c.name) ...
'Override to return True for columns that should not appear in logs.'
@classmethod def ShouldScrubColumn(cls, name):
return False
'Returns whether or not a column value has been modified.'
def _IsModified(self, name):
return self._columns[name].IsModified()
'Returns all column names.'
def GetColNames(self):
return self._columns.keys()
'Returns all column names where the column value has been modified.'
def GetModifiedColNames(self):
return [c.col_def.name for c in self._columns.values() if c.IsModified()]
'Sets the _reindex boolean. If set to True, index terms for all columns will be re-generated on update, regardless of whether or not the column has been modified. This is used during data migrations when the indexing algorithm for a particular column type (or types) has been modified. Only generates writes (and deletes...
def SetReindexOnUpdate(self, reindex):
self._reindex = reindex
'Creates a new object of type \'cls\' with attributes as specified in \'obj_dict\'. The key columns must be present in the attribute dictionary. Returns new object instance.'
@classmethod def CreateFromKeywords(cls, **obj_dict):
assert obj_dict.has_key(cls._table.hash_key_col.name) if cls._table.range_key_col: assert obj_dict.has_key(cls._table.range_key_col.name), (cls._table.range_key_col.name, obj_dict) o = cls() o.UpdateFromKeywords(**obj_dict) o._columns[schema.Table.VERSION_COLUMN.name].Set(Version.GetCurrentV...
'Updates the contents of the object according to **obj_dict.'
def UpdateFromKeywords(self, **obj_dict):
for (k, v) in obj_dict.items(): if (k in self._columns): self._columns[k].Set(v) else: raise KeyError(('column %s (value %r) not found in class %s' % (k, v, self.__class__)))
'Check that each of the dictionary values matches what\'s in the object. The only keys that don\'t need to match are ones contained in the mismatch_allowed_set. Returns: True if mismatch found. Otherwise, False.'
def HasMismatchedValues(self, mismatch_allowed_set=None, **obj_dict):
for (k, v) in obj_dict.items(): if (k in self._columns): if ((mismatch_allowed_set is None) or (k not in mismatch_allowed_set)): if (self._columns[k].Get(asdict=isinstance(v, dict)) != v): return True return False
'Updates or inserts the object. Only modified columns are updated. Updates the index terms first and finally the object, so the update operation, on retry, will be idempotent. \'expected\' are preconditions for attribute values for the update to succeed. If \'replace\' is False, forces a conditional update which verifi...
@return_future def Update(self, client, callback, expected=None, replace=True, return_col_names=False):
mod_cols = [c for c in self._columns.values() if c.IsModified()] if return_col_names: callback = partial(callback, [c.col_def.name for c in mod_cols]) if ((not mod_cols) and (not self._reindex)): callback() return if expected: expected = dict([(self._table.GetColumn(k).ke...
'Deletes all columns of the object and all associated index terms. Deletes the index terms first and finally the object, so the deletion operation, on retry, will be idempotent. \'expected\' are preconditions for attribute values for the delete to succeed.'
def Delete(self, client, callback, expected=None):
if expected: expected = dict([(self._table.GetColumn(k).key, v) for (k, v) in expected.items()]) def _OnDelete(result): callback() def _OnDeleteIndexTerms(): client.DeleteItem(table=self._table.name, key=self.GetKey(), callback=_OnDelete, expected=expected) def _OnQueryIndexTerms...
'Queries the index terms for the specified columns. If no columns are specified, invokes callback immediately. When a column is indexed, the set of index terms produced is stored near the column value to be queried on modifications. Having access to the old set is especially crucial if the indexing algorithm changes.'
def _QueryIndexTerms(self, client, col_names, callback):
idx_cols = [self._columns[name] for name in col_names if self._table.GetColumn(name).indexer] attrs = [(c.col_def.key + ':t') for c in idx_cols] def _OnQuery(get_result): 'Handle case of new object and a term attributes query failure.' if (get_result is None): ...
'Returns the indexing key for this object by calling the _MakeIndexKey class method, which is overridden by derived classes.'
def _GetIndexKey(self):
return self._MakeIndexKey(self.GetKey())
'Creates a new instance of cls and sets the values of its columns from \'attr_dict\'. Returns the new object instance.'
@classmethod def _CreateFromQuery(cls, **attr_dict):
assert attr_dict.has_key(cls._table.hash_key_col.key), attr_dict if cls._table.range_key_col: assert attr_dict.has_key(cls._table.range_key_col.key), attr_dict o = cls() for (k, v) in attr_dict.items(): name = cls._table.GetColumnName(k) o._columns[name].Load(v) return o
'Scans the table up to a count of \'limit\', starting at the hash key value provided in \'excl_start_key\'. Invokes the callback with the list of elements and the last scanned key (list, last_key). The last_key will be None if the last item was scanned. \'scan_filter\' is a map from attribute name to a tuple of ([attr_...
@classmethod def Scan(cls, client, col_names, callback, limit=None, excl_start_key=None, scan_filter=None):
if (limit == 0): callback(([], None)) col_set = cls._CreateColumnSet(col_names) if scan_filter: scan_filter = dict([(cls._table.GetColumn(k).key, v) for (k, v) in scan_filter.items()]) def _OnScan(result): objs = [] for item in result.items: objs.append(cls._C...
'Queries for a batch of items identified by DBKey objects in the \'keys\' array. Projects the specified columns (or all columns if col_names==None). If \'must_exist\' is False, then return None for each item that does not exist in the database.'
@classmethod @gen.engine def BatchQuery(cls, client, keys, col_names, callback, must_exist=True, consistent_read=False):
col_set = cls._CreateColumnSet(col_names) request = db_client.BatchGetRequest(keys=keys, attributes=[cls._table.GetColumn(name).key for name in col_set], consistent_read=consistent_read) result = (yield gen.Task(client.BatchGetItem, batch_dict={cls._table.name: request}, must_exist=must_exist)) result_o...
'Queries the specified columns (or all columns if col_names==None), using key as the object hash key.'
@classmethod def KeyQuery(cls, client, key, col_names, callback, must_exist=True, consistent_read=False):
col_set = cls._CreateColumnSet(col_names) def _OnQuery(result): o = None if (result and result.attributes): o = cls._CreateFromQuery(**result.attributes) callback(o) client.GetItem(table=cls._table.name, key=key, attributes=[cls._table.GetColumn(name).key for name in col_...
'Returns a sequence of object keys to \'callback\' resulting from execution of \'bound_query_str\'.'
@classmethod def IndexQueryKeys(cls, client, bound_query_str, callback, start_index_key=None, end_index_key=None, limit=50, consistent_read=False):
def _OnQueryKeys(index_keys): callback([cls._ParseIndexKey(index_key) for index_key in index_keys]) try: start_key = (cls._MakeIndexKey(start_index_key) if (start_index_key is not None) else None) end_key = (cls._MakeIndexKey(end_index_key) if (end_index_key is not None) else None) ...
'Returns a sequence of Objects resulting from the execution of \'query\' as the first parameter to \'callback\'. Only the columns specified in \'col_names\' are queried, or all columns if None.'
@classmethod @gen.engine def IndexQuery(cls, client, bound_query_str, col_names, callback, start_index_key=None, end_index_key=None, limit=50, consistent_read=False):
try: start_key = (cls._MakeIndexKey(start_index_key) if (start_index_key is not None) else None) end_key = (cls._MakeIndexKey(end_index_key) if (end_index_key is not None) else None) (query, param_dict) = query_parser.CompileQuery(cls._schema, bound_query_str) index_keys = (yield gen...
'Query for all object keys in the specified key range. For each key, invoke the "visitor" function: visitor(object_key, visit_callback) When the visitor function has completed the visit, it should invoke "visit_callback" with no parameters. Once all object keys have been visited, then "callback" is invoked.'
@classmethod def VisitIndexKeys(cls, client, bound_query_str, visitor, callback, start_index_key=None, end_index_key=None, consistent_read=False):
def _OnQueryKeys(index_keys): if (len(index_keys) < DBObject._VISIT_LIMIT): barrier_callback = callback else: barrier_callback = partial(DBObject.VisitIndexKeys, client, bound_query_str, visitor, callback, start_index_key=index_keys[(-1)], end_index_key=end_index_key, consist...
'Query for all objects in the specified key range. For each object, invoke the "visitor" function: visitor(object, visit_callback) When the visitor function has completed the visit, it should invoke "visit_callback" with no parameters. Once all objects have been visited, then "callback" is invoked.'
@classmethod def VisitIndex(cls, client, bound_query_str, visitor, col_names, callback, start_index_key=None, end_index_key=None, consistent_read=False):
def _OnQuery(objects): if (len(objects) < DBObject._VISIT_LIMIT): barrier_callback = callback else: barrier_callback = partial(DBObject.VisitIndex, client, bound_query_str, visitor, col_names, callback, start_index_key=objects[(-1)]._GetIndexKey(), end_index_key=end_index_key...
'Creates a set of column names from the \'col_names\' list (all columns in the table if col_names == None). Ensures that the hash key, range key, and version column are always included in the set.'
@classmethod def _CreateColumnSet(cls, col_names):
col_set = set((col_names or cls._table.GetColumnNames())) col_set.add(cls._table.hash_key_col.name) if cls._table.range_key_col: col_set.add(cls._table.range_key_col.name) col_set.add(schema.Table.VERSION_COLUMN.name) return col_set
'Allocates a block of \'allocation\' IDs from the \'id_allocator\' table. Specify allocation as a prime number to make it less likely that two allocating servers are handing out numbers with synchronized mod offsets. This shouldn\'t in practice be an issue as the hash prefix we compute is constructed via a crc32--synch...
def __init__(self, id_type=None, allocation=None):
super(IdAllocator, self).__init__() self.id_type = id_type self._allocation = (allocation or IdAllocator._DEFAULT_ALLOCATION) self._next_id_key = self._table.GetColumn('next_id').key self._cur_id = IdAllocator._START_ID self._last_id = IdAllocator._START_ID self._allocation_pending = False ...
'Executes callback with the value of _cur_id++. If _cur_id is None or _cur_id == _last_id, allocates a new block from the \'id_allocator\' table.'
def NextId(self, client, callback):
if self._allocation_pending: self._waiters.append(partial(self._AllocateId, callback)) elif (self._cur_id == self._last_id): self._waiters.append(partial(self._AllocateId, callback)) self._AllocateIds(client) else: self._AllocateId(callback)
'Invokes callback with a new id from the sequence; if type, value or traceback are not None, raises an exception.'
def _AllocateId(self, callback, type=None, value=None, traceback=None):
if ((type, value, traceback) != (None, None, None)): raise type, value, traceback assert (self._cur_id < self._last_id) new_id = self._cur_id self._cur_id += 1 callback(new_id)
'Iterates over list of waiters, returning new ids from the allocation stream. Returns true if all waiters were processed; false otherwise.'
def _ProcessWaiters(self):
while (len(self._waiters) and (self._cur_id < self._last_id)): self._waiters.popleft()() return (len(self._waiters) == 0)
'Allocates the next batch of IDs. On success, processes all pending waiters. If there are more waiters than ids, re-allocates. Otherwise, resets _allocation_pending.'
def _AllocateIds(self, client):
assert (self._cur_id == self._last_id), (self._cur_id, self._last_id) def _OnAllocate(result): self._last_id = result.return_values[self._next_id_key] if (self._last_id <= IdAllocator._START_ID): self._cur_id = self._last_id return self._AllocateIds(client) self._...
'Returns a hash prefix from 64-bit id with the specified number of bytes. The hash prefix for an ID is typically used to achieve uniform distribution of keys across shards. The high bytes of the crc32 checksum are used first.'
@staticmethod def ComputeHashPrefix(id, num_bytes=1):
assert ((num_bytes - 1) in xrange(4)), num_bytes return (zlib.crc32(struct.pack('>Q', id)) & [255, 65535, 16777215, 4294967295][(num_bytes - 1)])
'Resets the internal state of all ID allocators; for testing.'
@classmethod def ResetState(cls):
for id_alloc in IdAllocator._instances: id_alloc.Reset()
'Initialize a new Job object.'
def __init__(self, client, name):
self._client = client self._name = name self._lock = None self._start_time = None
'There\'s no point in attempting to release the lock in the destructor, it\'s much too unreliable.'
def __del__(self):
if (self._lock is not None): logging.error(('Job:%s is being cleaned, but lock was not released: %r' % (self._name, self._lock)))
'Start the start time to now.'
def Start(self):
self._start_time = int(time.time())
'Return true if a lock is held.'
def HasLock(self):
return (self._lock is not None)
'Attempt to acquire the lock "job:name". Returns True if acquired. If resource_data is None, a string is built consisting of the local user name, machine hostname and timestamp. If detect_abandonment is True, we allow acquisition of expired locks and specify an expiration on our lock. If False, acquiring an abandoned l...
@gen.engine def AcquireLock(self, callback, resource_data=None, detect_abandonment=True):
assert (self._lock is None), ('Job.AcquireLock called with existing lock held %r' % self._lock) data = (('%s@%s:%d' % (util.GetLocalUser(), os.uname()[1], time.time())) if (resource_data is None) else resource_data) result = (yield gen.Task(Lock.TryAcquire, self._client, LockResourceType.J...
'Release _lock if not None.'
@gen.engine def ReleaseLock(self, callback):
if (self._lock is not None): (yield gen.Task(self._lock.Release, self._client)) self._lock = None callback()
'Look for previous runs of this job in the metrics table. Return all found runs regardless of status. If start_timestamp is None, search for jobs started in the last week. If status is specified, only return runs that finished with this status, otherwise return all runs. If limit is not None, return only the latest \'l...
@gen.engine def FindPreviousRuns(self, callback, start_timestamp=None, status=None, limit=None):
assert (status in [None, Job.STATUS_SUCCESS, Job.STATUS_FAILURE]), ('Unknown status: %s' % status) runs = [] cluster = metric.JOBS_STATS_NAME group_key = metric.Metric.EncodeGroupKey(cluster, metric.Metric.FindIntervalForCluster(cluster, 'daily')) start_time = (start_timestamp if (start_timest...
'Find and return the latest successful run. Search back to start_timestamp (a week ago if None). If with_payload_key is not None, the key must be found in the payload (DotDict format). If with_payload_value is not None, the value at that key must match. Callback is run with the matching metric payload if found, else wi...
@gen.engine def FindLastSuccess(self, callback, start_timestamp=None, with_payload_key=None, with_payload_value=None):
payloads = (yield gen.Task(self.FindPreviousRuns, start_timestamp=start_timestamp, status=Job.STATUS_SUCCESS)) for p in reversed(payloads): assert (p['status'] == Job.STATUS_SUCCESS) if ((with_payload_key is not None) and (with_payload_key not in p)): continue if (with_payloa...
'Write the metric entry for this run. The start_time is set in Start(). end_time is now. If stats is not none, the DotDict is added to the metrics payload with the prefix \'stats\'. If failure_msg is not None and status==STATUS_FAILURE, write the message in payload.failure_msg.'
@gen.engine def RegisterRun(self, status, callback, stats=None, failure_msg=None):
assert (status in [None, Job.STATUS_SUCCESS, Job.STATUS_FAILURE]), ('Unknown status: %s' % status) assert (self._start_time is not None), 'Writing job summary, but Start never called.' end_time = int(time.time()) payload = DotDict() payload['start_time'] = self._start_time ...
'Initialize a new permissions object.'
def __init__(self, username=None, rights=None):
super(AdminPermissions, self).__init__() self.username = username if (rights is not None): self.SetRights(rights)
'Returns true if \'root\' is in the set of rights.'
def IsRoot(self):
return (AdminPermissions.ROOT in self.rights)
'Returns true if \'support\' is in the set of rights.'
def IsSupport(self):
return (AdminPermissions.SUPPORT in self.rights)
'Clear current set of rights and add the passed-in ones.'
def SetRights(self, rights):
self.rights = set() for r in rights: assert ((r == self.ROOT) or (r == self.SUPPORT)), ('unknown right: %s' % r) self.rights.add(r)
'Sets up a periodic callback for sync operations.'
def __init__(self, tables, table_schemas):
self._tables = tables self._table_schemas = table_schemas self._is_dirty = False self._db_dir = options.options.localdb_dir if options.options.localdb_dir: logging.info('enabling local datastore persistence') self._sync_callback = ioloop.PeriodicCallback(self._DBSync, (optio...
'Does a final sync on shutdown.'
def Shutdown(self):
self._DBSync()
'Called by the local datastore when its contents have been modified and another sync should be scheduled.'
def MarkDirty(self):
self._is_dirty = True
'Initializes the output directory and output files. The selected previous version is copied to \'<file>.0.sync\', and versions from previous runs are rolled. \'<file>.0.sync\' is then renamed to \'<file>.0\'.'
def _InitFiles(self):
try: files = os.listdir(self._db_dir) except: files = [] os.makedirs(self._db_dir) if (files and options.options.localdb_reset): logging.warning('resetting local datastore persistence') version_re = re.compile(('%s.([0-9]+)$' % DBPersist._BASE_NAME)) versions...
'Periodic callback for data persistence.'
def _DBSync(self):
if (not self._is_dirty): return self._is_dirty = False assert self._cur_file, self._tmp_file logging.info('syncing local datastore...') start_time = time.time() with open(self._tmp_file, 'w') as f: pickle.dump((self._tables, self._table_schemas), f, pickle.HIGHEST_PROTOCOL)...
'Returns true if the follower has not been REMOVED. REMOVED followers are not allowed to view viewpoint content.'
def CanViewContent(self):
return (Follower.REMOVED not in self.labels)
'Returns true if the follower has the ADMIN permission and hasn\'t been REMOVED.'
def CanAdminister(self):
return ((Follower.ADMIN in self.labels) and (Follower.REMOVED not in self.labels))
'Returns true if the follower has the CONTRIBUTE permission and hasn\'t been REMOVED.'
def CanContribute(self):
return ((Follower.CONTRIBUTE in self.labels) and (Follower.REMOVED not in self.labels))
'Returns true if the follower has the Follower.REMOVED label.'
def IsRemoved(self):
return (Follower.REMOVED in self.labels)
'Returns true if alerts should be suppressed for this follower.'
def IsMuted(self):
return (Follower.MUTED in self.labels)
'Returns true if the follower cannot be revived when activity on the followed viewpoint occurs.'
def IsUnrevivable(self):
return (Follower.UNREVIVABLE in self.labels)
'Returns true if photos added to the viewpoint should be automatically saved to this follower\'s default viewpoint.'
def ShouldAutoSave(self):
return (Follower.AUTOSAVE in self.labels)
'Projects all follower attributes that the follower himself can see.'
def MakeMetadataDict(self):
foll_dict = {'follower_id': self.user_id} util.SetIfNotNone(foll_dict, 'adding_user_id', self.adding_user_id) util.SetIfNotNone(foll_dict, 'viewed_seq', self.viewed_seq) if (self.labels is not None): foll_dict['labels'] = sorted(self.labels) return foll_dict
'Projects a subset of the follower attributes that should be provided to another user that is on the same viewpoint as this follower.'
def MakeFriendMetadataDict(self):
foll_dict = {'follower_id': self.user_id} util.SetIfNotNone(foll_dict, 'adding_user_id', self.adding_user_id) util.SetIfNotNone(foll_dict, 'follower_timestamp', self.timestamp) if self.IsUnrevivable(): foll_dict['labels'] = [Follower.REMOVED, Follower.UNREVIVABLE] return foll_dict
'Sets the labels attribute on the follower. This must be done with care in order to avoid security bugs such as allowing users to give themselves admin permissions, or allowing users to accidentally remove their right to see the viewpoint, or allowing a viewpoint to be removed without updating quota. TODO(Andy): Eventu...
def SetLabels(self, new_labels):
new_labels = set(new_labels) new_unsettable_labels = new_labels.intersection(Follower.UNSETTABLE_LABLES) existing_labels = set(self.labels) existing_unsettable_labels = existing_labels.intersection(Follower.UNSETTABLE_LABLES) if (new_unsettable_labels != existing_unsettable_labels): raise Pe...
'Removes a viewpoint from a user\'s inbox, and its content will become inaccessible to this follower. If "allow_revive" is true, then the viewpoint will automatically be "revived" when there is new activity by other followers that have not removed it. Adds the REMOVED label to this follower object and updates the db. C...
@gen.coroutine def RemoveViewpoint(self, client, allow_revive=True):
if (not self.IsRemoved()): assert (not self.IsUnrevivable()), self self.labels.add(Follower.REMOVED) if (not allow_revive): self.labels.add(Follower.UNREVIVABLE) (yield gen.Task(self.Update, client))
'Removes the REMOVED labels from any followers which are not marked as UNREVIVABLE, and updates those records in the DB.'
@classmethod @gen.coroutine def ReviveRemovedFollowers(cls, client, followers):
tasks = [] for follower in followers: if (follower.IsRemoved() and (not follower.IsUnrevivable())): follower.labels.remove(Follower.REMOVED) tasks.append(gen.Task(follower.Update, client)) (yield tasks)
'Creates a "sort_key" value, which is a concatenation of the timestamp (truncated to day boundary) and the viewpoint id.'
@classmethod def CreateSortKey(cls, viewpoint_id, timestamp):
prefix = util.CreateSortKeyPrefix(Followed._TruncateToDay(timestamp), randomness=False, reverse=True) return (prefix + viewpoint_id)
'Inserts a new followed record with date_updated set to the truncated "new_timestamp", and then deletes the followed record for "old_timestamp". A simple update is not possible because the "date_updated" attribute is part of the primary key. Optimize by not updating if the old and new "date_updated" values are the same...
@classmethod @gen.engine def UpdateDateUpdated(cls, client, user_id, viewpoint_id, old_timestamp, new_timestamp, callback):
assert (new_timestamp is not None), (user_id, viewpoint_id) if ((old_timestamp is None) or (old_timestamp < new_timestamp)): old_date_updated = Followed._TruncateToDay(old_timestamp) new_date_updated = Followed._TruncateToDay(new_timestamp) if (old_date_updated != new_date_updated): ...
'Truncate timestamp to day boundary.'
@classmethod def _TruncateToDay(cls, timestamp):
if (timestamp is None): return None return ((timestamp // constants.SECONDS_PER_DAY) * constants.SECONDS_PER_DAY)
'Returns True if the contact has the Contact.REMOVED label.'
def IsRemoved(self):
return (Contact.REMOVED in self.labels)
'Intercept base Update method to ensure that contact_id and sort_key are valid and correct for current attribute values.'
def Update(self, client, callback, expected=None, replace=True, return_col_names=False):
self._AssertValid() super(Contact, self).Update(client, callback, expected=expected, replace=replace, return_col_names=return_col_names)
'Calculate an encoded digest based on the dictionary passed in. The result is suitable for use in constructing the contact_id.'
@classmethod def CalculateContactEncodedDigest(cls, **dict_to_hash):
json_to_hash = util.ToCanonicalJSON(dict_to_hash) m = hashlib.sha256() m.update(json_to_hash) base64_encoded_digest = base64.b64encode(m.digest()) return base64_encoded_digest[:(len(base64_encoded_digest) / 2)]
'Calculate hash from contact dictionary.'
@classmethod def CalculateContactId(cls, contact_dict):
assert contact_dict.has_key('contact_source'), contact_dict assert contact_dict.has_key('identities_properties'), contact_dict assert (contact_dict['contact_source'] in Contact.ALL_SOURCES), contact_dict for identity_properties in contact_dict['identities_properties']: assert (len(identity_prope...
'Creates a dict with all properties needed for a contact. The identities_properties parameter is a list of tuples where each tuple is: (identity_key, description_string). Description string is for \'work\', \'mobile\', \'home\', etc... designation and may be None. This includes calculation of the contact_id and sort_k...
@classmethod def CreateContactDict(cls, user_id, identities_properties, timestamp, contact_source, **kwargs):
from viewfinder.backend.db.identity import Identity contact_dict = {'user_id': user_id, 'timestamp': timestamp, 'contact_source': contact_source} if (Contact.REMOVED not in kwargs.get('labels', [])): contact_dict['identities'] = {Identity.Canonicalize(identity_properties[0]) for identity_properties ...
'Override base CreateWithKeywords which ensures contact_id and sort_key are defined if not provided by the caller. Returns: Contact object.'
@classmethod def CreateFromKeywords(cls, user_id, identities_properties, timestamp, contact_source, **kwargs):
contact_dict = Contact.CreateContactDict(user_id, identities_properties, timestamp, contact_source, **kwargs) return super(Contact, cls).CreateFromKeywords(**contact_dict)
'Create instance of a removed contact for given user_id, contact_id, and timestamp.'
@classmethod def CreateRemovedContact(cls, user_id, contact_id, timestamp):
removed_contact_dict = {'user_id': user_id, 'identities_properties': None, 'timestamp': timestamp, 'contact_source': Contact.GetContactSourceFromContactId(contact_id), 'contact_id': contact_id, 'sort_key': Contact.CreateSortKey(contact_id, timestamp), 'labels': [Contact.REMOVED]} return Contact.CreateFromKeywor...
'Create value for sort_key attribute. This is derived from timestamp and contact_id.'
@classmethod def CreateSortKey(cls, contact_id, timestamp):
prefix = util.CreateSortKeyPrefix(timestamp, randomness=False) return (prefix + (contact_id if (contact_id is not None) else ''))
'Given list of contacts, delete any duplicates (preserving the newer contact). Returns: list of retained contacts.'
@classmethod @gen.coroutine def DeleteDuplicates(cls, client, contacts):
contacts_dict = dict() tasks = [] for contact in contacts: if (contact.contact_id in contacts_dict): if (contact.timestamp > contacts_dict[contact.contact_id].timestamp): contact_to_delete = contacts_dict[contact.contact_id] contacts_dict[contact.contact_i...
'Return the contact_id prefix which is the contact_source.'
@classmethod def GetContactSourceFromContactId(cls, contact_id):
return contact_id.split(':', 1)[0]
'Visits all users that have the given identity among their contacts. Invokes the "visitor" function with each user id. See VisitIndexKeys for additional detail.'
@classmethod @gen.coroutine def VisitContactUserIds(cls, client, contact_identity_key, visitor, consistent_read=False):
def _VisitContact(contact_key, callback): visitor(contact_key.hash_key, callback=callback) query_expr = ('contact.identities={id}', {'id': contact_identity_key}) (yield gen.Task(Contact.VisitIndexKeys, client, query_expr, _VisitContact))
'Assert that contact_id and sort_key are valid and correct for the current contact attributes.'
def _AssertValid(self):
if self.IsRemoved(): assert ((self.contact_source is not None) and (self.contact_source in Contact.ALL_SOURCES)), self else: contact_id = Contact.CalculateContactId(self._asdict()) assert (contact_id == self.contact_id), self assert (self.timestamp is not None), self sort_key = C...
'Returns true if this operation is in exponential backoff awaiting a retry.'
def IsBackedOff(self):
return (self.backoff > time.time())
'Stores progress information with the operation. If the operation is restarted, it can use this information to skip over steps it\'s already completed. The progress information is operation-specific and is not used in any way by the operation framework itself. The checkpoint is expected to be a JSON-serializable dict.'...
@gen.coroutine def SetCheckpoint(self, client, checkpoint):
assert (Operation.GetCurrent() == self), 'checkpoint should only be set during op execution' assert isinstance(checkpoint, dict), checkpoint self.checkpoint = checkpoint (yield self.Update(client))
'Returns an operation id constructed from component parts. See "ConstructAssetId" for details of the encoding.'
@classmethod def ConstructOperationId(cls, device_id, uniquifier):
return ConstructAssetId(IdPrefix.Operation, device_id, uniquifier)
'Returns the components of an operation id: device_id, and uniquifier.'
@classmethod def DeconstructOperationId(cls, operation_id):
return DeconstructAssetId(IdPrefix.Operation, operation_id)
'Ensures that a client-provided operation id is valid according to the rules specified in VerifyAssetId.'
@classmethod @gen.coroutine def VerifyOperationId(cls, client, user_id, device_id, operation_id):
(yield VerifyAssetId(client, user_id, device_id, IdPrefix.Operation, operation_id, has_timestamp=False))
'Returns the operation currently being executed. If no operation is being executed, returns a default operation with user_id and device_id set to None.'
@classmethod def GetCurrent(cls):
current = OpContext.current() if ((current is not None) and (current.executing_op is not None)): return current.executing_op return Operation()
'Creates a new nested operation, which is based on the current operation. The current operation is stopped so that the nested operation can be run. The nested operation must complete successfully before the parent operation will be continued. The new operation\'s id parenthesizes the current operation id. For example: ...
@classmethod @gen.coroutine def CreateNested(cls, client, method, args):
current = OpContext.current() assert ((current is not None) and (current.executing_op is not None)), 'outer operation must be running in order to execute a nested operation' current_op = current.executing_op assert ('headers' not in args), 'headers are derived f...
'Creates a new operation with \'method\' and \'args\' describing the operation. After successfully creating the operation, the operation is asynchronously executed. Returns the op that was executed.'
@classmethod @gen.engine def CreateAndExecute(cls, client, user_id, device_id, method, args, callback, message_version=message.MAX_SUPPORTED_MESSAGE_VERSION):
headers = args.pop('headers', {}) synchronous = headers.pop('synchronous', False) op_id = headers.pop('op_id', None) op_timestamp = headers.pop('op_timestamp', None) assert ((op_id is not None) == (op_timestamp is not None)), (op_id, op_timestamp) if ((op_id is not None) and (headers.get('origin...
'Similar to CreateAndExecute(), but uses the anonymous user and device and allocates the operation id from the id-allocator table.'
@classmethod def CreateAnonymous(cls, client, method, args, callback):
Operation.CreateAndExecute(client, Operation.ANONYMOUS_USER_ID, Operation.ANONYMOUS_DEVICE_ID, method, args, callback)
'Waits for the specified operation to complete. WaitForOp behaves exactly like using the "synchronous" option when submitting an operation. The callback will be invoked once the operation has completed or if it\'s backed off due to repeated failure.'
@classmethod def WaitForOp(cls, client, user_id, operation_id, callback):
OpManager.Instance().MaybeExecuteOp(client, user_id, operation_id, callback)
'Scans the Operation table for operations which have failed and for which the backoff time has expired. These operations can be retried. Returns a tuple containing the failed operations and the key of the last scanned operation.'
@classmethod def ScanFailed(cls, client, callback, limit=None, excl_start_key=None):
now = time.time() Operation.Scan(client, None, callback, limit=limit, excl_start_key=excl_start_key, scan_filter={'backoff': db_client.ScanFilter([now], 'LE')})
'Create a unique operation id that is generated using the system device allocator.'
@classmethod @gen.engine def AllocateSystemOperationId(cls, client, callback):
device_op_id = (yield gen.Task(Device.AllocateSystemObjectId, client)) op_id = Operation.ConstructOperationId(Device.SYSTEM, device_op_id) callback(op_id)
'Raises a non-abortable exception in order to cause the operation to restart. Only raises the exception if this failpoint has not yet been triggered for this operation. This facility is useful for testing operation idempotency in failure situations.'
@classmethod @gen.coroutine def TriggerFailpoint(cls, client):
if (not Operation.FAILPOINTS_ENABLED): return op = Operation.GetCurrent() assert (op.operation_id is not None), 'TriggerFailpoint can only be called in scope of executing operation' triggered_failpoints = (op.triggered_failpoints or []) frame = sys._getframe().f_ba...
'Creates a new user.'
def __init__(self, user_id=None):
super(User, self).__init__() self.user_id = user_id