desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Parse the full path to a user crash file.
Returns a tuple consisting of: (user_id, date, filename) or None if parsing failed.'
| def ParseRawLogPath(self, path):
| components = path.split('/')
if (len(components) != 3):
return None
assert (components[0] == self._user_id), ('%r vs %r' % (components[0], self._user_id))
return tuple(components)
|
'Parse the full path to a user merged crash file.
Returns a tuple consisting of: (user_id, date, filename) or None if parsing failed.'
| def ParseMergedLogPath(self, path):
| components = path.split('/')
if ((len(components) != 4) or (components[0] != self.kMergedLogsPrefix)):
return None
assert (components[1] == self._user_id), ('%r vs %r' % (components[1], self._user_id))
return tuple(components[1:])
|
'Returns the full data contained in this object in the form of a dotdict.'
| def ToDotDict(self):
| dt = DotDict()
dt['user_requests.all'] = self._active_all
dt['user_requests.post'] = self._active_post
dt['user_requests.share'] = self._active_share
dt['user_requests.view'] = self._active_view
return dt
|
'Load full data from a dotdict. This overwrites any existing data.'
| def FromDotDict(self, dt):
| assert ('user_requests' in dt)
base = dt['user_requests']
for (k, v) in base['all'].iteritems():
self.ActiveAll(k, v)
for (k, v) in base['post'].iteritems():
self.ActivePost(k, v)
for (k, v) in base['share'].iteritems():
self.ActiveShare(k, v)
for (k, v) in base['view'].i... |
'If S3 already has a file for this day/instance, fetch it and write its contents to the
local working file.'
| @gen.engine
def FetchExistingFromS3(self, callback):
| contents = (yield gen.Task(self._logs_store.Get, self._s3_filename, must_exist=False))
if (contents is not None):
logging.info(('Fetched %d bytes from existing S3 merged log file %s' % (len(contents), self._s3_filename)))
self._output.write(contents)
self._outp... |
'Add a single entry to the buffer.'
| def Append(self, entry):
| assert (self._output is not None)
self._buffer.append(entry)
|
'Write out all entries in the buffer.'
| def FlushBuffer(self):
| assert (self._output is not None)
if (not self._buffer):
return
for entry in self._buffer:
if self._needs_separator:
self._output.write('\n')
self._needs_separator = True
self._output.write(entry)
self._output.flush()
self._buffer = []
|
'Discard all entries in the buffer.'
| def DiscardBuffer(self):
| self._buffer = []
|
'Close the working file.'
| def Close(self):
| assert (self._output is not None)
self.FlushBuffer()
self._output.close()
self._output = None
|
'Upload working file to S3.'
| @gen.engine
def Upload(self, callback):
| assert (self._output is None), 'Upload called before Close.'
contents = open(self._working_filename, 'r').read()
timeout = max(20.0, ((len(contents) / 1024) * 1024))
(yield gen.Task(retry.CallWithRetryAsync, kS3UploadRetryPolicy, self._logs_store.Put, self._s3_filename, contents, request_timeou... |
'Delete the local working file.'
| def Cleanup(self):
| os.unlink(self._working_filename)
|
'Test path utility class for server logs.'
| def testServerLogsPaths(self):
| self.assertTrue(logs_util.IsEC2Instance('i-a92c0'))
self.assertFalse(logs_util.IsEC2Instance('vintner.local'))
slogs = logs_util.ServerLogsPaths('viewfinder', 'full')
self.assertEquals(slogs.RawDirectory(), 'viewfinder/full')
self.assertEquals(slogs.MergedDirectory(), 'merged_server_logs/viewfinder/... |
'Test path utility class for user analytics logs.'
| def testUserAnalyticsLogsPaths(self):
| clogs = logs_util.UserAnalyticsLogsPaths('112')
self.assertEquals(clogs.RawDirectory(), '112/')
self.assertEquals(clogs.MergedDirectory(), 'merged_user_analytics/')
self.assertEquals(clogs.ProcessedRegistryPath(), 'merged_user_analytics/PROCESSED/112')
res = clogs.ParseRawLogPath('112/2013-01-31/dev... |
'Test log line parsing functions.'
| def testLogParse(self):
| success_log_line = '2013-01-04 00:04:20:624 [pid:3883] user_op_manager:247: SUCCESS: user: 271, device: 1774, op: ovVqW7V, method: Device.UpdateOperation in 0.104s'
execute_log_line = "2013-02-25 00:02:05:691 [pid:3714] user_op_manager:356: EXECUTE: user:... |
'Test registry-related functions: read/write.'
| def testRegistry(self):
| contents = self._RunAsync(logs_util.GetRegistry, self.object_store, 'viewfinder/full/PROCESSED')
self.assertEquals(contents, None)
self._RunAsync(logs_util.WriteRegistry, self.object_store, 'viewfinder/full/PROCESSED', [])
contents = self._RunAsync(logs_util.GetRegistry, self.object_store, 'viewfinder/f... |
'Test functions that list user logs.'
| def testListUserLogs(self):
| self.assertEquals(self._RunAsync(logs_util.ListClientLogUsers, self.object_store), [])
raw_files = ['bogusdir/2013-01-31/dev-2900-22-43-02.757-1.1.11.log.gz', '112/2013-01-31/dev-2900-22-43-02.757-1.1.11.log.gz', '112/2013-01-31/dev-3293-00-39-29.430-1.2.1.13.log.gz', '112/2013-02-02/dev-3562-12-07-53.984-1.2.1... |
'Attempt to fetch \'url\' with optional \'data\'. We retry self._retry times, regardless of the error.'
| def _Fetch(self, url, data=None):
| retries = 0
while True:
logging.info(('fetching (%d) %s' % (retries, url)))
request = urllib2.Request(url, data)
handle = urllib2.urlopen(request)
logging.info(('fetch reply headers: %s' % handle.info()))
return handle.read()
try:
pass
... |
'Fetch a single day\'s worth of data. Exception could be due to http errors, unavailable date, or failed parsing.
TODO(marc): handle these cases separately.'
| @gen.engine
def FetchOneDay(self, day, callback):
| s3_filename = os.path.join(kS3Base, ('%s.gz' % day))
def DownloadFromiTunes():
(y, m, d) = day.split('-')
itunes_date = ('%s%s%s' % (y, m, d))
data = urllib.urlencode({'USERNAME': self._apple_id, 'PASSWORD': self._password, 'VNDNUMBER': self._vendor_id, 'TYPEOFREPORT': 'Sales', 'DATETYPE... |
'Returns a comment id constructed from component parts. Comments
sort from oldest to newest. See "ConstructTimestampAssetId" for
details of the encoding.'
| @classmethod
def ConstructCommentId(cls, timestamp, device_id, uniquifier):
| return ConstructTimestampAssetId(IdPrefix.Comment, timestamp, device_id, uniquifier, reverse_ts=False)
|
'Returns the components of a comment id: timestamp, device_id, and
uniquifier.'
| @classmethod
def DeconstructCommentId(cls, comment_id):
| return DeconstructTimestampAssetId(IdPrefix.Comment, comment_id, reverse_ts=False)
|
'Ensures that a client-provided comment id is valid according
to the rules specified in VerifyAssetId.'
| @classmethod
@gen.coroutine
def VerifyCommentId(cls, client, user_id, device_id, comment_id):
| (yield VerifyAssetId(client, user_id, device_id, IdPrefix.Comment, comment_id, has_timestamp=True))
|
'Creates the comment specified by "cm_dict". The caller is responsible for checking
permission to do this, as well as ensuring that the comment does not yet exist (or is
just being identically rewritten).
Returns the created comment.'
| @classmethod
@gen.coroutine
def CreateNew(cls, client, **cm_dict):
| comment = Comment.CreateFromKeywords(**cm_dict)
(yield gen.Task(comment.Update, client))
raise gen.Return(comment)
|
'Converts an asset key to a fingerprint-only asset key.
Asset keys from the client may (in 1.4) contain asset urls that
are only meaningful for that device. We only want to store
the fingerprint portion of the asset key.
If the asset key does not contain a fingerprint, returns None.'
| @classmethod
def AssetKeyToFingerprint(cls, asset_key):
| if asset_key.startswith('a/'):
(_, sep, fingerprint) = asset_key.rpartition('#')
if (sep and fingerprint):
return ('a/#' + fingerprint)
return None
|
'Merges the asset keys in new_keys into self.asset_keys.
Returns True if any changes were made.'
| def MergeAssetKeys(self, new_keys):
| changed = False
for key in new_keys:
fingerprint = UserPhoto.AssetKeyToFingerprint(key)
if ((fingerprint is not None) and (fingerprint not in self.asset_keys)):
self.asset_keys.add(fingerprint)
changed = True
return changed
|
'Cleanup on process exit.'
| def Shutdown(self):
| raise NotImplementedError()
|
'Lists the set of tables.'
| def ListTables(self, callback):
| raise NotImplementedError()
|
'Create a table with specified name, key schema and provisioned
throughput settings.'
| def CreateTable(self, table, hash_key_schema, range_key_schema, read_units, write_units, callback):
| raise NotImplementedError()
|
'Create a table with specified name, key schema and provisioned
throughput settings.'
| def DeleteTable(self, table, callback):
| raise NotImplementedError()
|
'Describes the named table.'
| def DescribeTable(self, table, callback):
| raise NotImplementedError()
|
'Gets the specified attribute values by key. \'must_exist\'
specifies whether to throw an exception if the item is not found.
If False, None is returned if not found. \'consistent_read\'
designates whether to fetch an authoritative value for the item.'
| def GetItem(self, table, key, callback, attributes, must_exist=True, consistent_read=False):
| raise NotImplementedError()
|
'Gets a batch of items from the database. Items to get are described in \'batch_dict\',
which has the following format:
{\'table-name-0\': BatchGetRequest(keys=<list of db-keys from the table>,
attributes=[attr-0, attr-1, ...],
consistent_read=<bool>),
\'table-name-1\': ...}
Returns results in the following format:
{\'... | def BatchGetItem(self, batch_dict, callback, must_exist=True):
| raise NotImplementedError()
|
'Sets the specified item attributes by key. \'attributes\' is a
dict {attr: value}. If \'expected\' is not None, requires that the
values specified in the expected dict {attr: value} match before
mutation. \'return_values\', if not None, must be one of (NONE,
ALL_OLD); if ALL_OLD, the previous values for the named attr... | def PutItem(self, table, key, callback, attributes, expected=None, return_values=None):
| raise NotImplementedError()
|
'Deletes the specified item by key. \'expected\' and
\'return_values\' are identical to PutItem().'
| def DeleteItem(self, table, key, callback, expected=None, return_values=None):
| raise NotImplementedError()
|
'Updates the specified item attributes by key. \'attributes\' is a
dict {attr: AttrUpdate} (see AttrUpdate named tuple above).
\'expected\' and \'return_values\' are the same as for PutItem(),
except that \'return_values\' may contain any of (NONE, ALL_OLD,
UPDATED_OLD, ALL_NEW, UPDATED_NEW).'
| def UpdateItem(self, table, key, callback, attributes, expected=None, return_values=None):
| raise NotImplementedError()
|
'Queries a range of values by \'hash_key\' and \'range_operator\'.
\'range_operator\' is of type RangeOperator (see named tuple above;
if None, selects all values). \'attributes\' is a list of
attributes to query, limit is an upper limit on the number of
results. If True, \'count\' will return just a count of items, bu... | def Query(self, table, hash_key, range_operator, callback, attributes, limit=None, consistent_read=False, count=False, scan_forward=True, excl_start_key=None):
| raise NotImplementedError()
|
'Scans the table starting at \'excl_start_key\' (if provided) and
reading the next \'limit\' rows, reading the specified \'attributes\'.
If \'scan_filter\' is specified, it is applied to each scanned item
to pre-filter returned results. \'scan_filter\' is a map from
attribute name to ScanFilter tuple.'
| def Scan(self, table, callback, attributes, limit=None, excl_start_key=None, scan_filter=None):
| raise NotImplementedError()
|
'Invokes the specified callback after \'deadline_secs\'. Returns a
handle which can be suppled to RemoveTimeout to disable the
timeout.'
| def AddTimeout(self, deadline_secs, callback):
| raise NotImplementedError()
|
'Invokes the specified callback at wall time
\'abs_timeout\'. Returns a handle which can be supplied to
RemoveTimeout to disable the timeout.'
| def AddAbsoluteTimeout(self, abs_timeout, callback):
| raise NotImplementedError()
|
'Removes a timeout added via AddTimeout or AddAbsoluteTimeout.'
| def RemoveTimeout(self, timeout):
| raise NotImplementedError()
|
'Sets a new instance for testing.'
| @staticmethod
def SetInstance(client):
| DBClient._instance = client
|
'Scans the entire Viewpoint table, looking for corruption in each
viewpoint that has not already been scanned in a previous pass.'
| @gen.engine
def CheckAllViewpoints(self, callback, last_scan=None):
| self._email_args = None
if (last_scan is None):
scan_filter = None
else:
scan_filter = {'last_updated': db_client.ScanFilter([last_scan], 'GE')}
(yield gen.Task(self._ThrottledScan, Viewpoint, visitor=self.CheckViewpoint, scan_filter=scan_filter, max_read_units=Viewpoint._table.read_unit... |
'Looks for corruption in each of the viewpoints in the
"viewpoint_ids" list.'
| @gen.engine
def CheckViewpointList(self, viewpoint_ids, callback):
| self._email_args = None
for vp_id in viewpoint_ids:
viewpoint = (yield gen.Task(Viewpoint.Query, self._client, vp_id, None))
(yield gen.Task(self.CheckViewpoint, viewpoint))
(yield gen.Task(self._CheckVisitedUsers))
(yield gen.Task(self._SendEmail))
callback()
|
'Checks the specified viewpoint for various kinds of corruption.'
| @gen.engine
def CheckViewpoint(self, viewpoint, callback):
| if (_TEST_MODE or (viewpoint.last_updated <= (time.time() - _CHECK_THRESHOLD_TIMESPAN))):
logging.info(('Processing viewpoint "%s"...' % viewpoint.viewpoint_id))
self._current_viewpoint = viewpoint.viewpoint_id
self._num_visited_viewpoints += 1
query_func = partial(Viewpoint.Qu... |
'Checks that a viewpoint has at most one share_new activity.'
| @gen.engine
def _CheckMultipleShareNew(self, viewpoint, activities, callback):
| earliest_activity = None
dup_activities = []
for activity in activities:
if (activity.name == 'share_new'):
if (earliest_activity is None):
earliest_activity = activity
elif ((activity.timestamp < earliest_activity.timestamp) and (activity.user_id == viewpoint... |
'Replaces extraneous share_new activities with corresponding
share_existing activity.'
| @gen.engine
def _RepairMultipleShareNew(self, activity, callback):
| assert (activity.name == 'share_new'), activity
act_args = json.loads(activity.json)
del act_args['follower_ids']
update_activity = Activity.CreateFromKeywords(viewpoint_id=activity.viewpoint_id, activity_id=activity.activity_id, name='share_existing', json=json.dumps(act_args))
(yield gen.Task(upda... |
'Checks that every follower, episode, photo, and comment is
referenced at least once by an activity.
TODO: Consider checking for missing unshare activities.'
| @gen.engine
def _CheckMissingActivities(self, viewpoint, activities, followers, ep_photos_list, comments, callback):
| index = set()
index.add(viewpoint.user_id)
has_share_new = False
for activity in activities:
if (activity.name == 'share_new'):
has_share_new = True
invalidate = json.loads(activity.json)
if (activity.name in ['add_followers', 'share_new']):
[index.add(f_i... |
'Adds a missing activity to the specified viewpoint.'
| @gen.engine
def _RepairMissingActivities(self, user_id, viewpoint, name, act_args, callback):
| timestamp = util.GetCurrentTimestamp()
unique_id = (yield gen.Task(Device.AllocateSystemObjectId, self._client))
activity_id = Activity.ConstructActivityId(timestamp, Device.SYSTEM, unique_id)
if (name == 'add_followers'):
(yield gen.Task(Activity.CreateAddFollowers, self._client, user_id, viewp... |
'Check activities for missing posts.'
| @gen.coroutine
def _CheckMissingPosts(self, viewpoint, activities, ep_photos_list):
| existing_posts = defaultdict(set)
for (_, photos, posts, _) in ep_photos_list:
for post in posts:
existing_posts[post.episode_id].add(post.photo_id)
for activity in activities:
if (activity.name in ['share_new', 'share_existing']):
for ep_dict in json.loads(activity.j... |
'Remove references to posts in activities if the posts don\'t exist.'
| @gen.coroutine
def _RepairMissingPosts(self, activities, existing_posts):
| @gen.coroutine
def _RebuildActivity(activity, act_args):
rebuilt_episodes = []
for ep_dict in act_args['episodes']:
if (ep_dict['episode_id'] in existing_posts):
new_ep_dict = {'episode_id': ep_dict['episode_id']}
for photo_id in list(ep_dict['photo_id... |
'Checks correctness of viewpoint metadata:
1. last_updated must be defined
2. timestamp must be defined'
| @gen.engine
def _CheckInvalidViewpointMetadata(self, viewpoint, activities, callback):
| if (viewpoint.last_updated is None):
(yield gen.Task(self._ReportCorruption, viewpoint.viewpoint_id, 'invalid viewpoint metadata', 'last_updated', partial(self._RepairInvalidViewpointMetadata, viewpoint, activities)))
if (viewpoint.timestamp is None):
(yield gen.Task(self._ReportCorruption... |
'Repairs invalid viewpoint metadata:
1. sets last_updated if it was not defined
2. sets timestamp if it was not defined'
| @gen.engine
def _RepairInvalidViewpointMetadata(self, viewpoint, activities, callback):
| timestamp = (min((a.timestamp for a in activities)) if activities else 0)
if (viewpoint.last_updated is None):
viewpoint.last_updated = timestamp
(yield gen.Task(viewpoint.Update, self._client))
logging.warning(' set last_updated to %d: %s', viewpoint.last_updated, vie... |
'Ensure that the cover photo is valid for this viewpoint.'
| @gen.coroutine
def _CheckBadCoverPhoto(self, viewpoint, ep_photos_list, activities):
| has_qualified_posts = False
if viewpoint.IsCoverPhotoSet():
cp_episode_id = viewpoint.cover_photo.get('episode_id')
cp_photo_id = viewpoint.cover_photo.get('photo_id')
if ((cp_episode_id is None) or (cp_photo_id is None)):
(yield gen.Task(self._ReportCorruption, viewpoint.vie... |
'Select a new cover photo for this viewpoint. Or clear it if none are available.'
| @gen.coroutine
def _RepairBadCoverPhoto(self, viewpoint, ep_photos_list, activities):
| shared_posts = {Post.ConstructPostId(post.episode_id, post.photo_id): post for (_, _, posts, _) in ep_photos_list for post in posts if (not post.IsRemoved())}
cover_photo = (yield gen.Task(viewpoint.SelectCoverPhoto, self._client, set(), activities_list=reversed(activities), available_posts_dict=shared_posts))
... |
'Checks for empty viewpoint.'
| @gen.engine
def _CheckEmptyViewpoint(self, viewpoint, activities, followers, ep_photos_list, comments, callback):
| if ((not viewpoint.IsDefault()) and (not activities) and (not ep_photos_list) and (not comments)):
(yield gen.Task(self._ReportCorruption, viewpoint.viewpoint_id, 'empty viewpoint', None, partial(self._RepairEmptyViewpoint, viewpoint, followers)))
callback()
|
'Deletes a corrupted viewpoint.'
| @gen.engine
def _RepairEmptyViewpoint(self, viewpoint, followers, callback):
| for follower in followers:
sort_key = Followed.CreateSortKey(viewpoint.viewpoint_id, (viewpoint.last_updated or 0))
followed = (yield gen.Task(Followed.Query, self._client, follower.user_id, sort_key, None, must_exist=False))
if (followed is not None):
(yield gen.Task(followed.De... |
'Checks for missing followed records.'
| @gen.engine
def _CheckMissingFollowed(self, viewpoint, followers, callback):
| for follower in followers:
sort_key = Followed.CreateSortKey(viewpoint.viewpoint_id, (viewpoint.last_updated or 0))
followed = (yield gen.Task(Followed.Query, self._client, follower.user_id, sort_key, None, must_exist=False))
if (followed is None):
(yield gen.Task(self._ReportCor... |
'Adds a Followed object for the specified user and viewpoint.'
| @gen.engine
def _RepairMissingFollowed(self, viewpoint, follower, sort_key, callback):
| (yield gen.Task(Followed.UpdateDateUpdated, self._client, follower.user_id, viewpoint.viewpoint_id, None, (viewpoint.last_updated or 0)))
logging.warning((' added followed: %s' % str((follower.user_id, sort_key))))
(yield self._CreateNotification(follower.user_id, 'dbchk add_followed', Notif... |
'Compute all accounting entries from ep_photos_list and verify that they match the entries in \'accounting\'.'
| @gen.engine
def _CheckBadViewpointAccounting(self, viewpoint, ep_photos_list, accounting_list, callback):
| act_dict = {}
def _IncrementAccountingWith(hash_key, sort_key, increment_from):
if (increment_from.num_photos == 0):
return
key = (hash_key, sort_key)
act_dict.setdefault(key, Accounting(hash_key, sort_key)).IncrementStatsFrom(increment_from)
for (episode, photos, posts, ... |
'If visited_users has grown too large, trigger CheckVisitedUsers, otherwise, simply return.
This is called at the end of CheckViewpoint.'
| @gen.engine
def _MaybeCheckVisitedUsers(self, callback):
| if (len(self._visited_users) >= DatabaseChecker._MAX_VISITED_USERS):
(yield gen.Task(self._CheckVisitedUsers))
callback()
|
'Check each user in the visited_users set and clear it. Called after processing all viewpoint.'
| @gen.engine
def _CheckVisitedUsers(self, callback):
| logging.info(('Processing %d visited users' % len(self._visited_users)))
(yield [gen.Task(self._CheckUser, user_id, vp_id) for (user_id, vp_id) in self._visited_users.iteritems()])
self._visited_users.clear()
callback()
|
'Check a single user. viewpoint_id is the visited viewpoint that last encounter this user.'
| @gen.engine
def _CheckUser(self, user_id, viewpoint_id, callback):
| logging.info(('Processing user %d' % user_id))
self._current_user = user_id
query_func = partial(Follower.RangeQuery, self._client, user_id, range_desc=None, col_names=None)
followed_vps = (yield gen.Task(self._CacheQuery, query_func))
accounting_vt = Accounting.CreateUserVisibleTo(user_id)
... |
'Repeatedly invokes the specified query function that takes an
"excl_start_key" and a "limit" argument for paging. The query
function must return an array of result items, or a tuple of
(items, last_key). Combines the result items from multiple calls
into a single array of results, and invokes the callback with it.'
| @gen.engine
def _CacheQuery(self, query_func, callback):
| _LIMIT = 100
excl_start_key = None
all_results = []
while True:
results = (yield gen.Task(query_func, limit=_LIMIT, excl_start_key=excl_start_key))
if isinstance(results, tuple):
(results, excl_start_key) = results
elif (len(results) > 0):
excl_start_key =... |
'Logs the corruption and sends occasional emails summarizing any
corruption that is found.'
| @gen.engine
def _ReportCorruption(self, viewpoint_id, name, args, repair_func, callback):
| args = ('' if (args is None) else (' (%s)' % str(args)))
logging.error(('Found database corruption in viewpoint %s: %s%s' % (viewpoint_id, name, args)))
logging.error((' python dbchk.py --devbox --repair=True --viewpoints=%s' % viewpoint_id))
self._corruptions.set... |
'Create notification in order to notify user\'s devices that
content needs to be re-loaded.'
| @gen.coroutine
def _CreateNotification(self, user_id, name, invalidate):
| op_id = Operation.ConstructOperationId(Operation.ANONYMOUS_DEVICE_ID, 0)
op = Operation(Operation.ANONYMOUS_USER_ID, op_id)
op.device_id = Operation.ANONYMOUS_DEVICE_ID
op.timestamp = util.GetCurrentTimestamp()
(yield Notification.CreateForUser(self._client, op, user_id, name, invalidate=invalidate)... |
'Scan over the "scan_cls" table, processing at most "max_read_units"
items per second. Invoke the "visitor" function for each item in the
table.'
| @gen.engine
def _ThrottledScan(self, scan_cls, visitor, callback, col_names=None, scan_filter=None, consistent_read=False, max_read_units=None):
| _SCAN_LIMIT = 50
assert ((max_read_units is None) or (max_read_units >= 1.0)), max_read_units
start_key = None
num_items = 0.0
start_time = time.time()
while True:
(items, start_key) = (yield gen.Task(scan_cls.Scan, self._client, None, limit=_SCAN_LIMIT, excl_start_key=start_key, scan_fi... |
'Runs the parser on the provided comma-separated string of attributes.'
| def Run(self, attributes):
| _ = run_text_parser(self._expr_parser, escape.to_unicode(attributes))
return self._updates
|
'Reads one attribute col_name=value. Creates a DB update
in self._updates.'
| @tri
def _ParsePhrase(self):
| col_name = self._token().lower()
col_def = self._table.GetColumn(col_name)
one_of('=')
commit()
phrase = self._phrase()
if phrase:
value = eval(phrase)
if (col_def.value_type == 'N'):
value = int(value)
if self._raw:
self._updates[col_def.key] = db... |
'Gets a new Credentials object with a session token, using this
instance\'s aws keys. Callback should operate on the new Credentials obj,
or else a boto.exception.BotoServerError.'
| def get_session_token(self, callback):
| return self.get_object('GetSessionToken', {}, Credentials, verb='POST', callback=callback)
|
'Get an instance of `cls` using `action`.'
| def get_object(self, action, params, cls, path='/', parent=None, verb='GET', callback=None):
| if (not parent):
parent = self
self.make_request(action, params, path, verb, functools.partial(self._finish_get_object, callback=callback, parent=parent, cls=cls))
|
'Process the body returned by STS. If an error is present,
convert from a tornado error to a boto error.'
| def _finish_get_object(self, response_body, callback, cls=None, parent=None, error=None):
| if error:
if (error.code == 403):
error_class = InvalidClientTokenIdError
else:
error_class = BotoServerError
return callback(None, error=error_class(error.code, error.message, response_body))
obj = cls(parent)
h = boto.handler.XmlHandler(obj, parent)
xml.... |
'Make an async request. This handles the logic of translating
from boto params to a tornado request obj, issuing the request,
and passing back the body.
The callback should operate on the body of the response, and take
an optional error argument that will be a tornado error.'
| def make_request(self, action, params={}, path='/', verb='GET', callback=None):
| request = HTTPRequest(('https://%s' % self.host), method=verb)
request.params = params
request.auth_path = '/'
request.host = self.host
if action:
request.params['Action'] = action
if self.APIVersion:
request.params['Version'] = self.APIVersion
self._auth_handler.add_auth(req... |
'Constructs a dictionary containing activity metadata in a format that conforms to
ACTIVITY in json_schema.py.'
| def MakeMetadataDict(self):
| activity_dict = self._asdict()
activity_dict[activity_dict.pop('name')] = json.loads(activity_dict.pop('json'))
return activity_dict
|
'Returns an activity id constructed from component parts. Activities sort from newest
to oldest. See "ConstructTimestampAssetId" for details of the encoding.'
| @classmethod
def ConstructActivityId(cls, timestamp, device_id, uniquifier):
| return ConstructTimestampAssetId(IdPrefix.Activity, timestamp, device_id, uniquifier)
|
'Returns an activity id constructed by combining the specified timestamp and the
device_id and device_op_id from the operation_id.'
| @classmethod
def ConstructActivityIdFromOperationId(cls, timestamp, operation_id):
| (device_id, uniquifier) = Operation.DeconstructOperationId(operation_id)
return Activity.ConstructActivityId(timestamp, device_id, uniquifier)
|
'Returns the components of an activity id: timestamp, device_id, and uniquifier.'
| @classmethod
def DeconstructActivityId(cls, activity_id):
| return DeconstructTimestampAssetId(IdPrefix.Activity, activity_id)
|
'Ensures that a client-provided activity id is valid according to the rules specified
in VerifyAssetId.'
| @classmethod
@gen.coroutine
def VerifyActivityId(cls, client, user_id, device_id, activity_id):
| (yield VerifyAssetId(client, user_id, device_id, IdPrefix.Activity, activity_id, has_timestamp=True))
|
'Creates an activity that tracks the changes to the specified viewpoint resulting from
an "add_followers" operation.'
| @classmethod
@gen.coroutine
def CreateAddFollowers(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, follower_ids):
| args_dict = {'follower_ids': follower_ids}
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'add_followers', args_dict))
raise gen.Return(activity)
|
'Creates an activity that tracks the changes to the specified viewpoint resulting from
a "merge_accounts" operation.'
| @classmethod
@gen.coroutine
def CreateMergeAccounts(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, target_user_id, source_user_id):
| args_dict = {'target_user_id': target_user_id, 'source_user_id': source_user_id}
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'merge_accounts', args_dict))
raise gen.Return(activity)
|
'Creates an activity that tracks the changes to the specified viewpoint resulting from
a "post_comment" operation.'
| @classmethod
@gen.coroutine
def CreatePostComment(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, cm_dict):
| args_dict = {'comment_id': cm_dict['comment_id']}
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'post_comment', args_dict))
raise gen.Return(activity)
|
'Creates an activity that tracks the changes to the specified viewpoint resulting from
an "remove_followers" operation.'
| @classmethod
@gen.coroutine
def CreateRemoveFollowers(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, follower_ids):
| args_dict = {'follower_ids': follower_ids}
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'remove_followers', args_dict))
raise gen.Return(activity)
|
'Creates an activity that tracks the changes to the specified viewpoint resulting from
a "remove_photos" operation.'
| @classmethod
@gen.coroutine
def CreateRemovePhotos(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, ep_dicts):
| args_dict = {'episodes': [{'episode_id': ep_dict['new_episode_id'], 'photo_ids': ep_dict['photo_ids']} for ep_dict in ep_dicts]}
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'remove_photos', args_dict))
raise gen.Return(activity)
|
'Creates an activity that tracks the changes to the specified viewpoint resulting from
a "save_photos" operation.'
| @classmethod
@gen.coroutine
def CreateSavePhotos(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, ep_dicts):
| args_dict = {'episodes': [{'episode_id': ep_dict['new_episode_id'], 'photo_ids': ep_dict['photo_ids']} for ep_dict in ep_dicts]}
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'save_photos', args_dict))
raise gen.Return(activity)
|
'Creates an activity that tracks the changes to the specified viewpoint resulting from
a "share_existing" operation.'
| @classmethod
@gen.coroutine
def CreateShareExisting(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, ep_dicts):
| args_dict = {'episodes': [{'episode_id': ep_dict['new_episode_id'], 'photo_ids': ep_dict['photo_ids']} for ep_dict in ep_dicts]}
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'share_existing', args_dict))
raise gen.Return(activity)
|
'Creates an activity that tracks the changes to the specified viewpoint resulting from
a "share_new" operation.'
| @classmethod
@gen.coroutine
def CreateShareNew(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, ep_dicts, follower_ids):
| args_dict = {'episodes': [{'episode_id': ep_dict['new_episode_id'], 'photo_ids': ep_dict['photo_ids']} for ep_dict in ep_dicts], 'follower_ids': follower_ids}
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'share_new', args_dict))
raise gen.Retu... |
'Creates an activity that tracks the changes to the specified viewpoint resulting from
a "unshare" operation.'
| @classmethod
@gen.coroutine
def CreateUnshare(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, ep_dicts):
| args_dict = {'episodes': [{'episode_id': ep_dict['episode_id'], 'photo_ids': ep_dict['photo_ids']} for ep_dict in ep_dicts]}
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'unshare', args_dict))
raise gen.Return(activity)
|
'Creates an activity that tracks the changes to the specified viewpoint resulting from
an "update_episode" operation.'
| @classmethod
@gen.coroutine
def CreateUpdateEpisode(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, ep_dict):
| args_dict = {'episode_id': ep_dict['episode_id']}
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'update_episode', args_dict))
raise gen.Return(activity)
|
'Creates an activity that tracks the changes to the specified viewpoint resulting from
an "update_viewpoint" operation.'
| @classmethod
@gen.coroutine
def CreateUpdateViewpoint(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, prev_values):
| args_dict = {'viewpoint_id': viewpoint_id}
args_dict.update(prev_values)
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'update_viewpoint', args_dict))
raise gen.Return(activity)
|
'Create an activity that tracks the changes to the specified viewpoint resulting from
a "upload_episode" operation.'
| @classmethod
@gen.coroutine
def CreateUploadEpisode(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, ep_dict, ph_dicts):
| args_dict = {'episode_id': ep_dict['episode_id'], 'photo_ids': [ph_dict['photo_id'] for ph_dict in ph_dicts]}
activity = (yield Activity._CreateActivity(client, user_id, viewpoint_id, activity_id, timestamp, update_seq, 'upload_episode', args_dict))
raise gen.Return(activity)
|
'Helper method that creates an activity for any kind of operation.'
| @classmethod
@gen.coroutine
def _CreateActivity(cls, client, user_id, viewpoint_id, activity_id, timestamp, update_seq, name, args_dict):
| activity = (yield gen.Task(Activity.Query, client, viewpoint_id, activity_id, None, must_exist=False))
if (activity is None):
from viewfinder.backend.base import message
args_dict['headers'] = dict(version=message.MAX_MESSAGE_VERSION)
activity = Activity.CreateFromKeywords(viewpoint_id=v... |
'Maps iTunes product names to Subscription attributes.
An iTunes "product" also includes information about the billing
cycle; by convention we name our products with a suffix of "_month"
or "_year" (etc).'
| @classmethod
def _GetITunesProductInfo(cls, verify_response):
| product_id = verify_response.GetProductId()
(base_product, billing_cycle) = product_id.rsplit('_', 1)
assert (billing_cycle in ('month', 'year')), billing_cycle
return Subscription._ITUNES_PRODUCTS[base_product]
|
'Returns the transaction id for an iTunes transaction.
The returned id is usable as a range key for Subscription.Query.'
| @classmethod
def GetITunesTransactionId(cls, verify_response):
| return (kITunesPrefix + verify_response.GetRenewalTransactionId())
|
'Returns the subscription id for an iTunes transaction.
THe returned id will be the same for all transactions in a series of renewals.'
| @classmethod
def GetITunesSubscriptionId(cls, verify_response):
| return (kITunesPrefix + verify_response.GetOriginalTransactionId())
|
'Creates a subscription object for an iTunes transaction.
The verify_response argument is a response from
viewfinder.backend.services.itunes_store.ITunesStoreClient.VerifyReceipt.
The new object is returned but not saved to the database.'
| @classmethod
def CreateFromITunes(cls, user_id, verify_response):
| assert verify_response.IsValid()
sub_dict = dict(user_id=user_id, transaction_id=Subscription.GetITunesTransactionId(verify_response), subscription_id=Subscription.GetITunesSubscriptionId(verify_response), timestamp=verify_response.GetTransactionTime(), expiration_ts=verify_response.GetExpirationTime(), payment... |
'Creates a subscription record for an iTunes transaction and saves it to the database.
The verify_response argument is a response from
viewfinder.backend.services.itunes_store.ITunesStoreClient.VerifyReceipt.'
| @classmethod
def RecordITunesTransaction(cls, client, callback, user_id, verify_response):
| sub = Subscription.CreateFromITunes(user_id, verify_response)
sub.Update(client, callback)
|
'Returns a list of Subscription objects for the given user.
By default only includes currently-active subscriptions, and only
one transaction per subscription. To return expired subscriptions,
pass include_expired=True. To return all transactions (even those
superceded by a renewal transaction for the same subscripti... | @classmethod
def QueryByUser(cls, client, callback, user_id, include_expired=False, include_history=False):
| history_results = []
latest = {}
def _VisitSub(sub, callback):
if include_history:
history_results.append(sub)
else:
if ((sub.expiration_ts < time.time()) and (not include_expired)):
callback()
return
if ((sub.subscription_i... |
'Project a subset of subscription attributes that can be provided to the user.'
| def MakeMetadataDict(self):
| sub_dict = {}
for attr_name in Subscription._JSON_ATTRIBUTES:
util.SetIfNotNone(sub_dict, attr_name, getattr(self, attr_name, None))
if self.extra_info:
sub_dict['extra_info'] = deepcopy(self.extra_info)
return sub_dict
|
'Constructs a dictionary containing photo metadata attributes, overridden by post and
user post attributes where required.'
| def MakeMetadataDict(self, post, user_post, user_photo):
| ph_dict = self._asdict()
labels = post.labels.combine()
if (user_post is not None):
labels = labels.union(user_post.labels.combine())
asset_keys = set()
if ((user_photo is not None) and user_photo.asset_keys):
asset_keys.update(user_photo.asset_keys)
if asset_keys:
ph_dic... |
'Returns a photo id constructed from component parts. Photos
sort from newest to oldest. See "ConstructTimestampAssetId" for
details of the encoding.'
| @classmethod
def ConstructPhotoId(cls, timestamp, device_id, uniquifier):
| return ConstructTimestampAssetId(IdPrefix.Photo, timestamp, device_id, uniquifier)
|
'Returns the components of a photo id: timestamp, device_id, and
uniquifier.'
| @classmethod
def DeconstructPhotoId(cls, photo_id):
| return DeconstructTimestampAssetId(IdPrefix.Photo, photo_id)
|
'Ensures that a client-provided photo id is valid according
to the rules specified in VerifyAssetId.'
| @classmethod
@gen.coroutine
def VerifyPhotoId(cls, client, user_id, device_id, photo_id):
| (yield VerifyAssetId(client, user_id, device_id, IdPrefix.Photo, photo_id, has_timestamp=True))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.