desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Tests an image request with resizing.'
def test_run_resize(self):
self.expect_datatore_lookup('SomeBlobKey', True) self.expect_open_image('SomeBlobKey', (1600, 1200)) self.expect_resize(32) self.expect_encode_image('SomeImageSize32') self.mox.ReplayAll() self._environ['PATH_INFO'] += '=s32' self.run_request('image/jpeg', 'SomeImageSize32')
'Tests an image request to resize with a padded blobkey.'
def test_run_resize_with_padded_blobkey(self):
padded_blobkey = 'SomeBlobKey===' self.expect_datatore_lookup(padded_blobkey, True) self.expect_open_image(padded_blobkey, (1600, 1200)) self.expect_resize(32) self.expect_encode_image('SomeImageSize32') self.mox.ReplayAll() self._environ['PATH_INFO'] += '====s32' self.run_request('image...
'Tests an image request with a resize and crop.'
def test_run_resize_and_crop(self):
self.expect_datatore_lookup('SomeBlobKey', True) self.expect_open_image('SomeBlobKey', (1600, 1200)) self.expect_crop(left_x=0.125, right_x=0.875) self.expect_resize(32) self.expect_encode_image('SomeImageSize32') self.mox.ReplayAll() self._environ['PATH_INFO'] += '=s32-c' self.run_reque...
'Tests an image request with a resize and crop in PNG.'
def test_run_resize_and_crop_png(self):
self.expect_datatore_lookup('SomeBlobKey', True) self.expect_open_image('SomeBlobKey', (1600, 1200), mime_type='PNG') self.expect_crop(left_x=0.125, right_x=0.875) self.expect_resize(32) self.expect_encode_image('SomeImageSize32', images_service_pb.OutputSettings.PNG) self.mox.ReplayAll() se...
'Tests an image request with a resize and crop on a padded blobkey.'
def test_run_resize_and_crop_with_padded_blobkey(self):
padded_blobkey = 'SomeBlobKey====' self.expect_datatore_lookup(padded_blobkey, True) self.expect_open_image(padded_blobkey, (1600, 1200)) self.expect_crop(left_x=0.125, right_x=0.875) self.expect_resize(32) self.expect_encode_image('SomeImageSize32') self.mox.ReplayAll() self._environ['P...
'Tests POSTing to a url.'
def test_not_get(self):
self._environ['REQUEST_METHOD'] = 'POST' self.assertResponse(('405 %s' % httplib.responses[405]), [], '', self.app, self._environ)
'Tests an image request for a key that doesn\'t exist.'
def test_key_not_found(self):
self.expect_datatore_lookup('SomeBlobKey', False) self.mox.ReplayAll() self.assertResponse(('404 %s' % httplib.responses[404]), [], '', self.app, self._environ)
'Tests an image request with an invalid path.'
def test_invalid_url(self):
self._environ['PATH_INFO'] = '/_ah/img/' self.mox.ReplayAll() self.assertResponse(('400 %s' % httplib.responses[400]), [], '', self.app, self._environ)
'Tests an image request with an invalid size.'
def test_invalid_options(self):
self.expect_datatore_lookup('SomeBlobKey', True) self.expect_open_image('SomeBlobKey', (1600, 1200)) self._environ['PATH_INFO'] += ('=s%s' % (blob_image._SIZE_LIMIT + 1)) self.mox.ReplayAll() self.assertResponse(('400 %s' % httplib.responses[400]), [], '', self.app, self._environ)
'Initializer for _ScriptHandler. Args: url_map: An appinfo.URLMap instance containing the configuration for this handler.'
def __init__(self, url_map):
try: url_pattern = re.compile(('%s$' % url_map.url)) except re.error as e: raise errors.InvalidAppConfigError(('invalid url %r in script handler: %s' % (url_map.url, e))) super(_ScriptHandler, self).__init__(url_map, url_pattern) self.url_map = url_map
'This is a dummy method that should never be called.'
def handle(self, match, environ, start_response):
raise NotImplementedError()
'Create an instance.InstanceFactory. Args: module_configuration: An application_configuration.ModuleConfiguration instance storing the configuration data for a module. Returns: A instance.InstanceFactory subclass that can be used to create instances with the provided configuration. Raises: RuntimeError: if the configur...
def _create_instance_factory(self, module_configuration):
if (module_configuration.runtime not in self._RUNTIME_INSTANCE_FACTORIES): raise RuntimeError(('Unknown runtime %r; supported runtimes are %s.' % (module_configuration.runtime, ', '.join(sorted((repr(k) for k in self._RUNTIME_INSTANCE_FACTORIES)))))) instance_factory = self._RUNTIME...
'Constructs URLHandlers based on the module configuration. Returns: A list of url_handler.URLHandlers corresponding that can react as described in the given configuration.'
def _create_url_handlers(self):
handlers = [] url_pattern = ('/%s$' % login.LOGIN_URL_RELATIVE) handlers.append(wsgi_handler.WSGIHandler(login.application, url_pattern)) url_pattern = ('/%s' % blob_upload.UPLOAD_URL_PATH) handlers.append(wsgi_handler.WSGIHandler(blob_upload.Application(self), url_pattern)) url_pattern = ('/%s'...
'Returns the configuration for the runtime. Returns: A runtime_config_pb2.Config instance representing the configuration to be passed to an instance. NOTE: This does *not* include the instance_id field, which must be populated elsewhere.'
def _get_runtime_config(self):
runtime_config = runtime_config_pb2.Config() runtime_config.app_id = self._module_configuration.application runtime_config.version_id = self._module_configuration.version_id runtime_config.threadsafe = (self._module_configuration.threadsafe or False) runtime_config.application_root = self._module_co...
'Restarts instances. May avoid some restarts depending on policy. One of config_changed or file_changed must be True. Args: config_changed: True if the configuration for the application has changed. file_changed: True if any file relevant to the application has changed.'
def _maybe_restart_instances(self, config_changed, file_changed):
if ((not config_changed) and (not file_changed)): return logging.debug('Restarting instances.') policy = self._instance_factory.FILE_CHANGE_INSTANCE_RESTART_POLICY assert (policy is not None), 'FILE_CHANGE_INSTANCE_RESTART_POLICY not set' with self._condition: instances_to_q...
'Handle file or configuration changes.'
def _handle_changes(self):
config_changes = self._module_configuration.check_for_updates() has_file_changes = self._watcher.has_changes() if (application_configuration.HANDLERS_CHANGED in config_changes): handlers = self._create_url_handlers() with self._handler_lock: self._handlers = handlers if has_f...
'Initializer for Module. Args: module_configuration: An application_configuration.ModuleConfiguration instance storing the configuration data for a module. host: A string containing the host that any HTTP servers should bind to e.g. "localhost". balanced_port: An int specifying the port where the balanced module for th...
def __init__(self, module_configuration, host, balanced_port, api_port, auth_domain, runtime_stderr_loglevel, php_executable_path, enable_php_remote_debugging, python_config, cloud_sql_config, default_version_port, port_registry, request_data, dispatcher, max_instances, use_mtime_file_watcher, automatic_restarts, allow...
self._module_configuration = module_configuration self._name = module_configuration.module_name self._host = host self._api_port = api_port self._auth_domain = auth_domain self._runtime_stderr_loglevel = runtime_stderr_loglevel self._balanced_port = balanced_port self._php_executable_pat...
'The name of the module, as defined in app.yaml. This value will be constant for the lifetime of the module even in the module configuration changes.'
@property def name(self):
return self._name
'The module is ready to handle HTTP requests.'
@property def ready(self):
return self._balanced_module.ready
'The port that the balanced HTTP server for the Module is listening on.'
@property def balanced_port(self):
assert self._balanced_module.ready, 'balanced module not running' return self._balanced_module.port
'The host that the HTTP server(s) for this Module is listening on.'
@property def host(self):
return self._host
'The address of the balanced HTTP server e.g. "localhost:8080".'
@property def balanced_address(self):
if (self.balanced_port != 80): return ('%s:%s' % (self.host, self.balanced_port)) else: return self.host
'The number of concurrent requests that each Instance can handle.'
@property def max_instance_concurrent_requests(self):
return self._instance_factory.max_concurrent_requests
'The application_configuration.ModuleConfiguration for this module.'
@property def module_configuration(self):
return self._module_configuration
'True if the module can evaluate arbitrary code and return the result.'
@property def supports_interactive_commands(self):
return self._instance_factory.SUPPORTS_INTERACTIVE_REQUESTS
'Handles a HTTP request that has matched a script handler. 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 that matched. match: A re.MatchObject containing...
def _handle_script_request(self, environ, start_response, url_map, match, inst=None):
raise NotImplementedError()
'Handle a HTTP request that does not match any user-defined handlers.'
def _no_handler_for_request(self, environ, start_response, request_id):
self._insert_log_message('No handlers matched this URL.', 2, request_id) start_response('404 Not Found', [('Content-Type', 'text/plain')]) return [('The url "%s" does not match any handlers.' % environ['PATH_INFO'])]
'A _handle_request wrapper that keeps track of active requests. Args: environ: An environ dict for the request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. Returns: An iterable over strings containing the body of the HTTP response.'
def _handle_request(self, environ, start_response, **kwargs):
with self.graceful_shutdown_lock: if self.sigterm_sent: start_response('503 Service Unavailable', [('Content-Type', 'text/plain')]) return ['This instance is shutting down'] self.request_count += 1 try: return self._handle_request_impl(environ, s...
'Handles a HTTP request. Args: environ: An environ dict for the request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. inst: The Instance to send the request to. If None then an appropriate Instance will be chosen. Setting inst is not meaningful if the request does not match a "scr...
def _handle_request_impl(self, environ, start_response, inst=None, request_type=instance.NORMAL_REQUEST):
try: environ['SERVER_PORT'] = environ['HTTP_HOST'].split(':')[1] except IndexError: scheme = environ['HTTP_X_FORWARDED_PROTO'] if (scheme == 'http'): environ['SERVER_PORT'] = 80 else: environ['SERVER_PORT'] = 443 if ('HTTP_HOST' in environ): en...
'Generate a random REQUEST_LOG_ID. Returns: A string suitable for use as a REQUEST_LOG_ID. The returned string is variable length to emulate the the production values, which encapsulate the application id, version and some log state.'
@staticmethod def generate_request_log_id():
return ''.join((random.choice(_LOWER_HEX_DIGITS) for _ in range(random.randrange(30, 100))))
'Generate a random REQUEST_ID_HASH.'
@staticmethod def generate_request_id_hash():
return ''.join((random.choice(_UPPER_HEX_DIGITS) for _ in range(_REQUEST_ID_HASH_LENGTH)))
'Sets the number of instances for this module to run. Args: instances: An int containing the number of instances to run.'
def set_num_instances(self, instances):
raise request_info.NotSupportedWithAutoScalingError()
'Returns the number of instances for this module to run.'
def get_num_instances(self):
raise request_info.NotSupportedWithAutoScalingError()
'Stops the module from serving requests.'
def suspend(self):
raise request_info.NotSupportedWithAutoScalingError()
'Restarts the module.'
def resume(self):
raise request_info.NotSupportedWithAutoScalingError()
'Returns the address of the HTTP server for an instance.'
def get_instance_address(self, instance_id):
return ('%s:%s' % (self.host, self.get_instance_port(instance_id)))
'Returns the port of the HTTP server for an instance.'
def get_instance_port(self, instance_id):
raise request_info.NotSupportedWithAutoScalingError()
'Returns the instance with the provided instance ID.'
def get_instance(self, instance_id):
raise request_info.NotSupportedWithAutoScalingError()
'Returns a InteractiveCommandModule that can be sent user commands.'
def create_interactive_command_module(self):
if self._instance_factory.SUPPORTS_INTERACTIVE_REQUESTS: return InteractiveCommandModule(self._module_configuration, self._host, self._balanced_port, self._api_port, self._auth_domain, self._runtime_stderr_loglevel, self._php_executable_path, self._enable_php_remote_debugging, self._python_config, self._clo...
'Parse a pending latency string into a float of the value in seconds. Args: timing: A str of the form 1.0s or 1000ms. Returns: A float representation of the value in seconds.'
@staticmethod def _parse_pending_latency(timing):
if timing.endswith('ms'): return (float(timing[:(-2)]) / 1000) else: return float(timing[:(-1)])
'Initializer for AutoScalingModule. Args: module_configuration: An application_configuration.ModuleConfiguration instance storing the configuration data for a module. host: A string containing the host that any HTTP servers should bind to e.g. "localhost". balanced_port: An int specifying the port where the balanced mo...
def __init__(self, module_configuration, host, balanced_port, api_port, auth_domain, runtime_stderr_loglevel, php_executable_path, enable_php_remote_debugging, python_config, cloud_sql_config, default_version_port, port_registry, request_data, dispatcher, max_instances, use_mtime_file_watcher, automatic_restarts, allow...
super(AutoScalingModule, self).__init__(module_configuration, host, balanced_port, api_port, auth_domain, runtime_stderr_loglevel, php_executable_path, enable_php_remote_debugging, python_config, cloud_sql_config, default_version_port, port_registry, request_data, dispatcher, max_instances, use_mtime_file_watcher, ...
'Start background management of the Module.'
def start(self):
self._balanced_module.start() self._port_registry.add(self.balanced_port, self, None) if self._watcher: self._watcher.start() self._instance_adjustment_thread.start()
'Stops the Module.'
def quit(self):
self._quit_event.set() self._instance_adjustment_thread.join() if self._watcher: self._watcher.quit() self._balanced_module.quit() with self._condition: instances = self._instances self._instances = set() self._condition.notify_all() for inst in instances: ...
'A set of all the instances currently in the Module.'
@property def instances(self):
with self._condition: return set(self._instances)
'The number of requests that instances are currently handling.'
@property def num_outstanding_instance_requests(self):
with self._condition: return self._num_outstanding_instance_requests
'Handles a request routed a particular Instance. 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 that matched. match: A re.MatchObject containing the resul...
def _handle_instance_request(self, environ, start_response, url_map, match, request_id, inst, request_type):
if (request_type != instance.READY_REQUEST): with self._condition: self._num_outstanding_instance_requests += 1 self._outstanding_request_history.append((time.time(), self.num_outstanding_instance_requests)) try: logging.debug('Dispatching request to %s', inst) ...
'Handles a HTTP request that has matched a script handler. 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 that matched. match: A re.MatchObject containing...
def _handle_script_request(self, environ, start_response, url_map, match, request_id, inst=None, request_type=instance.NORMAL_REQUEST):
if (inst is not None): return self._handle_instance_request(environ, start_response, url_map, match, request_id, inst, request_type) with self._condition: self._num_outstanding_instance_requests += 1 self._outstanding_request_history.append((time.time(), self.num_outstanding_instance_req...
'Creates and adds a new instance.Instance to the Module. Args: permit_warmup: If True then the new instance.Instance will be sent a new warmup request if it is configured to receive them. Returns: The newly created instance.Instance. Returns None if no new instance could be created because the maximum number of instanc...
def _add_instance(self, permit_warmup):
if (self._max_instances is not None): with self._condition: if (len(self._instances) >= self._max_instances): return None perform_warmup = (permit_warmup and ('warmup' in (self._module_configuration.inbound_services or []))) inst = self._instance_factory.new_instance(self...
'Send a warmup request to the given instance.'
def _warmup(self, inst):
try: environ = self.build_request_environ('GET', '/_ah/warmup', [], '', '0.1.0.3', self.balanced_port, fake_login=True) self._handle_request(environ, start_response_utils.null_start_response, inst=inst, request_type=instance.READY_REQUEST) with self._condition: self._condition.no...
'Asynchronously send a markup request to the given Instance.'
def _async_warmup(self, inst):
_THREAD_POOL.submit(self._warmup, inst)
'Removes obsolete entries from _outstanding_request_history.'
def _trim_outstanding_request_history(self):
window_start = (time.time() - self._REQUIRED_INSTANCE_WINDOW_SECONDS) with self._condition: while self._outstanding_request_history: (t, _) = self._outstanding_request_history[0] if (t < window_start): self._outstanding_request_history.popleft() else: ...
'Returns the number of Instances required to handle the request load.'
def _get_num_required_instances(self):
with self._condition: self._trim_outstanding_request_history() if (not self._outstanding_request_history): return 0 else: peak_concurrent_requests = max((current_requests for (t, current_requests) in self._outstanding_request_history)) return int(math.ceil...
'Returns a 2-tuple representing the required and extra Instances. Returns: A 2-tuple of (required_instances, not_required_instances): required_instances: The set of the instance.Instances, in a state that can handle requests, required to handle the current request load. not_required_instances: The set of the Instances ...
def _split_instances(self):
with self._condition: num_required_instances = self._get_num_required_instances() available = [inst for inst in self._instances if inst.can_accept_requests] available.sort(key=(lambda inst: (- inst.num_outstanding_requests))) required = set(available[:num_required_instances]) ...
'Returns the best Instance to handle a request or None if all are busy.'
def _choose_instance(self, timeout_time):
with self._condition: while (time.time() < timeout_time): (required_instances, not_required_instances) = self._split_instances() if required_instances: required_instances = sorted(required_instances, key=(lambda inst: inst.remaining_request_capacity)) ...
'Creates new Instances or deletes idle Instances based on current load.'
def _adjust_instances(self):
now = time.time() with self._condition: (_, not_required_instances) = self._split_instances() if (len(not_required_instances) < self._min_idle_instances): self._add_instance(permit_warmup=True) elif ((len(not_required_instances) > self._max_idle_instances) and (now > (self._last_instance...
'Loops until the Module exits, reloading, adding or removing Instances.'
def _loop_adjusting_instances(self):
while (not self._quit_event.is_set()): if self.ready: if self._automatic_restarts: self._handle_changes() self._adjust_instances() self._quit_event.wait(timeout=1)
'Initializer for ManualScalingModule. Args: module_configuration: An application_configuration.ModuleConfiguration instance storing the configuration data for a module. host: A string containing the host that any HTTP servers should bind to e.g. "localhost". balanced_port: An int specifying the port where the balanced ...
def __init__(self, module_configuration, host, balanced_port, api_port, auth_domain, runtime_stderr_loglevel, php_executable_path, enable_php_remote_debugging, python_config, cloud_sql_config, default_version_port, port_registry, request_data, dispatcher, max_instances, use_mtime_file_watcher, automatic_restarts, allow...
super(ManualScalingModule, self).__init__(module_configuration, host, balanced_port, api_port, auth_domain, runtime_stderr_loglevel, php_executable_path, enable_php_remote_debugging, python_config, cloud_sql_config, default_version_port, port_registry, request_data, dispatcher, max_instances, use_mtime_file_watcher...
'Start background management of the Module.'
def start(self):
self._balanced_module.start() self._port_registry.add(self.balanced_port, self, None) if self._watcher: self._watcher.start() self._change_watcher_thread.start() with self._instances_change_lock: if (self._max_instances is not None): initial_num_instances = min(self._max_...
'Stops the Module.'
def quit(self):
self._quit_event.set() self._change_watcher_thread.join() if self._watcher: self._watcher.quit() self._balanced_module.quit() for wsgi_servr in self._wsgi_servers: wsgi_servr.quit() with self._condition: instances = self._instances self._instances = [] sel...
'Returns the port of the HTTP server for an instance.'
def get_instance_port(self, instance_id):
try: instance_id = int(instance_id) except ValueError: raise request_info.InvalidInstanceIdError() with self._condition: if (0 <= instance_id < len(self._instances)): wsgi_servr = self._wsgi_servers[instance_id] else: raise request_info.InvalidInstance...
'A set of all the instances currently in the Module.'
@property def instances(self):
with self._condition: return set(self._instances)
'Handles a request routed a particular Instance. 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 that matched. match: A re.MatchObject containing the resul...
def _handle_instance_request(self, environ, start_response, url_map, match, request_id, inst, request_type):
start_time = time.time() timeout_time = (start_time + self._MAX_REQUEST_WAIT_TIME) try: while (time.time() < timeout_time): logging.debug('Dispatching request to %s after %0.4fs pending', inst, (time.time() - start_time)) try: return inst.han...
'Handles a HTTP request that has matched a script handler. 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 that matched. match: A re.MatchObject containing...
def _handle_script_request(self, environ, start_response, url_map, match, request_id, inst=None, request_type=instance.NORMAL_REQUEST):
if (((request_type in (instance.NORMAL_REQUEST, instance.READY_REQUEST)) and self._suspended) or self._quit_event.is_set()): return self._error_response(environ, start_response, 404) if self._module_configuration.is_backend: environ['BACKEND_ID'] = self._module_configuration.module_name else...
'Creates and adds a new instance.Instance to the Module. This must be called with _instances_change_lock held.'
def _add_instance(self):
instance_id = self.get_num_instances() assert ((self._max_instances is None) or (instance_id < self._max_instances)) inst = self._instance_factory.new_instance(instance_id, expect_ready_request=True) wsgi_servr = wsgi_server.WsgiServer((self._host, 0), functools.partial(self._handle_request, inst=inst))...
'Returns an Instance to handle a request or None if all are busy.'
def _choose_instance(self, timeout_time):
with self._condition: while (time.time() < timeout_time): for inst in self._instances: if inst.can_accept_requests: return inst self._condition.wait((timeout_time - time.time())) return None
'Handle file or configuration changes.'
def _handle_changes(self):
config_changes = self._module_configuration.check_for_updates() has_file_changes = self._watcher.has_changes() if (application_configuration.HANDLERS_CHANGED in config_changes): handlers = self._create_url_handlers() with self._handler_lock: self._handlers = handlers if has_f...
'Loops until the InstancePool is done watching for file changes.'
def _loop_watching_for_changes(self):
while (not self._quit_event.is_set()): if self.ready: if self._automatic_restarts: self._handle_changes() self._quit_event.wait(timeout=1)
'Suspends serving for this module, quitting all running instances.'
def suspend(self):
with self._instances_change_lock: if self._suspended: raise request_info.ModuleAlreadyStoppedError() self._suspended = True with self._condition: instances_to_stop = zip(self._instances, self._wsgi_servers) for wsgi_servr in self._wsgi_servers: ...
'Resumes serving for this module.'
def resume(self):
with self._instances_change_lock: if (not self._suspended): raise request_info.ModuleAlreadyStartedError() self._suspended = False with self._condition: if self._quit_event.is_set(): return wsgi_servers = self._wsgi_servers instance...
'Restarts the the module, replacing all running instances.'
def restart(self):
with self._instances_change_lock: with self._condition: if self._quit_event.is_set(): return instances_to_stop = self._instances[:] wsgi_servers = self._wsgi_servers[:] instances_to_start = [] for (instance_id, wsgi_servr) in enumerate(wsgi...
'Returns the instance with the provided instance ID.'
def get_instance(self, instance_id):
try: with self._condition: return self._instances[int(instance_id)] except (ValueError, IndexError): raise request_info.InvalidInstanceIdError()
'Parse a idle timeout string into an int of the value in seconds. Args: timing: A str of the form 1m or 10s. Returns: An int representation of the value in seconds.'
@staticmethod def _parse_idle_timeout(timing):
if timing.endswith('m'): return (int(timing[:(-1)]) * 60) else: return int(timing[:(-1)])
'Initializer for BasicScalingModule. Args: module_configuration: An application_configuration.ModuleConfiguration instance storing the configuration data for a module. host: A string containing the host that any HTTP servers should bind to e.g. "localhost". balanced_port: An int specifying the port where the balanced m...
def __init__(self, module_configuration, host, balanced_port, api_port, auth_domain, runtime_stderr_loglevel, php_executable_path, enable_php_remote_debugging, python_config, cloud_sql_config, default_version_port, port_registry, request_data, dispatcher, max_instances, use_mtime_file_watcher, automatic_restarts, allow...
super(BasicScalingModule, self).__init__(module_configuration, host, balanced_port, api_port, auth_domain, runtime_stderr_loglevel, php_executable_path, enable_php_remote_debugging, python_config, cloud_sql_config, default_version_port, port_registry, request_data, dispatcher, max_instances, use_mtime_file_watcher,...
'Start background management of the Module.'
def start(self):
self._balanced_module.start() self._port_registry.add(self.balanced_port, self, None) if self._watcher: self._watcher.start() self._change_watcher_thread.start() for (wsgi_servr, inst) in zip(self._wsgi_servers, self._instances): wsgi_servr.start() self._port_registry.add(wsg...
'Stops the Module.'
def quit(self):
self._quit_event.set() self._change_watcher_thread.join() if self._watcher: self._watcher.quit() self._balanced_module.quit() for wsgi_servr in self._wsgi_servers: wsgi_servr.quit() with self._condition: instances = self._instances self._instances = [] sel...
'Returns the port of the HTTP server for an instance.'
def get_instance_port(self, instance_id):
try: instance_id = int(instance_id) except ValueError: raise request_info.InvalidInstanceIdError() with self._condition: if (0 <= instance_id < len(self._instances)): wsgi_servr = self._wsgi_servers[instance_id] else: raise request_info.InvalidInstance...
'A set of all the instances currently in the Module.'
@property def instances(self):
with self._condition: return set(self._instances)
'Handles a request routed a particular Instance. 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 that matched. match: A re.MatchObject containing the resul...
def _handle_instance_request(self, environ, start_response, url_map, match, request_id, inst, request_type):
instance_id = inst.instance_id start_time = time.time() timeout_time = (start_time + self._MAX_REQUEST_WAIT_TIME) try: while (time.time() < timeout_time): logging.debug('Dispatching request to %s after %0.4fs pending', inst, (time.time() - start_time)) t...
'Handles a HTTP request that has matched a script handler. 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 that matched. match: A re.MatchObject containing...
def _handle_script_request(self, environ, start_response, url_map, match, request_id, inst=None, request_type=instance.NORMAL_REQUEST):
if self._quit_event.is_set(): return self._error_response(environ, start_response, 404) if self._module_configuration.is_backend: environ['BACKEND_ID'] = self._module_configuration.module_name else: environ['BACKEND_ID'] = self._module_configuration.version_id.split('.', 1)[0] if...
'Choose an inactive instance and start it asynchronously. Returns: An instance.Instance that will be started asynchronously or None if all instances are already running.'
def _start_any_instance(self):
with self._condition: for (instance_id, running) in enumerate(self._instance_running): if (not running): self._instance_running[instance_id] = True inst = self._instances[instance_id] break else: return None self._async_star...
'Returns an Instance to handle a request or None if all are busy.'
def _choose_instance(self, timeout_time):
with self._condition: while ((time.time() < timeout_time) and (not self._quit_event.is_set())): for inst in self._instances: if inst.can_accept_requests: return inst else: inst = self._start_any_instance() if inst: ...
'Handle file or configuration changes.'
def _handle_changes(self):
config_changes = self._module_configuration.check_for_updates() has_file_changes = self._watcher.has_changes() if (application_configuration.HANDLERS_CHANGED in config_changes): handlers = self._create_url_handlers() with self._handler_lock: self._handlers = handlers if has_f...
'Loops until the InstancePool is done watching for file changes.'
def _loop_watching_for_changes_and_idle_instances(self):
while (not self._quit_event.is_set()): if self.ready: self._shutdown_idle_instances() if self._automatic_restarts: self._handle_changes() self._quit_event.wait(timeout=1)
'Restarts the the module, replacing all running instances.'
def restart(self):
instances_to_stop = [] instances_to_start = [] with self._condition: if self._quit_event.is_set(): return for (instance_id, inst) in enumerate(self._instances): if self._instance_running[instance_id]: instances_to_stop.append((inst, self._wsgi_servers[...
'Returns the instance with the provided instance ID.'
def get_instance(self, instance_id):
try: with self._condition: return self._instances[int(instance_id)] except (ValueError, IndexError): raise request_info.InvalidInstanceIdError()
'Initializer for InteractiveCommandModule. Args: module_configuration: An application_configuration.ModuleConfiguration instance storing the configuration data for this module. host: A string containing the host that will be used when constructing HTTP headers sent to the Instance executing the interactive command e.g....
def __init__(self, module_configuration, host, balanced_port, api_port, auth_domain, runtime_stderr_loglevel, php_executable_path, enable_php_remote_debugging, python_config, cloud_sql_config, default_version_port, port_registry, request_data, dispatcher, use_mtime_file_watcher, allow_skipped_files):
super(InteractiveCommandModule, self).__init__(module_configuration, host, balanced_port, api_port, auth_domain, runtime_stderr_loglevel, php_executable_path, enable_php_remote_debugging, python_config, cloud_sql_config, default_version_port, port_registry, request_data, dispatcher, max_instances=1, use_mtime_file_...
'The port that the balanced HTTP server for the Module is listening on. The InteractiveCommandModule does not actually listen on this port but it is used when constructing the "SERVER_PORT" in the WSGI-environment.'
@property def balanced_port(self):
return self._balanced_port
'Stops the InteractiveCommandModule.'
def quit(self):
if self._inst: self._inst.quit(force=True) self._inst = None
'Handles a interactive request by forwarding it to the managed Instance. 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 that matched. match: A re.MatchObj...
def _handle_script_request(self, environ, start_response, url_map, match, request_id, inst=None, request_type=instance.INTERACTIVE_REQUEST):
assert (inst is None) assert (request_type == instance.INTERACTIVE_REQUEST) start_time = time.time() timeout_time = (start_time + self._MAX_REQUEST_WAIT_TIME) while (time.time() < timeout_time): new_instance = False with self._inst_lock: if (not self._inst): ...
'Restarts the the module.'
def restart(self):
with self._inst_lock: if self._inst: self._inst.quit(force=True) self._inst = None
'Sends an interactive command to the module. Args: command: The command to send e.g. "print 5+5". Returns: A string representing the result of the command e.g. "10 Raises: InteractiveCommandError: if the command failed for any reason.'
def send_interactive_command(self, command):
start_response = start_response_utils.CapturingStartResponse() environ = self.build_request_environ('POST', '/', [], command, '192.0.2.0', self.balanced_port) try: response = self._handle_request(environ, start_response, request_type=instance.INTERACTIVE_REQUEST) except Exception as e: r...
'Serves this request by forwarding it to the runtime process. 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.MatchObjec...
def handle(self, environ, start_response, url_map, match, request_id, request_type):
raise NotImplementedError()
'Starts the runtime process and waits until it is ready to serve.'
def start(self):
raise NotImplementedError()
'Terminates the runtime process.'
def quit(self):
raise NotImplementedError()
'Initializer for Instance. Args: request_data: A wsgi_request_info.WSGIRequestInfo that will be provided with request information for use by API stubs. instance_id: A string or integer representing the unique (per module) id of the instance. runtime_proxy: A RuntimeProxy instance that will be used to handle requests. m...
def __init__(self, request_data, instance_id, runtime_proxy, max_concurrent_requests, max_background_threads=0, expect_ready_request=False):
self._request_data = request_data self._instance_id = instance_id self._max_concurrent_requests = max_concurrent_requests self._max_background_threads = max_background_threads self._runtime_proxy = runtime_proxy self._condition = threading.Condition() self._num_outstanding_requests = 0 s...
'The unique string or integer id for the Instance.'
@property def instance_id(self):
return self._instance_id
'The total number requests that the Instance has handled.'
@property def total_requests(self):
with self._condition: return self._total_requests
'The number of extra requests that the Instance can currently handle.'
@property def remaining_request_capacity(self):
with self._condition: return (self._max_concurrent_requests - self._num_outstanding_requests)
'The number of extra background threads the Instance can handle.'
@property def remaining_background_thread_capacity(self):
with self._condition: return (self._max_background_threads - self._num_running_background_threads)
'The number of requests that the Instance is currently handling.'
@property def num_outstanding_requests(self):
with self._condition: return self._num_outstanding_requests