コード例 #1
0
ファイル: remote_consoles.py プロジェクト: andymcc/nova
    def create(self, req, server_id, body):
        context = req.environ['nova.context']
        context.can(rc_policies.BASE_POLICY_NAME)
        instance = common.get_instance(self.compute_api, context, server_id)
        protocol = body['remote_console']['protocol']
        console_type = body['remote_console']['type']
        try:
            handler = self.handlers.get(protocol)
            output = handler(context, instance, console_type)
            return {'remote_console': {'protocol': protocol,
                                       'type': console_type,
                                       'url': output['url']}}

        except exception.InstanceNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except (exception.ConsoleTypeInvalid,
                exception.ConsoleTypeUnavailable,
                exception.ImageSerialPortNumberInvalid,
                exception.ImageSerialPortNumberExceedFlavorValue,
                exception.SocketPortRangeExhaustedException) as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()
コード例 #2
0
ファイル: hypervisors.py プロジェクト: andymcc/nova
    def uptime(self, req, id):
        context = req.environ['nova.context']
        context.can(hv_policies.BASE_POLICY_NAME)
        try:
            hyp = self.host_api.compute_node_get(context, id)
            req.cache_db_compute_node(hyp)
        except (ValueError, exception.ComputeHostNotFound):
            msg = _("Hypervisor with ID '%s' could not be found.") % id
            raise webob.exc.HTTPNotFound(explanation=msg)

        # Get the uptime
        try:
            host = hyp.host
            uptime = self.host_api.get_host_uptime(context, host)
            service = self.host_api.service_get_by_compute_host(context, host)
        except NotImplementedError:
            common.raise_feature_not_supported()
        except exception.ComputeServiceUnavailable as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())
        except exception.HostMappingNotFound:
            # NOTE(danms): This mirrors the compute_node_get() behavior
            # where the node is missing, resulting in NotFound instead of
            # BadRequest if we fail on the map lookup.
            msg = _("Hypervisor with ID '%s' could not be found.") % id
            raise webob.exc.HTTPNotFound(explanation=msg)

        return dict(hypervisor=self._view_hypervisor(hyp, service, False, req,
                                                     uptime=uptime))
コード例 #3
0
ファイル: server_diagnostics.py プロジェクト: Juniper/nova
    def index(self, req, server_id):
        context = req.environ["nova.context"]
        context.can(sd_policies.BASE_POLICY_NAME)

        instance = common.get_instance(self.compute_api, context, server_id)

        try:
            if api_version_request.is_supported(req, min_version='2.48'):
                diagnostics = self.compute_api.get_instance_diagnostics(
                    context, instance)
                return self._view_builder.instance_diagnostics(diagnostics)

            return self.compute_api.get_diagnostics(context, instance)
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(state_error,
                    'get_diagnostics', server_id)
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except exception.InstanceDiagnosticsNotSupported:
            # NOTE(snikitin): During upgrade we may face situation when env
            # has new API and old compute. New compute returns a
            # Diagnostics object. Old compute returns a dictionary. So we
            # can't perform a request correctly if compute is too old.
            msg = _('Compute node is too old. You must complete the '
                    'upgrade process to be able to get standardized '
                    'diagnostics data which is available since v2.48. However '
                    'you are still able to get diagnostics data in '
                    'non-standardized format which is available until v2.47.')
            raise webob.exc.HTTPBadRequest(explanation=msg)
        except NotImplementedError:
            common.raise_feature_not_supported()
コード例 #4
0
ファイル: floating_ip_dns.py プロジェクト: hanbaoying/nova
    def show(self, req, domain_id, id):
        """Return the DNS entry that corresponds to domain_id and id."""
        context = req.environ['nova.context']
        authorize(context)
        domain = _unquote_domain(domain_id)

        floating_ip = None
        # Check whether id is a valid ipv4/ipv6 address.
        if netutils.is_valid_ip(id):
            floating_ip = id

        try:
            if floating_ip:
                entries = self.network_api.get_dns_entries_by_address(context,
                                                                  floating_ip,
                                                                  domain)
            else:
                entries = self.network_api.get_dns_entries_by_name(context,
                                                                   id,
                                                                   domain)
        except NotImplementedError:
            common.raise_feature_not_supported()

        if not entries:
            explanation = _("DNS entries not found.")
            raise webob.exc.HTTPNotFound(explanation=explanation)

        if floating_ip:
            entrylist = [_create_dns_entry(floating_ip, entry, domain)
                         for entry in entries]
            dns_entries = _translate_dns_entries_view(entrylist)
            return wsgi.ResponseObject(dns_entries)

        entry = _create_dns_entry(entries[0], id, domain)
        return _translate_dns_entry_view(entry)
コード例 #5
0
ファイル: floating_ip_dns.py プロジェクト: hanbaoying/nova
    def update(self, req, id, body):
        """Add or modify domain entry."""
        context = req.environ['nova.context']
        authorize(context, action="domain:update")
        fqdomain = _unquote_domain(id)
        entry = body['domain_entry']
        scope = entry['scope']
        project = entry.get('project', None)
        av_zone = entry.get('availability_zone', None)

        if scope == 'private' and project:
            msg = _("you can not pass project if the scope is private")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        if scope == 'public' and av_zone:
            msg = _("you can not pass av_zone if the scope is public")
            raise webob.exc.HTTPBadRequest(explanation=msg)

        if scope == 'private':
            create_dns_domain = self.network_api.create_private_dns_domain
            area_name, area = 'availability_zone', av_zone
        else:
            create_dns_domain = self.network_api.create_public_dns_domain
            area_name, area = 'project', project

        try:
            create_dns_domain(context, fqdomain, area)
        except NotImplementedError:
            common.raise_feature_not_supported()

        return _translate_domain_entry_view({'domain': fqdomain,
                                             'scope': scope,
                                             area_name: area})
コード例 #6
0
ファイル: remote_consoles.py プロジェクト: Pratyusha9/nova
    def get_serial_console(self, req, id, body):
        """Get connection to a serial console."""
        context = req.environ['nova.context']
        authorize(context)

        # If type is not supplied or unknown get_serial_console below will cope
        console_type = body['os-getSerialConsole'].get('type')
        try:
            instance = common.get_instance(self.compute_api, context, id)
            output = self.compute_api.get_serial_console(context,
                                                         instance,
                                                         console_type)
        except exception.InstanceNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except (exception.ConsoleTypeUnavailable,
                exception.ImageSerialPortNumberInvalid,
                exception.ImageSerialPortNumberExceedFlavorValue,
                exception.SocketPortRangeExhaustedException) as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()

        return {'console': {'type': console_type, 'url': output['url']}}
コード例 #7
0
ファイル: floating_ip_dns.py プロジェクト: hanbaoying/nova
    def update(self, req, domain_id, id, body):
        """Add or modify dns entry."""
        context = req.environ['nova.context']
        authorize(context)
        domain = _unquote_domain(domain_id)
        name = id
        entry = body['dns_entry']
        address = entry['ip']
        dns_type = entry['dns_type']

        try:
            entries = self.network_api.get_dns_entries_by_name(context,
                                                               name, domain)
            if not entries:
                # create!
                self.network_api.add_dns_entry(context, address, name,
                                               dns_type, domain)
            else:
                # modify!
                self.network_api.modify_dns_entry(context, name,
                                                  address, domain)
        except NotImplementedError:
            common.raise_feature_not_supported()

        return _translate_dns_entry_view({'ip': address,
                                          'name': name,
                                          'type': dns_type,
                                          'domain': domain})
コード例 #8
0
ファイル: remote_consoles.py プロジェクト: Pratyusha9/nova
    def get_rdp_console(self, req, id, body):
        """Get text console output."""
        context = req.environ['nova.context']
        authorize(context)

        # If type is not supplied or unknown, get_rdp_console below will cope
        console_type = body['os-getRDPConsole'].get('type')

        instance = common.get_instance(self.compute_api, context, id)
        try:
            # NOTE(mikal): get_rdp_console() can raise InstanceNotFound, so
            # we still need to catch it here.
            output = self.compute_api.get_rdp_console(context,
                                                      instance,
                                                      console_type)
        except exception.ConsoleTypeUnavailable as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())
        except exception.InstanceNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()

        return {'console': {'type': console_type, 'url': output['url']}}
コード例 #9
0
ファイル: remote_consoles.py プロジェクト: coryschwartz/nova
    def create(self, req, server_id, body):
        context = req.environ["nova.context"]
        authorize(context)
        instance = common.get_instance(self.compute_api, context, server_id)
        protocol = body["remote_console"]["protocol"]
        console_type = body["remote_console"]["type"]
        try:
            handler = self.handlers.get(protocol)
            output = handler(context, instance, console_type)
            return {"remote_console": {"protocol": protocol, "type": console_type, "url": output["url"]}}

        except exception.InstanceNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except (
            exception.ConsoleTypeInvalid,
            exception.ConsoleTypeUnavailable,
            exception.ImageSerialPortNumberInvalid,
            exception.ImageSerialPortNumberExceedFlavorValue,
            exception.SocketPortRangeExhaustedException,
        ) as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()
コード例 #10
0
    def get_console_output(self, req, id, body):
        """Get text console output."""
        context = req.environ['nova.context']
        authorize(context)

        instance = common.get_instance(self.compute_api, context, id)
        length = body['os-getConsoleOutput'].get('length')
        # TODO(cyeoh): In a future API update accept a length of -1
        # as meaning unlimited length (convert to None)

        try:
            output = self.compute_api.get_console_output(context,
                                                         instance,
                                                         length)
        # NOTE(cyeoh): This covers race conditions where the instance is
        # deleted between common.get_instance and get_console_output
        # being called
        except exception.InstanceNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()

        # XML output is not correctly escaped, so remove invalid characters
        # NOTE(cyeoh): We don't support XML output with V2.1, but for
        # backwards compatibility reasons we continue to filter the output
        # We should remove this in the future
        remove_re = re.compile('[\x00-\x08\x0B-\x1F]')
        output = remove_re.sub('', output)

        return {'output': output}
コード例 #11
0
ファイル: networks_associate.py プロジェクト: Juniper/nova
 def _disassociate_host_only(self, req, id, body):
     context = req.environ['nova.context']
     context.can(na_policies.BASE_POLICY_NAME)
     try:
         self.network_api.associate(context, id, host=None)
     except exception.NetworkNotFound:
         msg = _("Network not found")
         raise exc.HTTPNotFound(explanation=msg)
     except NotImplementedError:
         common.raise_feature_not_supported()
コード例 #12
0
ファイル: networks_associate.py プロジェクト: Pratyusha9/nova
 def _disassociate_project_only(self, req, id, body):
     context = req.environ['nova.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:
         common.raise_feature_not_supported()
コード例 #13
0
    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:
            common.raise_feature_not_supported()
コード例 #14
0
ファイル: hosts.py プロジェクト: isyippee/nova
 def _host_power_action(self, req, host_name, action):
     """Reboots, shuts down or powers up the host."""
     context = req.environ["nova.context"]
     authorize(context)
     try:
         result = self.api.host_power_action(context, host_name=host_name, action=action)
     except NotImplementedError:
         common.raise_feature_not_supported()
     except exception.HostNotFound as e:
         raise webob.exc.HTTPNotFound(explanation=e.format_message())
     except exception.ComputeServiceUnavailable as e:
         raise webob.exc.HTTPBadRequest(explanation=e.format_message())
     return {"host": host_name, "power_action": result}
コード例 #15
0
ファイル: hosts.py プロジェクト: andymcc/nova
 def _host_power_action(self, req, host_name, action):
     """Reboots, shuts down or powers up the host."""
     context = req.environ['nova.context']
     context.can(hosts_policies.BASE_POLICY_NAME)
     try:
         result = self.api.host_power_action(context, host_name, action)
     except NotImplementedError:
         common.raise_feature_not_supported()
     except (exception.HostNotFound, exception.HostMappingNotFound) as e:
         raise webob.exc.HTTPNotFound(explanation=e.format_message())
     except exception.ComputeServiceUnavailable as e:
         raise webob.exc.HTTPBadRequest(explanation=e.format_message())
     return {"host": host_name, "power_action": result}
コード例 #16
0
ファイル: networks.py プロジェクト: cyx1231st/nova
    def add(self, req, body):
        context = req.environ["nova.context"]
        context.can(net_policies.BASE_POLICY_NAME)

        network_id = body["id"]
        project_id = context.project_id

        try:
            self.network_api.add_network_to_project(context, project_id, network_id)
        except NotImplementedError:
            common.raise_feature_not_supported()
        except (exception.NoMoreNetworks, exception.NetworkNotFoundForUUID) as e:
            raise exc.HTTPBadRequest(explanation=e.format_message())
コード例 #17
0
ファイル: floating_ip_dns.py プロジェクト: hanbaoying/nova
    def delete(self, req, id):
        """Delete the domain identified by id."""
        context = req.environ['nova.context']
        authorize(context, action="domain:delete")
        domain = _unquote_domain(id)

        # Delete the whole domain
        try:
            self.network_api.delete_dns_domain(context, domain)
        except NotImplementedError:
            common.raise_feature_not_supported()
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
コード例 #18
0
ファイル: floating_ip_dns.py プロジェクト: hanbaoying/nova
    def delete(self, req, domain_id, id):
        """Delete the entry identified by req and id."""
        context = req.environ['nova.context']
        authorize(context)
        domain = _unquote_domain(domain_id)
        name = id

        try:
            self.network_api.delete_dns_entry(context, name, domain)
        except NotImplementedError:
            common.raise_feature_not_supported()
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
コード例 #19
0
ファイル: attach_interfaces.py プロジェクト: 375670450/nova
    def create(self, req, server_id, body):
        """Attach an interface to an instance."""
        context = req.environ['nova.context']
        authorize(context)

        network_id = None
        port_id = None
        req_ip = None
        if body:
            attachment = body['interfaceAttachment']
            network_id = attachment.get('net_id', None)
            port_id = attachment.get('port_id', None)
            try:
                req_ip = attachment['fixed_ips'][0]['ip_address']
            except Exception:
                pass

        if network_id and port_id:
            msg = _("Must not input both network_id and port_id")
            raise exc.HTTPBadRequest(explanation=msg)
        if req_ip and not network_id:
            msg = _("Must input network_id when request IP address")
            raise exc.HTTPBadRequest(explanation=msg)

        instance = common.get_instance(self.compute_api, context, server_id)
        try:
            vif = self.compute_api.attach_interface(context,
                instance, network_id, port_id, req_ip)
        except (exception.InterfaceAttachFailedNoNetwork,
                exception.NetworkDuplicated,
                exception.NetworkAmbiguous,
                exception.NoMoreFixedIps,
                exception.PortNotUsable) as e:
            raise exc.HTTPBadRequest(explanation=e.format_message())
        except (exception.InstanceIsLocked,
                exception.FixedIpAlreadyInUse,
                exception.PortInUse) as e:
            raise exc.HTTPConflict(explanation=e.format_message())
        except (exception.PortNotFound,
                exception.NetworkNotFound) as e:
            raise exc.HTTPNotFound(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()
        except exception.InterfaceAttachFailed as e:
            raise webob.exc.HTTPInternalServerError(
                explanation=e.format_message())
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(state_error,
                    'attach_interface', server_id)

        return self.show(req, server_id, vif['id'])
コード例 #20
0
ファイル: networks.py プロジェクト: binarycode/nova
    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:
            common.raise_feature_not_supported()
        except (exception.NoMoreNetworks,
                exception.NetworkNotFoundForUUID) as e:
            raise exc.HTTPBadRequest(explanation=e.format_message())
コード例 #21
0
ファイル: certificates.py プロジェクト: coryschwartz/nova
 def show(self, req, id):
     """Return certificate information."""
     context = req.environ["nova.context"]
     authorize(context, action="show")
     if id != "root":
         msg = _("Only root certificate can be retrieved.")
         # TODO(oomichi): This seems a HTTPBadRequest case because of the
         # above message. This will be changed with a microversion in the
         # future.
         common.raise_feature_not_supported(msg=msg)
     try:
         cert = self.cert_rpcapi.fetch_ca(context, project_id=context.project_id)
     except exception.CryptoCAFileNotFound as e:
         raise webob.exc.HTTPNotFound(explanation=e.format_message())
     return {"certificate": _translate_certificate_view(cert)}
コード例 #22
0
ファイル: pause_server.py プロジェクト: fabian4/nova
 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:
         common.raise_feature_not_supported()
コード例 #23
0
ファイル: admin_password.py プロジェクト: hanbaoying/nova
    def change_password(self, req, id, body):
        context = req.environ['nova.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")
            common.raise_feature_not_supported(msg=msg)
コード例 #24
0
ファイル: floating_ip_dns.py プロジェクト: hanbaoying/nova
    def index(self, req):
        """Return a list of available DNS domains."""
        context = req.environ['nova.context']
        authorize(context)

        try:
            domains = self.network_api.get_dns_domains(context)
        except NotImplementedError:
            common.raise_feature_not_supported()

        domainlist = [_create_domain_entry(domain['domain'],
                                         domain.get('scope'),
                                         domain.get('project'),
                                         domain.get('availability_zone'))
                    for domain in domains]

        return _translate_domain_entries_view(domainlist)
コード例 #25
0
ファイル: hosts.py プロジェクト: vmturbo/nova
 def _set_host_maintenance(self, context, host_name, mode=True):
     """Start/Stop host maintenance window. On start, it triggers
     guest VMs evacuation.
     """
     LOG.info("Putting host %(host_name)s in maintenance mode %(mode)s.",
              {'host_name': host_name, 'mode': mode})
     try:
         result = self.api.set_host_maintenance(context, host_name, mode)
     except NotImplementedError:
         common.raise_feature_not_supported()
     except exception.HostNotFound as e:
         raise webob.exc.HTTPNotFound(explanation=e.format_message())
     except exception.ComputeServiceUnavailable as e:
         raise webob.exc.HTTPBadRequest(explanation=e.format_message())
     if result not in ("on_maintenance", "off_maintenance"):
         raise webob.exc.HTTPBadRequest(explanation=result)
     return result
コード例 #26
0
ファイル: pause_server.py プロジェクト: 4everming/nova
 def _pause(self, req, id, body):
     """Permit Admins to pause the server."""
     ctxt = req.environ['nova.context']
     ctxt.can(ps_policies.POLICY_ROOT % 'pause')
     server = common.get_instance(self.compute_api, ctxt, id)
     try:
         self.compute_api.pause(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,
                 'pause', id)
     except (exception.InstanceUnknownCell,
                  exception.InstanceNotFound) as e:
         raise exc.HTTPNotFound(explanation=e.format_message())
     except NotImplementedError:
         common.raise_feature_not_supported()
コード例 #27
0
ファイル: attach_interfaces.py プロジェクト: bigswitch/nova
    def delete(self, req, server_id, id):
        """Detach an interface from an instance."""
        context = req.environ["nova.context"]
        authorize(context)
        port_id = id

        instance = common.get_instance(self.compute_api, context, server_id)
        try:
            self.compute_api.detach_interface(context, instance, port_id=port_id)
        except exception.PortNotFound as e:
            raise exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceIsLocked as e:
            raise exc.HTTPConflict(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(state_error, "detach_interface", server_id)
コード例 #28
0
ファイル: server_diagnostics.py プロジェクト: Pratyusha9/nova
    def index(self, req, server_id):
        context = req.environ["nova.context"]
        authorize(context)

        instance = common.get_instance(self.compute_api, context, server_id)

        try:
            # NOTE(gmann): To make V21 same as V2 API, this method will call
            # 'get_diagnostics' instead of 'get_instance_diagnostics'.
            # In future, 'get_instance_diagnostics' needs to be called to
            # provide VM diagnostics in a defined format for all driver.
            # BP - https://blueprints.launchpad.net/nova/+spec/v3-diagnostics.
            return self.compute_api.get_diagnostics(context, instance)
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(state_error,
                    'get_diagnostics', server_id)
        except NotImplementedError:
            common.raise_feature_not_supported()
コード例 #29
0
 def _set_host_maintenance(self, context, host_name, mode=True):
     """Start/Stop host maintenance window. On start, it triggers
     guest VMs evacuation.
     """
     LOG.info("Putting host %(host_name)s in maintenance mode %(mode)s.", {
         'host_name': host_name,
         'mode': mode
     })
     try:
         result = self.api.set_host_maintenance(context, host_name, mode)
     except NotImplementedError:
         common.raise_feature_not_supported()
     except (exception.HostNotFound, exception.HostMappingNotFound) as e:
         raise webob.exc.HTTPNotFound(explanation=e.format_message())
     except exception.ComputeServiceUnavailable as e:
         raise webob.exc.HTTPBadRequest(explanation=e.format_message())
     if result not in ("on_maintenance", "off_maintenance"):
         raise webob.exc.HTTPBadRequest(explanation=result)
     return result
コード例 #30
0
ファイル: attach_interfaces.py プロジェクト: bigswitch/nova
    def _items(self, req, server_id, entity_maker):
        """Returns a list of attachments, transformed through entity_maker."""
        context = req.environ["nova.context"]
        authorize(context)

        instance = common.get_instance(self.compute_api, context, server_id)
        search_opts = {"device_id": instance.uuid}

        try:
            data = self.network_api.list_ports(context, **search_opts)
        except exception.NotFound as e:
            raise exc.HTTPNotFound(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()

        ports = data.get("ports", [])
        results = [entity_maker(port) for port in ports]

        return {"interfaceAttachments": results}
コード例 #31
0
ファイル: attach_interfaces.py プロジェクト: 2020human/nova
    def _items(self, req, server_id, entity_maker):
        """Returns a list of attachments, transformed through entity_maker."""
        context = req.environ['nova.context']
        context.can(ai_policies.BASE_POLICY_NAME)

        instance = common.get_instance(self.compute_api, context, server_id)
        search_opts = {'device_id': instance.uuid}

        try:
            data = self.network_api.list_ports(context, **search_opts)
        except exception.NotFound as e:
            raise exc.HTTPNotFound(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()

        ports = data.get('ports', [])
        results = [entity_maker(port) for port in ports]

        return {'interfaceAttachments': results}
コード例 #32
0
ファイル: attach_interfaces.py プロジェクト: bopopescu/NOVA-7
    def _items(self, req, server_id, entity_maker):
        """Returns a list of attachments, transformed through entity_maker."""
        context = req.environ['nova.context']
        context.can(ai_policies.BASE_POLICY_NAME)

        instance = common.get_instance(self.compute_api, context, server_id)
        search_opts = {'device_id': instance.uuid}

        try:
            data = self.network_api.list_ports(context, **search_opts)
        except exception.NotFound as e:
            raise exc.HTTPNotFound(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()

        ports = data.get('ports', [])
        results = [entity_maker(port) for port in ports]

        return {'interfaceAttachments': results}
コード例 #33
0
 def _pause(self, req, id, body):
     """Permit Admins to pause the server."""
     ctxt = req.environ['nova.context']
     server = common.get_instance(self.compute_api, ctxt, id)
     ctxt.can(ps_policies.POLICY_ROOT % 'pause',
              target={
                  'user_id': server.user_id,
                  'project_id': server.project_id
              })
     try:
         self.compute_api.pause(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, 'pause', id)
     except exception.InstanceNotFound as e:
         raise exc.HTTPNotFound(explanation=e.format_message())
     except NotImplementedError:
         common.raise_feature_not_supported()
コード例 #34
0
    def index(self, req, server_id):
        context = req.environ["nova.context"]
        context.can(sd_policies.BASE_POLICY_NAME)

        instance = common.get_instance(self.compute_api, context, server_id)

        try:
            if api_version_request.is_supported(req, min_version='2.48'):
                diagnostics = self.compute_api.get_instance_diagnostics(
                    context, instance)
                return self._view_builder.instance_diagnostics(diagnostics)

            return self.compute_api.get_diagnostics(context, instance)
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(
                state_error, 'get_diagnostics', server_id)
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()
コード例 #35
0
    def change_password(self, req, id, body):
        context = req.environ['nova.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.InstanceUnknownCell as e:
            raise exc.HTTPNotFound(explanation=e.format_message())
        except (exception.InstancePasswordSetFailed,
                exception.SetAdminPasswdNotSupported,
                exception.InstanceAgentNotEnabled) 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")
            common.raise_feature_not_supported(msg=msg)
コード例 #36
0
ファイル: attach_interfaces.py プロジェクト: zhaoyiji/nova
    def delete(self, req, server_id, id):
        """Detach an interface from an instance."""
        context = req.environ['nova.context']
        authorize(context)
        port_id = id

        instance = common.get_instance(self.compute_api, context, server_id)
        try:
            self.compute_api.detach_interface(context,
                                              instance,
                                              port_id=port_id)
        except exception.PortNotFound as e:
            raise exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceIsLocked as e:
            raise exc.HTTPConflict(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(
                state_error, 'detach_interface', server_id)
コード例 #37
0
ファイル: hosts.py プロジェクト: greedyCat/nova
 def _set_enabled_status(self, context, host_name, enabled):
     """Sets the specified host's ability to accept new instances.
     :param enabled: a boolean - if False no new VMs will be able to start
                     on the host.
     """
     if enabled:
         LOG.info("Enabling host %s.", host_name)
     else:
         LOG.info("Disabling host %s.", host_name)
     try:
         result = self.api.set_host_enabled(context, host_name, enabled)
     except NotImplementedError:
         common.raise_feature_not_supported()
     except (exception.HostNotFound, exception.HostMappingNotFound) as e:
         raise webob.exc.HTTPNotFound(explanation=e.format_message())
     except exception.ComputeServiceUnavailable as e:
         raise webob.exc.HTTPBadRequest(explanation=e.format_message())
     if result not in ("enabled", "disabled"):
         raise webob.exc.HTTPBadRequest(explanation=result)
     return result
コード例 #38
0
    def index(self, req, server_id):
        context = req.environ["nova.context"]
        context.can(sd_policies.BASE_POLICY_NAME)

        instance = common.get_instance(self.compute_api, context, server_id)

        try:
            # NOTE(gmann): To make V21 same as V2 API, this method will call
            # 'get_diagnostics' instead of 'get_instance_diagnostics'.
            # In future, 'get_instance_diagnostics' needs to be called to
            # provide VM diagnostics in a defined format for all driver.
            # BP - https://blueprints.launchpad.net/nova/+spec/v3-diagnostics.
            return self.compute_api.get_diagnostics(context, instance)
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(
                state_error, 'get_diagnostics', server_id)
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()
コード例 #39
0
ファイル: hypervisors.py プロジェクト: bopopescu/nova-nfv-acc
    def uptime(self, req, id):
        context = req.environ['nova.context']
        authorize(context)
        try:
            hyp = self.host_api.compute_node_get(context, id)
            req.cache_db_compute_node(hyp)
        except (ValueError, exception.ComputeHostNotFound):
            msg = _("Hypervisor with ID '%s' could not be found.") % id
            raise webob.exc.HTTPNotFound(explanation=msg)

        # Get the uptime
        try:
            host = hyp.host
            uptime = self.host_api.get_host_uptime(context, host)
        except NotImplementedError:
            common.raise_feature_not_supported()

        service = self.host_api.service_get_by_compute_host(context, host)
        return dict(hypervisor=self._view_hypervisor(
            hyp, service, False, uptime=uptime))
コード例 #40
0
    def delete(self, req, server_id, id):
        """Detach an interface from an instance."""
        context = req.environ['nova.context']
        context.can(ai_policies.BASE_POLICY_NAME)
        context.can(ai_policies.POLICY_ROOT % 'delete')
        port_id = id

        instance = common.get_instance(self.compute_api, context, server_id,
                                       expected_attrs=['device_metadata'])
        try:
            self.compute_api.detach_interface(context,
                instance, port_id=port_id)
        except exception.PortNotFound as e:
            raise exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceIsLocked as e:
            raise exc.HTTPConflict(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()
        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(state_error,
                    'detach_interface', server_id)
コード例 #41
0
    def index(self, req, server_id):
        """Returns the list of interface attachments for a given instance."""
        context = req.environ['nova.context']
        instance = common.get_instance(self.compute_api, context, server_id)
        context.can(ai_policies.POLICY_ROOT % 'list',
                    target={'project_id': instance.project_id})

        search_opts = {'device_id': instance.uuid}

        try:
            data = self.network_api.list_ports(context, **search_opts)
        except exception.NotFound as e:
            raise exc.HTTPNotFound(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()

        # If showing tags, get the VirtualInterfaceList for the server and
        # map VIFs by port ID. Note that VirtualInterface records did not
        # exist for neutron ports until the Newton release so it's OK if we
        # are missing records for old servers.
        show_tag = api_version_request.is_supported(req, '2.70')
        tag_per_port_id = {}
        if show_tag:
            vifs = objects.VirtualInterfaceList.get_by_instance_uuid(
                context, server_id)
            tag_per_port_id = {vif.uuid: vif.tag for vif in vifs}

        results = []
        ports = data.get('ports', [])
        for port in ports:
            # Note that we do not pass show_tag=show_tag to
            # _translate_interface_attachment_view because we are handling it
            # ourselves here since we have the list of VIFs which is better
            # for performance than doing a DB query per port.
            info = _translate_interface_attachment_view(context, port)
            if show_tag:
                info['tag'] = tag_per_port_id.get(port['id'])
            results.append(info)

        return {'interfaceAttachments': results}
コード例 #42
0
    def uptime(self, req, id):
        context = req.environ['nova.context']
        context.can(hv_policies.BASE_POLICY_NAME)
        try:
            hyp = self.host_api.compute_node_get(context, id)
            req.cache_db_compute_node(hyp)
        except (ValueError, exception.ComputeHostNotFound):
            msg = _("Hypervisor with ID '%s' could not be found.") % id
            raise webob.exc.HTTPNotFound(explanation=msg)

        # Get the uptime
        try:
            host = hyp.host
            uptime = self.host_api.get_host_uptime(context, host)
        except NotImplementedError:
            common.raise_feature_not_supported()
        except exception.ComputeServiceUnavailable as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())

        service = self.host_api.service_get_by_compute_host(context, host)
        return dict(hypervisor=self._view_hypervisor(
            hyp, service, False, req, uptime=uptime))
コード例 #43
0
    def change_password(self, req, id, body):
        context = req.environ['nova.context']
        instance = common.get_instance(self.compute_api, context, id)
        context.can(ap_policies.BASE_POLICY_NAME,
                    target={
                        'user_id': instance.user_id,
                        'project_id': instance.project_id
                    })

        password = body['changePassword']['adminPass']
        try:
            self.compute_api.set_admin_password(context, instance, password)
        except (exception.InstancePasswordSetFailed,
                exception.SetAdminPasswdNotSupported,
                exception.InstanceAgentNotEnabled) 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")
            common.raise_feature_not_supported(msg=msg)
コード例 #44
0
    def get_spice_console(self, req, id, body):
        """Get text console output."""
        context = req.environ['nova.context']
        authorize(context)

        # If type is not supplied or unknown, get_spice_console below will cope
        console_type = body['os-getSPICEConsole'].get('type')

        try:
            instance = common.get_instance(self.compute_api, context, id)
            output = self.compute_api.get_spice_console(
                context, instance, console_type)
        except exception.ConsoleTypeUnavailable as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())
        except exception.InstanceNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()

        return {'console': {'type': console_type, 'url': output['url']}}
コード例 #45
0
    def get_serial_console(self, req, id, body):
        """Get connection to a serial console."""
        context = req.environ['nova.context']
        authorize(context)

        # If type is not supplied or unknown get_serial_console below will cope
        console_type = body['os-getSerialConsole'].get('type')
        try:
            instance = common.get_instance(self.compute_api, context, id)
            output = self.compute_api.get_serial_console(
                context, instance, console_type)
        except exception.InstanceNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except (exception.ConsoleTypeUnavailable,
                exception.ImageSerialPortNumberInvalid,
                exception.ImageSerialPortNumberExceedFlavorValue,
                exception.SocketPortRangeExhaustedException) as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()

        return {'console': {'type': console_type, 'url': output['url']}}
コード例 #46
0
    def get_rdp_console(self, req, id, body):
        """Get text console output."""
        context = req.environ['nova.context']
        context.can(rc_policies.BASE_POLICY_NAME)

        # If type is not supplied or unknown, get_rdp_console below will cope
        console_type = body['os-getRDPConsole'].get('type')

        instance = common.get_instance(self.compute_api, context, id)
        try:
            # NOTE(mikal): get_rdp_console() can raise InstanceNotFound, so
            # we still need to catch it here.
            output = self.compute_api.get_rdp_console(context, instance,
                                                      console_type)
        except exception.ConsoleTypeUnavailable as e:
            raise webob.exc.HTTPBadRequest(explanation=e.format_message())
        except exception.InstanceNotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.format_message())
        except exception.InstanceNotReady as e:
            raise webob.exc.HTTPConflict(explanation=e.format_message())
        except NotImplementedError:
            common.raise_feature_not_supported()

        return {'console': {'type': console_type, 'url': output['url']}}
コード例 #47
0
def _check_ironic_client_enabled():
    """Check whether Ironic is installed or not."""
    if ironic_client is None:
        common.raise_feature_not_supported()