desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Checks if a user has cloud admin privliges.
Args:
email: A string specifying an email address.
Returns:
A boolean indicating whether or not the user has admin privileges.
Raises:
UAException when unable to determine the status.'
| def is_user_cloud_admin(self, email):
| response = self.server.is_user_cloud_admin(email, self.secret)
if (response.lower() not in ['true', 'false']):
raise UAException(response)
return (response.lower() == 'true')
|
'Grants or revokes cloud admin privileges.
Args:
email: A string specifying an email address.
is_admin: A boolean specifying if the user should be admin or not.
Raises:
UAException if the operation was not successful.'
| def set_cloud_admin_status(self, email, is_admin):
| response = self.server.set_cloud_admin_status(email, str(is_admin).lower(), self.secret)
if (response.lower() != 'true'):
raise UAException(response)
|
'Creates a new MonitOperator. There should only be one.'
| def __init__(self):
| self.reload_future = None
self.client = AsyncHTTPClient()
self.last_reload = time.time()
|
'Groups closely-timed reload operations.'
| @gen.coroutine
def reload(self):
| if ((self.reload_future is None) or self.reload_future.done()):
self.reload_future = self._reload()
(yield self.reload_future)
|
'Retrieves the status of a given process.
Args:
process_name: A string specifying a monit watch.
Returns:
A string specifying the current status.'
| @gen.coroutine
def get_status(self, process_name):
| status_url = '{}/_status?format=xml'.format(self.LOCATION)
response = (yield self.client.fetch(status_url))
raise gen.Return(process_status(response.body, process_name))
|
'Sends a command to the Monit API.
Args:
process_name: A string specifying a monit watch.
command: A string specifying the command to send.'
| @gen.coroutine
def send_command(self, process_name, command):
| process_url = '{}/{}'.format(self.LOCATION, process_name)
payload = urllib.urlencode({'action': command})
while True:
try:
(yield self.client.fetch(process_url, method='POST', body=payload))
return
except HTTPError:
(yield gen.sleep(0.2))
|
'Waits until a process is in a desired state.
Args:
process_name: A string specifying a monit watch.
acceptable_states: An iterable of strings specifying states.'
| @gen.coroutine
def wait_for_status(self, process_name, acceptable_states):
| while True:
status = (yield self.get_status(process_name))
if (status in acceptable_states):
raise gen.Return(status)
(yield gen.sleep(0.2))
|
'Waits for a process to finish starting.
Args:
process_name: A string specifying a monit watch.'
| @gen.coroutine
def ensure_running(self, process_name):
| while True:
non_missing_states = (MonitStates.RUNNING, MonitStates.UNMONITORED, MonitStates.PENDING, MonitStates.STOPPED)
status_future = self.wait_for_status(process_name, non_missing_states)
status = (yield gen.with_timeout(timedelta(seconds=5), status_future, IOLoop.current()))
if... |
'Reloads Monit.'
| @gen.coroutine
def _reload(self):
| time_since_reload = (time.time() - self.last_reload)
wait_time = max((self.RELOAD_COOLDOWN - time_since_reload), 0)
(yield gen.sleep(wait_time))
self.last_reload = time.time()
subprocess.check_call(['monit', 'reload'])
|
'Constructor function for the search service. Initializes the lucene
connection.'
| def __init__(self):
| self.solr_conn = solr_interface.Solr()
|
'Handles unknown request types.
Args:
pb_type: The protocol buffer type.
Raises:
NotImplementedError: The unknown type is not implemented.'
| def unknown_request(self, pb_type):
| raise NotImplementedError('Unknown request of operation {0}'.format(pb_type))
|
'Handles remote requests with serialized protocol buffers.
Args:
app_data: A str. Serialized request data of the application.
Returns:
A str. Serialized protocol buffer response.'
| def remote_request(self, app_data):
| apirequest = remote_api_pb.Request()
apirequest.ParseFromString(app_data)
apiresponse = remote_api_pb.Response()
response = None
errcode = 0
errdetail = ''
apperror_pb = None
method = ''
http_request_data = ''
if (not apirequest.has_method()):
errcode = search_service_pb.... |
'Index a new document or update an existing document.
Args:
data: A str. Serialized protocol buffer.
Returns:
A tuple of an encoded response, error code, and error detail.'
| def index_document(self, data):
| request = search_service_pb.IndexDocumentRequest(data)
logging.debug('APP ID: {0}'.format(request.app_id()))
response = search_service_pb.IndexDocumentResponse()
params = request.params()
document_list = params.document_list()
index_spec = params.index_spec()
for doc in document_list:
... |
'Deletes a document.
Args:
data: A str. Serialized protocol buffer.
Returns:
A tuple of an encoded response, error code, and error detail.'
| def delete_document(self, data):
| request = search_service_pb.DeleteDocumentRequest(data)
params = request.params()
doc_id_list = params.doc_id_list()
response = search_service_pb.DeleteDocumentResponse()
for doc_id in doc_id_list:
try:
self.solr_conn.delete_doc(doc_id)
response.add_status().set_code(... |
'Lists all indexes for an application.
Args:
data: A str. Serialized protocol buffer.
Returns:
A tuple of an encoded response, error code, and error detail.'
| def list_indexes(self, data):
| request = search_service_pb.ListIndexesRequest(data)
response = search_service_pb.ListIndexesResponse()
return (response, 0, '')
|
'List all documents for an application.
Args:
data: A str. Serialized protocol buffer.
Returns:
A tuple of an encoded response, error code, and error detail.'
| def list_documents(self, data):
| request = search_service_pb.ListDocumentsRequest(data)
response = search_service_pb.ListDocumentsResponse()
status = response.mutable_status()
status.set_code(search_service_pb.SearchServiceError.OK)
return (response, 0, '')
|
'Search within a document.
Args:
data: A str. Serialized protocol buffer.
Returns:
A tuple of an encoded response, error code, and error detail.'
| def search(self, data):
| request = search_service_pb.SearchRequest(data)
logging.debug('Search request: {0}'.format(request))
params = request.params()
app_id = request.app_id()
index_spec = params.index_spec()
namespace = index_spec.namespace()
response = search_service_pb.SearchResponse()
try:
in... |
'Constructor for query parsing.
Args:
index: An Index for the query to run.
app_id: A str, the application ID.
namespace: A str, the current namespace.
field_spec: A search_service_pb.FieldSpec.
sort_list: A list of search_service_pb.SortSpec.
limit: An int, the max number of results to return.
offset: An int, the numb... | def __init__(self, index, app_id, namespace, field_spec, sort_list, limit, offset):
| self.__index = index
self.__app_id = app_id
self.__namespace = namespace
self.__field_spec = field_spec
self.__sort_list = sort_list
self.__limit = limit
self.__offset = offset
|
'Parses the query and returns a query string.
The fields must be replaced by the internal field name given.
Args:
query: The query string.
Returns:
A SOLR string.'
| def get_solr_query_string(self, query):
| query_string = 'q={0}{1}{2}'.format(Document.INDEX_NAME, COLON, self.__index.name)
if (len(query) > 0):
query = urllib.unquote(query)
query = query.strip()
if (not isinstance(query, unicode)):
query = unicode(query, 'utf-8')
logging.debug('Query: {0}'.format(query)... |
'Returns the SOLR string that restricts the number of results.
Returns:
A str that is the rows limit in a SOLR query.'
| def __get_row_limit(self):
| return '&rows={0}'.format(self.__limit)
|
'Returns the SOLR string that offsets the results.
Returns:
A str that tells SOLR how many documents to skip.'
| def __get_offset(self):
| return '&start={0}'.format(self.__offset)
|
'Gets the query fields for a SOLR query.
Return:
A str, a list of fields we want to restrict the result by.'
| def __get_query_fields(self):
| if (self.__field_spec.name_size() == 0):
schema_fields = self.__index.schema.fields
field_names = []
for field in schema_fields:
field_names.append(field['name'])
if field_names:
return '+'.join(field_names)
else:
return Document.INDEX_NAME... |
'Gets the SOLR sort list argument for the SOLR query.
Returns:
A str, the sort portion of the SOLR query string.'
| def __get_sort_list(self):
| field_list = []
for sort_spec in self.__sort_list:
new_field = '{0}_{1}'.format(self.__index.name, sort_spec.sort_expression())
if (sort_spec.sort_descending() == 1):
new_field += '+desc'
else:
new_field += '+asc'
field_list.append(new_field)
if field_... |
'Gets the field list for the SOLR query.
Returns:
A str, the field list for the query.'
| def __get_field_list(self):
| field_string = ''
field_list = []
if (self.__field_spec.name_size() > 0):
field_string += '&fl=id,'
for field_name in self.__field_spec.name_list():
field_list.append('{0}_{1}'.format(self.__index.name, field_name))
field_string += SPACE.join(field_list)
logging.d... |
'Creates a SOLR query string from a antlr3 parse tree.
Args:
query_tree: A antlr3.tree.CommonTree.
Returns:
A string which can be sent to SOLR.'
| def __create_query_string(self, query_tree):
| q_str = ''
if (query_tree.getType() == QueryParser.CONJUNCTION):
q_str += '('
for (index, child) in enumerate(query_tree.children):
if (index != 0):
q_str += '+AND'
q_str += self.__create_query_string(child)
q_str += ')'
elif (query_tree.getTyp... |
'Returns the string equivalent of the operation code.
Args:
op_code: An int which maps to a comparison operator.
Returns:
A str, the SOLR operator which maps from the operator code.'
| def __get_operator(self, op_code):
| if (op_code == QueryParser.EQ):
return ':'
return ':'
|
'Puts in escape characters for certain characters which are a part of
query syntax.
Args:
value: A str, the field value.
Returns:
A str, the escaped value.'
| def __escape_chars(self, value):
| new_value = ''
for char in value:
if (char in ['\\', '+', '-', '!', '(', ')', ':', '^', '[', ']', '"', '{', '}', '~', '*', '?', '|', '&', ';', '/', ' ']):
new_value += '\\'
new_value += char
return new_value
|
'Converts a field name to the internal field name used in SOLR.
Args:
field_name: A str, the field name supplied by the application.
Returns:
A str, the internal field name for SOLR.'
| def __get_internal_field_name(self, field_name):
| for field in self.__index.schema.fields:
if (field['name'].endswith(field_name) and field['name'].startswith('{0}_{1}_'.format(self.__app_id, self.__namespace))):
return field['name']
logging.error('Unable to find field name {0}'.format(field_name))
return ''
|
'Dumps the tree contents.
Args:
node: The head node to convert to a human readable string.
Returns:
A str, the tree in human readable format.'
| def __dump_tree(self, node):
| return node.toStringTree()
|
'Constructor for Document in SOLR.
Args:
identifier: A str, the ID of the document.
language: The language the document is in.
fields: Field list for the document.'
| def __init__(self, identifier, language, fields):
| self.id = identifier
self.language = language
self.fields = fields
|
'Class for initializing search service web handler.'
| def initialize(self, search_service):
| self.search_service = search_service
|
'A POST handler for request to this server.'
| @tornado.web.asynchronous
def post(self):
| request = self.request
http_request_data = request.body
pb_type = request.headers['protocolbuffertype']
if (pb_type == 'Request'):
response = self.search_service.remote_request(http_request_data)
else:
response = self.search_service.unknown_request(pb_type)
request.connection.wri... |
'Constructor for solr interface.'
| def __init__(self):
| self._search_location = appscale_info.get_search_location()
|
'Gets the internal index name.
Args:
app_id: A str, the application identifier.
namespace: A str, the application namespace.
name: A str, the index name.
Returns:
A str, the internal name of the index.'
| def __get_index_name(self, app_id, namespace, name):
| return ((((app_id + '_') + namespace) + '_') + name)
|
'Deletes a document by doc ID.
Args:
doc_id: A list of document IDs.
Raises:
search_exceptions.InternalError on internal errors.'
| def delete_doc(self, doc_id):
| solr_request = {'delete': {'id': doc_id}}
solr_url = 'http://{0}:{1}/solr/update?commit=true'.format(self._search_location, self.SOLR_SERVER_PORT)
logging.debug('SOLR URL: {0}'.format(solr_url))
json_request = json.dumps(solr_request)
logging.debug('SOLR JSON: {0}'.format(json_request))
... |
'Gets an index from SOLR.
Performs a JSON request to the SOLR schema API to get the list of defined
fields. Extracts the fields that match the naming convention
appid_[namespace]_index_name.
Args:
app_id: A str, the application identifier.
namespace: A str, the application namespace.
name: A str, the index name.
Raises... | def get_index(self, app_id, namespace, name):
| index_name = self.__get_index_name(app_id, namespace, name)
solr_url = 'http://{0}:{1}/solr/schema/fields'.format(self._search_location, self.SOLR_SERVER_PORT)
logging.debug('URL: {0}'.format(solr_url))
try:
conn = urllib2.urlopen(solr_url)
if (conn.getcode() != HTTP_OK):
... |
'Updates the schema of a document.
Args:
updates: A list of updates to apply.
Raises:
search_exceptions.InternalError on internal errors from SOLR.'
| def update_schema(self, updates):
| field_list = []
for update in updates:
field_list.append({'name': update['name'], 'type': update['type'], 'stored': 'true', 'indexed': 'true', 'multiValued': 'false'})
solr_url = 'http://{0}:{1}/solr/schema/fields'.format(self._search_location, self.SOLR_SERVER_PORT)
json_request = json.dumps(fi... |
'Converts a set of fields to a hash map/dictionary to send to SOLR.
Args:
index: A Index type.
solr_doc: A Document type.
Returns:
A dictionary to send for field/value updates.'
| def to_solr_hash_map(self, index, solr_doc):
| hash_map = {}
hash_map['id'] = solr_doc.id
hash_map[Document.INDEX_NAME] = index.name
if solr_doc.language:
hash_map[Document.INDEX_LOCALE] = solr_doc.language
for field in solr_doc.fields:
value = field.value
field_type = field.field_type
if (field_type == Field.HTML... |
'Commits field/value changes to SOLR.
Args:
hash_map: A dictionary to send to SOLR.
Raises:
search_exceptions.InternalError: On failure.'
| def commit_update(self, hash_map):
| docs = []
docs.append(hash_map)
json_payload = json.dumps(docs)
solr_url = 'http://{0}:{1}/solr/update/json?commit=true'.format(self._search_location, self.SOLR_SERVER_PORT)
try:
req = urllib2.Request(solr_url, data=json_payload)
req.add_header('Content-Type', 'application/json')
... |
'Updates a document in SOLR.
Args:
app_id: A str, the application identifier.
doc: The document to update.
index_spec: An index specification.'
| def update_document(self, app_id, doc, index_spec):
| solr_doc = self.to_solr_doc(doc)
index = self.get_index(app_id, index_spec.namespace(), index_spec.name())
updates = self.compute_updates(index.name, index.schema.fields, solr_doc.fields)
if (len(updates) > 0):
try:
self.update_schema(updates)
except search_exceptions.Interna... |
'Converts to an internal SOLR document.
Args:
doc: A document_pb.Document type.
Returns:
A converted Document type.
Raises:
search_exceptions.InternalError if field type is not valid.'
| def to_solr_doc(self, doc):
| fields = []
for field in doc.field_list():
value = field.value().string_value()
field_type = field.value().type()
if (field_type == FieldValue.TEXT):
lang = field.value().language()
name = field.name()
new_field = Field(name, (Field.TEXT_ + lang), valu... |
'Computes the updates needed to update a document in SOLR.
Args:
index_name: A str, the index name.
current_fields: The current SOLR schema fields set.
doc_fields: The fields that need to be updated.
Returns:
A list of dictionaries with SOLR field names that require updates.'
| def compute_updates(self, index_name, current_fields, doc_fields):
| fields_to_update = []
for doc_field in doc_fields:
doc_name = doc_field.name
found = False
for current_field in current_fields:
current_name = current_field['name']
if (current_name == ((index_name + '_') + doc_name)):
found = True
if (not ... |
'Creates a SOLR query string and runs it on SOLR.
Args:
result: A search_service_pb.SearchResponse.
index: Index for which we\'re running the query.
app_id: A str, the application identifier.
namespace: A str, the namespace.
search_params: A search_service_pb.SearchParams.'
| def run_query(self, result, index, app_id, namespace, search_params):
| query = search_params.query()
field_spec = search_params.field_spec()
sort_list = search_params.sort_spec_list()
parser = query_parser.SolrQueryParser(index, app_id, namespace, field_spec, sort_list, search_params.limit(), search_params.offset())
solr_query = parser.get_solr_query_string(query)
... |
'Executes query string on SOLR.
Args:
solr_query: A str, the query to run.
Returns:
The results from the query executing.
Raises:
search_exceptions.InternalError on internal SOLR error.'
| def __execute_query(self, solr_query):
| solr_url = 'http://{0}:{1}/solr/select/?wt=json&{2}'.format(self._search_location, self.SOLR_SERVER_PORT, solr_query)
logging.debug('SOLR URL: {0}'.format(solr_url))
try:
req = urllib2.Request(solr_url)
req.add_header('Content-Type', 'application/json')
conn = urllib2.urlopen(r... |
'Converts SOLR results in to GAE compatible documents.
Args:
result: A search_service_pb.SearchResponse.
solr_results: A dictionary returned from SOLR on a search query.
index: A Index that we are querying for.'
| def __convert_to_gae_results(self, result, solr_results, index):
| result.set_matched_count((len(solr_results['response']['docs']) + int(solr_results['response']['start'])))
result.mutable_status().set_code(search_service_pb.SearchServiceError.OK)
for doc in solr_results['response']['docs']:
new_result = result.add_result()
self.__add_new_doc(doc, new_resul... |
'Add a new document to a query result.
Args:
doc: A dictionary of SOLR document attributes.
new_result: A search_service_pb.SearchResult.
index: Index we queried for.'
| def __add_new_doc(self, doc, new_result, index):
| new_doc = new_result.mutable_document()
new_doc.set_id(doc['id'])
if (Document.INDEX_LOCALE in doc):
new_doc.set_language(doc[Document.INDEX_LOCALE][0])
for key in doc.keys():
if (not key.startswith(index.name)):
continue
field_name = key.split('{0}_'.format(index.nam... |
'Adds a value to a result field.
Args:
new_value: Value object to fill in.
value: A str, the internal value to be converted.
ftype: A str, the field type.'
| def __add_field_value(self, new_value, value, ftype):
| if (ftype == Field.DATE):
value = calendar.timegm(datetime.strptime(value[:(-1)], '%Y-%m-%dT%H:%M:%S').timetuple())
new_value.set_string_value(str(int((value * 1000))))
new_value.set_type(FieldValue.DATE)
elif (ftype == Field.TEXT):
new_value.set_string_value(value)
new_v... |
'Constructor for SOLR schema.
Args:
fields: A list of Fields for the schema.
response_header: The response header from SOLR.'
| def __init__(self, fields, response_header):
| self.fields = fields
self.response_header = response_header
|
'Constructor for SOLR index.
Args:
name: A str, the name of the index.
schema: A Schema for this index.'
| def __init__(self, name, schema):
| self.name = name
self.schema = schema
|
'Constructor for Header type.
Args:
status: The status for this header.
qtime: The reported qtime from SOLR.'
| def __init__(self, status, qtime):
| self.status = status
self.qtime = qtime
|
'Constructor for Field type.
Args:
name: The name of the field.
stored: Boolean if the field is stored.
indexed: Boolean if the field is indexed.
multi_valued: Boolean if the field has multiple values.
value: The value of the field.'
| def __init__(self, name, field_type, stored=True, indexed=True, multi_valued=False, value=None):
| self.name = name
self.field_type = field_type
self.stored = stored
self.indexed = indexed
self.multi_valued = multi_valued
self.value = value
|
'Constructor for Results type.'
| def __init__(self, num_found, docs, header):
| self.num_found = num_found
self.docs = docs
self.header = header
|
'Creates a new XMPPReceiver, which will listen for XMPP messages for
an App Engine app.
Args:
appid: A str representing the application ID that this XMPPReceiver
should poll on behalf of.
login_ip: A str representing the IP address or FQDN that runs the
full proxy nginx service, sitting in front of the app we\'ll be
po... | def __init__(self, appid, login_ip, app_password):
| self.appid = appid
self.login_ip = login_ip
self.app_password = app_password
self.my_jid = ((self.appid + '@') + self.login_ip)
log_file = '/var/log/appscale/xmppreceiver-{0}.log'.format(self.my_jid)
sys.stderr = open(log_file, 'a')
logging.basicConfig(level=logging.INFO, format='%(asctime)s... |
'Responds to the receipt of an XMPP message, by finding an App Server that
hosts the given application and POSTing the message\'s payload to it.
Args:
_: The connection that the message was received on (not used).
event: The actual message that was received.'
| def xmpp_message(self, _, event):
| logging.info('received a message from {0}, with body {1}'.format(event.getFrom().getStripped(), event.getBody()))
logging.info('message type is {0}'.format(event.getType))
from_jid = event.getFrom().getStripped()
params = {}
params['from'] = from_jid
params['to'] = ... |
'Responds to the receipt of a presence message, by telling the sender
that we are subscribing to their presence and that they should do the same.
Args:
conn: The connection that the message was received on.
event: The actual message that was received.'
| def xmpp_presence(self, conn, event):
| logging.info('received a presence from {0}, with payload {1}'.format(event.getFrom().getStripped(), event.getPayload()))
prs_type = event.getType()
logging.info('presence type is {0}'.format(prs_type))
who = event.getFrom()
if (prs_type == 'subscribe'):
conn.sen... |
'Polls the XMPP server for messages, responding to any that are seen.
Args:
messages_to_listen_for: An int that represents how many messages we
should listen for. If set to the default value (-1), then we listen
for an infinite number of messages.
Returns:
An int that indicates how many messages were processed.'
| def listen_for_messages(self, messages_to_listen_for=(-1)):
| jid = xmpp.protocol.JID(self.my_jid)
client = xmpp.Client(jid.getDomain(), debug=[])
if (not client.connect()):
logging.info('Could not connect')
raise SystemExit('Could not connect to XMPP server at {0}'.format(self.login_ip))
if (not client.auth(jid.getNode()... |
'Returns all tests of DB.'
| @classmethod
def all_tests(cls):
| return [cls.PUT, cls.GET, cls.QUERY, cls.DELETE]
|
'Returns all tests of Memcache.'
| @classmethod
def all_tests(cls):
| return [cls.SET, cls.GET, cls.DELETE]
|
'Returns all tests of Urlfetch.'
| @classmethod
def all_tests(cls):
| return [cls.GCS, cls.AWS, cls.GOOGLE]
|
'Returns all high level test suites for display.'
| @classmethod
def all_displayed_suites(cls):
| return [DBTestIdentifiers.DISPLAY_TAG, MemcacheTestIdentifiers.DISPLAY_TAG, UrlfetchTestIdentifiers.DISPLAY_TAG]
|
'Returns all high level test suites.'
| @classmethod
def all_suites(cls):
| return [DBTestIdentifiers.SUITE_TAG, MemcacheTestIdentifiers.SUITE_TAG, UrlfetchTestIdentifiers.SUITE_TAG]
|
'Returns all the test classes for each suite.'
| @classmethod
def get_all_identifiers(cls):
| return [DBTestIdentifiers, MemcacheTestIdentifiers, UrlfetchTestIdentifiers]
|
'Runs the URLfetch tests.
Returns:
A dictionary with results.'
| def run(self):
| result = {}
thismodule = sys.modules[__name__]
for test in constants.UrlfetchTestIdentifiers.all_tests():
result[test] = getattr(thismodule, test)(self.uuid_tag)
return result
|
'Clean up for URLfetch. Do nothing since operations are
idempotent.'
| def cleanup(self):
| pass
|
'Runs the Memcache tests.
Returns:
A dictionary with results.'
| def run(self):
| result = {}
thismodule = sys.modules[__name__]
for test in constants.MemcacheTestIdentifiers.all_tests():
result[test] = getattr(thismodule, test)(self.uuid_tag)
return result
|
'Clean up for Memcache. Since Memcache is transient, we do
not clean this up.'
| def cleanup(self):
| pass
|
'Runs the DB tests.
Returns:
A dictionary with results.'
| def run(self):
| result = {}
thismodule = sys.modules[__name__]
for test in constants.DBTestIdentifiers.all_tests():
result[test] = getattr(thismodule, test)(self.uuid_tag)
return result
|
'Shared constructor.'
| def __init__(self, uuid_tag):
| if (not isinstance(uuid_tag, str)):
raise TypeError('Expected a str')
self.uuid_tag = uuid_tag
|
'Run the given test and return a json string with results.'
| @abc.abstractmethod
def run(self):
| return
|
'Clean up any left over state.'
| @abc.abstractmethod
def cleanup(self):
| return
|
'GET path to do health checking on different APIs.'
| def get(self):
| remote_api_key = self.request.get(constants.ApiTags.API_KEY)
if (remote_api_key != settings.API_KEY):
logging.error('Request with bad API key')
self.response.set_status(constants.HTTP_DENIED)
self.response.write('Bad API Key')
return
results = {}
uuid_ta... |
'GET request request handler which returns text to notify
caller it is up.'
| def get(self):
| self.response.out.write(json.dumps({'status': 'up'}))
|
'POST request request handler which returns text to notify
caller it is up.'
| def post(self):
| self.response.out.write(json.dumps({'status': 'up'}))
|
'Creates a new ProjectPushWorkerManager.
Args:
zk_client: A KazooClient.
monit_operator: A MonitOperator.
project_id: A string specifying a project ID.'
| def __init__(self, zk_client, monit_operator, project_id):
| self.zk_client = zk_client
self.project_id = project_id
self.monit_operator = monit_operator
self.queues_node = '/appscale/projects/{}/queues'.format(project_id)
self.watch = zk_client.DataWatch(self.queues_node, self._update_worker)
self.monit_watch = 'celery-{}'.format(project_id)
self._st... |
'Updates a worker\'s configuration and restarts it.
Args:
queue_config: A JSON string specifying queue configuration.'
| @gen.coroutine
def update_worker(self, queue_config):
| self._write_worker_configuration(queue_config)
status = (yield self._wait_for_stable_state())
if (status == MonitStates.MISSING):
command = self.celery_command()
env_vars = {'APP_ID': self.project_id, 'HOST': options.login_ip, 'C_FORCE_ROOT': True}
pidfile = os.path.join(PID_DIR, 'ce... |
'Generates the Celery command for a project\'s push worker.'
| def celery_command(self):
| log_file = os.path.join(CELERY_WORKER_LOG_DIR, '{}.log'.format(self.project_id))
pidfile = os.path.join(PID_DIR, 'celery-{}.pid'.format(self.project_id))
state_db = os.path.join(CELERY_STATE_DIR, 'worker___{}.db'.format(self.project_id))
return ' '.join(['celery', 'worker', '--app', WORKER_MODULE, '-... |
'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_worker)
|
'Waits until the worker\'s state is not pending.'
| @gen.coroutine
def _wait_for_stable_state(self):
| stable_states = (MonitStates.MISSING, MonitStates.RUNNING, MonitStates.UNMONITORED)
status_future = self.monit_operator.wait_for_status(self.monit_watch, stable_states)
status = (yield gen.with_timeout(timedelta(seconds=60), status_future, IOLoop.current()))
raise gen.Return(status)
|
'Writes a worker\'s configuration file.
Args:
queue_config: A JSON string specifying queue configuration.'
| def _write_worker_configuration(self, queue_config):
| if (queue_config is None):
rates = {'default': '5/s'}
else:
queues = json.loads(queue_config)['queue']
rates = {queue_name: queue['rate'] for (queue_name, queue) in queues.items() if (('mode' not in queue) or (queue['mode'] == 'push'))}
config_location = os.path.join(CELERY_CONFIG_DI... |
'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_worker(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 GlobalPushWorkerManager.'
| def __init__(self, zk_client, monit_operator):
| self.zk_client = zk_client
self.monit_operator = monit_operator
self.projects = {}
ensure_path(CELERY_CONFIG_DIR)
ensure_path(CELERY_WORKER_DIR)
ensure_path(CELERY_WORKER_LOG_DIR)
ensure_path(CELERY_STATE_DIR)
zk_client.ensure_path('/appscale/projects')
zk_client.ChildrenWatch('/apps... |
'Establishes watches for each project\'s queue configuration.
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.projects if (project not in new_project_list)]
for project_id in to_stop:
del self.projects[project_id]
for new_project_id in new_project_list:
if (new_project_id not in self.projects):
self.projects[new_project_id] = ProjectPushWorkerManage... |
'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(self, new_projects):
| main_io_loop = IOLoop.instance()
main_io_loop.add_callback(self.update_projects, new_projects)
|
'Defines required resources to handle requests.
Args:
acc: An AppControllerClient.
ua_client: A UAClient.
zk_client: A KazooClient.
version_update_lock: A kazoo lock.
thread_pool: A ThreadPoolExecutor.'
| def initialize(self, acc, ua_client, zk_client, version_update_lock, thread_pool):
| self.acc = acc
self.ua_client = ua_client
self.zk_client = zk_client
self.version_update_lock = version_update_lock
self.thread_pool = thread_pool
|
'Retrieves the current user.
Returns:
A string specifying the user\'s email address.
Raises:
CustomHTTPError if the user is invalid.'
| def get_current_user(self):
| if ('AppScale-User' not in self.request.headers):
message = 'A required header is missing: AppScale-User'
raise CustomHTTPError(HTTPCodes.BAD_REQUEST, message=message)
user = self.request.headers['AppScale-User']
try:
user_exists = self.ua_client.does_user_exist(user)
... |
'Constructs version from payload.
Returns:
A dictionary containing version details.
Raises:
CustomHTTPError if payload is invalid.'
| def version_from_payload(self):
| try:
version = json_decode(self.request.body)
except ValueError:
raise CustomHTTPError(HTTPCodes.BAD_REQUEST, message='Payload must be valid JSON')
required_fields = ('deployment.zip.sourceUrl', 'id', 'runtime')
utils.assert_fields_in_resource(required_fields, 'version', vers... |
'Checks if a project exists.
Args:
project_id: A string specifying a project ID.
Raises:
CustomHTTPError if unable to determine if project exists.'
| def project_exists(self, project_id):
| try:
return self.ua_client.does_app_exist(project_id)
except UAException:
message = 'Unable to check if project exists: {}'.format(project_id)
logging.exception(message)
raise CustomHTTPError(HTTPCodes.INTERNAL_ERROR, message=message)
|
'Creates a new project.
Args:
project_id: A string specifying a project ID.
user: A string specifying a user\'s email address.
runtime: A string specifying the project\'s runtime.
Raises:
CustomHTTPError if unable to create new project.'
| def create_project(self, project_id, user, runtime):
| logging.info('Creating project: {}'.format(project_id))
try:
self.ua_client.commit_new_app(project_id, user, runtime)
except UAException:
message = 'Unable to ensure project exists: {}'.format(project_id)
logging.exception(message)
raise CustomHTTPError(H... |
'Ensures a user is the owner of a project.
Args:
project_id: A string specifying a project ID.
user: A string specifying a user\'s email address.
Raises:
CustomHTTPError if the user is not the owner.'
| def ensure_user_is_owner(self, project_id, user):
| if (project_id in constants.IMMUTABLE_PROJECTS):
return
try:
project_metadata = self.ua_client.get_app_data(project_id)
except UAException:
message = 'Unable to retrieve project metadata'
logging.exception(message)
raise CustomHTTPError(HTTPCodes.INTERNAL_... |
'Create or update version node.
Args:
project_id: A string specifying a project ID.
service_id: A string specifying a service ID.
new_version: A dictionary containing version details.
Returns:
A dictionary containing updated version details.'
| def put_version(self, project_id, service_id, new_version):
| version_node = constants.VERSION_NODE_TEMPLATE.format(project_id=project_id, service_id=service_id, version_id=new_version['id'])
try:
(old_version_json, _) = self.zk_client.get(version_node)
old_version = json.loads(old_version_json)
except NoNodeError:
old_version = {}
if ('app... |
'Triggers the deployment process.
Args:
project_id: A string specifying a project ID.
Raises:
CustomHTTPError if unable to start the deployment process.'
| def begin_deploy(self, project_id):
| try:
self.ua_client.enable_app(project_id)
except UAException:
message = 'Unable to enable project'
logging.exception(message)
raise CustomHTTPError(HTTPCodes.INTERNAL_ERROR, message=message)
try:
self.acc.update([project_id])
except AppControllerExceptio... |
'Marks this machine as having a version\'s source code.
Args:
project_id: A string specifying a project ID.
service_id: A string specifying a service ID.
version: A dictionary containing version details.'
| @gen.coroutine
def identify_as_hoster(self, project_id, service_id, version):
| revision_key = VERSION_PATH_SEPARATOR.join([project_id, service_id, version['id'], str(version['revision'])])
hoster_node = '/apps/{}/{}'.format(revision_key, options.private_ip)
source_location = version['deployment']['zip']['sourceUrl']
md5 = (yield self.thread_pool.submit(get_md5, source_location))
... |
'Creates or updates a version.
Args:
project_id: A string specifying a project ID.
service_id: A string specifying a service ID.'
| @gen.coroutine
def post(self, project_id, service_id):
| self.authenticate()
user = self.get_current_user()
version = self.version_from_payload()
project_exists = self.project_exists(project_id)
if (not project_exists):
self.create_project(project_id, user, version['runtime'])
if (service_id != constants.DEFAULT_SERVICE):
raise CustomH... |
'Defines required resources to handle requests.
Args:
acc: An AppControllerClient.
ua_client: A UAClient.
zk_client: A KazooClient.
version_update_lock: A kazoo lock.
thread_pool: A ThreadPoolExecutor.'
| def initialize(self, acc, ua_client, zk_client, version_update_lock, thread_pool):
| self.acc = acc
self.ua_client = ua_client
self.zk_client = zk_client
self.version_update_lock = version_update_lock
self.thread_pool = thread_pool
|
'Fetches a version node.
Args:
project_id: A string specifying a project ID.
service_id: A string specifying a service ID.
version_id: A string specifying a version ID.
Returns:
A dictionary containing version details.'
| def get_version(self, project_id, service_id, version_id):
| version_node = constants.VERSION_NODE_TEMPLATE.format(project_id=project_id, service_id=service_id, version_id=version_id)
try:
(version_json, _) = self.zk_client.get(version_node)
except NoNodeError:
raise CustomHTTPError(HTTPCodes.NOT_FOUND, message='Version not found')
return js... |
'Constructs version from payload.
Returns:
A dictionary containing version details.'
| def version_from_payload(self):
| update_mask = self.get_argument('updateMask', None)
if (not update_mask):
message = 'At least one field must be specified for this operation.'
raise CustomHTTPError(HTTPCodes.BAD_REQUEST, message=message)
desired_fields = update_mask.split(',')
supported_fields... |
'Updates a version node.
Args:
project_id: A string specifying a project ID.
service_id: A string specifying a service ID.
version_id: A string specifying a version ID.
new_fields: A dictionary containing version details.
Returns:
A dictionary containing completed version details.'
| def update_version(self, project_id, service_id, version_id, new_fields):
| version_node = constants.VERSION_NODE_TEMPLATE.format(project_id=project_id, service_id=service_id, version_id=version_id)
try:
(version_json, _) = self.zk_client.get(version_node)
except NoNodeError:
raise CustomHTTPError(HTTPCodes.NOT_FOUND, message='Version not found')
version =... |
'Assigns new ports to a version.
Args:
project_id: A string specifying a project ID.
service_id: A string specifying a service ID.
version_id: A string specifying a version ID.
http_port: An integer specifying a port.
https_port: An integer specifying a port.
Returns:
A dictionary containing completed version details.'... | @gen.coroutine
def relocate_version(self, project_id, service_id, version_id, http_port, https_port):
| new_fields = {'appscaleExtensions': {}}
if (http_port is not None):
new_fields['appscaleExtensions']['httpPort'] = http_port
if (https_port is not None):
new_fields['appscaleExtensions']['httpsPort'] = https_port
(yield self.thread_pool.submit(self.version_update_lock.acquire))
try:
... |
'Deletes a version.
Args:
project_id: A string specifying a project ID.
service_id: A string specifying a service ID.
version_id: A string specifying a version ID.'
| @gen.coroutine
def delete(self, project_id, service_id, version_id):
| self.authenticate()
if (project_id in constants.IMMUTABLE_PROJECTS):
raise CustomHTTPError(HTTPCodes.BAD_REQUEST, message='{} cannot be deleted'.format(project_id))
if (service_id != constants.DEFAULT_SERVICE):
raise CustomHTTPError(HTTPCodes.BAD_REQUEST, message='Invalid service... |
'Updates a version.
Args:
project_id: A string specifying a project ID.
service_id: A string specifying a service ID.
version_id: A string specifying a version ID.'
| @gen.coroutine
def patch(self, project_id, service_id, version_id):
| self.authenticate()
if (project_id in constants.IMMUTABLE_PROJECTS):
raise CustomHTTPError(HTTPCodes.BAD_REQUEST, message='{} cannot be updated'.format(project_id))
version = self.version_from_payload()
extensions = version.get('appscaleExtensions', {})
if (('httpPort' in extensions... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.