desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns true if self._encrypted_value is equal to the other\'s _encrypted_value.'
def __eq__(self, other):
if isinstance(other, _DelayedCrypt): return (self._encrypted_value == other._encrypted_value) return NotImplemented
'Returns true if self._encrypted_value is not equal to the other\'s _encrypted_value.'
def __ne__(self, other):
if isinstance(other, _DelayedCrypt): return (self._encrypted_value != other._encrypted_value) return NotImplemented
'Gets the encrypted value as an instance of _DelayedCrypt. This instance\'s Decrypt method must be invoked in order to extract the unencrypted value. See the docs for _DelayedCrypt for details.'
def Get(self, asdict=False):
if (self._value is not None): if asdict: return {'__crypt__': self._value} return _DelayedCrypt(self._value) else: return None
'Converts \'value\' to a JSON-encoded string and encrypts it before storing it.'
def Set(self, value):
if (value is None): encrypted_value = None elif isinstance(value, _DelayedCrypt): encrypted_value = value._encrypted_value elif (isinstance(value, dict) and ('__crypt__' in value)): encrypted_value = value['__crypt__'] else: crypter = _CryptValue._GetCrypter() enc...
'Return a set that adds the additions and removes the deletions.'
def combine(self):
return self.additions.union(self).difference(self.deletions)
'True if _modified or if additions or deletions are not empty.'
def IsModified(self):
return (self._modified or self._value.additions or self._value.deletions)
'Returns the partial set.'
def Get(self, asdict=False):
if asdict: return list(self._value) else: return self._value
'Stores the raw set value as a LayeredSet.'
def Load(self, value):
assert ((value is None) or isinstance(value, (list, tuple, set, frozenset))), type(value) if (value is None): self._value = _LayeredSet() else: self._value = _LayeredSet(value)
'Sets the contents of the entire set. This sets a flag which indicates that the DynamoDB update should use a PUT action to replace the previous contents of the set.'
def Set(self, value):
self.SetModified(True) self.Load(value)
'Returns an action {ADD, DELETE, PUT} and the set of values for an update depending on the state of the layered set. If the set was assigned directly, use PUT. If there are set additions, use ADD; otherwise DELETE.'
def Update(self):
if self._modified: if self._value.additions: value = list(self._value.union(self._value.additions)) else: value = list(self._value.difference(self._value.deletions)) if (not value): return db_client.UpdateAttr(None, action='DELETE') return db_clien...
'Called on completion of an update.'
def OnUpdate(self):
self._modified = False new_set = self._value.combine() self._value = _LayeredSet(new_set)
'Returns the set of index terms in conjunction with the action, which is one of {PUT, ADD, DELETE}. Index terms which are meant to replace the former set are returned with PUT. This requires the previous terms be queried. The differences between the old and the new term sets determines which old terms are deleted and w...
def IndexTerms(self):
assert (self.col_def.indexer and isinstance(self.col_def.indexer, indexers.SecondaryIndexer)) update = self.Update() term_dict = {} if (update.value is not None): for term in update.value: term_dict.update(self.col_def.indexer.Index(self.col_def, term).items()) return db_client.U...
'Key values are not updated. On creation, the key is already specified as part of the request.'
def Update(self):
assert self.IsModified() return None
'Creates a geographic location indexer if \'indexed\'.'
def __init__(self, name, key, indexer=None):
if (indexer is not None): assert (isinstance(indexer, indexers.BreadcrumbIndexer) or isinstance(indexer, indexers.LocationIndexer)) super(LatLngColumn, self).__init__(name, key, 'S', indexer=indexer)
'Returns the column name for a column key.'
def GetColumnName(self, key):
return self._key_to_name[key]
'Returns a list of column names (sorted in original order). Specify \'all_columns\' as True to include index term columns as well.'
def GetColumnNames(self, all_columns=False):
if all_columns: return self._all_column_names else: return self._column_names
'Returns a list of column definitions. Specify \'all_columns\' as True to include index term columns as well.'
def GetColumns(self, all_columns=False):
if all_columns: return self._columns.values() else: return [c for c in self._columns.values() if (not isinstance(c, IndexTermsColumn))]
'Returns the named column definition. Column names are not case sensitive.'
def GetColumn(self, name):
return self._columns[name.lower()]
'Returns the column definition by key.'
def GetColumnByKey(self, key):
return self._columns[self._key_to_name[key]]
'Verifies the columns are appropriately configured. - First column is a HashKeyColumn - Only second column may be a RangeKeyColumn - All column names are unique - All column keys are unique - If any columns are indexed, table is IndexedTable - SetColumns may only use SecondaryIndexer'
def _VerifyColumns(self, columns):
assert isinstance(columns[0], HashKeyColumn) column_keys = set([columns[0].key]) column_names = set([columns[0].name]) for i in xrange(1, len(columns)): c = columns[i] assert (not isinstance(c, HashKeyColumn)) if (i >= 2): assert (not isinstance(c, RangeKeyColumn)) ...
'A schema based on the provided sequence of table definitions.'
def __init__(self, tables):
self._tables = dict() self._tables_in_db = dict() for table in tables: self.AddTable(table)
'Returns a list of tables in the schema.'
def GetTables(self):
return sorted(self._tables.values())
'Returns the descriptor for the named table.'
def GetTable(self, table):
return self._tables[table.lower()]
'Given the name of a table in the database, translate to the name for that table that the application uses (which may be different if we\'ve done an upgrade). If the table exists in the database, but not in the application, just return the name in the database.'
def TranslateNameInDb(self, name_in_db):
key = name_in_db.lower() return (self._tables_in_db[key].name if (key in self._tables_in_db) else name_in_db)
'Adds the specified table to the schema.'
def AddTable(self, table):
assert (table.name not in self._tables), table assert (table.name_in_db not in self._tables_in_db), table self._tables[table.name.lower()] = table self._tables_in_db[table.name_in_db.lower()] = table
'Verifies the schema if it exists or creates it if not. Verification checks existing tables match the schema definition, warns of vestigial tables, and creates any tables which are missing. Vestigial tables may be deleted by specifying the --delete_vestigial command line flag. On completion, invokes callback with a lis...
def VerifyOrCreate(self, client, callback, verify_only=False):
def _OnDescribeTable(table, verify_cb, result): 'Verifies the table description in schema matches the\n table in the database.\n ' if verify_only: verify_cb((table.name, result)) return assert...
'Construct a guess id of the form <type>:<id>.'
@classmethod def ConstructGuessId(cls, type, id):
return ('%s:%s' % (type, id))
'Returns false if the number of incorrect guesses has already exceeded "max_guesses".'
@classmethod @gen.coroutine def CheckGuessLimit(cls, client, guess_id, max_guesses):
guess = (yield gen.Task(Guess.Query, client, guess_id, None, must_exist=False)) now = util.GetCurrentTimestamp() if ((guess is not None) and (now >= guess.expires)): guess = None raise gen.Return(((guess is None) or (guess.guesses < max_guesses)))
'Records an incorrect guess attempt by incrementing the guesses count.'
@classmethod @gen.coroutine def ReportIncorrectGuess(cls, client, guess_id):
guess = (yield gen.Task(Guess.Query, client, guess_id, None, must_exist=False)) now = util.GetCurrentTimestamp() if ((guess is not None) and (now < guess.expires)): guess.guesses += 1 else: guess = Guess(guess_id) guess.expires = (now + constants.SECONDS_PER_DAY) guess.gu...
'Parses and returns the JSON invalidate attribute as a python dict.'
def GetInvalidate(self):
return (json.loads(self.invalidate) if (self.invalidate is not None) else None)
'Sets invalidation python dict as JSON invalidate attribute.'
def SetInvalidate(self, invalidate_dict):
self.invalidate = json.dumps(invalidate_dict)
'Tries to create a "clear_badges" notification with the given id. Returns False if another notification with this id has already been created, else returns True.'
@classmethod @gen.coroutine def TryClearBadge(cls, client, user_id, device_id, notification_id):
notification = Notification(user_id, notification_id) notification.name = 'clear_badges' notification.timestamp = util.GetCurrentTimestamp() notification.sender_id = user_id notification.sender_device_id = device_id notification.badge = 0 success = (yield notification._TryUpdate(client)) ...
'Returns the notification with the highest notification_id, or None if the notification table is empty.'
@classmethod @gen.coroutine def QueryLast(cls, client, user_id, consistent_read=False):
notification_list = (yield gen.Task(Notification.RangeQuery, client, user_id, range_desc=None, limit=1, col_names=None, scan_forward=False, consistent_read=consistent_read)) raise gen.Return((notification_list[0] if (len(notification_list) > 0) else None))
'Creates a notification database record for the specified user, based upon the notification record that was last created and the current operation. If "inc_badge" is true, then increment the user\'s pending notification badge count. Returns the newly created notification.'
@classmethod @gen.coroutine def CreateForUser(cls, client, operation, user_id, name, invalidate=None, activity_id=None, viewpoint_id=None, seq_num_pair=None, inc_badge=False, consistent_read=False):
while True: last_notification = (yield Notification.QueryLast(client, user_id, consistent_read=consistent_read)) if (last_notification is None): notification_id = 1 badge = 0 else: notification_id = (last_notification.notification_id + 1) badge...
'Creates a new notification database record using the next available notification_id. Avoids race conditions by using the "expected" argument to Update in order to ensure that a unique notification_id is used. If another notification allocates a particular notification_id first, this method will return False. The calle...
@gen.coroutine def _TryUpdate(self, client):
try: (yield gen.Task(self.Update, client, expected={'notification_id': False})) except Exception as e: logging.info(('notification id %d is already in use: %s' % (self.notification_id, e))) raise gen.Return(False) raise gen.Return(True)
'Passes the requested counter data for this criteria to the handler, and adds the returned set of warnings and alerts to the report.'
def InspectMetrics(self, metric_data, report):
(alerts, warnings) = self.handler(*[metric_data[c.name] for c in self.counter_list]) for w in warnings: report.warnings.add(((self.name + ':') + w)) for a in alerts: report.alerts.add(((self.name + ':') + a))
'If an escalation threshold is set for this criteria, inspects previous reports and escalates warnings to alerts if they are present in a number of previous reports exceeding the threshold.'
def InspectTrends(self, old_reports, new_report):
if (self.escalation_threshold == 0): return current_warnings = [w for w in new_report.warnings.combine() if w.startswith((self.name + ':'))] for w in current_warnings: if (len([r for r in old_reports if (w in r.warnings)]) > self.escalation_threshold): new_report.alerts.add(w)
'Gets the list of criteria for server health checks. This is implemented as a class method to ensure that the static counters variable is completely loaded before accessing it, rather than depending on python module loading order.'
@classmethod def GetCriteriaList(cls):
if hasattr(cls, '_criteria_list'): return cls._criteria_list cls._criteria_list = [HealthCriteria('Errors', 'Error threshold exceeded.', ErrorCriteria, [counters.viewfinder.errors.error], 5), HealthCriteria('ReqFail', 'Failed Request threshold exceeded.', RequestsFailedCriteria, [counters...
'Performs a range query on the HealthReport table for the given group_key between the given start and end time. An optional start key can be specified to resume an earlier query which did not retrieve the full result set.'
@classmethod def QueryTimespan(cls, client, group_key, start_time, end_time, callback, excl_start_key=None):
HealthReport.RangeQuery(client, group_key, db_client.RangeOperator([start_time, end_time], 'BETWEEN'), None, None, callback=callback, excl_start_key=excl_start_key)
'Get a cluster health report for the given cluster and collection interval at the given timestamp. The report will be generated if it is not already available in the database. The given callback will be invoked with the report once it is retrieved or generated. A specific counter set can be provided if desired; by defa...
@classmethod def GetHealthReport(cls, client, cluster_name, interval, timestamp, callback, counter_set=None, criteria=None):
criteria = (criteria or HealthCriteria.GetCriteriaList()) counter_set = (counter_set or counters) group_key = metric.Metric.EncodeGroupKey(cluster_name, interval) newest_report_timestamp = (timestamp - (timestamp % interval.length)) oldest_report_timestamp = (newest_report_timestamp - (interval.leng...
'Creates a new identity with the specified key.'
def __init__(self, key=None, user_id=None):
super(Identity, self).__init__() self.key = key self.user_id = user_id
'Validates that the identity key has a valid format and is canonicalized.'
@classmethod def ValidateKey(cls, identity_key):
if (Identity.Canonicalize(identity_key) != identity_key): raise InvalidRequestError(('Identity %s is not in canonical form.' % identity_key))
'Returns the canonical form of the given identity key.'
@classmethod def Canonicalize(cls, identity_key):
for prefix in ['Email:', 'Phone:', 'FacebookGraph:', 'Local:', 'VF:']: if identity_key.startswith(prefix): value = identity_key[len(prefix):] if (prefix == 'Email:'): canonical_value = Identity.CanonicalizeEmail(value) if (value is not canonical_value)...
'Given an arbitrary string, validates that it is in legal email format. Normalizes the email by converting it to lower case and returns it. TODO(Andy): Add validation that email at least contains the \'@\' symbol. Consistent with the iOS client\'s ContactManager::CanonicalizeEmail() function.'
@classmethod def CanonicalizeEmail(cls, email):
return (email if email.islower() else email.lower())
'Given an arbitrary string, validates that it is in the expected E.164 phone number format. Since E.164 phone numbers are already canonical, there is no additional normalization step to take. Returns the valid, canonical phone number in E.164 format.'
@classmethod def CanonicalizePhone(cls, phone):
if (not phone): raise InvalidRequestError('Phone number cannot be empty.') if (phone[0] != '+'): raise InvalidRequestError(('Phone number "%s" is not in E.164 format.' % phone)) try: phone_num = phonenumbers.parse(phone) except phonenumbers.phonen...
'Given an arbitrary string, checks that it is in the expected E.164 phone number format. Returns: True if phone number can be successfully canonicalized.'
@classmethod def CanCanonicalizePhone(cls, phone):
try: Identity.CanonicalizePhone(phone) except InvalidRequestError: return False return True
'Creates identity for a new prospective user. This typically happens when photos are shared with a contact that is not yet a Viewfinder user.'
@classmethod @gen.coroutine def CreateProspective(cls, client, identity_key, user_id, timestamp):
identity = (yield gen.Task(Identity.Query, client, identity_key, None, must_exist=False)) if (identity is None): identity = Identity.CreateFromKeywords(key=identity_key) else: assert ((identity.user_id is None) or (identity.user_id == user_id)), ('the identity is already in us...
'Creates and returns a prospective user invitation ShortURL object. The URL is handled by an instance of AuthProspectiveHandler, which is "listening" at "/pr/...". The ShortURL group is partitioned by user id so that incorrect guesses only affect a single user.'
@classmethod @gen.coroutine def CreateInvitationURL(cls, client, user_id, identity_key, viewpoint_id, default_url):
(identity_type, identity_value) = Identity.SplitKey(identity_key) now = util.GetCurrentTimestamp() expires = (now + Identity._TIME_TO_INVITIATION_EXPIRATION) encoded_user_id = base64hex.B64HexEncode(util.EncodeVarLengthNumber(user_id), padding=False) short_url = (yield ShortURL.Create(client, group_...
'Creates a verification access token. The token is associated with a ShortURL that will be sent to the identity email address or phone number. Following the URL will reveal the access token. The user that presents the correct token to Identity.VerifyAccessToken is assumed to be in control of that email address or SMS n...
@gen.coroutine def CreateAccessTokenURL(self, client, group_id, use_short_token, **kwargs):
(identity_type, value) = Identity.SplitKey(self.key) (num_digits, good_for) = Identity.GetAccessTokenSettings(identity_type, use_short_token) now = util.GetCurrentTimestamp() access_token = None if ((self.authority == 'Viewfinder') and (now < self.expires) and (self.access_token is not None) and (le...
'Verifies the correctness of the given access token, that was previously generated in response to a CreateAccessTokenURL call. Verification will fail if any of these conditions is false. 1. The access token is expired. 2. Too many incorrect attempts to guess the token have been made in the past. 3. The access token doe...
@gen.coroutine def VerifyAccessToken(self, client, access_token):
(identity_type, identity_value) = Identity.SplitKey(self.key) now = time.time() if (identity_type == 'Email'): error = ExpiredError(EXPIRED_EMAIL_LINK_ERROR) else: error = ExpiredError(EXPIRED_ACCESS_CODE_ERROR) if (self.authority != 'Viewfinder'): logging.warning('the aut...
'Verifies that the specified access token matches the one stored in the identity. If this is the case, then the caller has confirmed control of the identity. Returns the identity DB object if so, else raises a permission exception.'
@classmethod @gen.coroutine def VerifyConfirmedIdentity(cls, client, identity_key, access_token):
Identity.ValidateKey(identity_key) identity = (yield gen.Task(Identity.Query, client, identity_key, None, must_exist=False)) if (identity is None): raise InvalidRequestError(BAD_IDENTITY, identity_key=identity_key) (yield identity.VerifyAccessToken(client, access_token)) identity.expires = 0...
'Unlinks the specified identity from the account identified by \'user_id\'. Queries all contacts which reference the identity and update their timestamps so that they will be picked up by query_contacts.'
@classmethod @gen.coroutine def UnlinkIdentity(cls, client, user_id, key, timestamp):
identity = (yield gen.Task(Identity.Query, client, key, None)) assert ((identity.user_id is None) or (identity.user_id == user_id)), identity (yield identity._RewriteContacts(client, timestamp)) (yield gen.Task(identity.Delete, client))
'Returns a description of the specified identity key suitable for UI display.'
@classmethod def GetDescription(cls, identity_key):
(identity_type, value) = Identity.SplitKey(identity_key) if (identity_type == 'Email'): return value elif (identity_type == 'FacebookGraph'): return 'your Facebook account' elif (identity_type == 'Phone'): phone = phonenumbers.parse(value) return phonenumbers.format...
'Splits the given identity key of the form <type>:<value> and returns the (type, value) as a tuple.'
@classmethod def SplitKey(cls, identity_key):
return identity_key.split(':', 1)
'Returns settings that control how the access token for various identity types behaves. The settings are returned as a tuple: (digit_count, good_for) digit_count: number of decimal digits in the access code good_for: time span (in seconds) during which the token is accepted'
@classmethod def GetAccessTokenSettings(cls, identity_type, use_short_token):
if ((identity_type == 'Phone') or use_short_token): return (4, constants.SECONDS_PER_HOUR) elif (identity_type == 'Email'): return (9, constants.SECONDS_PER_DAY) assert False, ('unsupported identity type "%s"' % identity_type)
'Refreshes an expired google access token using the refresh token.'
def RefreshGoogleAccessToken(self, client, callback):
def _OnRefresh(response): try: response_dict = www_util.ParseJSONResponse(response) except web.HTTPError as e: if (e.status_code == 400): logging.error(('%s: failed to refresh access token; clearing refresh token' % e)) ...
'Constructs an access token guess id value, used to limit the number of incorrect guesses that can be made for a particular identity type + user.'
@classmethod def _ConstructAccessTokenGuessId(cls, identity_type, user_id):
if (identity_type == 'Email'): return Guess.ConstructGuessId('em', user_id) assert (identity_type == 'Phone'), identity_type return Guess.ConstructGuessId('ph', user_id)
'Rewrites all contacts which refer to this identity. All timestamps are updated so that query_contacts will pick them up.'
@gen.coroutine def _RewriteContacts(self, client, timestamp):
@gen.coroutine def _RewriteOneContact(co): "Update the given contact's timestamp." new_co = Contact.CreateFromKeywords(co.user_id, co.identities_properties, timestamp, co.contact_source, name=co.name, given_name=co.given_name, family_name=co.family_name, rank=co.rank) if (co....
'Unlinks the specified identity from any associated viewfinder user.'
@classmethod @gen.coroutine def UnlinkIdentityOperation(cls, client, user_id, identity):
timestamp = Operation.GetCurrent().timestamp (yield Identity.UnlinkIdentity(client, user_id, identity, timestamp)) (yield NotificationManager.NotifyUnlinkIdentity(client, user_id, identity, timestamp))
'Parses the provided value into a dict of {tokenized term: freighted data}. By default, emits the column value as the only index term. Subclasses override for specific behavior.'
def Index(self, col, value):
return dict([(t, None) for t in self._ExpandTerm(col, value)])
'Returns a query string suitable for the query parser to match the specified value. In most cases, this is simply the term itself, prefixed with the key + \':\'. However, for full-text search, this would generate a succession of \'and\'s for phrase searches and potentially \'or\'s in cases where a term has homonyms, as...
def GetQueryString(self, col, value):
exp_terms = self._ExpandTerm(col, value) return (exp_terms[0] if (len(exp_terms) == 1) else (('(' + ' | '.join(exp_terms)) + ')'))
'Returns a value representing the unpacked contents of data that were freighted with the posting of this term. This is tokenizer- dependent. For example, the FullTextIndexer freights a list of word positions.'
def UnpackFreight(self, col, posting):
return None
'Returns either the first, second or both terms from the list depending on the value of option.'
def _InterpretOption(self, option, term, optional_term):
if (option == Indexer.Option.NO): return [term] elif (option == Indexer.Option.ONLY): return [optional_term] elif (option == Indexer.Option.YES): return [term, optional_term] raise TypeError()
'Expands each term in \'terms\'. In the base class, this merely prepends the table key + \':\' + column key + \':\' to each term.'
def _ExpandTerm(self, col, term):
prefix = (col.key + ':') if col.table: prefix = ((col.table.key + ':') + prefix) return [(prefix + ConvertToString(term))]
'Returns a quoted string to match the column value exactly.'
def GetQueryString(self, col, value):
exp_terms = self._ExpandTerm(col, value) assert (len(exp_terms) == 1) return ('"%s"' % exp_terms[0])
'Parses the provided value into a dict of {tokenized term: freighted data}. By default, emits the column value as the only index term. Subclasses override for specific behavior.'
def Index(self, col, value):
return dict([(t, None) for t in self._ExpandTerm(col, int(value))])
''
def GetQueryString(self, col, value):
exp_terms = self._ExpandTerm(col, int(value)) assert (len(exp_terms) == 1) return ('"%s"' % exp_terms[0])
'Generates implicated S2 patches at S2_CELL_LEVEL which cover an S2 cap centered at lat/lon with radius RADIUS.'
def Index(self, col, value):
(lat, lon, acc) = value cells = [c for c in s2.SearchCells(lat, lon, BreadcrumbIndexer.RADIUS, BreadcrumbIndexer.S2_CELL_LEVEL, BreadcrumbIndexer.S2_CELL_LEVEL)] assert (len(cells) <= 10), len(cells) return dict([(t, None) for c in cells for t in self._ExpandTerm(col, c)])
'The provided value is a latitude, longitude, accuracy tuple. Returns a search query for the indicated S2_CELL_LEVEL cell.'
def GetQueryString(self, col, value):
(lat, lon, acc) = [float(x) for x in value.split(',')] cells = s2.IndexCells(lat, lon, BreadcrumbIndexer.S2_CELL_LEVEL, BreadcrumbIndexer.S2_CELL_LEVEL) assert (len(cells) == 1), [repr(c) for c in cells] exp_terms = self._ExpandTerm(col, cells[0]) return (exp_terms[0] if (len(exp_terms) == 1) else (...
'Generates implicated S2 patches from levels (_S2_MIN, _S2_MAX).'
def Index(self, col, value):
(lat, lon, acc) = value cells = [c for c in s2.IndexCells(lat, lon, LocationIndexer._S2_MIN, LocationIndexer._S2_MAX)] cells.reverse() return dict([(t, None) for c in cells for t in self._ExpandTerm(col, c)])
'The provided value is a triplet of latitude, longitude and a radius in meters. Returns an \'or\'d set of S2 geometry patch terms that cover the region.'
def GetQueryString(self, col, value):
(lat, lon, rad) = [float(x) for x in value.split(',')] cells = [c for c in s2.SearchCells(lat, lon, rad, LocationIndexer._S2_MIN, LocationIndexer._S2_MAX)] exp_terms = [t for c in cells for t in self._ExpandTerm(col, c)] return (exp_terms[0] if (len(exp_terms) == 1) else (('(' + ' | '.join(exp_ter...
'Returns words as contiguous alpha numeric strings (and apostrophes) which are of length > 1 and are also not in the stop words list. Each term is freighted with a list of term positions (formatted as a packed binary string).'
def Index(self, col, value):
terms = {} expansions = {} tokens = self._Tokenize(value) for (pos, term) in zip(xrange(len(tokens)), tokens): if (term == '_'): continue if (term not in expansions): expansions[term] = self._ExpandTerm(col, term) for exp_term in expansions[term]: ...
'Returns a query string suitable for the query parser to match the specified value. If the value tokenizes to multiple terms, generates a conjunction of \'+\' operators which is like \'&", but with a positional requirement (this implements phrase search). Each term is then expanded into a conjunction of \'or\' operator...
def GetQueryString(self, col, value):
def _GetExpansionString(term): if (term == '_'): return term exp_terms = self._ExpandTerm(col, term) if (len(exp_terms) == 1): return exp_terms.pop() else: return (('(' + ' | '.join(exp_terms)) + ')') tokens = self._Tokenize(value) if...
'Strips all punctuation characters and tokenizes by whitespace.'
def _Tokenize(self, value):
return PlacemarkIndexer._SPLIT_CHARS.sub('', value.lower()).split()
'- metaphone: generate metaphone query terms. Metaphone is an expansive phonetic representation of english language words.'
def __init__(self, metaphone=Indexer.Option.NO):
super(FullTextIndexer, self).__init__() self._metaphone = metaphone
'Splits \'value\' into a sequence of (position, token) tuples according to whitespace. Stop words are represented by the \'_\' character.'
def _Tokenize(self, value):
tokens = FullTextIndexer._SPLIT_CHARS.sub(' ', value.lower()).split() tokens = [token.strip("'") for token in tokens] for i in xrange(len(tokens)): if ((tokens[i] in stopwords.STOP_WORDS) or (len(tokens[i]) == 1)): tokens[i] = '_' return tokens
'Expand term according to metaphone and then for each, expand using Indexer._ExpandTerm.'
def _ExpandTerm(self, col, term):
terms = set() for meta_term in self.__ExpandMetaphone(term): if meta_term: terms = terms.union(Indexer._ExpandTerm(self, col, meta_term)) return terms
'Expands term according to metaphone setting. Need to be careful here about the metaphone algorithm returning no matches, as is the case with numbers and sufficiently non-English words. In this case, where there are no metaphone results, we just add the term.'
def __ExpandMetaphone(self, term):
if (self._metaphone == Indexer.Option.NO): return set([term]) else: terms = set() for dmeta_term in _D_METAPHONE(term): if dmeta_term: terms = terms.union(self._InterpretOption(self._metaphone, term, dmeta_term)) if (not terms): terms.add(t...
'Stub retry method, indicating that all exceptions should result in a retry.'
def _ShouldRetry(self, type_, value_, traceback):
return True
'Initialize a new Metric object.'
def __init__(self, group_key=None, sort_key=None):
super(Metric, self).__init__() self.group_key = group_key self.sort_key = sort_key
'Performs a range query on the metrics table for the given group_key the given start and end time. An optional start key can be specified to resume an earlier query which did not retrieve the full result set. Either start_time or end_time may be None, but not both.'
@classmethod def QueryTimespan(cls, client, group_key, start_time, end_time, callback, excl_start_key=None):
assert ((start_time is not None) or (end_time is not None)), 'must specify at least one of start_time and end_time' operator = None start_rk = (util.CreateSortKeyPrefix(start_time, randomness=False) if (start_time is not None) else None) end_rk = (util.CreateSortKeyPrefix((end_ti...
'Create a new metric object with the given attributes. The sort key is computed automatically from the timestamp and machine id.'
@classmethod def Create(cls, group_key, machine_id, timestamp, payload):
sort_key = (util.CreateSortKeyPrefix(timestamp, randomness=False) + machine_id) metric = Metric(group_key, sort_key) metric.machine_id = machine_id metric.timestamp = timestamp metric.payload = payload return metric
'Starts an asynchronous loop which periodically samples performance counters and saves their values to the database. The interval parameter is a MetricInterval object which specifies the frequency of upload in seconds.'
@classmethod def StartMetricUpload(cls, client, cluster_name, interval):
retry_policy = MetricUploadRetryPolicy() machine_id = GetMachineKey() meter = counters.Meter(counters.counters) group_key = cls.EncodeGroupKey(cluster_name, interval) frequency_seconds = interval.length def _UploadError(type_, value_, traceback): logging.getLogger().error(('Unable to ...
'Stops the metrics upload process if it has already been started. This method is idempotent.'
@classmethod def StopMetricUpload(cls, group_key):
if (cls._timeouts.get(group_key, None) is not None): IOLoop.current().remove_timeout(cls._timeouts[group_key]) cls._timeouts[group_key] = None
'Encodes a group key for the Metric table. A group key is a combination of a machine cluster name and a collection interval name.'
@classmethod def EncodeGroupKey(cls, cluster_name, interval):
return ((cluster_name + '.') + interval.name)
'Attempts to decode a metrics group key. Returns the machine cluster name and metric interval used to encode the group.'
@classmethod def DecodeGroupKey(cls, group_key):
index = group_key.find('.') assert (index != (-1)) cluster = group_key[:index] interval = group_key[(index + 1):] return (cluster, cls.FindIntervalForCluster(cluster, interval))
'Look for and return \'interval\' for \'cluster\'. Returns None if not found.'
@classmethod def FindIntervalForCluster(cls, cluster, interval):
intervals = [] if (cluster == DEFAULT_CLUSTER_NAME): intervals = METRIC_INTERVALS elif (cluster == LOGS_STATS_NAME): intervals = LOGS_INTERVALS elif (cluster == JOBS_STATS_NAME): intervals = JOBS_INTERVALS for i in intervals: if (i.name == interval): retur...
'Adds a single sample to the aggregation.'
def AddSample(self, machine, timestamp, value):
self.machine_data.setdefault(machine, list()).append([timestamp, value]) if ((len(self.cluster_total) == 0) or (timestamp > self.cluster_total[(-1)][0])): self.cluster_total.append([timestamp, 0]) self.cluster_avg.append([timestamp, 0]) self.cluster_total[(-1)][1] += value self.cluster_a...
'Adds a single metric sample to the aggregation. Metric samples must be added in chronological order.'
def _AddMetric(self, metric):
machine = metric.machine_id time = metric.timestamp payload = DotDict(json.loads(metric.payload)).flatten() self.machines.add(machine) self.timestamps.add(time) for k in payload: if (k not in self.counter_data): continue val = payload.get(k, None) if (val is n...
'Creates an Aggregated Metric and for a set of counters and queries the database, aggregating all metrics for the given cluster and interval across the given time span. Invokes the given callback with the resulting AggregatedMetric object after the query is completed.'
@classmethod def CreateAggregateForTimespan(cls, client, group_key, start_time, end_time, counter_set, callback):
aggregator = AggregatedMetric(group_key, start_time, end_time, counter_set) def _OnQueryPartial(metrics): if (len(metrics) > 0): Metric.QueryTimespan(client, group_key, start_time, end_time, _OnQueryPartial, excl_start_key=metrics[(-1)].GetKey()) for m in metrics: ...
'Initialize a new Accounting object.'
def __init__(self, hash_key=None, sort_key=None):
super(Accounting, self).__init__() self.hash_key = hash_key self.sort_key = sort_key self.op_ids = None self._Reset()
'Reset counters to 0.'
def _Reset(self):
self.num_photos = 0 self.tn_size = 0 self.med_size = 0 self.full_size = 0 self.orig_size = 0
'Increment counters with the photo stats.'
def IncrementFromPhotoDict(self, photo_dict):
self.num_photos += 1 self.tn_size += photo_dict.get('tn_size', 0) self.med_size += photo_dict.get('med_size', 0) self.full_size += photo_dict.get('full_size', 0) self.orig_size += photo_dict.get('orig_size', 0)
'Increment counters with the photo stats.'
def IncrementFromPhotoDicts(self, photo_dicts):
for p in photo_dicts: self.IncrementFromPhotoDict(p)
'Increment counters with the photo stats.'
def IncrementFromPhoto(self, photo):
def _GetOrZero(val): if (val is not None): return val else: return 0 self.num_photos += 1 self.tn_size += _GetOrZero(photo.tn_size) self.med_size += _GetOrZero(photo.med_size) self.full_size += _GetOrZero(photo.full_size) self.orig_size += _GetOrZero(photo...
'Increment counters with the photo stats.'
def IncrementFromPhotos(self, photos):
for photo in photos: self.IncrementFromPhoto(photo)
'Decrement counters with the photo stats.'
def DecrementFromPhotoDicts(self, photo_dicts):
for p in photo_dicts: self.num_photos -= 1 self.tn_size -= p.get('tn_size', 0) self.med_size -= p.get('med_size', 0) self.full_size -= p.get('full_size', 0) self.orig_size -= p.get('orig_size', 0)
'Decrement counters with the photo stats.'
def DecrementFromPhotos(self, photos):
def _GetOrZero(val): if (val is not None): return val else: return 0 for p in photos: self.num_photos -= 1 self.tn_size -= _GetOrZero(p.tn_size) self.med_size -= _GetOrZero(p.med_size) self.full_size -= _GetOrZero(p.full_size) self....
'Copy the usage stats from another accounting object.'
def CopyStatsFrom(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
'Increment stats by another accounting object.'
def IncrementStatsFrom(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