desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Create a PushQueue object. Args: queue_info: A dictionary containing queue info. app: A string containing the application ID.'
def __init__(self, queue_info, app):
self.rate = self.DEFAULT_RATE if ('rate' in queue_info): self.rate = queue_info['rate'] self.task_age_limit = self.DEFAULT_AGE_LIMIT self.min_backoff_seconds = self.DEFAULT_MIN_BACKOFF self.max_backoff_seconds = self.DEFAULT_MAX_BACKOFF self.max_doublings = self.DEFAULT_MAX_DOUBLINGS ...
'Generates a string representation of the queue. Returns: A string representing the PushQueue.'
def __repr__(self):
attributes = {'app': self.app, 'task_retry_limit': self.task_retry_limit} for attribute in self.OPTIONAL_ATTRS: if hasattr(self, attribute): attributes[attribute] = getattr(self, attribute) attr_str = ', '.join(('{}={}'.format(attr, val) for (attr, val) in attributes.iteritems())) ...
'Create a PullQueue object. Args: queue_info: A dictionary containing queue info. app: A string containing the application ID. db_access: A DatastoreProxy object.'
def __init__(self, queue_info, app, db_access=None):
self.db_access = db_access self.index_cache = {'global': {}, 'by_tag': {}} self.index_cache_lock = Lock() super(PullQueue, self).__init__(queue_info, app)
'Adds a task to the queue. Args: task: A Task object. retries: The number of times to retry adding the task. Raises: InvalidTaskInfo if the task ID already exists in the queue.'
def add_task(self, task, retries=5):
if (not hasattr(task, 'payloadBase64')): raise InvalidTaskInfo('{} is missing a payload.'.format(task)) enqueue_time = datetime.datetime.utcnow() try: lease_expires = task.leaseTimestamp except AttributeError: lease_expires = datetime.datetime.utcfromtimestamp(0) ...
'Gets a task from the queue. Args: task: A Task object. omit_payload: A boolean indicating that the payload should not be fetched. Returns: A task object or None.'
def get_task(self, task, omit_payload=False):
payload = 'payload,' if omit_payload: payload = '' select_task = '\n SELECT {payload} enqueued, lease_expires, retry_count, tag\n FROM pull_queue_tasks\n WHERE app = %(app)s AND queue = %(queu...
'Deletes a task from the queue. Args: task: A Task object.'
def delete_task(self, task):
task = self.get_task(task, omit_payload=True) if (task is not None): self._delete_task_and_index(task)
'Updates the duration of a task lease. Args: task: A Task object. new_lease_seconds: An integer specifying when to set the new ETA. It represents the number of seconds from now. retries: The number of times to try the update. Returns: A Task object.'
def update_lease(self, task, new_lease_seconds, retries=5):
new_eta = (current_time_ms() + datetime.timedelta(seconds=new_lease_seconds)) parameters = {'app': self.app, 'queue': self.name, 'id': task.id, 'old_eta': task.get_eta(), 'new_eta': new_eta, 'current_time': datetime.datetime.utcnow(), 'op_id': uuid.uuid4()} self._update_lease(parameters, retries) task.l...
'Updates leased tasks. Args: task: A task object. new_lease_seconds: An integer specifying when to set the new ETA. It represents the number of seconds from now. retries: The number of times to try the update.'
def update_task(self, task, new_lease_seconds, retries=5):
new_eta = (current_time_ms() + datetime.timedelta(seconds=new_lease_seconds)) parameters = {'app': self.app, 'queue': self.name, 'id': task.id, 'new_eta': new_eta, 'current_time': datetime.datetime.utcnow(), 'op_id': uuid.uuid4()} try: old_eta = task.leaseTimestamp except AttributeError: ...
'List all non-deleted tasks in the queue. Args: limit: An integer specifying the maximum number of tasks to list. Returns: A list of Task objects.'
def list_tasks(self, limit=100):
session = self.db_access.session tasks = [] start_date = datetime.datetime.utcfromtimestamp(0) while True: query_tasks = '\n SELECT eta, id FROM pull_queue_tasks_index\n WHERE token(app, queue, eta) > token(...
'Acquires a lease on tasks from the queue. Args: num_tasks: An integer specifying the number of tasks to lease. lease_seconds: An integer specifying how long to lease the tasks. group_by_tag: A boolean indicating that only tasks of one tag should be leased. tag: A string containing the tag for the task. Returns: A list...
def lease_tasks(self, num_tasks, lease_seconds, group_by_tag=False, tag=None):
if (num_tasks > self.MAX_LEASE_AMOUNT): raise InvalidLeaseRequest('Only {} tasks can be leased at a time'.format(self.MAX_LEASE_AMOUNT)) if (lease_seconds > self.MAX_LEASE_TIME): raise InvalidLeaseRequest('Tasks can only be leased for up to {} s...
'Get the total number of tasks in the queue. Returns: An integer specifying the number of tasks in the queue.'
def total_tasks(self):
select_count = "\n SELECT COUNT(*) FROM pull_queue_tasks\n WHERE token(app, queue, id) >= token(%(app)s, %(queue)s, '')\n AND token(app, queue, id) < token(%(app)s, %(next_queue)s, '')\n ...
'Get the ETA of the oldest task Returns: A datetime object specifying the oldest ETA or None if there are no tasks.'
def oldest_eta(self):
session = self.db_access.session select_oldest = '\n SELECT eta FROM pull_queue_tasks_index\n WHERE token(app, queue, eta) >= token(%(app)s, %(queue)s, 0)\n AND token(app, queue, eta) < token(%(app)...
'Remove all tasks from queue. Cassandra cannot perform a range scan during a delete, so this function selects all the tasks before deleting them one at a time.'
def purge(self):
select_tasks = "\n SELECT id, enqueued, lease_expires FROM pull_queue_tasks\n WHERE token(app, queue, id) >= token(%(app)s, %(queue)s, '')\n AND token(app, queue, id) < token(%(app)s, %(next_qu...
'Generate a JSON representation of the queue. Args: include_stats: A boolean indicating whether or not to include stats. fields: A tuple of fields to include in the output. Returns: A string in JSON format representing the queue.'
def to_json(self, include_stats=False, fields=None):
if (fields is None): fields = QUEUE_FIELDS queue = {} if ('kind' in fields): queue['kind'] = 'taskqueues#taskqueue' if ('id' in fields): queue['id'] = self.name if ('maxLeases' in fields): queue['maxLeases'] = self.task_retry_limit stat_fields = () for field i...
'Checks if the task entry was last mutated with the given ID. Args: task_id: A string specifying the task ID. op_id: A uuid identifying a process that tried to mutate the task. Returns: A boolean indicating that the task was last mutated with the ID.'
def _task_mutated_by_id(self, task_id, op_id):
select_statement = SimpleStatement('\n SELECT op_id FROM pull_queue_tasks\n WHERE app = %(app)s AND queue = %(queue)s AND id = %(id)s\n ', consistency_level=ConsistencyLevel.SERIAL) parameters = {'app': self.a...
'Insert task entry into pull_queue_tasks. Args: parameters: A dictionary specifying the task parameters. retries: The number of times to try the insert. Raises: InvalidTaskInfo if the task ID already exists in the queue.'
def _insert_task(self, parameters, retries):
insert_statement = SimpleStatement('\n INSERT INTO pull_queue_tasks (\n app, queue, id, payload,\n enqueued, lease_expires, retry_count, tag, op_id\n )\n V...
'Update lease expiration on a task entry. Args: parameters: A dictionary specifying the new parameters. retries: The number of times to try the update. check_lease: A boolean specifying that the old lease_expires field must match the one provided. Raises: InvalidLeaseRequest if the lease has already expired.'
def _update_lease(self, parameters, retries, check_lease=True):
update_task = '\n UPDATE pull_queue_tasks\n SET lease_expires = %(new_eta)s, op_id = %(op_id)s\n WHERE app = %(app)s AND queue = %(queue)s AND id = %(id)s\n IF lease_e...
'Query the index table for available tasks. Args: num_tasks: An integer specifying the number of tasks to lease. group_by_tag: A boolean indicating that only tasks of one tag should be leased. tag: A string containing the tag for the task. Returns: A list of results from the index table.'
def _query_index(self, num_tasks, group_by_tag=False, tag=None):
if group_by_tag: query_tasks = '\n SELECT eta, id FROM pull_queue_tasks_index\n WHERE token(app, queue, eta) >= token(%(app)s, %(queue)s, 0)\n AND token(app, queue, eta) ...
'Query the cache or index table for available tasks. Args: num_tasks: An integer specifying the number of tasks to lease. group_by_tag: A boolean indicating that only tasks of one tag should be leased. tag: A string containing the tag for the task. Returns: A list of index results.'
def _query_available_tasks(self, num_tasks, group_by_tag=False, tag=None):
if (num_tasks > self.MAX_CACHE_SIZE): return self._query_index(num_tasks, group_by_tag, tag) with self.index_cache_lock: if group_by_tag: if (tag not in self.index_cache['by_tag']): self.index_cache['by_tag'][tag] = {} tag_cache = self.index_cache['by_tag'...
'Get the tag with the earliest ETA. Returns: A string containing a tag or None.'
def _get_earliest_tag(self):
get_earliest_tag = '\n SELECT tag FROM pull_queue_tasks_index WHERE tag_exists = true LIMIT 1\n ' try: tag = self.db_access.session.execute(get_earliest_tag)[0].tag except IndexError: return None return tag
'Update retry count for a task. Args: task: A Task object.'
def _increment_count_async(self, task):
session = self.db_access.session statement = '\n UPDATE pull_queue_tasks\n SET retry_count=?\n WHERE app=? AND queue=? AND id=?\n IF retry_count=?\n ' if (statement not in self....
'Acquires a lease on tasks in the queue. Args: indexes: An iterable containing results from the index table. new_eta: A datetime object containing the new lease expiration. Returns: A list of task objects or None if unable to acquire a lease.'
def _lease_batch(self, indexes, new_eta):
leased = [None for _ in indexes] session = self.db_access.session op_id = uuid.uuid4() lease_statement = '\n UPDATE pull_queue_tasks\n SET lease_expires = ?, op_id = ?\n WHERE app = ? AND queue = ...
'Updates the index table after leasing a task. Args: old_index: The row to remove from the index table. task: A Task object to create a new index entry for. Returns: A cassandra-driver future.'
def _update_index_async(self, old_index, task):
session = self.db_access.session old_eta = old_index.eta update_index = BatchStatement(retry_policy=BASIC_RETRIES) statement = '\n DELETE FROM pull_queue_tasks_index\n WHERE app=?\n AND queue=?\n AND ...
'Deletes an index entry for a task. Args: eta: A datetime object. task_id: A string containing the task ID.'
def _delete_index(self, eta, task_id):
delete_index = '\n DELETE FROM pull_queue_tasks_index\n WHERE app = %(app)s\n AND queue = %(queue)s\n AND eta = %(eta)s\n AND id = %(id)s\n ' ...
'Deletes a task and its index atomically. Args: task: A Task object.'
def _delete_task_and_index(self, task, retries=5):
delete_task = SimpleStatement('\n DELETE FROM pull_queue_tasks\n WHERE app = %(app)s AND queue = %(queue)s AND id = %(id)s\n IF EXISTS\n ', retry_policy=NO_RETRIES) parameters = {'app': ...
'Cleans up expired tasks and indices. Args: index: An index result.'
def _resolve_task(self, index):
task = self.get_task(Task({'id': index.id}), omit_payload=True) if (task is None): self._delete_index(index.eta, index.id) return if ((self.task_retry_limit != 0) and task.expired(self.task_retry_limit)): self._delete_task_and_index(task) return if (task.leaseTimestamp !=...
'Write queue metadata for keeping track of statistics.'
def _update_stats(self):
session = self.db_access.session ttl = (60 * 60) statement = '\n INSERT INTO pull_queue_leases (app, queue, leased)\n VALUES (?, ?, ?)\n USING TTL {ttl}\n '.format(ttl=ttl) if (statement not...
'Fetch queue statistics. Args: fields: A tuple of fields to include in the results. Returns: A dictionary containing queue statistics.'
def _get_stats(self, fields):
session = self.db_access.session stats = {} if ('totalTasks' in fields): stats['totalTasks'] = self.total_tasks() if ('oldestTask' in fields): epoch = datetime.datetime.utcfromtimestamp(0) oldest_eta = (self.oldest_eta() or epoch) stats['oldestTask'] = int((oldest_eta - e...
'Generates a string representation of the queue. Returns: A string representing the PullQueue.'
def __repr__(self):
return '<PullQueue {}: app={}, task_retry_limit={}>'.format(self.name, self.app, self.task_retry_limit)
'Kind name override.'
@classmethod def kind(cls):
return cls.STORED_KIND_NAME
'DistributedTaskQueue Constructor. Args: db_access: A DatastoreProxy object. zk_client: A KazooClient.'
def __init__(self, db_access, zk_client):
setup_env() db_proxy = appscale_info.get_db_proxy() connection_str = '{}:{}'.format(db_proxy, str(constants.DB_SERVER_PORT)) ds_distrib = datastore_distributed.DatastoreDistributed(constants.DASHBOARD_APP_ID, connection_str, require_indexes=False) apiproxy_stub_map.apiproxy.RegisterStub('datastore_v...
'Fetches a Queue object. Args: app: A string containing the application ID. queue: A string specifying the name of the queue. Returns: A Queue object or None.'
def get_queue(self, app, queue):
try: return self.queue_manager[app][queue] except KeyError: return None
'Parses JSON and validates that it contains the proper tags. Args: json_request: A JSON string. tags: The tags to validate if they are in the JSON string. Returns: A dictionary dumped from the JSON string.'
def __parse_json_and_validate_tags(self, json_request, tags):
try: json_response = json.loads(json_request) except ValueError: json_response = {'error': True, 'reason': 'Badly formed JSON'} return json_response for tag in tags: if (tag not in json_response): json_response = {'error': True, 'reason': (('Missing ' + t...
'Gets statistics about tasks in queues. Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def fetch_queue_stats(self, app_id, http_data):
epoch = datetime.datetime.utcfromtimestamp(0) request = taskqueue_service_pb.TaskQueueFetchQueueStatsRequest(http_data) response = taskqueue_service_pb.TaskQueueFetchQueueStatsResponse() for queue_name in request.queue_name_list(): queue = self.get_queue(app_id, queue_name) stats_respons...
'Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def purge_queue(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueuePurgeQueueRequest(http_data) response = taskqueue_service_pb.TaskQueuePurgeQueueResponse() queue = self.get_queue(app_id, request.queue_name()) queue.purge() return (response.Encode(), 0, '')
'Delete a task. Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def delete(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueueDeleteRequest(http_data) response = taskqueue_service_pb.TaskQueueDeleteResponse() queue = self.get_queue(app_id, request.queue_name()) for task_name in request.task_name_list(): queue.delete_task(Task({'id': task_name})) response.add_result(taskqu...
'Lease pull queue tasks. Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def query_and_own_tasks(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueueQueryAndOwnTasksRequest(http_data) response = taskqueue_service_pb.TaskQueueQueryAndOwnTasksResponse() queue = self.get_queue(app_id, request.queue_name()) tag = None if request.has_tag(): tag = request.tag() try: tasks = queue.lease_tasks(...
'Adds a single task to the task queue. Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def add(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueueAddRequest(http_data) request.set_app_id(app_id) response = taskqueue_service_pb.TaskQueueAddResponse() bulk_request = taskqueue_service_pb.TaskQueueBulkAddRequest() bulk_response = taskqueue_service_pb.TaskQueueBulkAddResponse() bulk_request.add_add_reque...
'Adds multiple tasks to the task queue. Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def bulk_add(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueueBulkAddRequest(http_data) response = taskqueue_service_pb.TaskQueueBulkAddResponse() self.__bulk_add(request, response) return (response.Encode(), 0, '')
'Function for bulk adding tasks. Args: request: taskqueue_service_pb.TaskQueueBulkAddRequest. response: taskqueue_service_pb.TaskQueueBulkAddResponse. Raises: apiproxy_error.ApplicationError.'
def __bulk_add(self, request, response):
if (request.add_request_size() == 0): return now = datetime.datetime.utcfromtimestamp(time.time()) error_found = False for add_request in request.add_request_list(): task_result = response.add_taskresult() if (add_request.has_mode() and (add_request.mode() == taskqueue_service_pb...
'Maps an int index to a string. Args: method: int representing a http method. Returns: A string version of the method.'
def __method_mapping(self, method):
if (method == taskqueue_service_pb.TaskQueueQueryTasksResponse_Task.GET): return 'GET' elif (method == taskqueue_service_pb.TaskQueueQueryTasksResponse_Task.POST): return 'POST' elif (method == taskqueue_service_pb.TaskQueueQueryTasksResponse_Task.HEAD): return 'HEAD' elif (metho...
'Tries to fetch the taskqueue name, if it exists it will raise an exception. We store a receipt of each enqueued task in the datastore. If we find that task in the datastore, we will raise an exception. If the task is not in the datastore, then it is assumed this is the first time seeing the tasks and we create a recei...
def __check_and_store_task_names(self, request):
task_name = request.task_name() item = TaskName.get_by_key_name(task_name) logger.debug('Task name {0}'.format(task_name)) if item: logger.warning('Task already exists') raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.TASK_ALREADY_EXISTS) ...
'Enqueues a batch of push tasks. Args: request: A taskqueue_service_pb.TaskQueueAddRequest.'
def __enqueue_push_task(self, request):
self.__validate_push_task(request) self.__check_and_store_task_names(request) args = self.get_task_args(request) headers = self.get_task_headers(request) countdown = (int(headers['X-AppEngine-TaskETA']) - int(datetime.datetime.now().strftime('%s'))) push_queue = self.get_queue(request.app_id(), ...
'Gets the task args used when making a task web request. Args: request: A taskqueue_service_pb.TaskQueueAddRequest. Returns: A dictionary used by a task worker.'
def get_task_args(self, request):
args = {} args['task_name'] = request.task_name() args['url'] = request.url() args['app_id'] = request.app_id() args['queue_name'] = request.queue_name() args['method'] = self.__method_mapping(request.method()) args['body'] = request.body() args['payload'] = request.payload() args['d...
'Gets the task headers used for a task web request. Args: request: A taskqueue_service_pb.TaskQueueAddRequest Returns: A dictionary of key/values for a web request.'
def get_task_headers(self, request):
headers = {} for header in request.header_list(): headers[header.key()] = header.value() eta = self.__when_to_run(request) secret = appscale_info.get_secret() secret_hash = hashlib.sha1(((request.app_id() + '/') + secret)).hexdigest() headers['X-AppEngine-Fake-Is-Admin'] = secret_hash ...
'Returns a datetime object of when a task should execute. Args: request: A taskqueue_service_pb.TaskQueueAddRequest. Returns: A datetime object for when the nearest time to run the task is.'
def __when_to_run(self, request):
if request.has_eta_usec(): eta = request.eta_usec() return datetime.datetime.fromtimestamp((eta / 1000000)) else: return datetime.datetime.now()
'Returns a datetime object of when a task should expire. Args: request: A taskqueue_service_pb.TaskQueueAddRequest. Returns: A datetime object of when the task should expire.'
def __when_to_expire(self, request):
if (request.has_retry_parameters() and request.retry_parameters().has_age_limit_sec()): limit = request.retry_parameters().age_limit_sec() return (datetime.datetime.now() + datetime.timedelta(seconds=limit)) else: return (datetime.datetime.now() + datetime.timedelta(days=self.DEFAULT_EXP...
'Checks to make sure the task request is valid. Args: request: A taskqueue_service_pb.TaskQueueAddRequest. Raises: apiproxy_errors.ApplicationError upon invalid tasks.'
def __validate_push_task(self, request):
if (not request.has_queue_name()): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INVALID_QUEUE_NAME) if (not request.has_task_name()): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INVALID_TASK_NAME) if (not request.has_...
'Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def modify_task_lease(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueueModifyTaskLeaseRequest(http_data) response = taskqueue_service_pb.TaskQueueModifyTaskLeaseResponse() queue = self.get_queue(app_id, request.queue_name()) task_info = {'id': request.task_name()} try: task = queue.update_task(Task(task_info), request.lea...
'Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def fetch_queue(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueueFetchQueuesRequest(http_data) response = taskqueue_service_pb.TaskQueueFetchQueuesResponse() return (response.Encode(), 0, '')
'Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def query_tasks(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueueQueryTasksRequest(http_data) response = taskqueue_service_pb.TaskQueueQueryTasksResponse() return (response.Encode(), 0, '')
'Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def fetch_task(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueueFetchTaskRequest(http_data) response = taskqueue_service_pb.TaskQueueFetchTaskResponse() return (response.Encode(), 0, '')
'Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def force_run(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueueForceRunRequest(http_data) response = taskqueue_service_pb.TaskQueueForceRunResponse() return (response.Encode(), 0, '')
'Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def pause_queue(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueuePauseQueueRequest(http_data) response = taskqueue_service_pb.TaskQueuePauseQueueResponse() return (response.Encode(), 0, '')
'Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def delete_group(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueueDeleteGroupRequest(http_data) response = taskqueue_service_pb.TaskQueueDeleteGroupResponse() return (response.Encode(), 0, '')
'Args: app_id: The application ID. http_data: The payload containing the protocol buffer request. Returns: A tuple of a encoded response, error code, and error detail.'
def update_storage_limit(self, app_id, http_data):
request = taskqueue_service_pb.TaskQueueUpdateStorageLimitRequest(http_data) response = taskqueue_service_pb.TaskQueueUpdateStorageLimitResponse() return (response.Encode(), 0, '')
'Removes any questionable characters which might be apart of a remote attack. Args: str_input: The string to cleanse. Returns: A string which has questionable characters replaced.'
def __cleanse(self, str_input):
for char in '~./\\!@#$%&*()]\\+=|': str_input = str_input.replace(char, '_') return str_input
'Determines if the hostname is that of the current host. Args: hostname: A string representing the hostname. Returns: True if its the localhost, false otherwise.'
def __is_localhost(self, hostname):
if (socket.gethostname() == hostname): return True elif (socket.gethostbyname(socket.gethostname()) == hostname): return True else: return False
'Provide access to the queue handler.'
def initialize(self, queue_handler):
self.queue_handler = queue_handler
'Return info about an existing queue. Args: project: A string containing an application ID. queue: A string containing a queue name.'
def get(self, project, queue):
queue = self.queue_handler.get_queue(project, queue) if (queue is None): write_error(self, HTTPCodes.NOT_FOUND, 'Queue not found.') return if (not isinstance(queue, PullQueue)): write_error(self, HTTPCodes.BAD_REQUEST, 'The REST API is only applicable to pu...
'Provide access to the queue handler.'
def initialize(self, queue_handler):
self.queue_handler = queue_handler
'List all non-deleted tasks in a queue, whether or not they are currently leased, up to a maximum of 100. Args: project: A string containing an application ID. queue: A string containing a queue name.'
def get(self, project, queue):
requested_fields = self.get_argument('fields', None) if (requested_fields is None): fields = ('kind', {'items': TASK_FIELDS}) else: fields = parse_fields(requested_fields) queue = self.queue_handler.get_queue(project, queue) if (queue is None): write_error(self, HTTPCodes.NOT...
'Insert a task into an existing queue. Args: project: A string containing an application ID. queue: A string containing a queue name.'
def post(self, project, queue):
try: task_info = tornado.escape.json_decode(self.request.body) except ValueError: write_error(self, HTTPCodes.BAD_REQUEST, 'The request body must contain a task.') return if ('payloadBase64' not in task_info): write_error(self, HTTPCodes.BAD_REQUEST, 'payloa...
'Provide access to the queue handler.'
def initialize(self, queue_handler):
self.queue_handler = queue_handler
'Acquire a lease on the topmost N unowned tasks in a queue. Args: project: A string containing an application ID. queue: A string containing a queue name.'
def post(self, project, queue):
try: lease_seconds = int(self.get_argument('leaseSecs')) except MissingArgumentError: write_error(self, HTTPCodes.BAD_REQUEST, 'Required parameter leaseSecs not specified.') return except ValueError: write_error(self, HTTPCodes.BAD_REQUEST, 'leaseSecs must b...
'Provide access to the queue handler.'
def initialize(self, queue_handler):
self.queue_handler = queue_handler
'Get the named task in a queue. Args: project: A string containing an application ID. queue: A string containing a queue name. task: A string containing a task ID.'
def get(self, project, queue, task):
task = Task({'id': task, 'queueName': queue}) requested_fields = self.get_argument('fields', None) if (requested_fields is None): fields = TASK_FIELDS else: fields = parse_fields(requested_fields) omit_payload = False if ('payloadBase64' not in fields): omit_payload = Tru...
'Update the duration of a task lease. Args: project: A string containing an application ID. queue: A string containing a queue name. task: A string containing a task ID.'
def post(self, project, queue, task):
try: task_info = tornado.escape.json_decode(self.request.body) except ValueError: write_error(self, HTTPCodes.BAD_REQUEST, 'The request body must contain a task.') return if ('leaseTimestamp' not in task_info): write_error(self, HTTPCodes.BAD_REQUEST, 'lease...
'Delete a task from a queue. Args: project: A string containing an application ID. queue: A string containing a queue name. task: A string containing a task ID.'
def delete(self, project, queue, task):
task = Task({'id': task}) queue = self.queue_handler.get_queue(project, queue) if (queue is None): write_error(self, HTTPCodes.NOT_FOUND, 'Queue not found.') return queue.delete_task(task)
'Update tasks that are leased out of a queue. Args: project: A string containing an application ID. queue: A string containing a queue name. task: A string containing a task ID.'
def patch(self, project, queue, task):
try: task_info = tornado.escape.json_decode(self.request.body) except ValueError: write_error(self, HTTPCodes.BAD_REQUEST, 'The request body must contain a task.') return if ('queueName' not in task_info): write_error(self, HTTPCodes.BAD_REQUEST, 'queueName ...
'Create a Task object. Args: task_info: A dictionary containing task info.'
def __init__(self, task_info):
self.retry_count = 0 if ('payloadBase64' in task_info): encoded_payload = task_info['payloadBase64'] missing_padding = (4 - (len(encoded_payload) % 4)) encoded_payload += ('=' * missing_padding) payload = base64.urlsafe_b64decode(encoded_payload.encode('utf8')) self.paylo...
'Make sure the existing attributes are valid. Raises: InvalidTaskInfo if one of the attribute fails validation.'
def validate_info(self):
for (attribute, rule) in QUEUE_ATTRIBUTE_RULES.iteritems(): try: value = getattr(self, attribute) except AttributeError: continue if (not rule(value)): raise InvalidTaskInfo('Invalid task info: {}={}'.format(attribute, value))
'Returns the ETA for a task. Raises: InvalidTaskInfo if ETA information is not set.'
def get_eta(self):
epoch = datetime.datetime.utcfromtimestamp(0) if (hasattr(self, 'leaseTimestamp') and (self.leaseTimestamp != epoch)): return self.leaseTimestamp try: return self.enqueueTimestamp except AttributeError: raise InvalidTaskInfo('No ETA info for {}'.format(self))
'Checks whether or not a task has expired. Args: max_retries: An integer specifying the queue\'s task retry limit. Returns: A boolean indicating whether or not the task has expired.'
def expired(self, max_retries):
if (self.retry_count < max_retries): return False if (self.leaseTimestamp >= datetime.datetime.utcnow()): return False return True
'Generates a string representation of the task. Returns: A string representing the task.'
def __repr__(self):
return '<Task: {}>'.format(self.id)
'Generate a JSON-safe dictionary representation of the task. Args: fields: A list of fields to include in the response. Returns: A JSON-safe dictionary representing the task.'
def json_safe_dict(self, fields=TASK_FIELDS):
task = {} if ('kind' in fields): task['kind'] = 'taskqueues#task' if ('id' in fields): task['id'] = self.id if ('retry_count' in fields): task['retry_count'] = self.retry_count epoch = datetime.datetime.utcfromtimestamp(0) for attribute in self.OPTIONAL_ATTRS: if ...
'Encode this task as a protocol buffer response. Returns: A TaskQueueQueryAndOwnTasksResponse_Task object.'
def encode_lease_pb(self):
task_pb = taskqueue_service_pb.TaskQueueQueryAndOwnTasksResponse_Task() task_pb.set_task_name(self.id) epoch = datetime.datetime.utcfromtimestamp(0) task_pb.set_eta_usec((int((self.get_eta() - epoch).total_seconds()) * 1000000)) task_pb.set_retry_count(self.retry_count) task_pb.set_body(base64.u...
'Function which handles unknown protocol buffers. Args: app_id: A string, the application ID. http_request_data: The encoded protocol buffer from the AppServer. Raise: NotImplementedError: This unknown type is not implemented.'
def unknown_request(self, app_id, http_request_data, pb_type):
raise NotImplementedError(('Unknown request of operation %s' % pb_type))
'Function which handles POST requests. Data of the request is the request from the AppServer in an encoded protocol buffer format.'
@tornado.web.asynchronous def post(self):
global task_queue request = self.request http_request_data = request.body pb_type = request.headers['protocolbuffertype'] app_data = request.headers['appdata'] app_data = app_data.split(':') app_id = app_data[0] if (pb_type == 'Request'): self.remote_request(app_id, http_request_...
'Handles get request for the web server. Returns that it is currently up in JSON.'
@tornado.web.asynchronous def get(self):
global task_queue tq_stats = {'status': 'up', 'details': STATS} self.write(json.dumps(tq_stats)) self.finish()
'Receives a remote request to which it should give the correct response. The http_request_data holds an encoded protocol buffer of a certain type. Each type has a particular response type. Args: app_id: The application ID that is sending this request. http_request_data: Encoded protocol buffer.'
def remote_request(self, app_id, http_request_data):
global task_queue apirequest = remote_api_pb.Request() apirequest.ParseFromString(http_request_data) apiresponse = remote_api_pb.Response() response = None errcode = 0 errdetail = '' method = '' http_request_data = '' if (not apirequest.has_method()): errcode = taskqueue_...
'Creates a new ProjectQueueManager. Args: zk_client: A KazooClient. db_access: A DatastoreProxy. project_id: A string specifying a project ID.'
def __init__(self, zk_client, db_access, project_id):
super(ProjectQueueManager, self).__init__() self.zk_client = zk_client self.project_id = project_id self.db_access = db_access self.queues_node = '/appscale/projects/{}/queues'.format(project_id) self.watch = zk_client.DataWatch(self.queues_node, self._update_queues_watch) self.celery = None...
'Caches new configuration details and cleans up old state. Args: queue_config: A JSON string specifying queue configuration.'
def update_queues(self, queue_config):
logger.info('Updating queues for {}'.format(self.project_id)) if (not queue_config): new_queue_config = {'default': {'rate': '5/s'}} else: new_queue_config = json.loads(queue_config)['queue'] to_stop = [queue for queue in self if (queue not in new_queue_config)] for queue_na...
'Restart the watch if it has been cancelled.'
def ensure_watch(self):
if self._stopped: self._stopped = False self.watch = self.zk_client.DataWatch(self.queues_node, self._update_queues_watch)
'Close the Celery connections if they still exist.'
def stop(self):
if (self.celery is not None): self.celery.close()
'Handles updates to a queue configuration node. Since this runs in a separate thread, it doesn\'t change any state directly. Instead, it just acts as a bridge back to the main IO loop. Args: queue_config: A JSON string specifying queue configuration.'
def _update_queues_watch(self, queue_config, _):
main_io_loop = IOLoop.instance() if (queue_config is None): try: project_exists = (self.zk_client.exists('/appscale/projects/{}'.format(self.project_id)) is not None) except ZookeeperError: project_exists = True if (not project_exists): self._stopped =...
'Creates a new GlobalQueueManager. Args: zk_client: A KazooClient. db_access: A DatastoreProxy.'
def __init__(self, zk_client, db_access):
super(GlobalQueueManager, self).__init__() self.zk_client = zk_client self.db_access = db_access zk_client.ensure_path('/appscale/projects') zk_client.ChildrenWatch('/appscale/projects', self._update_projects_watch)
'Establishes watches for all existing projects. Args: new_project_list: A fresh list of strings specifying existing project IDs.'
def update_projects(self, new_project_list):
to_stop = [project for project in self if (project not in new_project_list)] for project_id in to_stop: self[project_id].stop() del self[project_id] for project_id in new_project_list: if (project_id not in self): self[project_id] = ProjectQueueManager(self.zk_client, sel...
'Handles creation and deletion of projects. Since this runs in a separate thread, it doesn\'t change any state directly. Instead, it just acts as a bridge back to the main IO loop. Args: new_projects: A list of strings specifying all existing project IDs.'
def _update_projects_watch(self, new_projects):
main_io_loop = IOLoop.instance() main_io_loop.add_callback(self.update_projects, new_projects)
'Initialize a new instance of the infrastructure manager service. Args: host Hostname to which the service should bind (Optional). Defaults to 0.0.0.0. port Port of the service (Optional). Default to 17444. ssl True if SSL should be engaged or False otherwise (Optional). Defaults to True. When engaged, this impleme...
def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT, ssl=True):
self.host = host self.port = port secret = None while True: try: secret = utils.get_secret((self.APPSCALE_DIR + 'secret.key')) break except Exception: logging.info('Waiting for the secret key to become available') utils...
'Start the infrastructure manager service. This method blocks as long as the service is alive. The caller should handle the threading requirements'
def start(self):
if self.started: logging.warn('Start called on already running server') else: logging.info('Starting AppScale Infrastructure Manager on port: {}'.format(self.port)) self.started = True while self.started: self.server.serve_forever()
'Stop the infrastructure manager service.'
def stop(self):
if self.started: logging.info('Stopping AppScale Infrastructure Manager') self.started = False self.server.shutdown() else: logging.warn('Stop called on already stopped server')
'Configure and setup security features for the VMs spawned via this agent. This method is called whenever InfrastructureManager is about start a set of VMs using this agent. Implementations may configure security features such as VM login and firewalls in this method. Implementations also have the option of not taking ...
def configure_instance_security(self, parameters):
raise NotImplementedError
'Start a set of virtual machines using the parameters provided. Args: count An integer that indicates the number of VMs to be spawned parameters A dictionary of parameters required by the agent implementation to create the VMs security_configured True if security has been configured for the...
def run_instances(self, count, parameters, security_configured):
raise NotImplementedError
'Terminate a set of virtual machines using the parameters given. Args: parameters A dictionary of parameters'
def terminate_instances(self, parameters):
raise NotImplementedError
'Check whether all the platform specific parameters are present in the provided dictionary. If all the parameters required to perform the given operation is available this method simply returns. Otherwise it throws an AgentConfigurationException. Args: parameters A dictionary of parameters (as provided by the client) ...
def assert_required_parameters(self, parameters, operation):
raise NotImplementedError
'Acquires a previously created persistent disk and attaches it to this machine. The disk is not guaranteed to be formatted, nor is it mounted. Args: parameters: A dict containing the parameters necessary to communicate with the underlying cloud infrastructure. disk_name: A str naming the persistent disk to attach to th...
def attach_disk(self, parameters, disk_name):
raise NotImplementedError
'Instantiate a new infrastructure agent. Args: infrastructure A string indicating the type of infrastructure agent to be initialized. Returns: An infrastructure agent instance that implements the BaseAgent API Raises: NameError If the given input string does not map to any known agent type.'
def create_agent(self, infrastructure):
if self.agents.has_key(infrastructure): return self.agents[infrastructure]() else: raise NameError(('Unrecognized infrastructure: ' + infrastructure))
'Setup OpenStack security keys and groups. Required input values are read from the parameters dictionary. More specifically, this method expects tofind a \'keyname\' parameter and a \'group\' parameter in the parameters dictionary. Using these provided values, this method will create a new OpenStack key-pair and a secu...
def configure_instance_security(self, parameters):
keyname = parameters[self.PARAM_KEYNAME] group = parameters[self.PARAM_GROUP] key_path = '{}/{}.key'.format(utils.KEY_DIRECTORY, keyname) ssh_key = os.path.abspath(key_path) utils.log('About to spawn OpenStack instances - Expecting to find a key at {0}'.format(ssh...
'Spawns the specified number of OpenStack instances using the parameters provided. This method is blocking in that it waits until the requested VMs are properly booted up. However if the requested VMs cannot be procured within 1800 seconds, this method will treat it as an error and return. (Also see documentation for t...
def run_instances(self, count, parameters, security_configured):
if (parameters[self.PARAM_SPOT] == 'True'): parameters[self.PARAM_SPOT] = 'False' utils.log('OpenStack does not support spot instances') super.run_instances(self, count, parameters, security_configured)