desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Match a textual field with a phrase query node.'
def _MatchPhrase(self, field, match, document):
field_text = field.value().string_value() phrase_text = query_parser.GetPhraseQueryNodeText(match) if (field.value().type() == document_pb.FieldValue.ATOM): return (field_text == phrase_text) phrase = self._parser.TokenizeText(phrase_text) field_text = self._parser.TokenizeText(field_text) ...
'Check if a textual field matches a query tree node.'
def _MatchTextField(self, field, match, document):
if (match.getType() == QueryParser.VALUE): if query_parser.IsPhrase(match): return self._MatchPhrase(field, match, document) if (field.value().type() == document_pb.FieldValue.ATOM): return (field.value().string_value() == query_parser.GetQueryNodeText(match)) query_t...
'Check if a date field matches a query tree node.'
def _MatchDateField(self, field, match, operator, document):
return self._MatchComparableField(field, match, search_util.DeserializeDate, operator, document)
'Check if a numeric field matches a query tree node.'
def _MatchNumericField(self, field, match, operator, document):
return self._MatchComparableField(field, match, float, operator, document)
'A generic method to test matching for comparable types. Comparable types are defined to be anything that supports <, >, <=, >=, == and !=. For our purposes, this is numbers and dates. Args: field: The document_pb.Field to test match: The query node to match against cast_to_type: The type to cast the node string values...
def _MatchComparableField(self, field, match, cast_to_type, op, document):
field_val = cast_to_type(field.value().string_value()) if (match.getType() == QueryParser.VALUE): try: match_val = cast_to_type(query_parser.GetQueryNodeText(match)) except ValueError: return False else: return False if (op == QueryParser.EQ): retu...
'Check if a field matches a query tree. Args: field_query_node: Either a string containing the name of a field, a query node whose text is the name of the field, or a document_pb.Field. match: A query node to match the field with. operator: The a query node type corresponding to the type of match to perform (eg QueryPa...
def _MatchField(self, field, match, operator, document):
if isinstance(field, (basestring, tree.CommonTree)): if isinstance(field, tree.CommonTree): field = query_parser.GetQueryNodeText(field) fields = search_util.GetAllFieldInDocument(document, field) return any((self._MatchField(f, match, operator, document) for f in fields)) if...
'Check if a document matches a query tree.'
def _CheckMatch(self, node, document):
if (node.getType() == QueryParser.CONJUNCTION): return all((self._CheckMatch(child, document) for child in node.children)) if (node.getType() == QueryParser.DISJUNCTION): return any((self._CheckMatch(child, document) for child in node.children)) if (node.getType() == QueryParser.NEGATION): ...
'Initializer. Args: chars: The string representation of the token. position: The position of the token in the sequence from the document field. field_name: The name of the field the token occured in. Raises: TypeError: If an unknown argument is passed.'
def __init__(self, chars=None, position=None, field_name=None):
if (isinstance(chars, basestring) and (not isinstance(chars, unicode))): chars = unicode(chars, 'utf-8') self._chars = chars self._position = position self._field_name = field_name
'Returns a list of fields of the document.'
@property def chars(self):
value = self._chars if (not isinstance(value, basestring)): value = str(self._chars) if self._field_name: return ((self._field_name + ':') + value) return value
'Returns a list of fields of the document.'
@property def position(self):
return self._position
'Creates a copy of this Token and sets field_name.'
def RestrictField(self, field_name):
return Token(chars=self.chars, position=self.position, field_name=field_name)
'Returns the angle between equatorial plan and line thru the geo point.'
@property def latitude(self):
return self._latitude
'Returns the angle from a reference meridian to another meridian.'
@property def longitude(self):
return self._longitude
'Raise an exception if the input fails to parse correctly. Overriding the default, which normally just prints a message to stderr. Arguments: msg: the error message Raises: ExpressionException: always.'
def emitErrorMessage(self, msg):
raise ExpressionException(msg)
'Raise an exception if the input fails to parse correctly. Overriding the default, which normally just prints a message to stderr. Arguments: msg: the error message Raises: ExpressionException: always.'
def emitErrorMessage(self, msg):
raise ExpressionException(msg)
'Constructor. Args: capabilities: list of strings methods: list of strings'
def __init__(self, package, capabilities=None, methods=None, stub_map=apiproxy_stub_map):
if (capabilities is None): capabilities = [] if (methods is None): methods = [] self._package = package self._capabilities = (['*'] + capabilities) self._methods = methods self._stub_map = stub_map
'Tests whether the capabilities is currently enabled. Returns: True if API calls that require these capabillities will succeed. Raises: UnknownCapabilityError, if a specified capability was not recognized.'
def is_enabled(self):
config = self._get_status() return (config.summary_status() in (IsEnabledResponse.ENABLED, IsEnabledResponse.SCHEDULED_FUTURE, IsEnabledResponse.SCHEDULED_NOW))
'Returns true if it will remain enabled for the specified amount of time. DEPRECATED: this method was never fully implemented and is considered deprecated. Use is_enabled() instead. Args: time: Number of seconds in the future to look when checking for scheduled downtime. Returns: True if there is no scheduled downtime...
def will_remain_enabled_for(self, time=60):
warnings.warn('will_remain_enabled_for() is deprecated: use is_enabled instead.', DeprecationWarning, stacklevel=2) config = self._get_status() status = config.summary_status() if (status == IsEnabledResponse.ENABLED): return True elif (status == IsEnabledResponse.SCHEDULED_NO...
'Get any administrator notice messages for these capabilities. Returns: A string containing one or more admin messages, or an empty string. Raises: UnknownCapabilityError, if a specified capability was not recognized.'
def admin_message(self):
message_list = [] for config in self._get_status().config_list(): message = config.admin_message() if (message and (message not in message_list)): message_list.append(message) return ' '.join(message_list)
'Get an IsEnabledResponse for the capabilities listed. Returns: IsEnabledResponse for the specified capabilities. Raises: UnknownCapabilityError: If an unknown capability was requested.'
def _get_status(self):
req = IsEnabledRequest() req.set_package(self._package) for capability in self._capabilities: req.add_capability(capability) for method in self._methods: req.add_call(method) resp = capability_service_pb.IsEnabledResponse() self._stub_map.MakeSyncCall('capability_service', 'IsEna...
'Constructor. Args: service_name: Service name expected for all calls.'
def __init__(self, service_name='capability_service'):
super(CapabilityServiceStub, self).__init__(service_name) self._packages = dict.fromkeys(SUPPORTED_CAPABILITIES, True)
'Set all features of a given package to enabled. This method is thread-unsafe, so should only be called during set-up, before multiple API server threads start. Args: package: Name of package. enabled: True to enable, False to disable.'
def SetPackageEnabled(self, package, enabled):
self._packages[package] = enabled
'Implementation of CapabilityService::IsEnabled(). Args: request: An IsEnabledRequest. response: An IsEnabledResponse.'
def _Dynamic_IsEnabled(self, request, response):
default_config = response.add_config() default_config.set_package('') default_config.set_capability('') try: package_enabled = self._packages[request.package()] except KeyError: summary_status = IsEnabledResponse.UNKNOWN config_status = CapabilityConfig.UNKNOWN else: ...
'Constructor. Args: service_name: Service name expected for all calls. max_request_size: int, maximum allowable size of the incoming request. A apiproxy_errors.RequestTooLargeError will be raised if the inbound request exceeds this size. Default is 1 MB. request_data: A request_info.RequestInfo instance used to look ...
def __init__(self, service_name, max_request_size=MAX_REQUEST_SIZE, request_data=None):
self.__service_name = service_name self.__max_request_size = max_request_size self.request_data = (request_data or request_info._local_request_info) self._mutex = threading.RLock() self.__error = None self.__error_dict = {}
'Creates RPC object instance. Returns: a instance of RPC.'
def CreateRPC(self):
return apiproxy_rpc.RealRPC(stub=self)
'The main RPC entry point. Args: service: Must be name as provided to service_name of constructor. call: A string representing the rpc to make. Must be part of the underlying services methods and impemented by _Dynamic_<call>. request: A protocol buffer of the type corresponding to \'call\'. response: A protocol buffe...
def MakeSyncCall(self, service, call, request, response, request_id=None):
assert (service == self.__service_name), ('Expected "%s" service name, was "%s"' % (self.__service_name, service)) if (request.ByteSize() > self.__max_request_size): raise apiproxy_errors.RequestTooLargeError(('The request to API call %s.%s() was too large.' % (ser...
'Set an error condition that may be raised when calls made to stub. If a method is specified, the error will only apply to that call. The error rate is applied to the method specified or all calls if method is not set. Args: error: An instance of apiproxy_errors.Error or None for no error. method: A string representing...
def SetError(self, error, method=None, error_rate=1):
assert ((error is None) or isinstance(error, apiproxy_errors.Error)) if (method and error): self.__error_dict[method] = (error, error_rate) else: self.__error_rate = error_rate self.__error = error
'Object mapper starts off with empty value.'
def __init__(self):
self.value = None self.seen = set()
'Set value of instance to map to. Args: value: Instance that this mapper maps to.'
def set_value(self, value):
self.value = value
'Object sequencer starts off with empty value.'
def __init__(self):
self.value = [] self.constructor = None
'Set object used for constructing new sequence instances. Args: constructor: Callable which can accept no arguments. Must return an instance of the appropriate class for the container.'
def set_constructor(self, constructor):
self.constructor = constructor
'Initialize validated object builder. Args: default_class: Class that is instantiated upon the detection of a new document. An instance of this class will act as the document itself.'
def __init__(self, default_class):
self.default_class = default_class
'Get the ultimate type of a repeated validator. Looks for an instance of validation.Repeated, returning its constructor. Args: attribute: Repeated validator attribute to find type for. Returns: The expected class of of the Type validator, otherwise object.'
def _GetRepeated(self, attribute):
if isinstance(attribute, validation.Optional): attribute = attribute.validator if isinstance(attribute, validation.Repeated): return attribute.constructor return object
'Instantiate new root validated object. Returns: New instance of validated object.'
def BuildDocument(self):
return self.default_class()
'New instance of object mapper for opening map scope. Args: top_value: Parent of nested object. Returns: New instance of object mapper.'
def BuildMapping(self, top_value):
result = _ObjectMapper() if isinstance(top_value, self.default_class): result.value = top_value return result
'When leaving scope, makes sure new object is initialized. This method is mainly for picking up on any missing required attributes. Args: top_value: Parent of closing mapping object. mapping: _ObjectMapper instance that is leaving scope.'
def EndMapping(self, top_value, mapping):
try: mapping.value.CheckInitialized() except validation.ValidationError: raise except Exception as e: try: error_str = str(e) except Exception: error_str = '<unknown>' raise validation.ValidationError(error_str, e)
'New instance of object sequence. Args: top_value: Object that contains the new sequence. Returns: A new _ObjectSequencer instance.'
def BuildSequence(self, top_value):
return _ObjectSequencer()
'Map key-value pair to an objects attribute. Args: subject: _ObjectMapper of object that will receive new attribute. key: Key of attribute. value: Value of new attribute. Raises: UnexpectedAttribute when the key is not a validated attribute of the subject value class.'
def MapTo(self, subject, key, value):
assert isinstance(subject.value, validation.ValidatedBase) try: attribute = subject.value.GetValidator(key) except validation.ValidationError as err: raise yaml_errors.UnexpectedAttribute(err) if isinstance(value, _ObjectMapper): value.set_value(attribute.expected_type()) ...
'Append a value to a sequence. Args: subject: _ObjectSequence that is receiving new value. value: Value that is being appended to sequence.'
def AppendTo(self, subject, value):
if isinstance(value, _ObjectMapper): value.set_value(subject.constructor()) subject.value.append(value.value) else: subject.value.append(value)
'Initializer. Args: persist: For backwards compatability. Has no effect. logs_path: A str containing the filename to use for logs storage. Defaults to in-memory if unset. request_data: A apiproxy_stub.RequestData instance used to look up state associated with the request that generated an API call.'
def __init__(self, persist=False, logs_path=None, request_data=None):
super(LogServiceStub, self).__init__('logservice', request_data=request_data) self._pending_requests = defaultdict(logging_capnp.RequestLog.new_message) self._pending_requests_applogs = dict() self._log_server = defaultdict(Queue) self._log_server_ip = file_io.read('/etc/appscale/head_node_private_i...
'Starts logging for a request. Each start_request call must be followed by a corresponding end_request call to cleanup resources allocated in start_request. Args: request_id: A unique string identifying the request associated with the API call. user_request_id: A user-visible unique string for retrieving the request lo...
@apiproxy_stub.Synchronized def start_request(self, request_id, user_request_id, ip, app_id, version_id, nickname, user_agent, host, method, resource, http_version, start_time=None):
if (start_time is None): start_time = self._get_time_usec() rl = self._pending_requests[request_id] rl.appId = app_id rl.versionId = version_id rl.requestId = request_id rl.ip = ip rl.nickname = nickname rl.startTime = start_time rl.method = method rl.resource = resource ...
'Ends logging for a request. Args: request_id: A unique string identifying the request associated with the API call. status: An int containing the HTTP status code for this request. response_size: An int containing the content length of the response. end_time: An int containing the end time in micro-seconds. If unset, ...
@apiproxy_stub.Synchronized def end_request(self, request_id, status, response_size, end_time=None):
if (end_time is None): end_time = self._get_time_usec() rl = self._pending_requests.get(request_id, None) if (rl is None): return rl.status = status rl.responseSize = response_size rl.endTime = end_time self._pending_requests_applogs[request_id].finish() buf = rl.to_bytes...
'Writes application-level log messages for a request.'
def _Dynamic_Flush(self, request, unused_response, request_id):
rl = self._pending_requests.get(request_id, None) if (rl is None): return group = log_service_pb.UserAppLogGroup(request.logs()) logs = group.log_line_list() for log in logs: al = self._pending_requests_applogs[request_id].add() al.time = log.timestamp_usec() al.level...
'Binary offset indicating the current position in the result stream. May be submitted to future Log read requests to continue iterating logs starting exactly where this iterator left off. Returns: A byte string representing an offset into the log stream, or None.'
@property def offset(self):
return self.__offset
'End time of the last request examined prior to the timeout, or None. Returns: A float representing the completion time in seconds since the Unix epoch of the last request examined.'
@property def last_end_time(self):
return self.__last_end_time
'Initializes the buffer, which wraps the given stream or sys.stderr. The state of the LogsBuffer is protected by a separate lock. The lock is acquired before any variables are mutated or accessed, and released afterward. A recursive lock is used so that a single thread can acquire the lock multiple times, and release...
def __init__(self, stream=None, stderr=False):
self._stderr = stderr if self._stderr: assert (stream is None) else: self._stream = (stream or cStringIO.StringIO()) self._lock = threading.RLock() self._reset()
'Calls \'method\' while holding the buffer lock.'
def _lock_and_call(self, method, *args):
self._lock.acquire() try: return method(*args) finally: self._lock.release()
'Returns the underlying file-like object used to buffer logs.'
def stream(self):
if self._stderr: return sys.stderr else: return self._stream
'Returns the number of log lines currently buffered.'
def lines(self):
return self._lock_and_call((lambda : self._lines))
'Returns the size of the log buffer, in bytes.'
def bytes(self):
return self._lock_and_call((lambda : self._bytes))
'Returns the number of seconds since the log buffer was flushed.'
def age(self):
return self._lock_and_call((lambda : (time.time() - self._flush_time)))
'Returns last time that the log buffer was flushed.'
def flush_time(self):
return self._lock_and_call((lambda : self._flush_time))
'Returns the contents of the logs buffer.'
def contents(self):
return self._lock_and_call(self._contents)
'Internal version of contents() with no locking.'
def _contents(self):
try: return self.stream().getvalue() except AttributeError: return ''
'Resets the buffer state, without clearing the underlying stream.'
def reset(self):
self._lock_and_call(self._reset)
'Internal version of reset() with no locking.'
def _reset(self):
contents = self._contents() self._bytes = len(contents) self._lines = (len(contents.split('\n')) - 1) self._flush_time = time.time() self._request = logsutil.RequestID()
'Clears the contents of the logs buffer, and resets autoflush state.'
def clear(self):
self._lock_and_call(self._clear)
'Internal version of clear() with no locking.'
def _clear(self):
if (self._bytes > 0): self.stream().truncate(0) self._reset()
'Closes the underlying stream, flushing the current contents.'
def close(self):
self._lock_and_call(self._close)
'Internal version of close() with no locking.'
def _close(self):
self._flush() self.stream().close()
'Parse the contents of the buffer and return an array of log lines.'
def parse_logs(self):
return logsutil.ParseLogs(self.contents())
'Writes a line to the logs buffer.'
def write(self, line):
return self._lock_and_call(self._write, line)
'Writes each line in the given sequence to the logs buffer.'
def writelines(self, seq):
for line in seq: self.write(line)
'Writes a line to the logs buffer.'
def _write(self, line):
if (self._request != logsutil.RequestID()): self._reset() self.stream().write(line) self._lines += 1 self._bytes += len(line) self._autoflush()
'Truncates a potentially long log down to a specified maximum length.'
@staticmethod def _truncate(line, max_length=_MAX_LINE_SIZE):
if (len(line) > max_length): original_length = len(line) suffix = ('...(length %d)' % original_length) line = (line[:(max_length - len(suffix))] + suffix) return line
'Flushes the contents of the logs buffer. This method holds the buffer lock until the API call has finished to ensure that flush calls are performed in the correct order, so that log messages written during the flush call aren\'t dropped or accidentally wiped, and so that the other buffer state variables (flush time, l...
def flush(self):
self._lock_and_call(self._flush)
'Internal version of flush() with no locking.'
def _flush(self):
logs = self.parse_logs() first_iteration = True while (logs or first_iteration): first_iteration = False request = log_service_pb.FlushRequest() group = log_service_pb.UserAppLogGroup() byte_size = 0 n = 0 for entry in logs: if (len(entry[2]) > Log...
'Flushes the buffer if certain conditions have been met.'
def autoflush(self):
self._lock_and_call(self._autoflush)
'Internal version of autoflush() with no locking.'
def _autoflush(self):
if (not self.autoflush_enabled()): return if ((AUTOFLUSH_EVERY_SECONDS and (self.age() >= AUTOFLUSH_EVERY_SECONDS)) or (AUTOFLUSH_EVERY_LINES and (self.lines() >= AUTOFLUSH_EVERY_LINES)) or (AUTOFLUSH_EVERY_BYTES and (self.bytes() >= AUTOFLUSH_EVERY_BYTES))): self._flush()
'Indicates if the buffer will periodically flush logs during a request.'
def autoflush_enabled(self):
return AUTOFLUSH_ENABLED
'Constructor. Args: request: A LogReadRequest object that will be used for Read calls.'
def __init__(self, request, timeout=None):
self._request = request self._logs = [] self._read_called = False self._last_end_time = None self._end_time = None if (timeout is not None): self._end_time = (time.time() + timeout)
'Provides an iterator that yields log records one at a time.'
def __iter__(self):
while True: for log_item in self._logs: (yield RequestLog(log_item)) if ((not self._read_called) or self._request.has_offset()): if (self._end_time and (time.time() >= self._end_time)): offset = None if self._request.has_offset(): ...
'Acquires additional logs via cursor. This method is used by the iterator when it has exhausted its current set of logs to acquire more logs and update its internal structures accordingly.'
def _advance(self):
response = log_service_pb.LogReadResponse() try: apiproxy_stub_map.MakeSyncCall('logservice', 'Read', self._request, response) except apiproxy_errors.ApplicationError as e: if (e.application_error == log_service_pb.LogServiceError.INVALID_REQUEST): raise InvalidArgumentError(e.er...
'Application id that handled this request, as a string.'
@property def app_id(self):
return self.__pb.app_id()
'Module id that handled this request, as a string.'
@property def server_id(self):
logging.warning('The server_id property is deprecated, please use the module_id property instead.') return self.__pb.module_id()
'Module id that handled this request, as a string.'
@property def module_id(self):
return self.__pb.module_id()
'Version of the application that handled this request, as a string.'
@property def version_id(self):
return self.__pb.version_id()
'Globally unique identifier for a request, based on request start time. Request ids for requests which started later will compare greater as binary strings than those for requests which started earlier. Returns: A byte string containing a unique identifier for this request.'
@property def request_id(self):
return self.__pb.request_id()
'Binary offset indicating current position in the result stream. May be submitted to future Log read requests to continue immediately after this request. Returns: A byte string representing an offset into the active result stream.'
@property def offset(self):
if self.__pb.has_offset(): return self.__pb.offset().Encode() return None
'The origin IP address of the request, as a string.'
@property def ip(self):
return self.__pb.ip()
'Nickname of the user that made the request if known and logged in. Returns: A string representation of the logged in user\'s nickname, or None.'
@property def nickname(self):
if self.__pb.has_nickname(): return self.__pb.nickname() return None
'Time at which request was known to have begun processing. Returns: A float representing the time this request began processing in seconds since the Unix epoch.'
@property def start_time(self):
return (self.__pb.start_time() / 1000000.0)
'Time at which request was known to have completed. Returns: A float representing the request completion time in seconds since the Unix epoch.'
@property def end_time(self):
return (self.__pb.end_time() / 1000000.0)
'Time required to process request in seconds, as a float.'
@property def latency(self):
return (self.__pb.latency() / 1000000.0)
'Number of machine cycles used to process request, as an integer.'
@property def mcycles(self):
return self.__pb.mcycles()
'Request method (GET, PUT, POST, etc), as a string.'
@property def method(self):
return self.__pb.method()
'Resource path on server requested by client. For example, http://nowhere.com/app would have a resource string of \'/app\'. Returns: A string containing the path component of the request URL.'
@property def resource(self):
return self.__pb.resource()
'HTTP version of request, as a string.'
@property def http_version(self):
return self.__pb.http_version()
'Response status of request, as an int.'
@property def status(self):
return self.__pb.status()
'Size in bytes sent back to client by request, as a long.'
@property def response_size(self):
return self.__pb.response_size()
'Referrer URL of request as a string, or None.'
@property def referrer(self):
if self.__pb.has_referrer(): return self.__pb.referrer() return None
'User agent used to make the request as a string, or None.'
@property def user_agent(self):
if self.__pb.has_user_agent(): return self.__pb.user_agent() return None
'File or class within URL mapping used for request. Useful for tracking down the source code which was responsible for managing request, especially for multiply mapped handlers. Returns: A string containing a file or class name.'
@property def url_map_entry(self):
return self.__pb.url_map_entry()
'Apache combined log entry for request. The information in this field can be constructed from the rest of this message, however, this field is included for convenience. Returns: A string containing an Apache-style log line in the form documented at http://httpd.apache.org/docs/1.3/logs.html.'
@property def combined(self):
return self.__pb.combined()
'Number of machine cycles spent in API calls while processing request. Deprecated. This value is no longer meaningful. Returns: Number of API machine cycles used as a long, or None if not available.'
@property def api_mcycles(self):
warnings.warn('api_mcycles does not return a meaningful value.', DeprecationWarning, stacklevel=2) if self.__pb.has_api_mcycles(): return self.__pb.api_mcycles() return None
'The Internet host and port number of the resource being requested. Returns: A string representing the host and port receiving the request, or None if not available.'
@property def host(self):
if self.__pb.has_host(): return self.__pb.host() return None
'The estimated cost of this request, in fractional dollars. Returns: A float representing an estimated fractional dollar cost of this request, or None if not available.'
@property def cost(self):
if self.__pb.has_cost(): return self.__pb.cost() return None
'The request\'s queue name, if generated via the Task Queue API. Returns: A string containing the request\'s queue name if relevant, or None.'
@property def task_queue_name(self):
if self.__pb.has_task_queue_name(): return self.__pb.task_queue_name() return None
'The request\'s task name, if generated via the Task Queue API. Returns: A string containing the request\'s task name if relevant, or None.'
@property def task_name(self):
if self.__pb.has_task_name(): return self.__pb.task_name()
'Returns whether this request was a loading request for an instance. Returns: A bool indicating whether this request was a loading request.'
@property def was_loading_request(self):
return bool(self.__pb.was_loading_request())