def __call__(self, request): path = request.path_qs if path == "/rate-limit": request.response = webob.exc.HTTPRequestEntityTooLarge() elif path == "/rate-limit-retry": request.response.retry_after = 10 request.response.status = http_client.REQUEST_ENTITY_TOO_LARGE elif path == "/service-unavailable": request.response = webob.exc.HTTPServiceUnavailable() elif path == "/service-unavailable-retry": request.response.retry_after = 10 request.response.status = http_client.SERVICE_UNAVAILABLE elif path == "/expectation-failed": request.response = webob.exc.HTTPExpectationFailed() elif path == "/server-error": request.response = webob.exc.HTTPServerError() elif path == "/server-traceback": raise exception.ServerError()
def __call__(self, request): path = request.path_qs if path == "/rate-limit": request.response = webob.exc.HTTPRequestEntityTooLarge() elif path == "/rate-limit-retry": request.response.retry_after = 10 request.response.status = 413 elif path == "/service-unavailable": request.response = webob.exc.HTTPServiceUnavailable() elif path == "/service-unavailable-retry": request.response.retry_after = 10 request.response.status = 503 elif path == "/expectation-failed": request.response = webob.exc.HTTPExpectationFailed() elif path == "/server-error": request.response = webob.exc.HTTPServerError() elif path == "/server-traceback": raise exception.ServerError()
def test_image_stage_raises_internal_error(self): image_id = str(uuid.uuid4()) request = unit_test_utils.get_fake_request() self.image_repo.result = exception.ServerError() self.assertRaises(exception.ServerError, self.controller.stage, request, image_id, 'YYYYYYY', 7)
def _validate_policy_enforcement_configuration(): if CONF.enforce_secure_rbac != CONF.oslo_policy.enforce_new_defaults: fail_message = ( "[DEFAULT] enforce_secure_rbac does not match " "[oslo_policy] enforce_new_defaults. Please set both to " "True to enable secure RBAC personas. Otherwise, make sure " "both are False.") raise exception.ServerError(fail_message)
def main(): try: config.parse_args() config.set_config_defaults() wsgi.set_eventlet_hub() logging.setup(CONF, 'glance') gmr.TextGuruMeditation.setup_autorun(version) notifier.set_defaults() if CONF.profiler.enabled: osprofiler.initializer.init_from_conf( conf=CONF, context={}, project="glance", service="api", host=CONF.bind_host ) if CONF.enforce_secure_rbac != CONF.oslo_policy.enforce_new_defaults: fail_message = ( "[DEFAULT] enforce_secure_rbac does not match " "[oslo_policy] enforce_new_defaults. Please set both to " "True to enable secure RBAC personas. Otherwise, make sure " "both are False.") raise exception.ServerError(fail_message) # NOTE(danms): Configure system-wide threading model to use eventlet glance.async_.set_threadpool_model('eventlet') # NOTE(abhishekk): Added initialize_prefetcher KW argument to Server # object so that prefetcher object should only be initialized in case # of API service and ignored in case of registry. Once registry is # removed this parameter should be removed as well. initialize_prefetcher = False if CONF.paste_deploy.flavor == 'keystone+cachemanagement': initialize_prefetcher = True server = wsgi.Server(initialize_glance_store=True, initialize_prefetcher=initialize_prefetcher) server.start(config.load_paste_app('glance-api'), default_port=9292) server.wait() except Exception as e: fail(e)
def _do_request(self, method, url, body, headers): """ Connects to the server and issues a request. Handles converting any returned HTTP error status codes to OpenStack/Glance exceptions and closing the server connection. Returns the result data, or raises an appropriate exception. :param method: HTTP method ("GET", "POST", "PUT", etc...) :param url: urlparse.ParsedResult object with URL information :param body: data to send (as string, filelike or iterable), or None (default) :param headers: mapping of key/value pairs to add as headers :note If the body param has a read attribute, and method is either POST or PUT, this method will automatically conduct a chunked-transfer encoding and use the body as a file object or iterable, transferring chunks of data using the connection's send() method. This allows large objects to be transferred efficiently without buffering the entire body in memory. """ if url.query: path = url.path + "?" + url.query else: path = url.path try: connection_type = self.get_connection_type() headers = self._encode_headers(headers or {}) if 'x-auth-token' not in headers and self.auth_tok: headers['x-auth-token'] = self.auth_tok c = connection_type(url.hostname, url.port, **self.connect_kwargs) def _pushing(method): return method.lower() in ('post', 'put') def _simple(body): return body is None or isinstance(body, six.string_types) def _filelike(body): return hasattr(body, 'read') def _sendbody(connection, iter): connection.endheaders() for sent in iter: # iterator has done the heavy lifting pass def _chunkbody(connection, iter): connection.putheader('Transfer-Encoding', 'chunked') connection.endheaders() for chunk in iter: connection.send('%x\r\n%s\r\n' % (len(chunk), chunk)) connection.send('0\r\n\r\n') # Do a simple request or a chunked request, depending # on whether the body param is file-like or iterable and # the method is PUT or POST # if not _pushing(method) or _simple(body): # Simple request... c.request(method, path, body, headers) elif _filelike(body) or self._iterable(body): c.putrequest(method, path) use_sendfile = self._sendable(body) # According to HTTP/1.1, Content-Length and Transfer-Encoding # conflict. for header, value in headers.items(): if use_sendfile or header.lower() != 'content-length': c.putheader(header, str(value)) iter = self.image_iterator(c, headers, body) if use_sendfile: # send actual file without copying into userspace _sendbody(c, iter) else: # otherwise iterate and chunk _chunkbody(c, iter) else: raise TypeError('Unsupported image type: %s' % body.__class__) res = c.getresponse() def _retry(res): return res.getheader('Retry-After') status_code = self.get_status_code(res) if status_code in self.OK_RESPONSE_CODES: return res elif status_code in self.REDIRECT_RESPONSE_CODES: raise exception.RedirectException(res.getheader('Location')) elif status_code == httplib.UNAUTHORIZED: raise exception.NotAuthenticated(res.read()) elif status_code == httplib.FORBIDDEN: raise exception.Forbidden(res.read()) elif status_code == httplib.NOT_FOUND: raise exception.NotFound(res.read()) elif status_code == httplib.CONFLICT: raise exception.Duplicate(res.read()) elif status_code == httplib.BAD_REQUEST: raise exception.Invalid(res.read()) elif status_code == httplib.MULTIPLE_CHOICES: raise exception.MultipleChoices(body=res.read()) elif status_code == httplib.REQUEST_ENTITY_TOO_LARGE: raise exception.LimitExceeded(retry=_retry(res), body=res.read()) elif status_code == httplib.INTERNAL_SERVER_ERROR: raise exception.ServerError() elif status_code == httplib.SERVICE_UNAVAILABLE: raise exception.ServiceUnavailable(retry=_retry(res)) else: raise exception.UnexpectedStatus(status=status_code, body=res.read()) except (socket.error, IOError) as e: raise exception.ClientConnectionError(e)
def test_upload_storage_internal_error(self): request = unit_test_utils.get_fake_request() self.image_repo.result = exception.ServerError() self.assertRaises(exception.ServerError, self.controller.upload, request, unit_test_utils.UUID1, 'ABC', 3)