def add(self, req, body): context = req.environ['nova.context'] authorize(context) if not body: raise exc.HTTPUnprocessableEntity() network_id = body.get('id', None) project_id = context.project_id LOG.debug( _("Associating network %(network)s" " with project %(project)s") % { "network": network_id or "", "project": project_id }) try: self.network_api.add_network_to_project(context, project_id, network_id) except NotImplementedError: msg = (_("VLAN support must be enabled")) raise exc.HTTPNotImplemented(explanation=msg) except Exception as ex: msg = (_("Cannot associate network %(network)s" " with project %(project)s: %(message)s") % { "network": network_id or "", "project": project_id, "message": getattr(ex, "value", str(ex)) }) raise exc.HTTPBadRequest(explanation=msg) return webob.Response(status_int=202)
def change_password(self, req, id, body): context = req.environ['nova.context'] authorize(context) if (not self.is_valid_body(body, 'change_password') or 'admin_password' not in body['change_password']): msg = _("No admin_password was specified") raise exc.HTTPBadRequest(explanation=msg) password = body['change_password']['admin_password'] if not isinstance(password, six.string_types): msg = _("Invalid admin password") raise exc.HTTPBadRequest(explanation=msg) try: instance = self.compute_api.get(context, id) except exception.InstanceNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) try: self.compute_api.set_admin_password(context, instance, password) except exception.InstancePasswordSetFailed as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as e: raise common.raise_http_conflict_for_instance_invalid_state( e, 'change_password') except NotImplementedError: msg = _("Unable to set password on instance") raise exc.HTTPNotImplemented(explanation=msg)
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'admin_password' in body['rescue']: password = body['rescue']['admin_password'] else: password = utils.generate_password() instance = common.get_instance(self.compute_api, context, id, want_objects=True) try: self.compute_api.rescue(context, instance, rescue_password=password) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'rescue') except exception.InvalidVolume as volume_error: raise exc.HTTPConflict(explanation=volume_error.format_message()) except exception.InstanceNotRescuable as non_rescuable: raise exc.HTTPBadRequest( explanation=non_rescuable.format_message()) except NotImplementedError: msg = _("The rescue operation is not implemented by this cloud.") raise exc.HTTPNotImplemented(explanation=msg) if CONF.enable_instance_password: return {'admin_password': password} else: return {}
def _rescue(self, req, id, body): """Rescue an instance.""" context = req.environ["nova.context"] authorize(context) if body['rescue'] and 'adminPass' in body['rescue']: password = body['rescue']['adminPass'] else: password = utils.generate_password() instance = self._get_instance(context, id, want_objects=True) try: rescue_image_ref = None if self.ext_mgr.is_loaded("os-extended-rescue-with-image"): if body['rescue'] and 'rescue_image_ref' in body['rescue']: rescue_image_ref = body['rescue']['rescue_image_ref'] self.compute_api.rescue(context, instance, rescue_password=password, rescue_image_ref=rescue_image_ref) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'rescue') except exception.InvalidVolume as volume_error: raise exc.HTTPConflict(explanation=volume_error.format_message()) except exception.InstanceNotRescuable as non_rescuable: raise exc.HTTPBadRequest( explanation=non_rescuable.format_message()) except NotImplementedError: msg = _("The rescue operation is not implemented by this " "cloud.") raise exc.HTTPNotImplemented(explanation=msg) return {'adminPass': password}
def test_uptime_notimplemented(self): with mock.patch.object( self.controller.host_api, 'get_host_uptime', side_effect=exc.HTTPNotImplemented()) as mock_get_uptime: req = self._get_request(True) self.assertRaises(exc.HTTPNotImplemented, self.controller.uptime, req, self.TEST_HYPERS_OBJ[0].id) self.assertEqual(1, mock_get_uptime.call_count)
def vifinfo_request(self, method, path, body=None): self.LOG.debug("vifinfo_request() called:%s %s %s" % (method, path, body)) if body: body = json.dumps(body) conn = httplib.HTTPConnection(self.server) if method == "POST" or "PUT": header = {'Content-Type': "application/json"} conn.request(method, path, body, header) else: conn.request(method, path, body) res = conn.getresponse() conn.close self.LOG.debug("vifinfo_request(): Quantum server returns %s(%s)" % (res.status, res.reason)) if hasattr(res, 'status_int'): status_code = res.status_int else: status_code = res.status data = res.read() if method in ("GET", "POST"): if res.status != 200: self.LOG.warning("vifinfo_request(): bad response `%s' " "for method `%s'" % (res.status, method)) elif method in ("DELETE", "PUT"): if res.status != 204: self.LOG.warning("vifinfo_request(): bad response `%s' " "for method `%s'" % (res.status, method)) if status_code in (httplib.OK, httplib.CREATED, httplib.ACCEPTED): return json.loads(data) elif status_code == httplib.NO_CONTENT: return None else: error_message = data self.LOG.debug("Server returned error: %s" % status_code) self.LOG.debug("Error message: %s" % error_message) # error_message = {res.reason: # {'message': error_message, # 'code': status_code, # 'detail': error_message}} if status_code == httplib.NOT_FOUND: # 404 raise exc.HTTPNotFound(error_message) elif status_code == httplib.METHOD_NOT_ALLOWED: # 405 raise exc.HTTPMethodNotAllowed(error_message) elif status_code == httplib.UNPROCESSABLE_ENTITY: # 422 raise exc.HTTPUnprocessableEntity(error_message) elif status_code == httplib.NOT_IMPLEMENTED: # 501 raise exc.HTTPNotImplemented(error_message) else: # other error is 500 raise exc.HTTPInternalServerError(error_message)
def _adapter(environ, start_response): def _attach(resp): req.response = resp req = Request(environ) req.response = exc.HTTPNotImplemented() task = func(req).bimap(build_error_response, build_success_response) task.fork(_attach, _attach) return req.response(environ, start_response)
def _action_reboot(self, input_dict, req, id): try: reboot_type = input_dict['reboot']['type'] except Exception: raise faults.Fault(exc.HTTPNotImplemented()) try: # TODO(gundlach): pass reboot_type, support soft reboot in # virt driver self.compute_api.reboot(req.environ['nova.context'], id) except: return faults.Fault(exc.HTTPUnprocessableEntity()) return exc.HTTPAccepted()
def _disassociate_project_only(self, req, id, body): context = req.environ['patron.context'] authorize(context) try: self.network_api.associate(context, id, project=None) except exception.NetworkNotFound: msg = _("Network not found") raise exc.HTTPNotFound(explanation=msg) except NotImplementedError: msg = _('Disassociate project is not implemented by the ' 'configured Network API') raise exc.HTTPNotImplemented(explanation=msg)
def code2exception(code, detail): """Transforms a code + detail into a WebOb exception""" if code == 400: return exc.HTTPBadRequest(detail) if code == 401: return exc.HTTPUnauthorized(detail) if code == 402: return exc.HTTPPaymentRequired(detail) if code == 403: return exc.HTTPForbidden(detail) if code == 404: return exc.HTTPNotFound(detail) if code == 405: return exc.HTTPMethodNotAllowed(detail) if code == 406: return exc.HTTPNotAcceptable(detail) if code == 407: return exc.HTTPProxyAuthenticationRequired(detail) if code == 408: return exc.HTTPRequestTimeout(detail) if code == 409: return exc.HTTPConflict(detail) if code == 410: return exc.HTTPGone(detail) if code == 411: return exc.HTTPLengthRequired(detail) if code == 412: return exc.HTTPPreconditionFailed(detail) if code == 413: return exc.HTTPRequestEntityTooLarge(detail) if code == 414: return exc.HTTPRequestURITooLong(detail) if code == 415: return exc.HTTPUnsupportedMediaType(detail) if code == 416: return exc.HTTPRequestRangeNotSatisfiable(detail) if code == 417: return exc.HTTPExpectationFailed(detail) if code == 500: return exc.HTTPInternalServerError(detail) if code == 501: return exc.HTTPNotImplemented(detail) if code == 502: return exc.HTTPBadGateway(detail) if code == 503: return exc.HTTPServiceUnavailable(detail) if code == 504: return exc.HTTPGatewayTimeout(detail) if code == 505: return exc.HTTPVersionNotSupported(detail) raise NotImplementedError(code)
def test_not_implemented_error(self): expected_res = {'body': {'NeutronError': {'detail': '', 'message': _( 'The server has either erred or is ' 'incapable of performing the requested ' 'operation.'), 'type': 'HTTPNotImplemented'}}} res = self._make_request_with_side_effect(exc.HTTPNotImplemented()) self.assertEqual(exc.HTTPNotImplemented.code, res.status_int) self.assertEqual(expected_res, self._get_deserializer().deserialize(res.body))
def _disassociate_host_only(self, req, id, body): context = req.environ['nova.context'] authorize(context) LOG.debug("Disassociating host with network with id %s", id) try: self.network_api.associate(context, id, host=None) except exception.NetworkNotFound: msg = _("Network not found") raise exc.HTTPNotFound(explanation=msg) except NotImplementedError: msg = _('Disassociate host is not implemented by the configured ' 'Network API') raise exc.HTTPNotImplemented(explanation=msg)
def _associate_host(self, req, id, body): context = req.environ['nova.context'] authorize(context) try: self.network_api.associate(context, id, host=body['associate_host']) except exception.NetworkNotFound: msg = _("Network not found") raise exc.HTTPNotFound(explanation=msg) except NotImplementedError: msg = _('Associate host is not implemented by the configured ' 'Network API') raise exc.HTTPNotImplemented(explanation=msg)
def _disassociate_host_only(self, req, id, body): context = req.environ['nova.context'] authorize(context) try: self.network_api.associate(context, id, host=None) except exception.NetworkNotFound: msg = _("Network not found") raise exc.HTTPNotFound(explanation=msg) except NotImplementedError: msg = _('Disassociate host is not implemented by the configured ' 'Network API') raise exc.HTTPNotImplemented(explanation=msg) return webob.Response(status_int=202)
def _unrescue(self, req, id, body): """Unrescue an instance.""" context = req.environ["nova.context"] authorize(context) instance = self._get_instance(context, id, want_objects=True) try: self.compute_api.unrescue(context, instance) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'unrescue') except NotImplementedError: msg = _("The unrescue operation is not implemented by this cloud.") raise exc.HTTPNotImplemented(explanation=msg) return webob.Response(status_int=202)
def _action_change_password(self, req, id, body): context = req.environ['nova.context'] if ('changePassword' not in body or 'adminPass' not in body['changePassword']): msg = _("No adminPass was specified") raise exc.HTTPBadRequest(explanation=msg) password = self._get_server_admin_password(body['changePassword']) server = self._get_server(context, req, id) try: self.compute_api.set_admin_password(context, server, password) except NotImplementedError: msg = _("Unable to set password on instance") raise exc.HTTPNotImplemented(explanation=msg) return webob.Response(status_int=202)
def _disassociate_host_and_project(self, req, id, body): context = req.environ['nova.context'] authorize(context) LOG.debug("Disassociating network with id %s", id) try: self.network_api.associate(context, id, host=None, project=None) except exception.NetworkNotFound: msg = _("Network not found") raise exc.HTTPNotFound(explanation=msg) except NotImplementedError: msg = _('Disassociate network is not implemented by the ' 'configured Network API') raise exc.HTTPNotImplemented(explanation=msg) return exc.HTTPAccepted()
def _disassociate_project_only(self, req, id, body): context = req.environ['nova.context'] authorize(context) LOG.debug("Disassociating project with network with id %s", id) try: self.network_api.associate(context, id, project=None) except exception.NetworkNotFound: msg = _("Network not found") raise exc.HTTPNotFound(explanation=msg) except NotImplementedError: msg = _('Disassociate project is not implemented by the ' 'configured Network API') raise exc.HTTPNotImplemented(explanation=msg) return webob.Response(status_int=202)
def add(self, req, body): context = req.environ['nova.context'] authorize(context) network_id = body['id'] project_id = context.project_id try: self.network_api.add_network_to_project(context, project_id, network_id) except NotImplementedError: msg = (_("VLAN support must be enabled")) raise exc.HTTPNotImplemented(explanation=msg) except (exception.NoMoreNetworks, exception.NetworkNotFoundForUUID) as e: raise exc.HTTPBadRequest(explanation=e.format_message())
def change_password(self, req, id, body): context = req.environ['patron.context'] authorize(context) password = body['changePassword']['adminPass'] instance = common.get_instance(self.compute_api, context, id) try: self.compute_api.set_admin_password(context, instance, password) except exception.InstancePasswordSetFailed as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as e: raise common.raise_http_conflict_for_instance_invalid_state( e, 'changePassword', id) except NotImplementedError: msg = _("Unable to set password on instance") raise exc.HTTPNotImplemented(explanation=msg)
def app(self, environ, start_response): """Main dispatcher. pops PATH_INFO and delegates to exposed methods.""" req = Request(environ.copy()) resp = Response(request=req, content_type='text/html; charset=UTF8') first_part = req.path_info_pop() or 'index' method = getattr(self, first_part, None) if getattr(method, 'exposed', False): output = method(req, resp) if isinstance(output, unicode): resp.body = output.encode('utf-8') elif isinstance(output, str): resp.body = output elif output: resp = output else: resp = exc.HTTPNotImplemented() return resp(environ, start_response)
def _unpause(self, req, id, body): """Permit Admins to unpause the server.""" ctxt = req.environ['nova.context'] authorize(ctxt, action='unpause') server = common.get_instance(self.compute_api, ctxt, id) try: self.compute_api.unpause(ctxt, server) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'unpause', id) except exception.InstanceNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except NotImplementedError: msg = _("Virt driver does not implement pause function.") raise exc.HTTPNotImplemented(explanation=msg)
def action(self, req, id): """Multi-purpose method used to reboot, rebuild, or resize a server""" actions = { 'reboot': self._action_reboot, 'resize': self._action_resize, 'confirmResize': self._action_confirm_resize, 'revertResize': self._action_revert_resize, 'rebuild': self._action_rebuild, } input_dict = self._deserialize(req.body, req.get_content_type()) for key in actions.keys(): if key in input_dict: return actions[key](input_dict, req, id) return faults.Fault(exc.HTTPNotImplemented())
def _disassociate_host_only(self, req, id, body): context = req.environ['compute.context'] authorize(context) # NOTE(shaohe-feng): back-compatible with db layer hard-code # admin permission checks. call db API objects.Network.associate nova_context.require_admin_context(context) try: self.network_api.associate(context, id, host=None) except exception.NetworkNotFound: msg = _("Network not found") raise exc.HTTPNotFound(explanation=msg) except NotImplementedError: msg = _('Disassociate host is not implemented by the configured ' 'Network API') raise exc.HTTPNotImplemented(explanation=msg) return webob.Response(status_int=202)
def app(self, environ, start_response): req = Request(environ) resp = Response(request=req, content_type='text/html; charset=utf-8') # Leave the interactive flag in tw.framework so demo controllers can know # if it is safe to enable advanced/unsecure features. tw.framework.request_local.interactive = self.interactive tw.framework.request_local.browser_prefix = req.script_name # Lookup widget XXX: Yuck! if req.path_info == '/': controller = self.home elif req.path_info.startswith('/_repl') and self.http_repl: req.path_info_pop() return self.http_repl(environ, start_response) elif req.path_info.startswith('/widgets'): controller = self.widgets else: try: widget, action = self.lookup_widget_action(req.path_info) except LookupError: resp = exc.HTTPNotFound('No widget at %s' % req.path_info) return resp(environ, start_response) # Lookup controller try: controller = self.lookup_controller(widget, action) except LookupError: resp = exc.HTTPNotImplemented() return resp(environ, start_response) # If it's a widget class instantiate it with no arguments if isinstance(widget, twc.WidgetMeta): widget = widget('test_widget') req.widget = widget # Call controller and handle output output = controller(req, resp) if isinstance(output, str): resp.body = output elif isinstance(output, unicode): resp.body = output.encode('utf-8') elif output: resp = output return resp(environ, start_response)
def action(self, req, id, body): """Multi-purpose method used to reboot, rebuild, or resize a server""" actions = { 'changePassword': self._action_change_password, 'reboot': self._action_reboot, 'resize': self._action_resize, 'confirmResize': self._action_confirm_resize, 'revertResize': self._action_revert_resize, 'rebuild': self._action_rebuild, 'migrate': self._action_migrate } for key in actions.keys(): if key in body: return actions[key](body, req, id) raise exc.HTTPNotImplemented()
def _adapter(environ, start_response): def _build_and_save_cookies((attrs, cs)): resp = build_success_response(attrs) if isinstance(resp, Response): # a kludge return writer(cs, resp).fmap(always(resp)) else: return resolve(resp) def _attach(resp): req.response = resp req = Request(environ) req.response = exc.HTTPNotImplemented() task = ((func(req) >> _build_and_save_cookies).bimap( build_error_response, identity)) task.fork(_attach, _attach) return req.response(environ, start_response)
def _action_change_password(self, req, id, body): context = req.environ['nova.context'] if (not body.get('changePassword') or 'adminPass' not in body['changePassword']): msg = _("No adminPass was specified") raise exc.HTTPBadRequest(explanation=msg) password = self._get_server_admin_password(body['changePassword']) server = self._get_server(context, req, id) try: self.compute_api.set_admin_password(context, server, password) except exception.InstancePasswordSetFailed as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as e: raise common.raise_http_conflict_for_instance_invalid_state( e, 'changePassword', id) except NotImplementedError: msg = _("Unable to set password on instance") raise exc.HTTPNotImplemented(explanation=msg) return webob.Response(status_int=202)
def add(self, req, body): context = req.environ['nova.context'] authorize(context) if not body: raise exc.HTTPUnprocessableEntity() network_id = body.get('id', None) project_id = context.project_id try: self.network_api.add_network_to_project(context, project_id, network_id) except NotImplementedError: msg = (_("VLAN support must be enabled")) raise exc.HTTPNotImplemented(explanation=msg) except (exception.NoMoreNetworks, exception.NetworkNotFoundForUUID) as e: raise exc.HTTPBadRequest(explanation=e.format_message()) return webob.Response(status_int=202)
def _unpause(self, req, id, body): """Permit Admins to unpause the server.""" ctxt = req.environ['nova.context'] authorize(ctxt, 'unpause') try: server = self.compute_api.get(ctxt, id, want_objects=True) self.compute_api.unpause(ctxt, server) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state( state_error, 'unpause') except exception.InstanceNotFound: raise exc.HTTPNotFound(_("Server not found")) except NotImplementedError: msg = _("Virt driver does not implement unpause function.") raise exc.HTTPNotImplemented(explanation=msg) except Exception: readable = traceback.format_exc() LOG.exception(_("Compute.api::unpause %s"), readable) raise exc.HTTPUnprocessableEntity() return webob.Response(status_int=202)