desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Starts the API Server process.'
def Start(self):
assert (not self._process), 'Start() can only be called once' self._process = subprocess.Popen(self._args)
'Waits until the API Server is ready to handle requests. Args: timeout: The maximum number of seconds to wait for the server to be ready. Raises: Error: if the server process exits or is not ready in "timeout" seconds.'
def WaitUntilServing(self, timeout=30.0):
assert self._process, 'server was not started' finish_time = (time.time() + timeout) while (time.time() < finish_time): if (self._process.poll() is not None): raise Error('server has already exited with return: %r', self._process.returncode) if self._Ca...
'Causes the API Server process to exit. Args: timeout: The maximum number of seconds to wait for an orderly shutdown before forceably killing the process.'
def Quit(self, timeout=5.0):
assert self._process, 'server was not started' if (self._process.poll() is None): try: urllib2.urlopen((self.url + QUIT_PATH)) except urllib2.URLError: pass finish_time = (time.time() + timeout) while ((time.time() < finish_time) and (self._proces...
'Process an HTTP request. Args: method: A str containing the HTTP method of the request. relative_url: A str containing path and query string of the request. headers: A list of (key, value) tuples where key and value are both str. body: A str containing the request body. source_ip: The source ip address for the request...
def add_request(self, method, relative_url, headers, body, source_ip, server_name=None, version=None, instance_id=None):
try: header_dict = wsgiref.headers.Headers(headers) connection_host = header_dict.get('host') connection = httplib.HTTPConnection(connection_host) connection.putrequest(method, relative_url, skip_host=('host' in header_dict), skip_accept_encoding=('accept-encoding' in header_dict)) ...
'Creates a new HttpRpcServer. Args: host: The host to send requests to. auth_function: A function that takes no arguments and returns an (email, password) tuple when called. Will be called if authentication is required. user_agent: The user-agent string to send to the server. Specify None to omit the user-agent header....
def __init__(self, host, auth_function, user_agent, source, host_override=None, extra_headers=None, save_cookies=False, auth_tries=3, account_type=None, debug_data=True, secure=True, ignore_certs=False, rpc_tries=3):
self._APPSCALE_LOGIN_PAGE = 'users/login' self._APPSCALE_AUTH_PAGE = 'users/authenticate' if secure: self.scheme = 'https' else: self.scheme = 'http' self.ignore_certs = ignore_certs self.host = host self.host_override = host_override self.auth_function = auth_function ...
'Returns an OpenerDirector for making HTTP requests. Returns: A urllib2.OpenerDirector object.'
def _GetOpener(self):
raise NotImplementedError
'Creates a new urllib request.'
def _CreateRequest(self, url, data=None):
req = fancy_urllib.FancyRequest(url, data=data) if self.host_override: req.add_header('Host', self.host_override) for (key, value) in self.extra_headers.iteritems(): req.add_header(key, value) return req
'Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user\'s email address password: The user\'s password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authentication token returned...
def _GetAuthToken(self, email, password):
account_type = self.account_type if (not account_type): if (self.host.split(':')[0].endswith('.google.com') or (self.host_override and self.host_override.split(':')[0].endswith('.google.com'))): account_type = 'HOSTED_OR_GOOGLE' else: account_type = 'GOOGLE' data = {'...
'Returns the AppDashboard\'s public IP address. AppScale uses this method to avoid having to run the AppDashboard on every virtual machine in the deployment. We ask for the public IP (as opposed to the private IP) because we force the user to redirect their web browser to that IP, so it must be accessible from the user...
def _GetAppDashboardPublicIP(self):
try: file_handle = open(APPSCALE_LOGIN_IP) raw_ips = file_handle.read() file_handle.close() ips = raw_ips.split('\n') ip = ips[0] except IOError: logger.info(("Saw an IOError when trying to get the AppDashboard's" + 'public IP, return...
'Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies.'
def _GetAuthCookie(self, auth_token):
continue_location = ('http://%s:1080/' % self._GetAppDashboardPublicIP()) args = {'continue': continue_location, 'auth': auth_token} login_path = os.environ.get('APPCFG_LOGIN_PATH', '/_ah') req = self._CreateRequest(('%s://%s%s/login?%s' % (self.scheme, self.host, login_path, urllib.urlencode(args)))) ...
'Authenticates the user. The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). 3) We pass the auth token to /_ah/login on the server to obtain an authen...
def _Authenticate(self):
for unused_i in range(self.auth_tries): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) if (os.getenv('APPENGINE_RPC_USE_SID', '0') == '1'): return except ClientLoginError as e: if (e....
'Attempts to authenticate user with AppScale\'s AppServer. If successful, saves authentication information to the cookies directory which is mapped to HttpRpcServer.APPSCALE_COOKIE_DIR.'
def _AppScaleAuthenticate(self):
if (not self.read_credentials): credentials = self.auth_function() self.username = credentials[0] self.password = credentials[1] self.read_credentials = True curl_command = 'curl -k ' curl_command += ('-c %s ' % self._GetAppScaleCookiePath()) curl_command += (...
'Extracts the AppServer IP/DNS from the AppServer URL. Returns: AppServer IP extracted from the AppServer URL. Example : 128.111.55.227.'
def _GetAppServerName(self):
tokens = self.appserver_url.split(':') if (len(tokens) == 0): return None return tokens[0]
'Takes the host and port of where the application is hosted and extracts the host of the AppScale Dashboard. Returns: The host of the AppScale Dashboard. Raises: AppScaleAuthenticationError: When it fails to parse the hostname.'
def _GetAppScaleDashboardHost(self):
host = self.host.split(':') if (len(host) < 1): raise AppScaleAuthenticationError(('Could not authenticate with ' + ('AppScale. Bad URL endpoint provided: %s.' % self.host))) return host[0]
'Returns the authentication URL for the AppScale Dashboard based off the location of where the application is hosted. Returns: A str of the URL for the AppScale Dashboard\'s authentication page'
def _GetAppScaleDashboardAuthUrl(self):
host = self._GetAppScaleDashboardHost() scheme = (self.scheme if self.scheme.endswith('s') else (self.scheme + 's')) return ('%s://%s:1443/%s' % (scheme, host, self._APPSCALE_AUTH_PAGE))
'Runs a system command and reports failures. Args: command: Command string to be executed. Raises: BadCommandError: On failure to execute the given command. Returns: A tuple containing : (command_exit_status, command_output). command_exit_status: an integer containing the exit status of the command. command_output: a s...
def _RunCommand(self, command):
(cmd_status, cmd_output) = commands.getstatusoutput(command) if (cmd_status != 0): raise BadCommandError(cmd_status, command) return (cmd_status, cmd_output)
'Returns the cookie path for the current AppServer. Returns: A string to the file system location of the AppScale cookie.'
def _GetAppScaleCookiePath(self):
app_server_name = None if (self.appserver_url is not None): app_server_name = self._GetAppServerName() else: app_server_name = '' return os.path.expanduser(('%s_%s' % (HttpRpcServer.APPSCALE_COOKIE_FILE_PATH, app_server_name)))
'Loads the AppScale authentication cookie for the current AppServer.'
def _LoadAppScaleCookie(self):
self.cookie_jar.clear_session_cookies() self.cookie_jar.filename = self._GetAppScaleCookiePath() if os.path.exists(self.cookie_jar.filename): try: self.cookie_jar.load() logger.info(('Loaded authentication cookies from %s' % self.cookie_jar.filename)) exce...
'Extracts the web application remote API path from the request path. Example: If request path is "/apps/guestbook/remote_api", then the value returned is "/remote_api". Args: request_path: String containing the request_path.'
def _ExtractRemoteApiPath(self, request_path):
remoteApiPath = request_path if request_path.endswith('remote_api'): return '/remote_api' return remoteApiPath
'Authenticates the user on the dev_appserver.'
def _DevAppServerAuthenticate(self):
credentials = self.auth_function() value = dev_appserver_login.CreateCookieData(credentials[0], True) self.extra_headers['Cookie'] = ('dev_appserver_login="%s"; Path=/;' % value)
'Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for large requests o...
def Send(self, request_path, payload='', content_type='application/octet-stream', timeout=None, **kwargs):
auth_domain = '' if ('AUTH_DOMAIN' in os.environ): auth_domain = os.environ['AUTH_DOMAIN'].lower() old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: tries = 0 while True: tries += 1 if (auth_domain == 'appscale'): ...
'Creates a new urllib request.'
def _CreateRequest(self, url, data=None):
req = super(HttpRpcServer, self)._CreateRequest(url, data) if (self.cert_file_available and fancy_urllib.can_validate_certs()): req.set_ssl_info(ca_certs=self.certpath) return req
'Save the cookie jar after authentication.'
def _Authenticate(self):
if (self.cert_file_available and (not fancy_urllib.can_validate_certs())): logger.warn('ssl module not found.\nWithout the ssl module, the identity of the remote host cannot be verified, and\nconnections may NOT be secure. To fix this, ...
'Attempts to authenticate user with AppServer. If successful, saves authentication information to the cookie file mapped to HttpRpcServer.APPSCALE_COOKIE_FILE_PATH.'
def _AppScaleAuthenticate(self):
super(HttpRpcServer, self)._AppScaleAuthenticate() if ((self.cookie_jar.filename is not None) and (not self.save_cookies)): logger.info(('Deleting authentication cookie : %s' % self.cookie_jar.filename)) os.remove(self.cookie_jar.filename)
'Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object.'
def _GetOpener(self):
opener = urllib2.OpenerDirector() opener.add_handler(fancy_urllib.FancyProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler()) opener.add_handler(urllib2.HTTPDefaultErrorHandler()) opener.add_handler(urllib2.HTTPSHandler()) opener.add_handler(ur...
'Creates a new BadCommandError exception. Args: exit_status: Integer representing the exit status of the failed command. command: String containing the command.'
def __init__(self, exit_status, command):
self.exit_status = exit_status self.command = command Exception.__init__(self, command)
'Creates a new AppScaleRedirectionError exception. Args: reason: Message explaining the redirection failure.'
def __init__(self, reason):
self.reason = reason Exception.__init__(self, reason)
'Creates a new AppScaleRedirectionError exception. Args: reason: Message explaining the AppScale authentication failure.'
def __init__(self, reason):
self.reason = reason Exception.__init__(self, reason)
'Configures which paths are allowed to be accessed. Must be called at least once before any file objects are created in the hardened environment. Args: root_path: Absolute path to the root of the application. application_paths: List of additional paths that the application may access, this must include the App Engine r...
@staticmethod def SetAllowedPaths(root_path, application_paths):
FakeFile._application_paths = (set((os.path.realpath(path) for path in application_paths)) | set((os.path.abspath(path) for path in application_paths))) FakeFile._application_paths.add(root_path) FakeFile._root_path = os.path.join(root_path, '') FakeFile._availability_cache = {}
'Configures access to files matching FakeFile._skip_files. Args: allow_skipped_files: Boolean whether to allow access to skipped files'
@staticmethod def SetAllowSkippedFiles(allow_skipped_files):
FakeFile._allow_skipped_files = allow_skipped_files FakeFile._availability_cache = {}
'Allow the use of a module based on where it is located. Meant to be used by use_library() so that it has a link back into the trusted part of the interpreter. Args: name: Name of the module to allow.'
@staticmethod def SetAllowedModule(name):
(stream, pathname, description) = imp.find_module(name) pathname = os.path.normcase(os.path.abspath(pathname)) if stream: stream.close() FakeFile.ALLOWED_FILES.add(pathname) FakeFile.ALLOWED_FILES.add(os.path.realpath(pathname)) else: assert (description[2] == imp.PKG_DIR...
'Sets which files in the application directory are to be ignored. Must be called at least once before any file objects are created in the hardened environment. Must be called whenever the configuration was updated. Args: skip_files: Object with .match() method (e.g. compiled regexp).'
@staticmethod def SetSkippedFiles(skip_files):
FakeFile._skip_files = skip_files FakeFile._availability_cache = {}
'Sets StaticFileConfigMatcher instance for checking if a file is static. Must be called at least once before any file objects are created in the hardened environment. Must be called whenever the configuration was updated. Args: static_file_config_matcher: StaticFileConfigMatcher instance.'
@staticmethod def SetStaticFileConfigMatcher(static_file_config_matcher):
FakeFile._static_file_config_matcher = static_file_config_matcher FakeFile._availability_cache = {}
'Determines if a file\'s path is accessible. SetAllowedPaths(), SetSkippedFiles() and SetStaticFileConfigMatcher() must be called before this method or else all file accesses will raise an error. Args: filename: Path of the file to check (relative or absolute). May be a directory, in which case access for files inside ...
@staticmethod def IsFileAccessible(filename, normcase=os.path.normcase, py27_optional=False):
logical_filename = normcase(os.path.abspath(filename)) result = FakeFile._availability_cache.get(logical_filename) if (result is None): result = FakeFile._IsFileAccessibleNoCache(logical_filename, normcase=normcase, py27_optional=py27_optional) FakeFile._availability_cache[logical_filename] ...
'Determines if a file\'s path is accessible. This is an internal part of the IsFileAccessible implementation. Args: logical_filename: Absolute path of the file to check. normcase: Used for dependency injection. py27_optional: Whether the filename being checked matches the name of an optional python27 runtime library. R...
@staticmethod def _IsFileAccessibleNoCache(logical_filename, normcase=os.path.normcase, py27_optional=False):
logical_dirfakefile = logical_filename is_dir = False if os.path.isdir(logical_filename): logical_dirfakefile = os.path.join(logical_filename, 'foo') is_dir = True if IsPathInSubdirectories(logical_dirfakefile, [FakeFile._root_path], normcase=normcase): relative_filename = logica...
'Initializer. See file built-in documentation.'
def __init__(self, filename, mode='r', bufsize=(-1), **kwargs):
if (mode not in FakeFile.ALLOWED_MODES): raise IOError(('invalid mode: %s' % mode)) if (not FakeFile.IsFileAccessible(filename)): raise IOError(errno.EACCES, 'file not accessible', filename) super(FakeFile, self).__init__(filename, mode, bufsize, **kwargs)
'Initializer. Args: original_func: Callable that takes as its first argument the path to a file or directory on disk; all subsequent arguments may be variable.'
def __init__(self, original_func):
self._original_func = original_func
'Enforces access permissions for the function passed to the constructor.'
def __call__(self, path, *args, **kwargs):
if (not FakeFile.IsFileAccessible(path)): raise OSError(errno.EACCES, 'path not accessible', path) return self._original_func(path, *args, **kwargs)
'Logs an import-related message to stderr, with indentation based on current call-stack depth. Args: message: Logging format string. args: Positional format parameters for the logging message.'
def log(self, message, *args):
if HardenedModulesHook.ENABLE_LOGGING: indent = (self._indent_level * ' ') print >>sys.__stderr__, (indent + (message % args))
'Initializer. Args: config: AppInfoExternal instance representing the parsed app.yaml file. module_dict: Module dictionary to use for managing system modules. Should be sys.modules. app_code_path: The absolute path to the application code on disk. imp_module, os_module, dummy_thread_module, etc.: References to modules ...
def __init__(self, config, module_dict, app_code_path, imp_module=imp, os_module=os, dummy_thread_module=dummy_thread, pickle_module=pickle):
self._config = config self._module_dict = module_dict self._imp = imp_module self._os = os_module self._dummy_thread = dummy_thread_module self._pickle = pickle self._indent_level = 0 self._app_code_path = app_code_path self._white_list_c_modules = list(self._WHITE_LIST_C_MODULES) ...
'See PEP 302.'
@Trace def find_module(self, fullname, path=None):
if (fullname in ('cPickle', 'thread')): return self search_path = path all_modules = fullname.split('.') try: for (index, current_module) in enumerate(all_modules): current_module_fullname = '.'.join(all_modules[:(index + 1)]) if ((current_module_fullname == fulln...
'Check if the named module has a stub replacement.'
def StubModuleExists(self, name):
if (name in sys.builtin_module_names): name = ('py_%s' % name) if (self._config and (self._config.runtime == 'python27')): if (name in dist27.MODULE_OVERRIDES): return True elif (name in dist.__all__): return True return False
'Import the stub module replacement for the specified module.'
def ImportStubModule(self, name):
if (name in sys.builtin_module_names): name = ('py_%s' % name) providing_dist = dist if (self._config and (self._config.runtime == 'python27')): if (name in dist27.__all__): providing_dist = dist27 fullname = ('%s.%s' % (providing_dist.__name__, name)) __import__(fullname...
'Prunes and overrides restricted module attributes. Args: module: The module to prune. This should be a new module whose attributes reference back to the real module\'s __dict__ members.'
@Trace def FixModule(self, module):
if (module.__name__ in self._white_list_partial_modules): allowed_symbols = self._white_list_partial_modules[module.__name__] for symbol in (set(module.__dict__) - set(allowed_symbols)): if (not (symbol.startswith('__') and symbol.endswith('__'))): del module.__dict__[sym...
'Locates a module while enforcing module import restrictions. Args: submodule: The short name of the submodule (i.e., the last section of the fullname; for \'foo.bar\' this would be \'bar\'). submodule_fullname: The fully qualified name of the module to find (e.g., \'foo.bar\'). search_path: List of paths to search for...
@Trace def FindModuleRestricted(self, submodule, submodule_fullname, search_path):
if (search_path is None): search_path = ([None] + sys.path) search_path += ['/usr/local/lib/python2.7/dist-packages/lxml-3.2.3-py2.7-linux-x86_64.egg'] py27_optional = False py27_enabled = False topmodule = None if (self._config and (self._config.runtime == 'python27')): topm...
'Helper for FindModuleRestricted to find a module in a sys.path entry. Args: submodule: submodule_fullname: path_entry: A single sys.path entry, or None representing the builtins. Returns: Either None (if nothing was found), or a triple (source_file, path_name, description). See the doc string for FindModuleRestricted...
def FindPathHook(self, submodule, submodule_fullname, path_entry):
if (path_entry is None): if (submodule_fullname in sys.builtin_module_names): try: result = self._imp.find_module(submodule) except ImportError: pass else: (source_file, pathname, description) = result (suffi...
'Loads a module while enforcing module import restrictions. As a byproduct, the new module will be added to the module dictionary. Args: submodule_fullname: The fully qualified name of the module to find (e.g., \'foo.bar\'). source_file: File-like object that contains the module\'s source code, or a PEP-302-style loade...
@Trace def LoadModuleRestricted(self, submodule_fullname, source_file, pathname, description):
if (description == (None, None, None)): return source_file.load_module(submodule_fullname) try: return self._imp.load_module(submodule_fullname, source_file, pathname, description) except: if (submodule_fullname in self._module_dict): del self._module_dict[submodule_fulln...
'Finds and loads a module, loads it, and adds it to the module dictionary. Args: submodule: Name of the module to import (e.g., baz). submodule_fullname: Full name of the module to import (e.g., foo.bar.baz). search_path: Path to use for searching for this submodule. For top-level modules this should be None; otherwise...
@Trace def FindAndLoadModule(self, submodule, submodule_fullname, search_path):
module = self._imp.new_module(submodule_fullname) if (submodule_fullname == 'thread'): module.__dict__.update(self._dummy_thread.__dict__) module.__name__ = 'thread' elif (submodule_fullname == 'cPickle'): module.__dict__.update(self._pickle.__dict__) module.__name__ = 'cPick...
'Retrieves the parent package of a fully qualified module name. Args: fullname: Full name of the module whose parent should be retrieved (e.g., foo.bar). Returns: Module instance for the parent or None if there is no parent module. Raise: ImportError exception if the module\'s parent could not be found.'
@Trace def GetParentPackage(self, fullname):
all_modules = fullname.split('.') parent_module_fullname = '.'.join(all_modules[:(-1)]) if parent_module_fullname: if (self.find_module(fullname) is None): raise ImportError(('Could not find module %s' % fullname)) return self._module_dict[parent_module_fullname] ...
'Determines the search path of a module\'s parent package. Args: fullname: Full name of the module to look up (e.g., foo.bar). Returns: Tuple (submodule, search_path) where: submodule: The last portion of the module name from fullname (e.g., if fullname is foo.bar, then this is bar). search_path: List of paths that bel...
@Trace def GetParentSearchPath(self, fullname):
submodule = GetSubmoduleName(fullname) parent_package = self.GetParentPackage(fullname) search_path = None if ((parent_package is not None) and hasattr(parent_package, '__path__')): search_path = parent_package.__path__ return (submodule, search_path)
'Determines the path on disk and the search path of a module or package. Args: fullname: Full name of the module to look up (e.g., foo.bar). Returns: Tuple (pathname, search_path, submodule) where: pathname: String containing the full path of the module on disk, or None if the module wasn\'t loaded from disk (e.g. from...
@Trace def GetModuleInfo(self, fullname):
(submodule, search_path) = self.GetParentSearchPath(fullname) (source_file, pathname, description) = self.FindModuleRestricted(submodule, fullname, search_path) (suffix, mode, file_type) = description module_search_path = None if (file_type == self._imp.PKG_DIRECTORY): module_search_path = [...
'See PEP 302.'
@Trace def load_module(self, fullname):
all_modules = fullname.split('.') submodule = all_modules[(-1)] parent_module_fullname = '.'.join(all_modules[:(-1)]) search_path = None if (parent_module_fullname and (parent_module_fullname in self._module_dict)): parent_module = self._module_dict[parent_module_fullname] if hasattr...
'See PEP 302 extensions.'
@Trace def is_package(self, fullname):
(submodule, search_path) = self.GetParentSearchPath(fullname) (source_file, pathname, description) = self.FindModuleRestricted(submodule, fullname, search_path) (suffix, mode, file_type) = description if (file_type == self._imp.PKG_DIRECTORY): return True return False
'See PEP 302 extensions.'
@Trace def get_source(self, fullname):
(full_path, search_path, submodule) = self.GetModuleInfo(fullname) if (full_path is None): return None source_file = open(full_path) try: return source_file.read() finally: source_file.close()
'See PEP 302 extensions.'
@Trace def get_code(self, fullname):
(full_path, search_path, submodule) = self.GetModuleInfo(fullname) if (full_path is None): return None source_file = open(full_path) try: source_code = source_file.read() finally: source_file.close() source_code = source_code.replace('\r\n', '\n') if (not source_code....
'Add a new socket to watch. Args: s: A socket to select on. callback: A callable with no args to be called when s is ready for a read.'
def add_socket(self, s, callback):
with self._lock: self._file_descriptors = self._file_descriptors.union([s.fileno()]) new_file_descriptor_to_callback = self._file_descriptor_to_callback.copy() new_file_descriptor_to_callback[s.fileno()] = callback self._file_descriptor_to_callback = new_file_descriptor_to_callback
'Remove a watched socket.'
def remove_socket(self, s):
with self._lock: self._file_descriptors = self._file_descriptors.difference([s.fileno()]) new_file_descriptor_to_callback = self._file_descriptor_to_callback.copy() del new_file_descriptor_to_callback[s.fileno()] self._file_descriptor_to_callback = new_file_descriptor_to_callback
'Constructs a _SingleAddressWsgiServer. Args: host: A (hostname, port) tuple containing the hostname and port to bind. The port can be 0 to allow any port. app: A WSGI app to handle requests.'
def __init__(self, host, app):
super(_SingleAddressWsgiServer, self).__init__(host, self) self._lock = threading.Lock() self._app = app self._error = None self.requests = SharedCherryPyThreadPool() self.software = http_runtime_constants.SERVER_SOFTWARE self.request_queue_size = 100
'Starts the _SingleAddressWsgiServer. This is a modified version of the base class implementation. Changes: - Removed unused functionality (Unix domain socket and SSL support). - Raises BindError instead of socket.error. - Uses SharedCherryPyThreadPool instead of wsgiserver.ThreadPool. - Calls _SELECT_THREAD.add_socket...
def start(self):
(host, port) = self.bind_addr try: info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) except socket.gaierror: if (':' in host): info = [(socket.AF_INET6, socket.SOCK_STREAM, 0, '', (self.bind_addr + (0, 0)))] else: ...
'Quits the _SingleAddressWsgiServer.'
def quit(self):
_SELECT_THREAD.remove_socket(self.socket) self.requests.stop(timeout=1)
'Returns the port that the server is bound to.'
@property def port(self):
return self.socket.getsockname()[1]
'Sets the PEP-333 app to use to serve requests.'
def set_app(self, app):
with self._lock: self._app = app
'Sets the HTTP status code to serve for all requests.'
def set_error(self, error):
with self._lock: self._error = error self._app = None
'Constructs a WsgiServer. Args: host: A (hostname, port) tuple containing the hostname and port to bind. The port can be 0 to allow any port. app: A WSGI app to handle requests.'
def __init__(self, host, app):
self.bind_addr = host self._app = app self._servers = []
'Starts the WsgiServer. This starts multiple _SingleAddressWsgiServers to bind the address in all address families. Raises: BindError: The address could not be bound.'
def start(self):
(host, port) = self.bind_addr try: info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) except socket.gaierror: if (':' in host): info = [(socket.AF_INET6, socket.SOCK_STREAM, 0, '', self.bind_addr)] else: info = [(...
'Starts a server for each specified address with a fixed port. Does the work of actually trying to create a _SingleAddressWsgiServer for each specified address. Args: info: An iterable with the same structure as returned by socket.getaddrinfo(). Raises: BindError: The address could not be bound.'
def _start_all_fixed_port(self, info):
for res in info: (_, _, _, _, bind_addr) = res (host, port) = bind_addr[:2] assert (port != 0) server = _SingleAddressWsgiServer((host, port), self._app) try: server.start() except BindError as bind_error: logging.debug('Failed to bind ...
'Starts a server for each specified address with a dynamic port. Does the work of actually trying to create a _SingleAddressWsgiServer for each specified address. Args: info: An iterable with the same structure as returned by socket.getaddrinfo(). Returns: The list of all servers (also saved as self._servers). A non em...
def _start_all_dynamic_port(self, info):
port = 0 for res in info: (_, _, _, _, bind_addr) = res (host, _) = bind_addr[:2] server = _SingleAddressWsgiServer((host, port), self._app) try: server.start() if (port == 0): port = server.port except BindError as bind_error: ...
'Quits the WsgiServer.'
def quit(self):
for server in self._servers: server.quit()
'Returns the port that the server is bound to.'
@property def port(self):
return self._servers[0].socket.getsockname()[1]
'Sets the PEP-333 app to use to serve requests.'
def set_app(self, app):
self._app = app for server in self._servers: server.set_app(app)
'Sets the HTTP status code to serve for all requests.'
def set_error(self, error):
self._error = error self._app = None for server in self._servers: server.set_error(error)
'Serves a request by displaying an error page. Args: environ: An environ dict for the request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. url_map: An appinfo.URLMap instance containing the configuration for the handler matching this request. match: A re.MatchObject containing th...
def handle(self, environ, start_response, url_map, match, request_id, request_type):
start_response('500 Internal Server Error', [('Content-Type', 'text/html')]) (yield '<html><head><title>Invalid PHP Configuration</title></head>') (yield '<body>') (yield '<title>Invalid PHP Configuration</title>') (yield '<b>The PHP interpreter specified with the...
'Initializer for PHPRuntimeInstanceFactory. Args: request_data: A wsgi_request_info.WSGIRequestInfo that will be provided with request information for use by API stubs. runtime_config_getter: A function that can be called without arguments and returns the runtime_config_pb2.Config containing the configuration for the r...
def __init__(self, request_data, runtime_config_getter, module_configuration):
super(PHPRuntimeInstanceFactory, self).__init__(request_data, (8 if runtime_config_getter().threadsafe else 1)) self._runtime_config_getter = runtime_config_getter self._module_configuration = module_configuration self._bad_environment_proxy = None
'Create and return a new Instance. Args: instance_id: A string or integer representing the unique (per module) id of the instance. expect_ready_request: If True then the instance will be sent a special request (i.e. /_ah/warmup or /_ah/start) before it can handle external requests. Returns: The newly created instance.I...
def new_instance(self, instance_id, expect_ready_request=False):
def instance_config_getter(): runtime_config = self._runtime_config_getter() runtime_config.instance_id = str(instance_id) return runtime_config php_executable_path = self._runtime_config_getter().php_config.php_executable_path if (self._php_binary_to_bad_environment_proxy.get(php_ex...
'Initializer for StaticContentHandler. Args: root_path: A string containing the full path of the directory containing the application\'s app.yaml file. url_map: An appinfo.URLMap instance containing the configuration for this handler. url_pattern: A re.RegexObject that matches URLs that should be handled by this handle...
def __init__(self, root_path, url_map, url_pattern):
super(StaticContentHandler, self).__init__(url_map, url_pattern) self._root_path = root_path
'Returns the mime type for the file at the given path.'
def _get_mime_type(self, path):
if (self._url_map.mime_type is not None): return self._url_map.mime_type (_, extension) = os.path.splitext(path) return mimetypes.types_map.get(extension, 'application/octet-stream')
'Serves the response to an OSError or IOError. Args: start_response: A function with semantics defined in PEP-333. This function will be called with a status appropriate to the given exception. e: An instance of OSError or IOError used to generate an HTTP status. Returns: An emply iterable.'
def _handle_io_exception(self, start_response, e):
if (e.errno in _FILE_MISSING_ERRNO_CONSTANTS): start_response('404 Not Found', []) else: start_response('403 Forbidden', []) return []
'Serves the response to a request for a particular file. Note that production App Engine treats all methods as "GET" except "HEAD". Unless set explicitly, the "Expires" and "Cache-Control" headers are deliberately different from their production values to make testing easier. If set explicitly then the values are prese...
def _handle_path(self, full_path, environ, start_response):
data = None if (full_path in self._filename_to_mtime_and_etag): (last_mtime, etag) = self._filename_to_mtime_and_etag[full_path] else: last_mtime = etag = None user_headers = (self._url_map.http_headers or appinfo.HttpHeadersDict()) if_match = environ.get('HTTP_IF_MATCH') if_none...
'Checks if an etag header matches a given etag. Args: etag_headers: A string representing an e-tag header value e.g. \'"xyzzy", "r2d2xxxx", W/"c3piozzzz"\' or \'*\'. etag: The etag to match the header to. If None then only the \'*\' header with match. allow_weak_match: If True then weak etags are allowed to match. Retu...
@staticmethod def _check_etag_match(etag_headers, etag, allow_weak_match):
for etag_header in etag_headers.split(','): if etag_header.startswith('W/'): if allow_weak_match: etag_header = etag_header[2:] else: continue etag_header = etag_header.strip().strip('"') if ((etag_header == '*') or (etag_header == etag...
'Initializer for StaticFilesHandler. Args: root_path: A string containing the full path of the directory containing the application\'s app.yaml file. url_map: An appinfo.URLMap instance containing the configuration for this handler.'
def __init__(self, root_path, url_map):
try: url_pattern = re.compile(('%s$' % url_map.url)) except re.error as e: raise errors.InvalidAppConfigError(('invalid url %r in static_files handler: %s' % (url_map.url, e))) super(StaticFilesHandler, self).__init__(root_path, url_map, url_pattern)
'Serves the file content matching the request. Args: match: The re.MatchObject containing the result of matching the URL against this handler\'s URL pattern. environ: An environ dict for the current request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. Returns: An iterable over st...
def handle(self, match, environ, start_response):
full_path = os.path.join(self._root_path, match.expand(self._url_map.static_files)) return self._handle_path(full_path, environ, start_response)
'Initializer for StaticDirHandler. Args: root_path: A string containing the full path of the directory containing the application\'s app.yaml file. url_map: An appinfo.URLMap instance containing the configuration for this handler.'
def __init__(self, root_path, url_map):
url = url_map.url if (url[(-1)] != '/'): url += '/' try: url_pattern = re.compile(('%s(?P<file>.*)$' % url)) except re.error as e: raise errors.InvalidAppConfigError(('invalid url %r in static_dir handler: %s' % (url, e))) super(StaticDirHandler, self).__ini...
'Serves the file content matching the request. Args: match: The re.MatchObject containing the result of matching the URL against this handler\'s URL pattern. environ: An environ dict for the current request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. Returns: An iterable over st...
def handle(self, match, environ, start_response):
full_path = os.path.join(self._root_path, self._url_map.static_dir, match.group('file')) return self._handle_path(full_path, environ, start_response)
'Start watching a directory for changes.'
def start(self):
self._watcher_thread.start()
'Stop watching a directory for changes.'
def quit(self):
self._quit_event.set()
'Returns True if the watched directory has changed since the last call. start() must be called before this method. Returns: Returns True if the watched directory has changed since the last call to has_changes or, if has_changes has never been called, since start was called.'
def has_changes(self):
with self._has_changes_lock: has_changes = self._has_changes self._has_changes = False return has_changes
'Initializer for Dispatcher. Args: configuration: An application_configuration.ApplicationConfiguration instance storing the configuration data for the app. host: A string containing the host that any HTTP servers should bind to e.g. "localhost". port: An int specifying the first port where servers should listen. auth_...
def __init__(self, configuration, host, port, auth_domain, runtime_stderr_loglevel, php_executable_path, enable_php_remote_debugging, python_config, cloud_sql_config, module_to_max_instances, use_mtime_file_watcher, automatic_restart, allow_skipped_files):
self._configuration = configuration self._php_executable_path = php_executable_path self._enable_php_remote_debugging = enable_php_remote_debugging self._python_config = python_config self._cloud_sql_config = cloud_sql_config self._request_data = None self._api_port = None self._running_...
'Starts the configured modules. Args: api_port: The port that APIServer listens for RPC requests on. request_data: A wsgi_request_info.WSGIRequestInfo that will be provided with request information for use by API stubs.'
def start(self, api_port, request_data):
self._api_port = api_port self._request_data = request_data port = self._port self._executor.start() if self._configuration.dispatch: self._dispatch_server = wsgi_server.WsgiServer((self._host, port), self) self._dispatch_server.start() logging.info('Starting dispatcher ...
'The port that the dispatch HTTP server for the Module is listening on.'
@property def dispatch_port(self):
assert self._dispatch_server, 'dispatch server not running' assert self._dispatch_server.ready, 'dispatch server not ready' return self._dispatch_server.port
'The host that the HTTP server for this Dispatcher is listening on.'
@property def host(self):
return self._host
'The address of the dispatch HTTP server e.g. "localhost:8080".'
@property def dispatch_address(self):
if (self.dispatch_port != 80): return ('%s:%s' % (self.host, self.dispatch_port)) else: return self.host
'Loops until the Dispatcher exits, reloading dispatch.yaml config.'
def _loop_checking_for_updates(self):
while (not self._quit_event.is_set()): self._check_for_updates() self._quit_event.wait(timeout=1)
'Quits all modules.'
def quit(self):
self._executor.quit() self._quit_event.set() if self._dispatch_server: self._dispatch_server.quit() for _module in self._module_name_to_module.values(): with _module.graceful_shutdown_lock: _module.sigterm_sent = True logging.info('Waiting for instances to fin...
'Returns the hostname for a (module, version, instance_id) tuple. If instance_id is set, this will return a hostname for that particular instances. Otherwise, it will return the hostname for load-balancing. Args: module_name: A str containing the name of the module. version: A str containing the version. instance_id: A...
def get_hostname(self, module_name, version, instance_id=None):
_module = self._get_module(module_name, version) if (instance_id is None): return _module.balanced_address else: return _module.get_instance_address(instance_id)
'Returns a list of module names.'
def get_module_names(self):
return list(self._module_name_to_module)
'Returns the module with the given name. Args: _module: A str containing the name of the module. Returns: The module.Module with the provided name. Raises: request_info.ModuleDoesNotExistError: The module does not exist.'
def get_module_by_name(self, _module):
try: return self._module_name_to_module[_module] except KeyError: raise request_info.ModuleDoesNotExistError(_module)
'Returns a list of versions for a module. Args: _module: A str containing the name of the module. Returns: A list of str containing the versions for the specified module. Raises: request_info.ModuleDoesNotExistError: The module does not exist.'
def get_versions(self, _module):
if (_module in self._module_configurations): return [self._module_configurations[_module].major_version] else: raise request_info.ModuleDoesNotExistError(_module)
'Returns the default version for a module. Args: _module: A str containing the name of the module. Returns: A str containing the default version for the specified module. Raises: request_info.ModuleDoesNotExistError: The module does not exist.'
def get_default_version(self, _module):
if (_module in self._module_configurations): return self._module_configurations[_module].major_version else: raise request_info.ModuleDoesNotExistError(_module)
'Add a callable to be run at the specified time. Args: runnable: A callable object to call at the specified time. eta: An int containing the time to run the event, in seconds since the epoch. service: A str containing the name of the service that owns this event. This should be set if event_id is set. event_id: A str c...
def add_event(self, runnable, eta, service=None, event_id=None):
if ((service is not None) and (event_id is not None)): key = (service, event_id) else: key = None self._executor.add_event(runnable, eta, key)
'Update the eta of a scheduled event. Args: eta: An int containing the time to run the event, in seconds since the epoch. service: A str containing the name of the service that owns this event. event_id: A str containing the id of the event to update.'
def update_event(self, eta, service, event_id):
self._executor.update_event(eta, (service, event_id))