desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Asynchronously get the current details about this queue. Args: rpc: An optional UserRPC object. Returns: A UserRPC object, call get_result to complete the RPC and obtain a QueueStatistics instance containing information about this queue.'
def fetch_statistics_async(self, rpc=None):
return QueueStatistics.fetch_async(self, rpc)
'Get the current details about this queue. Args: deadline: The maximum number of seconds to wait before aborting the method call. Returns: A QueueStatistics instance containing information about this queue. Error-subclass on application errors.'
def fetch_statistics(self, deadline=10):
_ValidateDeadline(deadline) rpc = create_rpc(deadline) self.fetch_statistics_async(rpc) return rpc.get_result()
'Constructor. Args: app_id: The application ID. host: The nginx host. service_name: Service name expected for all calls.'
def __init__(self, app_id, host, service_name='taskqueue'):
super(TaskQueueServiceStub, self).__init__(service_name, max_request_size=MAX_REQUEST_SIZE) self.__app_id = app_id self.__nginx_host = host
'Gets a list of TaskQueue proxies.'
def _GetTQLocations(self):
if os.path.exists(TASKQUEUE_PROXY_FILE): try: with open(TASKQUEUE_PROXY_FILE) as tq_file: ips = [ip for ip in tq_file.read().split('\n') if ip] except IOError: raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INTERNAL_ERROR) ...
'Creates a task name that the system can use to address tasks from different apps and queues. Args: app_name: The application name. queue_name: A str representing the queue name that the task goes in. user_chosen: A string name the user selected for their application. Returns: A randomized string representing a task na...
def _ChooseTaskName(self, app_name, queue_name, user_chosen=None):
RAND_LENGTH_SIZE = 32 if (not user_chosen): user_chosen = ''.join((random.choice((string.ascii_uppercase + string.digits)) for x in range(RAND_LENGTH_SIZE))) return ('task_%s_%s_%s' % (app_name, queue_name, user_chosen))
'Add a transactional task. Args: request: A taskqueue_service_pb.TaskQueueAddRequest. response: A taskqueue_service_pb.TaskQueueAddResponse. Returns: The taskqueue response.'
def _AddTransactionalBulkTask(self, request, response):
for add_request in request.add_request_list(): task_result = response.add_taskresult() task_name = None if add_request.has_task_name(): task_name = add_request.task_name() namespaced_name = self._ChooseTaskName(add_request.app_id(), add_request.queue_name(), user_chosen=t...
'Add a single task to a queue. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: The taskqueue_service_pb.TaskQueueAddRequest. See taskqueue_service.proto. response: The taskqueue_service_pb.TaskQueueAddResponse. See ta...
def _Dynamic_Add(self, request, response, request_id=None):
bulk_request = taskqueue_service_pb.TaskQueueBulkAddRequest() bulk_response = taskqueue_service_pb.TaskQueueBulkAddResponse() bulk_request.add_add_request().CopyFrom(request) self._Dynamic_BulkAdd(bulk_request, bulk_response, request_id) assert (bulk_response.taskresult_size() == 1) result = bul...
'Add many tasks to a queue using a single request. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: The taskqueue_service_pb.TaskQueueBulkAddRequest. See taskqueue_service.proto. response: The taskqueue_service_pb.Task...
def _Dynamic_BulkAdd(self, request, response, request_id=None):
assert request.add_request_size(), 'taskqueue should prevent empty requests' if request.add_request(0).has_transaction(): self._AddTransactionalBulkTask(request, response) return response port_file_location = os.path.join('/', 'etc', 'appscale', 'port-{}.txt'.format(self.__app_id...
'Local implementation of the UpdateQueue RPC in TaskQueueService. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueueUpdateQueueRequest. unused_response: A taskqueue_service_pb.TaskQueueUp...
def _Dynamic_UpdateQueue(self, request, unused_response, request_id=None):
self._RemoteSend(request, unused_response, 'UpdateQueue', request_id) return unused_response
'Local implementation of the FetchQueues RPC in TaskQueueService. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueueFetchQueuesRequest. response: A taskqueue_service_pb.TaskQueueFetchQueu...
def _Dynamic_FetchQueues(self, request, response, request_id=None):
self._RemoteSend(request, response, 'FetchQueues', request_id) return response
'Local \'random\' implementation of the TaskQueueService.FetchQueueStats. This implementation loads some stats from the task store, the rest with random numbers. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskq...
def _Dynamic_FetchQueueStats(self, request, response, request_id=None):
self._RemoteSend(request, response, 'FetchQueueStats', request_id) return response
'Local implementation of the TaskQueueService.QueryTasks RPC. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueueQueryTasksRequest. response: A taskqueue_service_pb.TaskQueueQueryTasksResp...
def _Dynamic_QueryTasks(self, request, response, request_id=None):
self._RemoteSend(request, response, 'QueryTasks', request_id) return response
'Local implementation of the TaskQueueService.FetchTask RPC. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueueFetchTaskRequest. response: A taskqueue_service_pb.TaskQueueFetchTaskRespons...
def _Dynamic_FetchTask(self, request, response, request_id=None):
self._RemoteSend(request, response, 'FetchTask', request_id) return response
'Local delete implementation of TaskQueueService.Delete. Deletes tasks from the task store. A 1/20 chance of a transient error. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueueDeleteReq...
def _Dynamic_Delete(self, request, response, request_id=None):
self._RemoteSend(request, response, 'Delete', request_id) return response
'Local force run implementation of TaskQueueService.ForceRun. Forces running of a task in a queue. This is a no-op here. This will fail randomly for testing. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue...
def _Dynamic_ForceRun(self, request, response, request_id=None):
self._RemoteSend(request, response, 'ForceRun', request_id) return response
'Local delete implementation of TaskQueueService.DeleteQueue. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueueDeleteQueueRequest. response: A taskqueue_service_pb.TaskQueueDeleteQueueRe...
def _Dynamic_DeleteQueue(self, request, response, request_id=None):
self._RemoteSend(request, response, 'DeleteQueue', request_id) return response
'Remote pause implementation of TaskQueueService.PauseQueue. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueuePauseQueueRequest. response: A taskqueue_service_pb.TaskQueuePauseQueueRespo...
def _Dynamic_PauseQueue(self, request, response, request_id=None):
self._RemoteSend(request, response, 'PauseQueue', request_id) return response
'Remote purge implementation of TaskQueueService.PurgeQueue. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueuePurgeQueueRequest. response: A taskqueue_service_pb.TaskQueuePurgeQueueRespo...
def _Dynamic_PurgeQueue(self, request, response, request_id=None):
self._RemoteSend(request, response, 'PurgeQueue', request_id) return response
'Remote delete implementation of TaskQueueService.DeleteGroup. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueueDeleteGroupRequest. response: A taskqueue_service_pb.TaskQueueDeleteGroupR...
def _Dynamic_DeleteGroup(self, request, response, request_id=None):
self._RemoteSend(request, response, 'DeleteGroup', request_id)
'Remote implementation of TaskQueueService.UpdateStorageLimit. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueueUpdateStorageLimitRequest. response: A taskqueue_service_pb.TaskQueueUpdat...
def _Dynamic_UpdateStorageLimit(self, request, response, request_id=None):
self._RemoteSend(request, response, 'UpdateStorageLimit', request_id)
'Local implementation of TaskQueueService.QueryAndOwnTasks. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueueQueryAndOwnTasksRequest. response: A taskqueue_service_pb.TaskQueueQueryAndOw...
def _Dynamic_QueryAndOwnTasks(self, request, response, request_id=None):
self._RemoteSend(request, response, 'QueryAndOwnTasks', request_id)
'Local implementation of TaskQueueService.ModifyTaskLease. Args: request: A taskqueue_service_pb.TaskQueueModifyTaskLeaseRequest. response: A taskqueue_service_pb.TaskQueueModifyTaskLeaseResponse. request_id: A string specifying the request ID.'
def _Dynamic_ModifyTaskLease(self, request, response, request_id=None):
self._RemoteSend(request, response, 'ModifyTaskLease', request_id)
'Sends a request remotely to the taskqueue server. Args: request: A protocol buffer request. response: A protocol buffer response. method: The function which is calling the remote server. request_id: A string specifying a request ID. Raises: taskqueue_service_pb.InternalError:'
def _RemoteSend(self, request, response, method, request_id=None):
tag = self.__app_id api_request = remote_api_pb.Request() api_request.set_method(method) api_request.set_service_name('taskqueue') api_request.set_request(request.Encode()) if (request_id is not None): api_request.set_request_id(request_id) tq_locations = self._GetTQLocations() f...
'Test the constructor.'
def test_taskqueue_service_stub(self):
tqd = flexmock(taskqueue_distributed.TaskQueueServiceStub) tqd.should_receive('_GetTQLocations').and_return(['some_location']) taskqueue_distributed.TaskQueueServiceStub('app_id', 'hostname')
'Constructor. Args: queue_yaml_parser: A function that takes no parameters and returns the parsed results of the queue.yaml file. If this queue is not based on a queue.yaml file use None. app_id: The app id this Group is representing or None if it is the currently running application. _all_queues_valid: Automatically g...
def __init__(self, queue_yaml_parser=None, app_id=None, _all_queues_valid=False, _update_newest_eta=None, _testing_validate_state=False):
self._queues = {} self._queue_yaml_parser = queue_yaml_parser self._all_queues_valid = _all_queues_valid self._next_task_id = 1 self._app_id = app_id if (_update_newest_eta is None): self._update_newest_eta = (lambda x: None) else: self._update_newest_eta = _update_newest_eta...
'Gets all the applications\'s queues. Returns: A list of dictionaries, where each dictionary contains one queue\'s attributes. E.g.: [{\'name\': \'some-queue\', \'max_rate\': \'1/s\', \'bucket_size\': 5, \'oldest_task\': \'2009/02/02 05:37:42\', \'eta_delta\': \'0:00:06.342511 ago\', \'tasks_in_queue\': 12, \'acl\': [\...
def GetQueuesAsDicts(self):
self._ReloadQueuesFromYaml() now = datetime.datetime.utcnow() queues = [] for (queue_name, queue) in sorted(self._queues.items()): queue_dict = {} queues.append(queue_dict) queue_dict['name'] = queue_name queue_dict['bucket_size'] = queue.bucket_capacity if (queue...
'Check if the specified queue_name references a valid queue. Args: queue_name: The name of the queue to check. Returns: True if the queue exists, False otherwise.'
def HasQueue(self, queue_name):
self._ReloadQueuesFromYaml() return ((queue_name in self._queues) and (self._queues[queue_name] is not None))
'Gets the _Queue instance for the specified queue. Args: queue_name: The name of the queue to fetch. Returns: The _Queue instance for the specified queue. Raises: KeyError if the queue does not exist.'
def GetQueue(self, queue_name):
self._ReloadQueuesFromYaml() return self._queues[queue_name]
'Finds the task with the lowest eta. Returns: A tuple containing the queue and task instance for the task with the lowest eta, or (None, None) if there are no tasks.'
def GetNextPushTask(self):
min_eta = INF result = (None, None) for queue in self._queues.itervalues(): if (queue.queue_mode == QUEUE_MODE.PULL): continue task = queue.OldestTask() if (not task): continue if (task.eta_usec() < min_eta): result = (queue, task) ...
'Update the queue map with the contents of the queue.yaml file. This function will remove queues that no longer exist in the queue.yaml file. If no queue yaml parser has been defined, this function is a no-op.'
def _ReloadQueuesFromYaml(self):
if (not self._queue_yaml_parser): return queue_info = self._queue_yaml_parser() if (queue_info and queue_info.queue): queues = queue_info.queue else: queues = [] old_queues = set(self._queues) new_queues = set() for entry in queues: queue_name = entry.name ...
'Tests if the specified queue exists and creates it if needed. This function replicates the behaviour of the taskqueue service by automatically creating the \'automatic\' queues when they are first accessed. Args: queue_name: The name queue of the queue to check. Returns: If there are no problems, returns TaskQueueServ...
def _ValidateQueueName(self, queue_name):
if (not queue_name): return taskqueue_service_pb.TaskQueueServiceError.INVALID_QUEUE_NAME elif (queue_name not in self._queues): if ((queue_name in AUTOMATIC_QUEUES) or self._all_queues_valid): self._ConstructAutomaticQueue(queue_name) else: return taskqueue_servi...
'Ensures the specified queue exists and creates it if needed. This function replicates the behaviour of the taskqueue service by automatically creating the \'automatic\' queues when they are first accessed. Args: queue_name: The name queue of the queue to check Raises: ApplicationError: If the queue name is invalid, to...
def _CheckQueueForRpc(self, queue_name):
self._ReloadQueuesFromYaml() response = self._ValidateQueueName(queue_name) if (response != taskqueue_service_pb.TaskQueueServiceError.OK): raise apiproxy_errors.ApplicationError(response)
'Returns a string containing a unique task name.'
def _ChooseTaskName(self):
self._next_task_id += 1 return ('task%d' % (self._next_task_id - 1))
'Checks that a TaskQueueAddRequest is valid. Checks that a TaskQueueAddRequest specifies a valid eta and a valid queue. Args: request: The taskqueue_service_pb.TaskQueueAddRequest to validate. now: A datetime.datetime object containing the current time in UTC. Returns: A taskqueue_service_pb.TaskQueueServiceError indic...
def _VerifyTaskQueueAddRequest(self, request, now):
if (request.eta_usec() < 0): return taskqueue_service_pb.TaskQueueServiceError.INVALID_ETA eta = datetime.datetime.utcfromtimestamp(_UsecToSec(request.eta_usec())) max_eta = (now + MAX_ETA) if (eta > max_eta): return taskqueue_service_pb.TaskQueueServiceError.INVALID_ETA queue_name_r...
'Add many tasks to a queue using a single request. Args: request: The taskqueue_service_pb.TaskQueueBulkAddRequest. See taskqueue_service.proto. response: The taskqueue_service_pb.TaskQueueBulkAddResponse. See taskqueue_service.proto.'
def BulkAdd_Rpc(self, request, response):
self._ReloadQueuesFromYaml() if (not request.add_request(0).queue_name()): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_QUEUE) error_found = False task_results_with_chosen_names = set() now = datetime.datetime.utcfromtimestamp(time.time()) for...
'Uses datastore.AddActions to associate tasks with a transaction. Args: request: The taskqueue_service_pb.TaskQueueBulkAddRequest containing the tasks to add. N.B. all tasks in the request have been validated and assigned unique names.'
def _TransactionalBulkAdd(self, request):
try: apiproxy_stub_map.MakeSyncCall('datastore_v3', 'AddActions', request, api_base_pb.VoidProto()) except apiproxy_errors.ApplicationError as e: raise apiproxy_errors.ApplicationError((e.application_error + taskqueue_service_pb.TaskQueueServiceError.DATASTORE_ERROR), e.error_detail)
'Adds tasks to the appropriate _Queue instance. Args: request: The taskqueue_service_pb.TaskQueueBulkAddRequest containing the tasks to add. N.B. all tasks in the request have been validated and those with empty names have been assigned unique names. response: The taskqueue_service_pb.TaskQueueBulkAddResponse to popula...
def _NonTransactionalBulkAdd(self, request, response, now):
queue_mode = request.add_request(0).mode() queue_name = request.add_request(0).queue_name() store = self._queues[queue_name] if (store.queue_mode != queue_mode): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INVALID_QUEUE_MODE) for (add_request, task_resul...
'Implementation of the UpdateQueue RPC. Args: request: A taskqueue_service_pb.TaskQueueUpdateQueueRequest. response: A taskqueue_service_pb.TaskQueueUpdateQueueResponse.'
def UpdateQueue_Rpc(self, request, response):
queue_name = request.queue_name() response = self._ValidateQueueName(queue_name) is_unknown_queue = (response == taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_QUEUE) if ((response != taskqueue_service_pb.TaskQueueServiceError.OK) and (not is_unknown_queue)): raise apiproxy_errors.Applicatio...
'Implementation of the FetchQueues RPC. Args: request: A taskqueue_service_pb.TaskQueueFetchQueuesRequest. response: A taskqueue_service_pb.TaskQueueFetchQueuesResponse.'
def FetchQueues_Rpc(self, request, response):
self._ReloadQueuesFromYaml() for queue_name in sorted(self._queues): if (response.queue_size() > request.max_rows()): break if (self._queues[queue_name] is None): continue self._queues[queue_name].FetchQueues_Rpc(request, response)
'Implementation of the FetchQueueStats rpc which returns \'random\' data. This implementation loads some stats from the task store, the rest are random numbers. Args: request: A taskqueue_service_pb.TaskQueueFetchQueueStatsRequest. response: A taskqueue_service_pb.TaskQueueFetchQueueStatsResponse.'
def FetchQueueStats_Rpc(self, request, response):
for queue_name in request.queue_name_list(): stats = response.add_queuestats() if (queue_name not in self._queues): stats.set_num_tasks(0) stats.set_oldest_eta_usec((-1)) continue store = self._queues[queue_name] stats.set_num_tasks(store.Count()) ...
'Implementation of the QueryTasks RPC. Args: request: A taskqueue_service_pb.TaskQueueQueryTasksRequest. response: A taskqueue_service_pb.TaskQueueQueryTasksResponse.'
def QueryTasks_Rpc(self, request, response):
self._CheckQueueForRpc(request.queue_name()) self._queues[request.queue_name()].QueryTasks_Rpc(request, response)
'Implementation of the FetchTask RPC. Args: request: A taskqueue_service_pb.TaskQueueFetchTaskRequest. response: A taskqueue_service_pb.TaskQueueFetchTaskResponse.'
def FetchTask_Rpc(self, request, response):
self._ReloadQueuesFromYaml() self._CheckQueueForRpc(request.queue_name()) self._queues[request.queue_name()].FetchTask_Rpc(request, response)
'Implementation of the Delete RPC. Deletes tasks from the task store. Args: request: A taskqueue_service_pb.TaskQueueDeleteRequest. response: A taskqueue_service_pb.TaskQueueDeleteResponse.'
def Delete_Rpc(self, request, response):
self._ReloadQueuesFromYaml() def _AddResultForAll(result): for _ in request.task_name_list(): response.add_result(result) if (request.queue_name() not in self._queues): _AddResultForAll(taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_QUEUE) elif (self._queues[request.queue...
'Implementation of the DeleteQueue RPC. Tombstones the queue. Args: request: A taskqueue_service_pb.TaskQueueDeleteQueueRequest. response: A taskqueue_service_pb.TaskQueueDeleteQueueResponse.'
def DeleteQueue_Rpc(self, request, response):
self._CheckQueueForRpc(request.queue_name()) self._queues[request.queue_name()] = None
'Implementation of the PauseQueue RPC. Args: request: A taskqueue_service_pb.TaskQueuePauseQueueRequest. response: A taskqueue_service_pb.TaskQueuePauseQueueResponse.'
def PauseQueue_Rpc(self, request, response):
self._CheckQueueForRpc(request.queue_name()) self._queues[request.queue_name()].paused = request.pause()
'Implementation of the PurgeQueue RPC. Args: request: A taskqueue_service_pb.TaskQueuePurgeQueueRequest. response: A taskqueue_service_pb.TaskQueuePurgeQueueResponse.'
def PurgeQueue_Rpc(self, request, response):
self._CheckQueueForRpc(request.queue_name()) self._queues[request.queue_name()].PurgeQueue()
'Implementation of the QueryAndOwnTasks RPC. Args: request: A taskqueue_service_pb.TaskQueueQueryAndOwnTasksRequest. response: A taskqueue_service_pb.TaskQueueQueryAndOwnTasksResponse.'
def QueryAndOwnTasks_Rpc(self, request, response):
self._CheckQueueForRpc(request.queue_name()) self._queues[request.queue_name()].QueryAndOwnTasks_Rpc(request, response)
'Implementation of the ModifyTaskLease RPC. Args: request: A taskqueue_service_pb.TaskQueueModifyTaskLeaseRequest. response: A taskqueue_service_pb.TaskQueueModifyTaskLeaseResponse.'
def ModifyTaskLease_Rpc(self, request, response):
self._CheckQueueForRpc(request.queue_name()) self._queues[request.queue_name()].ModifyTaskLease_Rpc(request, response)
'Constructor. Args: task: A taskqueue_service_pb.TaskQueueQueryTasksResponse_Task instance. May be None. queue: A _Queue instance. May be None.'
def __init__(self, task, queue):
if ((task is not None) and task.has_retry_parameters()): self._params = task.retry_parameters() elif ((queue is not None) and (queue.retry_parameters is not None)): self._params = queue.retry_parameters else: self._params = self._default_params
'Computes whether a task can be retried. Args: retry_count: An integer specifying which retry this is. age_usec: An integer specifying the microseconds since the first try. Returns: True if a task is eligible for retrying.'
def CanRetry(self, retry_count, age_usec):
if (self._params.has_retry_limit() and self._params.has_age_limit_sec()): return ((self._params.retry_limit() >= retry_count) or (self._params.age_limit_sec() >= _UsecToSec(age_usec))) if self._params.has_retry_limit(): return (self._params.retry_limit() >= retry_count) if self._params.has_a...
'Calculates time before the specified retry. Args: retry_count: An integer specifying which retry this is. Returns: The number of microseconds before a task should be retried.'
def CalculateBackoffUsec(self, retry_count):
exponent = min((retry_count - 1), self._params.max_doublings()) linear_steps = (retry_count - exponent) min_backoff_usec = _SecToUsec(self._params.min_backoff_sec()) max_backoff_usec = _SecToUsec(self._params.max_backoff_sec()) backoff_usec = min_backoff_usec if (exponent > 0): backoff_u...
'Ensures that all three indexes are in a valid state. This method is used by internal tests and should not need to be called in any other circumstances. Raises: AssertionError: if the indexes are not in a valid state.'
def VerifyIndexes(self):
assert self._IsInOrder(self._sorted_by_name) assert self._IsInOrder(self._sorted_by_eta) assert self._IsInOrder(self._sorted_by_tag) tasks_by_name = set() tasks_with_tags = set() for (name, task) in self._sorted_by_name: assert (name == task.task_name()) assert (name not in tasks...
'Determine if the specified list is in ascending order. Args: l: The list to check Returns: True if the list is in order, False otherwise'
@staticmethod def _IsInOrder(l):
sorted_list = sorted(l) return (l == sorted_list)
'Runs the decorated function within self._lock. Args: f: The function to be delegated to. Must be a member function (take self as the first parameter). Returns: The result of f.'
def _WithLock(f):
def _Inner(self, *args, **kwargs): with self._lock: ret = f(self, *args, **kwargs) if self._testing_validate_state: self.VerifyIndexes() return ret _Inner.__doc__ = f.__doc__ return _Inner
'Implementation of the UpdateQueue RPC. Args: request: A taskqueue_service_pb.TaskQueueUpdateQueueRequest. response: A taskqueue_service_pb.TaskQueueUpdateQueueResponse.'
@_WithLock def UpdateQueue_Rpc(self, request, response):
assert (request.queue_name() == self.queue_name) self.bucket_refill_per_second = request.bucket_refill_per_second() self.bucket_capacity = request.bucket_capacity() if request.has_user_specified_rate(): self.user_specified_rate = request.user_specified_rate() else: self.user_specifie...
'Fills out a queue message on the provided TaskQueueFetchQueuesResponse. Args: request: A taskqueue_service_pb.TaskQueueFetchQueuesRequest. response: A taskqueue_service_pb.TaskQueueFetchQueuesResponse.'
@_WithLock def FetchQueues_Rpc(self, request, response):
response_queue = response.add_queue() response_queue.set_queue_name(self.queue_name) response_queue.set_bucket_refill_per_second(self.bucket_refill_per_second) response_queue.set_bucket_capacity(self.bucket_capacity) if (self.user_specified_rate is not None): response_queue.set_user_specifie...
'Implementation of the QueryTasks RPC. Args: request: A taskqueue_service_pb.TaskQueueQueryTasksRequest. response: A taskqueue_service_pb.TaskQueueQueryTasksResponse.'
@_WithLock def QueryTasks_Rpc(self, request, response):
assert (not request.has_start_tag()) if request.has_start_eta_usec(): tasks = self._LookupNoAcquireLock(request.max_rows(), name=request.start_task_name(), eta=request.start_eta_usec()) else: tasks = self._LookupNoAcquireLock(request.max_rows(), name=request.start_task_name()) for task i...
'Implementation of the FetchTask RPC. Args: request: A taskqueue_service_pb.TaskQueueFetchTaskRequest. response: A taskqueue_service_pb.TaskQueueFetchTaskResponse.'
@_WithLock def FetchTask_Rpc(self, request, response):
task_name = request.task_name() pos = self._LocateTaskByName(task_name) if (pos is None): if (task_name in self.task_name_archive): error = taskqueue_service_pb.TaskQueueServiceError.TOMBSTONED_TASK else: error = taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_TASK...
'Implementation of the Delete RPC. Deletes tasks from the task store. We mimic a 1/20 chance of a TRANSIENT_ERROR when the request has an app_id. Args: request: A taskqueue_service_pb.TaskQueueDeleteRequest. response: A taskqueue_service_pb.TaskQueueDeleteResponse.'
@_WithLock def Delete_Rpc(self, request, response):
for taskname in request.task_name_list(): if (request.has_app_id() and (random.random() <= 0.05)): response.add_result(taskqueue_service_pb.TaskQueueServiceError.TRANSIENT_ERROR) else: response.add_result(self._DeleteNoAcquireLock(taskname))
'Implementation of the QueryAndOwnTasks RPC. Args: request: A taskqueue_service_pb.TaskQueueQueryAndOwnTasksRequest. response: A taskqueue_service_pb.TaskQueueQueryAndOwnTasksResponse.'
@_WithLock def QueryAndOwnTasks_Rpc(self, request, response):
if (self.queue_mode != QUEUE_MODE.PULL): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INVALID_QUEUE_MODE) lease_seconds = request.lease_seconds() if (lease_seconds < 0): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INV...
'Implementation of the ModifyTaskLease RPC. Args: request: A taskqueue_service_pb.TaskQueueQueryAndOwnTasksRequest. response: A taskqueue_service_pb.TaskQueueQueryAndOwnTasksResponse.'
@_WithLock def ModifyTaskLease_Rpc(self, request, response):
if (self.queue_mode != QUEUE_MODE.PULL): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INVALID_QUEUE_MODE) if self.paused: raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.QUEUE_PAUSED) lease_seconds = request.lease_seconds...
'Increment the retry count of a task by 1. Args: task_name: The name of the task to update.'
@_WithLock def IncRetryCount(self, task_name):
pos = self._LocateTaskByName(task_name) assert (pos is not None), 'Task does not exist when trying to increase retry count.' task = self._sorted_by_name[pos][1] self._IncRetryCount(task)
'Gets all of the tasks in this queue. Returns: A list of dictionaries, where each dictionary contains one task\'s attributes. E.g. [{\'name\': \'task-123\', \'queue_name\': \'default\', \'url\': \'/update\', \'method\': \'GET\', \'eta\': \'2009/02/02 05:37:42\', \'eta_delta\': \'0:00:06.342511 ago\', \'body\': \'\', \'...
@_WithLock def GetTasksAsDicts(self):
tasks = [] now = datetime.datetime.utcnow() for (_, _, task_response) in self._sorted_by_eta: tasks.append(QueryTasksResponseToDict(self.queue_name, task_response, now)) return tasks
'Gets a specific task from this queue. Returns: A dictionary containing one task\'s attributes. E.g. [{\'name\': \'task-123\', \'queue_name\': \'default\', \'url\': \'/update\', \'method\': \'GET\', \'eta\': \'2009/02/02 05:37:42\', \'eta_delta\': \'0:00:06.342511 ago\', \'body\': \'\', \'headers\': [(\'user-header\', ...
@_WithLock def GetTaskAsDict(self, task_name):
task_responses = self._LookupNoAcquireLock(maximum=1, name=task_name) if (not task_responses): return (task_response,) = task_responses if (task_response.task_name() != task_name): return now = datetime.datetime.utcnow() return QueryTasksResponseToDict(self.queue_name, task_respo...
'Removes all content from the queue.'
@_WithLock def PurgeQueue(self):
self._sorted_by_name = [] self._sorted_by_eta = [] self._sorted_by_tag = []
'Helper method for tests returning all tasks sorted by eta. Returns: A list of taskqueue_service_pb.TaskQueueQueryTasksResponse_Task objects sorted by eta.'
@_WithLock def _GetTasks(self):
return self._GetTasksNoAcquireLock()
'Helper method for tests returning all tasks sorted by eta. Returns: A list of taskqueue_service_pb.TaskQueueQueryTasksResponse_Task objects sorted by eta.'
def _GetTasksNoAcquireLock(self):
assert self._lock.locked() tasks = [] for (eta, task_name, task) in self._sorted_by_eta: tasks.append(task) return tasks
'Insert a task into the store, keeps lists sorted. Args: task: the new task.'
def _InsertTask(self, task):
assert self._lock.locked() eta = task.eta_usec() name = task.task_name() bisect.insort_left(self._sorted_by_eta, (eta, name, task)) if task.has_tag(): bisect.insort_left(self._sorted_by_tag, (task.tag(), eta, name, task)) bisect.insort_left(self._sorted_by_name, (name, task)) self.ta...
'Change the eta of a task to now. Args: task: The TaskQueueQueryTasksResponse_Task run now. This must be stored in this queue (otherwise an AssertionError is raised).'
@_WithLock def RunTaskNow(self, task):
self._PostponeTaskNoAcquireLock(task, 0, increase_retries=False)
'Postpone the task to a future time and increment the retry count. Args: task: The TaskQueueQueryTasksResponse_Task to postpone. This must be stored in this queue (otherwise an AssertionError is raised). new_eta_usec: The new eta to set on the task. This must be greater then the current eta on the task.'
@_WithLock def PostponeTask(self, task, new_eta_usec):
assert (new_eta_usec > task.eta_usec()) self._PostponeTaskNoAcquireLock(task, new_eta_usec)
'Lookup a number of sorted tasks from the store. If \'eta\' is specified, the tasks are looked up in a list sorted by \'eta\', then \'name\'. Otherwise they are sorted by \'name\'. We need to be able to sort by \'eta\' and \'name\' because tasks can have identical eta. If you had 20 tasks with the same ETA, you wouldn\...
@_WithLock def Lookup(self, maximum, name=None, eta=None):
return self._LookupNoAcquireLock(maximum, name, eta)
'Return the result of a \'scan\' over the given index. The scan is inclusive of start_key and exclusive of end_key. It returns at most max_rows from the index. Args: index: One of the index lists, eg self._sorted_by_tag. start_key: The key to start at. end_key: Optional end key. max_rows: The maximum number of rows to ...
def _IndexScan(self, index, start_key, end_key=None, max_rows=None):
assert self._lock.locked() start_pos = bisect.bisect_left(index, start_key) end_pos = INF if (end_key is not None): end_pos = bisect.bisect_left(index, end_key) if (max_rows is not None): end_pos = min(end_pos, (start_pos + max_rows)) end_pos = min(end_pos, len(index)) tasks ...
'Returns the number of tasks in the store.'
@_WithLock def Count(self):
return len(self._sorted_by_name)
'Returns the task with the oldest eta in the store.'
@_WithLock def OldestTask(self):
if self._sorted_by_eta: return self._sorted_by_eta[0][2] return None
'Returns the oldest eta in the store, or None if no tasks.'
@_WithLock def Oldest(self):
if self._sorted_by_eta: return self._sorted_by_eta[0][0] return None
'Locate the index of a task in _sorted_by_name list. If the task does not exist in the list, return None. Args: task_name: Name of task to be located. Returns: Index of the task in _sorted_by_name list if task exists, None otherwise.'
def _LocateTaskByName(self, task_name):
assert self._lock.locked() pos = bisect.bisect_left(self._sorted_by_name, (task_name,)) if ((pos >= len(self._sorted_by_name)) or (self._sorted_by_name[pos][0] != task_name)): return None return pos
'Inserts a new task into the store. Args: request: A taskqueue_service_pb.TaskQueueAddRequest. now: A datetime.datetime object containing the current time in UTC. Raises: apiproxy_errors.ApplicationError: If a task with the same name is already in the store, or the task is tombstoned.'
@_WithLock def Add(self, request, now):
if (self._LocateTaskByName(request.task_name()) is not None): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.TASK_ALREADY_EXISTS) if (request.task_name() in self.task_name_archive): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceErr...
'Deletes a task from the store by name. Args: name: the name of the task to delete. Returns: TaskQueueServiceError.UNKNOWN_TASK: if the task is unknown. TaskQueueServiceError.INTERNAL_ERROR: if the store is corrupted. TaskQueueServiceError.TOMBSTONED: if the task was deleted. TaskQueueServiceError.OK: otherwise.'
@_WithLock def Delete(self, name):
return self._DeleteNoAcquireLock(name)
'Remove a task from the specified index. Args: index: The index list that needs to be mutated. index_tuple: The tuple to search for in the index. task: The task instance that is expected to be stored at this location. Returns: True if the task was successfully removed from the index, False otherwise.'
def _RemoveTaskFromIndex(self, index, index_tuple, task):
assert self._lock.locked() pos = bisect.bisect_left(index, index_tuple) if (index[pos][(-1)] is not task): logging.debug('Expected %s, found %s', task, index[pos][(-1)]) return False index.pop(pos) return True
'Populates the store with a number of tasks. Args: num_tasks: the number of tasks to insert.'
@_WithLock def Populate(self, num_tasks):
def RandomTask(): 'Creates a new task and randomly populates values.' assert self._lock.locked() task = taskqueue_service_pb.TaskQueueQueryTasksResponse_Task() task.set_task_name(''.join((random.choice(string.ascii_lowercase) for x in range(20)))) task.se...
'Constructor. Args: default_host: a string to use as the host/port to connect to if the host header is not specified in the task. request_data: A request_info.RequestInfo instance used to look up state associated with the request that generated an API call.'
def __init__(self, default_host, request_data):
self._default_host = default_host self._request_data = request_data
'Constructs the http headers for the given task. This function will remove special headers (values in BUILT_IN_HEADERS) and add the taskqueue headers. Args: task: The task, a TaskQueueQueryTasksResponse_Task instance. queue: The queue that this task belongs to, an _Queue instance. Returns: A tuple of (header_dict, head...
def _HeadersFromTask(self, task, queue):
headers = [] header_dict = {} for header in task.header_list(): header_key_lower = header.key().lower() if (header_key_lower not in BUILT_IN_HEADERS): headers.append((header.key(), header.value())) header_dict.setdefault(header_key_lower, []).append(header.value()) ...
'Construct a http request from the task and dispatch it. Args: task: The task to convert to a http request and then send. An instance of taskqueue_service_pb.TaskQueueQueryTasksResponse_Task queue: The queue that this task belongs to. An instance of _Queue. Returns: Http Response code from the task\'s execution, 0 if a...
def ExecuteTask(self, task, queue):
method = task.RequestMethod_Name(task.method()) (header_dict, headers) = self._HeadersFromTask(task, queue) (connection_host,) = header_dict.get('host', [self._default_host]) if (connection_host is None): logging.error('Could not determine where to send the task "%s" (...
'Constructor. Args: group: The group that we will automatically execute tasks from. Must be an instance of _Group. task_executor: The class used to convert a task into a http request. Must be an instance of _TaskExecutor. retry_seconds: The number of seconds to delay a task by if its execution fails. _get_time: a calla...
def __init__(self, group, task_executor, retry_seconds, **kwargs):
self._group = group self._should_exit = False self._next_wakeup = INF self._event = threading.Event() self._wakeup_lock = threading.Lock() self.task_executor = task_executor self.default_retry_seconds = retry_seconds self._get_time = kwargs.pop('_get_time', time.time) if kwargs: ...
'Notify the TaskExecutor of the closest event it needs to process. Args: next_event_time: The time of the event in seconds since the epoch.'
def UpdateNextEventTime(self, next_event_time):
with self._wakeup_lock: if (next_event_time < self._next_wakeup): self._next_wakeup = next_event_time self._event.set()
'Request this TaskExecutor to exit.'
def Shutdown(self):
self._should_exit = True self._event.set()
'Block until we need to process a task or we need to exit.'
def _Wait(self):
now = self._get_time() while ((not self._should_exit) and (self._next_wakeup > now)): timeout = (self._next_wakeup - now) self._event.wait(timeout) self._event.clear() now = self._get_time()
'The main loop of the scheduler.'
def MainLoop(self):
while (not self._should_exit): self._ProcessQueues() self._Wait()
'Constructor. Args: service_name: Service name expected for all calls. root_path: Root path to the directory of the application which may contain a queue.yaml file. If None, then it\'s assumed no queue.yaml file is available. auto_task_running: When True, the dev_appserver should automatically run tasks after they are ...
def __init__(self, service_name='taskqueue', root_path=None, auto_task_running=False, task_retry_seconds=30, _all_queues_valid=False, default_http_server=None, _testing_validate_state=False, request_data=None):
super(TaskQueueServiceStub, self).__init__(service_name, max_request_size=MAX_REQUEST_SIZE, request_data=request_data) self._queues = {} self._all_queues_valid = _all_queues_valid self._root_path = root_path self._testing_validate_state = _testing_validate_state self._queues[None] = _Group(self....
'Start automatic task execution.'
def StartBackgroundExecution(self):
if ((not self._started) and self._auto_task_running): task_scheduler_thread = threading.Thread(target=self._task_scheduler.MainLoop) task_scheduler_thread.setDaemon(True) task_scheduler_thread.start() self._started = True
'Requests the task scheduler to shutdown.'
def Shutdown(self):
self._task_scheduler.Shutdown()
'Loads the queue.yaml file and parses it. Returns: None if queue.yaml doesn\'t exist, otherwise a queueinfo.QueueEntry object populated from the queue.yaml.'
def _ParseQueueYaml(self):
if hasattr(self, 'queue_yaml_parser'): return self.queue_yaml_parser(self._root_path) if (self._root_path is None): return None for queueyaml in ('queue.yaml', 'queue.yml'): try: path = os.path.join(self._root_path, queueyaml) modified = os.stat(path).st_mtime...
'Enqueue a task to be automatically scheduled. Note: If auto task running is disabled, this function is a no-op. Args: callback_time: The earliest time this task may be run, in seconds since the epoch.'
def _UpdateNextEventTime(self, callback_time):
self._task_scheduler.UpdateNextEventTime(callback_time)
'Get the _Group instance for app_id, creating a new one if needed. Args: app_id: The app id in question. Note: This field is not validated.'
def _GetGroup(self, app_id=None):
if (app_id not in self._queues): self._queues[app_id] = _Group(app_id=app_id, _all_queues_valid=self._all_queues_valid, _testing_validate_state=self._testing_validate_state) return self._queues[app_id]
'Add a single task to a queue. This method is a wrapper around the BulkAdd RPC request. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: The taskqueue_service_pb.TaskQueueAddRequest. See taskqueue_service.proto. respon...
def _Dynamic_Add(self, request, response):
bulk_request = taskqueue_service_pb.TaskQueueBulkAddRequest() bulk_response = taskqueue_service_pb.TaskQueueBulkAddResponse() bulk_request.add_add_request().CopyFrom(request) self._Dynamic_BulkAdd(bulk_request, bulk_response) assert (bulk_response.taskresult_size() == 1) result = bulk_response.t...
'Add many tasks to a queue using a single request. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: The taskqueue_service_pb.TaskQueueBulkAddRequest. See taskqueue_service.proto. response: The taskqueue_service_pb.Task...
def _Dynamic_BulkAdd(self, request, response):
assert request.add_request_size(), 'taskqueue should prevent empty requests' self._GetGroup(_GetAppId(request.add_request(0))).BulkAdd_Rpc(request, response)
'Gets all the application\'s queues. Returns: A list of dictionaries, where each dictionary contains one queue\'s attributes. E.g.: [{\'name\': \'some-queue\', \'max_rate\': \'1/s\', \'bucket_size\': 5, \'oldest_task\': \'2009/02/02 05:37:42\', \'eta_delta\': \'0:00:06.342511 ago\', \'tasks_in_queue\': 12}, ...] The li...
def GetQueues(self):
return self._GetGroup().GetQueuesAsDicts()
'Gets a queue\'s tasks. Args: queue_name: Queue\'s name to return tasks for. Returns: A list of dictionaries, where each dictionary contains one task\'s attributes. E.g. [{\'name\': \'task-123\', \'queue_name\': \'default\', \'url\': \'/update\', \'method\': \'GET\', \'eta\': \'2009/02/02 05:37:42\', \'eta_delta\': \'0...
def GetTasks(self, queue_name):
return self._GetGroup().GetQueue(queue_name).GetTasksAsDicts()
'Deletes a task from a queue, without leaving a tombstone. Args: queue_name: the name of the queue to delete the task from. task_name: the name of the task to delete.'
def DeleteTask(self, queue_name, task_name):
if self._GetGroup().HasQueue(queue_name): queue = self._GetGroup().GetQueue(queue_name) queue.Delete(task_name) queue.task_name_archive.discard(task_name)
'Removes all tasks from a queue, without leaving tombstones. Args: queue_name: the name of the queue to remove tasks from.'
def FlushQueue(self, queue_name):
if self._GetGroup().HasQueue(queue_name): self._GetGroup().GetQueue(queue_name).PurgeQueue() self._GetGroup().GetQueue(queue_name).task_name_archive.clear()