desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Creates the viewpoint specified by \'vp_dict\' and creates a follower relation between the requesting user and the viewpoint with the ADMIN label. The caller is responsible for checking permission to do this, as well as ensuring that the viewpoint does not yet exist (or is just being identically rewritten). Returns a ...
@classmethod @gen.coroutine def CreateNew(cls, client, **vp_dict):
tasks = [] assert (('viewpoint_id' in vp_dict) and ('user_id' in vp_dict) and ('timestamp' in vp_dict)), vp_dict viewpoint = Viewpoint.CreateFromKeywords(**vp_dict) viewpoint.last_updated = viewpoint.timestamp viewpoint.update_seq = 0 tasks.append(gen.Task(viewpoint.Update, client)) foll_dic...
'Calls the "CreateWithFollower" method to create a viewpoint with a single follower (the current user). Then, all users identified by "follower_ids" are added to that viewpoint as followers. Ensure that every pair of followers is friends with each other. The caller is responsible for checking permission to do this, as ...
@classmethod @gen.coroutine def CreateNewWithFollowers(cls, client, follower_ids, **vp_dict):
(viewpoint, owner_follower) = (yield Viewpoint.CreateNew(client, **vp_dict)) followers = (yield viewpoint.AddFollowers(client, vp_dict['user_id'], [vp_dict['user_id']], follower_ids, viewpoint.timestamp)) followers.append(owner_follower) raise gen.Return((viewpoint, followers))
'Queries the specified viewpoint and follower and returns them as a (viewpoint, follower) tuple.'
@classmethod @gen.coroutine def QueryWithFollower(cls, client, user_id, viewpoint_id):
(viewpoint, follower) = (yield [gen.Task(Viewpoint.Query, client, viewpoint_id, None, must_exist=False), gen.Task(Follower.Query, client, user_id, viewpoint_id, None, must_exist=False)]) assert ((viewpoint is not None) or (follower is None)), (viewpoint, follower) raise gen.Return((viewpoint, follower))
'Queries episodes belonging to the viewpoint (up to \'limit\' total) for the specified \'viewpoint_id\'. Starts with episodes having a key greater than \'excl_start_key\'. Returns a tuple with the array of episodes and the last queried key.'
@classmethod @gen.engine def QueryEpisodes(cls, client, viewpoint_id, callback, excl_start_key=None, limit=None):
from viewfinder.backend.db.episode import Episode query_expr = ('episode.viewpoint_id={id}', {'id': viewpoint_id}) start_index_key = (db_client.DBKey(excl_start_key, None) if (excl_start_key is not None) else None) episode_keys = (yield gen.Task(Episode.IndexQueryKeys, client, query_expr, start_index_ke...
'Query followers belonging to the viewpoint (up to \'limit\' total) for the specified \'viewpoint_id\'. The query is for followers starting with (but excluding) \'excl_start_key\'. The callback is invoked with an array of follower objects and the last queried key.'
@classmethod @gen.coroutine def QueryFollowers(cls, client, viewpoint_id, excl_start_key=None, limit=None):
query_expr = ('follower.viewpoint_id={id}', {'id': viewpoint_id}) start_index_key = (db_client.DBKey(excl_start_key, viewpoint_id) if (excl_start_key is not None) else None) follower_keys = (yield gen.Task(Follower.IndexQueryKeys, client, query_expr, start_index_key=start_index_key, limit=limit)) last_k...
'Query followers belonging to the viewpoint (up to \'limit\' total) for the specified \'viewpoint_id\'. The query is for followers starting with (but excluding) \'excl_start_key\'. The callback is invoked with an array of follower user ids and the last queried key.'
@classmethod def QueryFollowerIds(cls, client, viewpoint_id, callback, excl_start_key=None, limit=None):
def _OnQueryFollowerKeys(follower_keys): follower_ids = [key.hash_key for key in follower_keys] last_key = (follower_ids[(-1)] if (len(follower_ids) > 0) else None) callback((follower_ids, last_key)) query_expr = ('follower.viewpoint_id={id}', {'id': viewpoint_id}) start_index_key = ...
'Visit all followers of the specified viewpoint and invoke the "visitor" function with each follower id. See VisitIndexKeys for additional detail.'
@classmethod def VisitFollowerIds(cls, client, viewpoint_id, visitor, callback, consistent_read=False):
def _OnVisit(follower_key, visit_callback): visitor(follower_key.hash_key, visit_callback) query_expr = ('follower.viewpoint_id={id}', {'id': viewpoint_id}) Follower.VisitIndexKeys(client, query_expr, _OnVisit, callback, consistent_read=consistent_read)
'Queries activities belonging to the viewpoint (up to \'limit\' total) for the specified \'viewpoint_id\'. Starts with activities having a key greater than \'excl_start_key\'. Returns a tuple with the array of activities and the last queried key.'
@classmethod def QueryActivities(cls, client, viewpoint_id, callback, excl_start_key=None, limit=None):
def _OnQueryActivities(activities): callback((activities, (activities[(-1)].activity_id if (len(activities) > 0) else None))) Activity.RangeQuery(client, viewpoint_id, range_desc=None, limit=limit, col_names=None, callback=_OnQueryActivities, excl_start_key=excl_start_key)
'Queries comments belonging to the viewpoint (up to \'limit\' total) for the specified \'viewpoint_id\'. Starts with comments having a key greater than \'excl_start_key\'. Returns a tuple with the array of comments and the last queried key.'
@classmethod def QueryComments(cls, client, viewpoint_id, callback, excl_start_key=None, limit=None):
def _OnQueryComments(comments): callback((comments, (comments[(-1)].comment_id if (len(comments) > 0) else None))) Comment.RangeQuery(client, viewpoint_id, range_desc=None, limit=limit, col_names=None, callback=_OnQueryComments, excl_start_key=excl_start_key)
'Adds contacts as followers to the specified viewpoint. Notifies all viewpoint followers about the new followers.'
@classmethod @gen.engine def AddFollowersOperation(cls, client, callback, activity, user_id, viewpoint_id, contacts):
from viewfinder.backend.op.add_followers_op import AddFollowersOperation AddFollowersOperation.Execute(client, activity, user_id, viewpoint_id, contacts, callback=callback)
'Updates viewpoint metadata.'
@classmethod @gen.engine def UpdateOperation(cls, client, callback, act_dict, vp_dict):
from viewfinder.backend.op.update_viewpoint_op import UpdateViewpointOperation user_id = vp_dict.pop('user_id') UpdateViewpointOperation.Execute(client, act_dict, user_id, vp_dict, callback=callback)
'Set to affect mutations on the database. If False, the planned modifications to each item are verbosely logged but not persisted.'
@classmethod def SetMutateItems(cls, mutate):
Version._mutate_items = mutate
'Allow S3 queries. If False, upgrades that involve querying S3 will skip it, but may perform other work. eg: CreateMD5Hashes and FillFileSizes both use S3 queries as a fallback when the desired fields are not found the Photo.client_data.'
@classmethod def SetAllowS3Queries(cls, allow):
Version._allow_s3_queries = allow
'Returns the maximum version. New objects have item._version set to this value.'
@classmethod def GetCurrentVersion(cls):
if Version._rank_ordering: return Version._rank_ordering[(-1)] else: return 0
'Migrates the data in one table row (\'item\') by advancing \'item\'s version via successive data migrations. If \'item\' does not have a version yet, all data migrations are applied. If item\'s version is current, does nothing. Return the migrated object if mutations are enabled, or the original object if not. Take ca...
@classmethod def MaybeMigrate(cls, client, original_item, versions, callback):
def _Migrate(start_rank, mutate_item): last_rank = 0 for version in versions: if (version.rank < start_rank): last_rank = version.rank continue assert (version.rank > last_rank), ('tags listed out of order (! %d > %d)' %...
'Log the changes to the object.'
def _LogUpdate(self, item):
mods = [('%s => %r' % (n, getattr(item, n))) for n in item.GetColNames() if item._IsModified(n)] if mods: logging.info(('%s (%r): %s' % (type(item)._table.name, item.GetKey(), ', '.join(mods))))
'Implement in each subclass to effect the required data migration. \'callback\' should be invoked on completion with the update object. If no async processing is required, it should be invoked directly.'
def Transform(self, client, item, callback):
raise NotImplementedError()
'If an attribute does not exist, create it with default value.'
def Transform(self, client, item, callback):
item = item._Clone() if (item.attr0 is None): item.attr0 = 100 self._LogUpdate(item) if Version._mutate_items: item.Update(client, partial(callback, item)) else: callback(item)
'If an attribute does exist, delete it.'
def Transform(self, client, item, callback):
if (item.attr1 is not None): item.attr1 = None self._LogUpdate(item) if Version._mutate_items: item.Update(client, partial(callback, item)) else: callback(item)
'Returns an episode id constructed from component parts. Episodes sort from newest to oldest. See "ConstructTimestampAssetId" for details of the encoding.'
@classmethod def ConstructEpisodeId(cls, timestamp, device_id, uniquifier):
return ConstructTimestampAssetId(IdPrefix.Episode, timestamp, device_id, uniquifier)
'Returns the components of an episode id: timestamp, device_id, and uniquifier.'
@classmethod def DeconstructEpisodeId(cls, episode_id):
return DeconstructTimestampAssetId(IdPrefix.Episode, episode_id)
'Ensures that a client-provided episode id is valid according to the rules specified in VerifyAssetId.'
@classmethod @gen.coroutine def VerifyEpisodeId(cls, client, user_id, device_id, episode_id):
(yield VerifyAssetId(client, user_id, device_id, IdPrefix.Episode, episode_id, has_timestamp=True))
'Creates the episode specified by \'ep_dict\'. The caller is responsible for checking permission to do this, as well as ensuring that the episode does not yet exist (or is just being identically rewritten). Returns: The created episode.'
@classmethod @gen.coroutine def CreateNew(cls, client, **ep_dict):
assert (('episode_id' in ep_dict) and ('user_id' in ep_dict) and ('viewpoint_id' in ep_dict)), ep_dict assert ('timestamp' in ep_dict), ('timestamp attribute required in episode: "%s"' % ep_dict) assert ('publish_timestamp' in ep_dict), ('publish_timestamp attribute required in ep...
'Updates an existing episode.'
@gen.coroutine def UpdateExisting(self, client, **ep_dict):
assert (('publish_timestamp' not in ep_dict) and ('parent_ep_id' not in ep_dict)), ep_dict self.UpdateFromKeywords(**ep_dict) (yield gen.Task(self.Update, client))
'If the user has viewing rights to the specified episode, returns that episode, otherwise returns None. The user has viewing rights if the user is a follower of the episode\'s viewpoint. If must_exist is true and the episode does not exist, raises an InvalidRequest exception.'
@classmethod @gen.coroutine def QueryIfVisible(cls, client, user_id, episode_id, must_exist=True, consistent_read=False):
episode = (yield gen.Task(Episode.Query, client, episode_id, None, must_exist=False, consistent_read=consistent_read)) if (episode is None): if (must_exist == True): raise InvalidRequestError(('Episode "%s" does not exist.' % episode_id)) else: follower = (yield gen.T...
'Queries posts (up to \'limit\' total) for the specified \'episode_id\', viewable by \'user_id\'. The query is for posts starting with (but excluding) \'excl_start_key\'. The photo metadata for each post relation are in turn queried and the post and photo metadata are combined into a single dict. The callback is invoke...
@classmethod def QueryPosts(cls, client, episode_id, user_id, callback, limit=None, excl_start_key=None, base_results=None):
def _OnQueryMetadata(posts, results): 'Constructs the photo metadata to return. The "check_label" argument\n is used to determine whether to use the old permissions model or the\n new one. If "...
'Shutdown persistence on process exit.'
def Shutdown(self):
self._persist.Shutdown()
'Moves sequentially through entire table until \'excl_start_key\' is located. Then iterates, passing each item through the conditions of \'scan_filter\', accumulating up to \'limit\' results.'
def Scan(self, table, callback, attributes, limit=None, excl_start_key=None, scan_filter=None):
assert ((limit is None) or (limit > 0)), limit items = [] last_key = None bytes_read = 0 found = False def _FilterItem(item): "Returns whether the item passes the conditions of\n 'scan_filter'. This implementation is incomplete ...
'Invokes the specified callback after \'deadline_secs\'.'
def AddTimeout(self, deadline_secs, callback):
return IOLoop.current().add_timeout((time.time() + deadline_secs), callback)
'Invokes the specified callback at time \'abs_timeout\'.'
def AddAbsoluteTimeout(self, abs_timeout, callback):
return IOLoop.current().add_timeout(abs_timeout, callback)
'Removes an existing timeout.'
def RemoveTimeout(self, timeout):
IOLoop.current().remove_timeout(timeout)
'Verifies the key matches the key schema.'
def _CheckKey(self, table, key, must_exist, expected):
assert (table in self._table_schemas), ('table %s does not exist in %r' % (table, self._table_schemas)) schema = self._table_schemas[table] if (expected and expected.has_key(schema.hash_key_schema.name)): assert (expected[schema.hash_key_schema.name] == False) must_exist = ...
'Ensures that \'value\' is of a type compatible with \'key_schema\' (which is either \'N\' for number or \'S\' for string).'
def _CheckKeyType(self, table, key_schema, key_type, value):
if (key_schema.value_type == 'N'): assert isinstance(value, (int, long, float)), ('%s for column "%s" in table "%s" must be a number: %s' % (key_type, key_schema.name, table, repr(value))) elif (key_schema.value_type == 'S'): assert isinstance(value, (str, unicod...
'Returns a new schema with status set to \'new_status\'.'
def _NewSchemaStatus(self, schema, new_status):
return TableSchema(create_time=schema.create_time, hash_key_schema=schema.hash_key_schema, range_key_schema=schema.range_key_schema, read_units=schema.read_units, write_units=schema.write_units, status=new_status)
'Fetches the item from the store by table & key. If \'delete\', deletes the item.'
def _GetItem(self, table, key, delete=False):
if (key.range_key is not None): if (key.hash_key not in self._tables[table]): self._tables[table][key.hash_key] = dict() if (key.range_key not in self._tables[table][key.hash_key]): self._tables[table][key.hash_key][key.range_key] = dict() if (not delete): ...
'Gets the list of named \'attributes\' from the item. If an attribute is not present in the item, it won\'t be returned. If attributes is None, all attributes are returned.'
def _GetAttributes(self, item, attributes):
if (not attributes): return item result = dict([(a, item[a]) for a in attributes if item.has_key(a)]) return result
'Logic to update a data item. Called from PutItem() and UpdateItem().'
def _UpdateItem(self, item, attributes, expected, return_values):
if expected: for (k, v) in expected.items(): if isinstance(v, bool): assert (v == False) if item.has_key(k): raise DBConditionalCheckFailedError(('expected attr %s not to exist, but exists with value %r' % (k, item...
'If callback is not None, runs asynchronously; otherwise, runs synchronously.'
def _HandleCallback(self, callback, result):
if any((isinstance(result, rt) for rt in LocalClient._MUTATING_RESULTS)): self._persist.MarkDirty() if callback: IOLoop.current().add_callback(partial(callback, result)) else: return result
'Computes the number of elements in the table. If the table schema has a composite key, iterates over each hash key to compute the full length.'
def _GetTableSize(self, table):
schema = self._table_schemas[table] if schema.range_key_schema: return sum([len(rd) for rd in self._tables[table].values()]) else: return len(self._tables[table])
'Returns true if this ShortURL has expired.'
def IsExpired(self):
return (util.GetCurrentTimestamp() >= self.expires)
'Expires the ShortURL by setting the expires field to 0 and calling Update.'
@gen.coroutine def Expire(self, client):
self.expires = 0 (yield gen.Task(self.Update, client))
'Allocate a new ShortURL DB object by finding an unused random key within the group.'
@classmethod @gen.coroutine def Create(cls, client, group_id, timestamp, expires, **kwargs):
for i in xrange(ShortURL._KEY_GEN_TRIES): random_key = base64hex.B64HexEncode(os.urandom(ShortURL.KEY_LEN_IN_BYTES)) short_url = ShortURL(group_id, random_key) short_url.timestamp = timestamp short_url.expires = expires short_url.json = kwargs try: (yield ...
'Register a counter with the manager. Counters are organized into namespaces using \'.\' as a separator. Examples of module names: # Valid counter names my_counter module.counters.another_counter Note that it is invalid for a counter\'s name to be the namespace of another counter: # Invalid counter names, due to name...
def register(self, counter):
cname = counter.name if (len(cname) == 0): raise ValueError('Cannot register counter with a blank name.') existing = self.get(cname, None) if existing: if isinstance(existing, DotDict): raise KeyError(('Cannot register counter with name %s ...
'Returns a closure function which can be called repeatedly to sample the counter. The use of a closure function ensures that multiple Meters can be used simultaneously without interference.'
def get_sampler(self):
last_sample = [self._raw_sample()] def sampler_func(): old_sample = last_sample[0] last_sample[0] = self._raw_sample() return self._computed_sample(old_sample, last_sample[0]) return sampler_func
'Returns a raw sample for the counter, which represents the value of internal counters at the moment the sample is taken. Two raw samples will be used inside of _computed_sample() to return a value from the counter with proper units.'
def _raw_sample(self):
raise NotImplementedError('_raw_sample() must be implemented in a subclass.')
'Using two raw samples taken previously, creates a sample in units which are appropriate to the specific type of counter.'
def _computed_sample(self, s1, s2):
raise NotImplementedError('_computed_sample() must be implemented in a subclass.')
'Increments the internal counter by a value. If not value is provided, increments by one.'
def increment(self, value=1):
self._counter += value
'Decrements the internal counter by a value. If not value is provided, decrements by one.'
def decrement(self, value=1):
self._counter -= value
'Adds the value from a single occurrence to the counter.'
def add(self, value):
self._counter += value self._base_counter += 1
'Initialize a new meter object. If the optional counters parameter is provided, its value is passed immediately to the add_counters() method.'
def __init__(self, counters=None):
self._counters = dict() self._description = None if (counters is not None): self.add_counters(counters)
'Add an additional counter or collection of counters to this meter. The intention is for a portion of the global \'counters\' instance (or another CounterManager object) to be passed to this method.'
def add_counters(self, counters):
if isinstance(counters, DotDict): flat = counters.flatten() self._counters.update([(v, v.get_sampler()) for v in flat.itervalues()]) else: self._counters[counters] = counters.get_sampler() self._description = None
'Samples all counters being tracked by this meter, returning a DotDict object with all of the sampled values organized by namespace.'
def sample(self):
new_sample = DotDict() for k in self._counters.keys(): new_sample[k.name] = self._counters[k]() return new_sample
'Returns the description of all counters being tracked by this meter. The returned object is a DotDict object with all of the descriptions organized by counter namespace.'
def describe(self):
if (self._description is None): new_description = DotDict() for k in self._counters.keys(): new_description[k.name] = k.description self._description = new_description return self._description
'Configures the daemon based on the command line --daemon option. If no option is specified, then run_callback is invoked with shutdown_callback as a parameter. If \'start\' or \'restart\' is specified, then the current process will be converted to a daemon before invoking run_callback. If \'stop\' is specified, then a...
def SetupFromCommandLine(self, run_callback, shutdown_callback):
opt = options.options.daemon.lower() if (opt == 'none'): run_callback(shutdown_callback) return def _shutdown_daemon(): self._context.close() shutdown_callback() opt = options.options.daemon.lower() if (opt == 'start'): self.StartDaemon() run_callback(...
'Converts the current process to a daemon unless another daemon process is already running on the system.'
def StartDaemon(self):
current_pid = self._get_current_pid() if (current_pid is not None): raise DaemonError(('Daemon process is already started with PID:%s' % current_pid)) self._context = daemon.daemon.DaemonContext(pidfile=self.lockfile) try: self._context.open() except pidlockfile.Alr...
'Stops any currently running daemon process on the system.'
def StopDaemon(self, require_running=True):
current_pid = self._get_current_pid() if (require_running and (current_pid is None)): raise DaemonError('Daemon process was not running.') try: os.kill(current_pid, signal.SIGTERM) except OSError as exc: raise DaemonError(('Failed to stop daemon process ...
'Get the process ID of any currently running daemon process. Returns None if no process is running.'
def _get_current_pid(self):
current_pid = None if self.lockfile.is_locked(): current_pid = self.lockfile.read_pid() if (current_pid is not None): try: os.kill(current_pid, 0) except OSError as exc: if (exc.errno == errno.ESRCH): current_pid = None ...
'Returns true if running as if on a developer machine.'
@staticmethod def IsDevBox():
assert (_server_environment is not None) return _server_environment._is_devbox
'Returns true if running as a staging server.'
@staticmethod def IsStaging():
assert (_server_environment is not None) return _server_environment._is_staging
'Gets name of current host. This will be staging.<domain> if running as staging server, or www.<domain> if running as production server.'
@staticmethod def GetHost():
assert (_server_environment is not None) return (_server_environment._staging_host if _server_environment._is_staging else _server_environment._prod_host)
'Gets the path to the temp dir that viewfinder should use as temp.'
@staticmethod def GetViewfinderTempDirPath():
assert (_server_environment is not None) if (not _server_environment._vf_temp_dir): assert _server_environment._is_devbox _server_environment._vf_temp_dir = tempfile.mkdtemp() atexit.register(shutil.rmtree, _server_environment._vf_temp_dir) return _server_environment._vf_temp_dir
'Gets name of host to which staging/production users are redirected if they don\'t "match" the current host. This will be staging.<domain> if running as production server, or www.<domain> if running as staging server.'
@staticmethod def GetRedirectHost():
assert (_server_environment is not None) return (_server_environment._prod_host if _server_environment._is_staging else _server_environment._staging_host)
'Collects information during startup about the current server environment. This will retry on transient errors and assert for non-transient issues such as mis-configuration.'
@staticmethod def InitServerEnvironment():
global _server_environment is_devbox = options.options.devbox is_staging = options.options.is_staging if (is_staging is None): if is_devbox: is_staging = False else: instance_id = GetAMIMetadata().get('meta-data/instance-id', None) if (instance_id is N...
'Attempts to retrieve the current mercurial revision number from the local filesystem.'
@staticmethod def GetHGRevision():
filename = os.path.join(os.path.dirname(__file__), '../../hg_revision.txt') try: with open(filename) as f: return f.read().strip() except IOError: return None
'Creates a `Metadata`. If `callback` is specified, launches async retrieval of commonly used metadata values and the userdata and invokes `callback` upon completion. Callback is invoked with a dictionary containing the common metadata and the userdata. :arg callback: invoked when default metadata is available :arg quer...
def __init__(self, callback=None, query_ip=_QUERY_IP, query_version=_QUERY_VERSION):
self._query_ip = query_ip self._query_version = query_version if callback: self._FetchCommonMetadata(callback)
'Asynchronously fetches metadata for the specified path(s) and on completion invokes the callback with the retrieved metadata value. \'paths\' can be iterable over multiple metadata to fetch; if not, adds it to a list.'
def FetchMetadata(self, paths, callback):
metadata = {} def _OnFetch(path, callback, response): if (response.code == 200): metadata[path] = response.body.strip() else: logging.error("error fetching '%s': %s", path, response.error) callback() if (type(paths) in (unicode, str)): paths =...
'Returns a query URL for instance metadata using the specified path.'
def _GetQueryURL(self, path):
return 'http://{0}/{1}/{2}'.format(self._query_ip, self._query_version, path)
'Fetches common metadata values and compiles the results into a dictionary, which is passed to the callback on completion. NOTE: the AWS metadata server has some sort of internal rate-limiting for this data and will return 404 errors if too many are done in parallel. So, we fetch them serially.'
def _FetchCommonMetadata(self, callback):
paths = ['meta-data/hostname', 'meta-data/instance-id', 'user-data/passphrase'] self.FetchMetadata(paths, callback)
'Maintain stack of previous instances. This is a stack to support re-entry of a context.'
def __init__(self):
self.__previous_instances = []
'Retrieves the currently in-scope instance of context class cls, or a default instance if no instance is currently in scope.'
@classmethod def current(cls):
current_value = cls._contexts.current.get(cls.__name__, None) return (current_value if (current_value is not None) else cls._default_instance)
'Sets this instance to be the currently in-scope instance of its class.'
def __enter__(self):
cls = type(self) self.__previous_instances.append(cls._contexts.current.get(cls.__name__, None)) cls._contexts.current[cls.__name__] = self
'Sets the currently in-scope instance of this class to its previous value.'
def __exit__(self, exc_type, exc_value, exc_traceback):
cls = type(self) cls._contexts.current[cls.__name__] = self.__previous_instances.pop()
'StackContext takes a \'context factory\' as a parameter, which is a callable which should return a context object. By making an instance of this class return itself when called, each instance becomes its own factory.'
def __call__(self):
return self
'Initialize a default instance of the RetryPolicy, choosing among the following properties: max_tries (int) Maximum number of tries that will be attempted. timeout (timedelta or int or float) If this amount of time is exceeded, then the operation will not be retried. This is only checked between attempts. If a number i...
def __init__(self, max_tries=sys.maxint, timeout=timedelta.max, min_delay=timedelta(seconds=0), max_delay=timedelta.max, check_result=None, check_exception=None):
self.max_tries = max_tries self.timeout = (timeout if (type(timeout) is timedelta) else timedelta(seconds=timeout)) self.min_delay = (min_delay if (type(min_delay) is timedelta) else timedelta(seconds=min_delay)) self.max_delay = (max_delay if (type(max_delay) is timedelta) else timedelta(seconds=max_de...
'Called by CallWithRetry in order to create a RetryManager which can track the progress of a particular operation. This method can be overridden if a custom retry policy is created.'
def CreateManager(self):
return RetryManager(self)
'Static method to always retry on exceptions.'
@staticmethod def AlwaysRetryOnException(type, value, traceback):
return True
'Create a RetryManager that is capable of tracking properties defined in the RetryPolicy base class. This involves tracking the number of tries attempted so far, along with whether the timeout deadline has been exceeded.'
def __init__(self, retry_policy):
self.retry_policy = retry_policy self._num_tries = 0 self._deadline = (time.time() + retry_policy.timeout.total_seconds()) self._delay = None
'This function is called by CallWithRetryAsync once the asynchronous operation has completed and has invoked its callback function. It returns true if a retry should be attempted.'
def MaybeRetryOnResult(self, retry_func, *result_args, **result_kwargs):
def CheckRetry(): 'Retry should be attempted if the result inspector function exists and returns true.' return (self.retry_policy.check_result and self.retry_policy.check_result(*result_args, **result_kwargs)) def GetLoggingText(): 'Return text t...
'This function is called by CallWithRetryAsync if the asynchronous operation raises an exception. It returns true if a retry should be attempted.'
def MaybeRetryOnException(self, retry_func, type, value, tb):
def CheckRetry(): 'Retry should be attempted if the exception inspector function exists and returns true.' return (self.retry_policy.check_exception and self.retry_policy.check_exception(type, value, tb)) def GetLoggingText(): 'Return text that ...
'Helper function that determines whether a retry should be attempted. A retry is only attempted if "check_func" returns true. The "log_func" is invoked if a retry is attempted in order to get text that shows the context of the retry, and which will be logged.'
def _MaybeRetry(self, retry_func, check_retry_func, log_func):
self._num_tries += 1 if (self._num_tries >= self.retry_policy.max_tries): return False if (time.time() >= self._deadline): return False if (not check_retry_func()): return False if (not self._delay): self._delay = self.retry_policy.min_delay else: self._de...
'Returns a callback upon which the barrier will be gated. For completion, every callback returned via invocations of this method must be invoked. If \'key\' is not None, the result returned with the callback will be a dict. Otherwise, results (if any) will be returned as an ordered list.'
def Callback(self, key=None):
assert (self._type != _Barrier.EXC_BARRIER), 'exception barriers do not have results' if (key is not None): assert (self._type == _Barrier.DICT_BARRIER), 'this barrier is not configured as a dictionary of results' else: if (self._type == _Barrier.ARR...
'Invoked when all constituent async ops which this barrier is gated on have been launched. This is called from the BarrierContext\'s __exit__ method.'
def Start(self):
logging.debug('starting %s with %d async execution pathways...', _Barrier._types[self._type], self._cur) assert (self._state == _Barrier._INITIALIZING), 'barrier was already started' self._state = _Barrier._STARTED self._MaybeReturn()
'Called when an exception occurs during initialization or during async op execution. Discards all results, transitions the barrier to the FAULTED state, and invokes the \'_on_exception\' callback. Returns True if the exception should not be propagated further.'
def ReportException(self, type, value, tb):
if ((self._state == _Barrier._INITIALIZING) or (self._state == _Barrier._STARTED)): self._state = _Barrier._FAULTED self._results = None self._callback = None if (self._on_exception is not None): ioloop.IOLoop.current().add_callback(self._on_exception, type, value, tb) ...
'Return a human-readable format of the location of the barrier in the source code.'
def _FormatBarrierLocation(self):
return ('%s:%d' % (self._filename, self._lineno))
'Result callback for constituent asynchronous operations which the barrier is gated on. The results are aggregated in self._result based on \'*args\'.'
def _Invoke(self, *args):
assert (len(args) >= 1), args key = args[0] val = None if (len(args) > 1): val = (args[1] if (len(args) == 2) else args[1:]) if (self._state == _Barrier._FAULTED): logging.info(('discarding result %r intended for faulted barrier (%d): %r' % (key, self._cur, Fo...
'Schedules the barrier callback if the barrier has been started and all results have been received. If all results were empty, schedules the barrier callback with no arguments. If the barrier is a mono barrier, and the results are a list, schedules the callback with the list expanded into positional arguments. The cal...
def _MaybeReturn(self):
if ((self._n == 0) and (self._state == _Barrier._STARTED) and (self._type != _Barrier.EXC_BARRIER)): self._state = _Barrier._COMPLETED callback = self._callback self._callback = None results = self._results self._results = None if (self._type == _Barrier.BARRIER): ...
'The \'half_life\' is specified in seconds.'
def __init__(self, half_life, now=None):
self._half_life = half_life self._last_time = (now if (now is not None) else time.time()) self._value = 0
'QPS is the number of desired queries per second. \'unavailable_qps\' will be subtracted from \'qps\'. If \'qps_counter\' is not None, it is incremented when Add() is called. If \'backoff_counter\' is not None, it is incremented by the backoff time in seconds when ComputeBackoffSecs is called'
def __init__(self, qps, unavailable_qps=0.0, qps_counter=None, backoff_counter=None):
self._qps = qps self._unavailable_qps = unavailable_qps self._qps_counter = qps_counter self._backoff_counter = backoff_counter self.available = (self._qps - self._unavailable_qps) self.last_time = time.time()
'Return the actual rate-limit we want to use.'
def _GetQPS(self):
return (self._qps - self._unavailable_qps)
'Add qps * time_spent to available.'
def _Recompute(self):
now = time.time() delta = (now - self.last_time) limit = self._GetQPS() self.available += (limit * delta) self.available = max((- limit), min(limit, self.available)) self.last_time = now
'Specify the number of requests issued. Can be negative if correcting for a previous Add().'
def Add(self, requests):
self.available -= requests if (self._qps_counter is not None): self._qps_counter.increment(requests)
'Specify a new value for QPS. No need to verify ceilings on \'available\', ComputeBackoffSecs will do that.'
def SetQPS(self, new_qps):
self.available += (new_qps - self._qps) self._qps = new_qps
'Specify a new value for unavailable QPS. No need to verify ceilings on \'available\', ComputeBackoffSecs will do that.'
def SetUnavailableQPS(self, new_unavailable_qps):
self.available -= (new_unavailable_qps - self._unavailable_qps) self._unavailable_qps = new_unavailable_qps
'Return the number of backoff seconds needed to remain within the desired qps. This should be called only if the backoff will be done. To check whether backoff is needed without performing it, call NeedsBackoff.'
def ComputeBackoffSecs(self):
self._Recompute() if (self.available >= 0.0): return 0.0 else: backoff = min(1.0, math.fabs(((self.available - 1.0) / self._GetQPS()))) if (self._backoff_counter is not None): self._backoff_counter.increment(backoff) return backoff
'Returns whether or not we will need to backoff. This does not increment the backoff counter.'
def NeedsBackoff(self):
self._Recompute() return (self.available < 0.0)
'It is convenient to repeatedly use the "wait" method in order to create synchronous tests. If the async call raises an exception, then the wait method will re-raise that exception, which is desirable. However, when this happens, Tornado "remembers" the exception, and will re-throw it *every* time that wait is called f...
def wait(self, condition=None, timeout=5):
try: return super(BaseTestCase, self).wait(condition, timeout) finally: self._AsyncTestCase__failure = None
'Runs an async function which takes a callback argument. Waits for the function to complete and returns any result.'
def _RunAsync(self, func, *args, **kwargs):
func(callback=self.stop, *args, **kwargs) return self.wait()
'Override the run method in order to set the root logger to the NOTSET logging level, so that no logging done by the test case will be suppressed. Restore the original logging level once the test case has been run.'
def run(self, result=None):
logger = logging.getLogger() current_level = logger.level try: logger.setLevel('NOTSET') super(LogMatchTestCase, self).run(result) finally: logger.setLevel(current_level)
'Fail the test unless the intercepted log matches the regular expression.'
def assertLogMatches(self, expected_regexp, msg=None):
format = ('%s: %%r was not found in log' % (msg or "Regexp didn't match")) self._AssertLogMatches(expected_regexp, False, format)
'Fail the test if the intercepted log *does* match the regular expression.'
def assertNotLogMatches(self, expected_regexp, msg=None):
format = ('%s: %%r was found in log' % (msg or 'Regexp matches')) self._AssertLogMatches(expected_regexp, True, format)