def test_extension_authorizer_throws_exception_if_policy_fails(self): target = {"project_id": "1234", "user_id": "5678"} self.mox.StubOutWithMock(nova.policy, "enforce") nova.policy.enforce(self.fake_context, "compute_extension:used_limits_for_admin", target).AndRaise( exception.PolicyNotAuthorized(action="compute_extension:used_limits_for_admin") ) self.mox.ReplayAll() authorize = base_extensions.extension_authorizer("compute", "used_limits_for_admin") self.assertRaises(exception.PolicyNotAuthorized, authorize, self.fake_context, target=target)
def test_extension_authorizer_throws_exception_if_policy_fails(self): target = {'project_id': '1234', 'user_id': '5678'} self.mox.StubOutWithMock(nova.policy, 'enforce') nova.policy.enforce(self.fake_context, "compute_extension:used_limits_for_admin", target).AndRaise( exception.PolicyNotAuthorized( action="compute_extension:used_limits_for_admin")) ('compute', 'used_limits_for_admin') self.mox.ReplayAll() authorize = base_extensions.extension_authorizer('compute', 'used_limits_for_admin' ) self.assertRaises(exception.PolicyNotAuthorized, authorize, self.fake_context, target=target)
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """The Aggregate admin API extension.""" from webob import exc from nova.api.openstack import extensions from nova import compute from nova import exception from nova import log as logging LOG = logging.getLogger("nova.api.openstack.compute.contrib.host_aggregates") authorize = extensions.extension_authorizer('compute', 'aggregates') def _get_context(req): return req.environ['nova.context'] def get_host_from_body(fn): """Makes sure that the host exists.""" def wrapped(self, req, id, body, *args, **kwargs): if len(body) == 1 and "host" in body: host = body['host'] else: raise exc.HTTPBadRequest return fn(self, req, id, host, *args, **kwargs) return wrapped
# under the License. import datetime import webob.exc from nova.api.openstack import extensions from nova import db from nova import flags from nova import utils FLAGS = flags.FLAGS authorize = extensions.extension_authorizer('compute', 'instance_usage_audit_log') class InstanceUsageAuditLogController(object): def index(self, req): context = req.environ['nova.context'] authorize(context) task_log = self._get_audit_task_logs(context) return {'instance_usage_audit_logs': task_log} def show(self, req, id): context = req.environ['nova.context'] authorize(context) try: if '.' in id:
except cfg.DuplicateOptError: # NOTE(jkoelker) These options are verbatim elsewhere this is here # to make sure they are registered for our use. pass if CONF.enable_network_quota: opts = [ cfg.IntOpt('quota_networks', default=3, help='Number of private networks allowed per project'), ] CONF.register_opts(opts) QUOTAS = quota.QUOTAS LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'os-tenant-networks') def network_dict(network): return {"id": network.get("uuid") or network.get("id"), "cidr": network.get("cidr"), "label": network.get("label")} class NetworkController(object): def __init__(self, network_api=None): self.network_api = nova.network.API() self._default_networks = [] def _refresh_default_networks(self): self._default_networks = []
def authorize(context, action_name): action = 'v3:%s:%s' % (ALIAS, action_name) extensions.extension_authorizer('compute', action)(context)
# License for the specific language governing permissions and limitations # under the License. """The virtual interfaces extension.""" from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import compute from nova import log as logging from nova import network LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'virtual_interfaces') vif_nsmap = {None: wsgi.XMLNS_V11} class VirtualInterfaceTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('virtual_interfaces') elem = xmlutil.SubTemplateElement(root, 'virtual_interface', selector='virtual_interfaces') elem.set('id') elem.set('mac_address') return xmlutil.MasterTemplate(root, 1, nsmap=vif_nsmap)
from xml.dom import minidom from xml.parsers import expat from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova.api.openstack import extensions from nova import compute from nova import exception from nova import flags from nova import log as logging from nova.scheduler import api as scheduler_api LOG = logging.getLogger("nova.api.openstack.compute.contrib.hosts") FLAGS = flags.FLAGS authorize = extensions.extension_authorizer('compute', 'hosts') class HostIndexTemplate(xmlutil.TemplateBuilder): def construct(self): def shimmer(obj, do_raise=False): # A bare list is passed in; we need to wrap it in a dict return dict(hosts=obj) root = xmlutil.TemplateElement('hosts', selector=shimmer) elem = xmlutil.SubTemplateElement(root, 'host', selector='hosts') elem.set('host_name') elem.set('service') return xmlutil.MasterTemplate(root, 1)
from nova.api.openstack import wsgi import nova.context from nova import db from nova import exception from nova.i18n import _ from nova import quota from nova import utils QUOTAS = quota.QUOTAS # Quotas that are only enabled by specific extensions EXTENDED_QUOTAS = {'server_groups': 'os-server-group-quotas', 'server_group_members': 'os-server-group-quotas'} authorize = extensions.extension_authorizer('compute', 'quota_classes') class QuotaClassSetsController(wsgi.Controller): supported_quotas = [] def __init__(self, ext_mgr): self.ext_mgr = ext_mgr self.supported_quotas = QUOTAS.resources for resource, extension in EXTENDED_QUOTAS.items(): if not self.ext_mgr.is_loaded(extension): self.supported_quotas.remove(resource) def _format_quota_set(self, quota_class, quota_set): """Convert the quota object to a result dict."""
# License for the specific language governing permissions and limitations # under the License. from oslo.config import cfg import webob.exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import compute from nova import db from nova import exception from nova.openstack.common import timeutils from nova import utils authorize = extensions.extension_authorizer('compute', 'services') CONF = cfg.CONF CONF.import_opt('service_down_time', 'nova.service') class ServicesIndexTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('services') elem = xmlutil.SubTemplateElement(root, 'service', selector='services') elem.set('binary') elem.set('host') elem.set('zone') elem.set('status') elem.set('state') elem.set('updated_at')
import nova.context from nova import db from nova import exception from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging from nova.openstack.common import strutils from nova import quota from nova import utils QUOTAS = quota.QUOTAS LOG = logging.getLogger(__name__) NON_QUOTA_KEYS = ['tenant_id', 'id', 'force'] authorize_update = extensions.extension_authorizer('compute', 'quotas:update') authorize_show = extensions.extension_authorizer('compute', 'quotas:show') authorize_delete = extensions.extension_authorizer('compute', 'quotas:delete') class QuotaTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('quota_set', selector='quota_set') root.set('id') for resource in QUOTAS.resources: elem = xmlutil.SubTemplateElement(root, resource) elem.text = resource return xmlutil.MasterTemplate(root, 1)
# License for the specific language governing permissions and limitations # under the License from oslo.config import cfg from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import availability_zones from nova import db from nova import servicegroup CONF = cfg.CONF authorize_list = extensions.extension_authorizer('compute', 'availability_zone:list') authorize_detail = extensions.extension_authorizer('compute', 'availability_zone:detail') def make_availability_zone(elem): elem.set('name', 'zoneName') zoneStateElem = xmlutil.SubTemplateElement(elem, 'zoneState', selector='zoneState') zoneStateElem.set('available') hostsElem = xmlutil.SubTemplateElement(elem, 'hosts', selector='hosts') hostElem = xmlutil.SubTemplateElement(hostsElem, 'host',
# License for the specific language governing permissions and limitations # under the License. import netaddr from webob import exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import exception from nova.i18n import _ from nova import network from nova.objects import base as base_obj from nova.objects import fields as obj_fields ALIAS = 'os-networks' authorize = extensions.extension_authorizer('compute', 'v3:' + ALIAS) authorize_view = extensions.extension_authorizer('compute', 'v3:' + ALIAS + ':view') def network_dict(context, network): fields = ('id', 'cidr', 'netmask', 'gateway', 'broadcast', 'dns1', 'dns2', 'cidr_v6', 'gateway_v6', 'label', 'netmask_v6') admin_fields = ('created_at', 'updated_at', 'deleted_at', 'deleted', 'injected', 'bridge', 'vlan', 'vpn_public_address', 'vpn_public_port', 'vpn_private_address', 'dhcp_start', 'project_id', 'host', 'bridge_interface', 'multi_host', 'priority', 'rxtx_base', 'mtu', 'dhcp_server', 'enable_dhcp', 'share_address') if network: # NOTE(mnaser): We display a limited set of fields so users can know
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """The volume types manage extension.""" import webob from nova.api.openstack import extensions from nova.api.openstack.volume import types from nova.api.openstack.volume.views import types as views_types from nova.api.openstack import wsgi from nova import exception from nova.volume import volume_types authorize = extensions.extension_authorizer('volume', 'types_manage') class VolumeTypesManageController(wsgi.Controller): """ The volume types API controller for the OpenStack API """ _view_builder_class = views_types.ViewBuilder @wsgi.action("create") @wsgi.serializers(xml=types.VolumeTypeTemplate) def _create(self, req, body): """Creates a new volume type.""" context = req.environ['nova.context'] authorize(context) if not body or body == "":
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """The virtual interfaces extension.""" import webob from nova.api.openstack import common from nova.api.openstack import extensions from nova import compute from nova.i18n import _ from nova import network authorize = extensions.extension_authorizer('compute', 'virtual_interfaces') def _translate_vif_summary_view(vif): """Maps keys for VIF summary view.""" d = {} d['id'] = vif.uuid d['mac_address'] = vif.address return d class ServerVirtualInterfaceController(object): """The instance VIF API HeterogeneousController for the OpenStack API. """ def __init__(self): self.compute_api = compute.API()
# License for the specific language governing permissions and limitations # under the License. from webob import exc from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute from nova import exception from nova.i18n import _ from nova.openstack.common import strutils from nova import utils authorize = extensions.extension_authorizer('compute', 'evacuate') class Controller(wsgi.Controller): def __init__(self, ext_mgr, *args, **kwargs): super(Controller, self).__init__(*args, **kwargs) self.compute_api = compute.API() self.host_api = compute.HostAPI() self.ext_mgr = ext_mgr @wsgi.action('evacuate') def _evacuate(self, req, id, body): """Permit admins to evacuate a server from a failed host to a new one. If host is empty, the scheduler will select one. """
from webob import exc from nova.api.openstack import common from nova.api.openstack import extensions from nova.cells import rpcapi as cells_rpcapi from nova.compute import api as compute from nova import exception from nova.i18n import _ from nova import rpc CONF = cfg.CONF CONF.import_opt('name', 'nova.cells.opts', group='cells') CONF.import_opt('capabilities', 'nova.cells.opts', group='cells') authorize = extensions.extension_authorizer('compute', 'cells') def _filter_keys(item, keys): """Filters all model attributes except for keys item is a dict """ return {k: v for k, v in item.iteritems() if k in keys} def _fixup_cell_info(cell_info, keys): """If the transport_url is present in the cell, derive username, rpc_host, and rpc_port from it. """
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import webob from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.consoleauth import rpcapi as consoleauth_rpcapi from nova.i18n import _ authorize = extensions.extension_authorizer('compute', 'console_auth_tokens') class ConsoleAuthTokensController(wsgi.Controller): def __init__(self, *args, **kwargs): self._consoleauth_rpcapi = consoleauth_rpcapi.ConsoleAuthAPI() super(ConsoleAuthTokensController, self).__init__(*args, **kwargs) def show(self, req, id): """Checks a console auth token and returns the related connect info.""" context = req.environ['nova.context'] authorize(context) token = id connect_info = self._consoleauth_rpcapi.check_token(context, token) if not connect_info:
from nova.api.openstack import xmlutil from nova.api.openstack import extensions from nova.auth import manager from nova.cloudpipe import pipelib from nova import compute from nova.compute import vm_states from nova import db from nova import exception from nova import flags from nova import log as logging from nova import utils FLAGS = flags.FLAGS LOG = logging.getLogger("nova.api.openstack.compute.contrib.cloudpipe") authorize = extensions.extension_authorizer('compute', 'cloudpipe') class CloudpipeTemplate(xmlutil.TemplateBuilder): def construct(self): return xmlutil.MasterTemplate(xmlutil.make_flat_dict('cloudpipe'), 1) class CloudpipesTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('cloudpipes') elem = xmlutil.make_flat_dict('cloudpipe', selector='cloudpipes', subselector='cloudpipe') root.append(elem) return xmlutil.MasterTemplate(root, 1)
import netaddr from webob import exc from nova.api.openstack.compute.schemas.v3 import networks as schema from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api import validation from nova import exception from nova.i18n import _ from nova import network from nova.objects import base as base_obj from nova.objects import fields as obj_fields ALIAS = 'os-networks' authorize = extensions.extension_authorizer('compute', 'v3:' + ALIAS) authorize_view = extensions.extension_authorizer('compute', 'v3:' + ALIAS + ':view') def network_dict(context, network): fields = ('id', 'cidr', 'netmask', 'gateway', 'broadcast', 'dns1', 'dns2', 'cidr_v6', 'gateway_v6', 'label', 'netmask_v6') admin_fields = ('created_at', 'updated_at', 'deleted_at', 'deleted', 'injected', 'bridge', 'vlan', 'vpn_public_address', 'vpn_public_port', 'vpn_private_address', 'dhcp_start', 'project_id', 'host', 'bridge_interface', 'multi_host', 'priority', 'rxtx_base', 'mtu', 'dhcp_server', 'enable_dhcp', 'share_address') if network: # NOTE(mnaser): We display a limited set of fields so users can know
# under the License. from oslo_log import log as logging import webob from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute from nova import exception from nova.i18n import _ from nova.i18n import _LI from nova import objects from nova.objects import external_event as external_event_obj LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'os-server-external-events') class ServerExternalEventsController(wsgi.Controller): def __init__(self): self.compute_api = compute.API() super(ServerExternalEventsController, self).__init__() def create(self, req, body): """Creates a new instance event.""" context = req.environ['nova.context'] authorize(context, action='create') response_events = [] accepted_events = [] accepted_instances = set()
import webob from webob import exc from nova.api.openstack.compute.contrib import security_groups as sg from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import exception from nova.i18n import _ from nova.network.security_group import openstack_driver from nova.openstack.common import log as logging from nova.openstack.common import xmlutils LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'security_group_default_rules') sg_nsmap = {None: wsgi.XMLNS_V11} def make_default_rule(elem): elem.set('id') proto = xmlutil.SubTemplateElement(elem, 'ip_protocol') proto.text = 'ip_protocol' from_port = xmlutil.SubTemplateElement(elem, 'from_port') from_port.text = 'from_port' to_port = xmlutil.SubTemplateElement(elem, 'to_port') to_port.text = 'to_port'
# under the License. import itertools import os from oslo.config import cfg from webob import exc from nova.api.openstack import common from nova.api.openstack import extensions from nova import compute from nova import exception from nova.i18n import _ from nova import utils authorize = extensions.extension_authorizer('compute', 'fping') authorize_all_tenants = extensions.extension_authorizer( 'compute', 'fping:all_tenants') fping_opts = [ cfg.StrOpt("fping_path", default="/usr/sbin/fping", help="Full path to fping."), ] CONF = cfg.CONF CONF.register_opts(fping_opts) class FpingController(object): def __init__(self, network_api=None): self.compute_api = compute.API()
def authorize(context, action_name): action = 'admin_actions:%s' % action_name extensions.extension_authorizer('compute', action)(context)
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import six from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import quota QUOTAS = quota.QUOTAS XMLNS = "http://docs.openstack.org/compute/ext/used_limits/api/v1.1" ALIAS = "os-used-limits" authorize = extensions.soft_extension_authorizer('compute', 'used_limits') authorize_for_admin = extensions.extension_authorizer('compute', 'used_limits_for_admin') class UsedLimitsController(wsgi.Controller): def __init__(self, ext_mgr): self.ext_mgr = ext_mgr @staticmethod def _reserved(req): try: return int(req.GET['reserved']) except (ValueError, KeyError): return False @wsgi.extends def index(self, req, resp_obj):
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.config import cfg from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import availability_zones from nova import db from nova import servicegroup CONF = cfg.CONF ALIAS = "os-availability-zone" ATTRIBUTE_NAME = "%s:availability_zone" % ALIAS authorize_list = extensions.extension_authorizer('compute', 'v3:' + ALIAS + ':list') authorize_detail = extensions.extension_authorizer('compute', 'v3:' + ALIAS + ':detail') class AvailabilityZoneController(wsgi.Controller): """The Availability Zone API controller for the OpenStack API.""" def __init__(self): super(AvailabilityZoneController, self).__init__() self.servicegroup_api = servicegroup.API() def _get_filtered_availability_zones(self, zones, is_available): result = [] for zone in zones: # Hide internal_service_availability_zone
from oslo_log import log as logging from oslo_utils import uuidutils import webob from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute from nova.compute import utils as compute_utils from nova import exception from nova.i18n import _ from nova.i18n import _LW from nova import network LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'floating_ips') def _translate_floating_ip_view(floating_ip): result = { 'id': floating_ip['id'], 'ip': floating_ip['address'], 'pool': floating_ip['pool'], } # If fixed_ip is unset on floating_ip, then we can't get any of the next # stuff, so we'll just short-circuit if 'fixed_ip' not in floating_ip: result['fixed_ip'] = None result['instance_id'] = None return {'floating_ip': result}
from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import compute from nova import exception from nova.objects import block_device as block_device_obj from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging from nova.openstack.common import strutils from nova.openstack.common import uuidutils from nova import volume LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer("compute", "volumes") authorize_attach = extensions.extension_authorizer("compute", "volume_attachments") def _translate_volume_detail_view(context, vol): """Maps keys for volumes details view.""" d = _translate_volume_summary_view(context, vol) # No additional data / lookups at the moment return d def _translate_volume_summary_view(context, vol):
# under the License. """The deferred instance delete extension.""" import webob from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute from nova import exception from nova import log as logging LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'deferred_delete') class DeferredDeleteController(wsgi.Controller): def __init__(self, *args, **kwargs): super(DeferredDeleteController, self).__init__(*args, **kwargs) self.compute_api = compute.API() @wsgi.action('restore') def _restore(self, req, id, body): """Restore a previously deleted instance.""" context = req.environ["nova.context"] authorize(context) instance = self.compute_api.get(context, id) try: self.compute_api.restore(context, instance)
from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import compute from nova.compute import api as compute_api from nova import db from nova import exception from nova.network.security_group import openstack_driver from nova.network.security_group import quantum_driver from nova.openstack.common import log as logging from nova import utils from nova.virt import netutils LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'security_groups') softauth = extensions.soft_extension_authorizer('compute', 'security_groups') def make_rule(elem): elem.set('id') elem.set('parent_group_id') proto = xmlutil.SubTemplateElement(elem, 'ip_protocol') proto.text = 'ip_protocol' from_port = xmlutil.SubTemplateElement(elem, 'from_port') from_port.text = 'from_port' to_port = xmlutil.SubTemplateElement(elem, 'to_port') to_port.text = 'to_port'
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """The Aggregate admin API extension.""" import datetime from webob import exc from nova.api.openstack import extensions from nova.compute import api as compute_api from nova import exception from nova.i18n import _ from nova import utils authorize = extensions.extension_authorizer('compute', 'aggregates') def _get_context(req): return req.environ['nova.context'] def get_host_from_body(fn): """Makes sure that the host exists.""" def wrapped(self, req, id, body, *args, **kwargs): if len(body) != 1: msg = _('Only host parameter can be specified') raise exc.HTTPBadRequest(explanation=msg) elif 'host' not in body: msg = _('Host parameter must be specified') raise exc.HTTPBadRequest(explanation=msg)
# License for the specific language governing permissions and limitations # under the License. """The instance type extra specs extension.""" from webob import exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import db from nova import exception from nova.openstack.common.gettextutils import _ authorize = extensions.extension_authorizer('compute', 'flavorextraspecs') class ExtraSpecsTemplate(xmlutil.TemplateBuilder): def construct(self): return xmlutil.MasterTemplate(xmlutil.make_flat_dict('extra_specs'), 1) class ExtraSpecTemplate(xmlutil.TemplateBuilder): def construct(self): sel = xmlutil.Selector(xmlutil.get_items, 0) root = xmlutil.TemplateElement('extra_spec', selector=sel) root.set('key', 0) root.text = 1 return xmlutil.MasterTemplate(root, 1)
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Keypair management extension""" import webob import webob.exc from nova.api.openstack.compute import servers from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova.compute import api as compute_api from nova import exception authorize = extensions.extension_authorizer('compute', 'keypairs') soft_authorize = extensions.soft_extension_authorizer('compute', 'keypairs') class KeypairTemplate(xmlutil.TemplateBuilder): def construct(self): return xmlutil.MasterTemplate(xmlutil.make_flat_dict('keypair'), 1) class KeypairsTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('keypairs') elem = xmlutil.make_flat_dict('keypair', selector='keypairs', subselector='keypair') root.append(elem)
# License for the specific language governing permissions and limitations # under the License. from oslo.config import cfg import webob.exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import compute from nova import exception from nova.openstack.common.gettextutils import _ from nova import servicegroup from nova import utils authorize = extensions.extension_authorizer('compute', 'services') CONF = cfg.CONF CONF.import_opt('service_down_time', 'nova.service') class ServicesIndexTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('services') elem = xmlutil.SubTemplateElement(root, 'service', selector='services') elem.set('id') elem.set('binary') elem.set('host') elem.set('zone') elem.set('status') elem.set('state') elem.set('updated_at')
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License import re import webob from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute from nova import exception from nova.openstack.common import log as logging LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'console_output') class ConsoleOutputController(wsgi.Controller): def __init__(self, *args, **kwargs): super(ConsoleOutputController, self).__init__(*args, **kwargs) self.compute_api = compute.API() @wsgi.action('os-getConsoleOutput') def get_console_output(self, req, id, body): """Get text console output.""" context = req.environ['nova.context'] authorize(context) try: instance = self.compute_api.get(context, id)
from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import compute from nova.compute import utils as compute_utils from nova import exception from nova.i18n import _ from nova.i18n import _LW from nova import network from nova.openstack.common import log as logging from nova.openstack.common import uuidutils LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer("compute", "floating_ips") def make_float_ip(elem): elem.set("id") elem.set("ip") elem.set("pool") elem.set("fixed_ip") elem.set("instance_id") class FloatingIPTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement("floating_ip", selector="floating_ip") make_float_ip(root) return xmlutil.MasterTemplate(root, 1)
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License import webob from nova.api.openstack.compute import flavors as flavors_api from nova.api.openstack.compute.views import flavors as flavors_view from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.compute import instance_types from nova import exception from nova.openstack.common import log as logging LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'flavormanage') class FlavorManageController(wsgi.Controller): """ The Flavor Lifecycle API controller for the OpenStack API. """ _view_builder_class = flavors_view.ViewBuilder def __init__(self): super(FlavorManageController, self).__init__() @wsgi.action("delete") def _delete(self, req, id): context = req.environ['nova.context'] authorize(context)
# under the License. import datetime import iso8601 from oslo_utils import timeutils import six import six.moves.urllib.parse as urlparse from webob import exc from nova.api.openstack import extensions from nova import exception from nova.i18n import _ from nova import objects authorize_show = extensions.extension_authorizer('compute', 'simple_tenant_usage:show') authorize_list = extensions.extension_authorizer('compute', 'simple_tenant_usage:list') def parse_strtime(dstr, fmt): try: return timeutils.parse_strtime(dstr, fmt) except (TypeError, ValueError) as e: raise exception.InvalidStrTime(reason=six.text_type(e)) class SimpleTenantUsageController(object): def _hours_for(self, instance, period_start, period_stop): launched_at = instance.launched_at terminated_at = instance.terminated_at
# under the License. """The instance interfaces extension.""" import webob from webob import exc from nova.api.openstack import extensions from nova import compute from nova import exception from nova import network from nova.openstack.common import log as logging LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'attach_interfaces') def _translate_interface_attachment_view(port_info): """Maps keys for interface attachment details view.""" return { 'net_id': port_info['network_id'], 'port_id': port_info['id'], 'mac_addr': port_info['mac_address'], 'port_state': port_info['status'], 'fixed_ips': port_info.get('fixed_ips', None), } class InterfaceAttachmentController(object): """The interface attachment API controller for the OpenStack API."""
import webob from webob import exc from nova.api.openstack import extensions as exts from nova.api.openstack import wsgi from nova import compute from nova import exception from nova import flags from nova import log as logging from nova import utils FLAGS = flags.FLAGS LOG = logging.getLogger(__name__) authorize = exts.extension_authorizer('compute', 'rescue') class RescueController(wsgi.Controller): def __init__(self, *args, **kwargs): super(RescueController, self).__init__(*args, **kwargs) self.compute_api = compute.API() def _get_instance(self, context, instance_id): try: return self.compute_api.get(context, instance_id) except exception.InstanceNotFound: msg = _("Server not found") raise exc.HTTPNotFound(msg) @wsgi.action('rescue')
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """The bare-metal admin extension.""" import webob from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import exception from nova.virt.baremetal import db authorize = extensions.extension_authorizer('compute', 'baremetal_nodes') node_fields = ['id', 'cpus', 'local_gb', 'memory_mb', 'pm_address', 'pm_user', 'service_host', 'terminal_port', 'instance_uuid', ] interface_fields = ['id', 'address', 'datapath_id', 'port_no'] def _node_dict(node_ref): d = {} for f in node_fields: d[f] = node_ref.get(f) return d
from nova.api.openstack import common from nova.api.openstack.compute.schemas.v3 import extended_volumes from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api import validation from nova import compute from nova import exception from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging from nova import volume ALIAS = "os-extended-volumes" LOG = logging.getLogger(__name__) authorize = extensions.soft_extension_authorizer('compute', 'v3:' + ALIAS) authorize_attach = extensions.extension_authorizer('compute', 'v3:%s:attach' % ALIAS) authorize_detach = extensions.extension_authorizer('compute', 'v3:%s:detach' % ALIAS) authorize_swap = extensions.extension_authorizer('compute', 'v3:%s:swap' % ALIAS) class ExtendedVolumesController(wsgi.Controller): def __init__(self, *args, **kwargs): super(ExtendedVolumesController, self).__init__(*args, **kwargs) self.compute_api = compute.API() self.volume_api = volume.API() def _extend_server(self, context, server, instance): bdms = self.compute_api.get_instance_bdms(context, instance) volume_ids = [bdm['volume_id'] for bdm in bdms if bdm['volume_id']]
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import webob from webob import exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import context as nova_context from nova import exception from nova.i18n import _ from nova import network authorize = extensions.extension_authorizer('compute', 'networks_associate') class NetworkAssociateActionController(wsgi.Controller): """Network Association API Controller.""" def __init__(self, network_api=None): self.network_api = network_api or network.API() @wsgi.action("disassociate_host") def _disassociate_host_only(self, req, id, body): context = req.environ['nova.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)
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License import webob from nova.api.openstack.compute import flavors as flavors_api from nova.api.openstack.compute.views import flavors as flavors_view from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.compute import flavors from nova import exception authorize = extensions.extension_authorizer('compute', 'flavormanage') class FlavorManageController(wsgi.Controller): """ The Flavor Lifecycle API controller for the OpenStack API. """ _view_builder_class = flavors_view.ViewBuilder def __init__(self): super(FlavorManageController, self).__init__() @wsgi.action("delete") def _delete(self, req, id): context = req.environ['nova.context'] authorize(context)
from nova.cloudpipe import pipelib from nova import compute from nova.compute import utils as compute_utils from nova.compute import vm_states from nova import exception from nova.i18n import _ from nova import network from nova import objects from nova.openstack.common import fileutils from nova import utils CONF = cfg.CONF CONF.import_opt('keys_path', 'nova.crypto') ALIAS = 'os-cloudpipe' authorize = extensions.extension_authorizer('compute', 'v3:' + ALIAS) class CloudpipeController(wsgi.Controller): """Handle creating and listing cloudpipe instances.""" def __init__(self): self.compute_api = compute.API() self.network_api = network.API() self.cloudpipe = pipelib.CloudPipe() self.setup() def setup(self): """Ensure the keychains and folders exist.""" # NOTE(vish): One of the drawbacks of doing this in the api is # the keys will only be on the api node that launched
# under the License import webob from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import compute from nova import exception from nova import log as logging from nova import network from nova.rpc import common as rpc_common LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'floating_ips') def make_float_ip(elem): elem.set('id') elem.set('ip') elem.set('pool') elem.set('fixed_ip') elem.set('instance_id') class FloatingIPTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('floating_ip', selector='floating_ip') make_float_ip(root)
from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova.cloudpipe import pipelib from nova import compute from nova.compute import utils as compute_utils from nova.compute import vm_states from nova import exception from nova.i18n import _ from nova import network from nova.openstack.common import fileutils from nova import utils CONF = cfg.CONF CONF.import_opt('keys_path', 'nova.crypto') authorize = extensions.extension_authorizer('compute', 'cloudpipe') class CloudpipeTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('cloudpipe') elem = xmlutil.SubTemplateElement(root, 'instance_id', selector='instance_id') elem.text = str return xmlutil.MasterTemplate(root, 1) class CloudpipesTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('cloudpipes')
# under the License. import webob from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import compute from nova import exception from nova.openstack.common.gettextutils import _ from nova.openstack.common import jsonutils from nova.openstack.common import log as logging LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'os-assisted-volume-snapshots') def make_snapshot(elem): elem.set('id') elem.set('volumeId') class SnapshotTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('snapshot', selector='snapshot') make_snapshot(root) return xmlutil.MasterTemplate(root, 1) class AssistedVolumeSnapshotsController(wsgi.Controller):
# under the License. import datetime import iso8601 from oslo.utils import timeutils import six import six.moves.urllib.parse as urlparse from webob import exc from nova.api.openstack import extensions from nova import exception from nova.i18n import _ from nova import objects authorize_show = extensions.extension_authorizer('compute', 'simple_tenant_usage:show') authorize_list = extensions.extension_authorizer('compute', 'simple_tenant_usage:list') def parse_strtime(dstr, fmt): try: return timeutils.parse_strtime(dstr, fmt) except (TypeError, ValueError) as e: raise exception.InvalidStrTime(reason=six.text_type(e)) class SimpleTenantUsageController(object): def _hours_for(self, instance, period_start, period_stop): launched_at = instance.launched_at terminated_at = instance.terminated_at
from nova.api.openstack import extensions from nova.api.openstack import wsgi import nova.context from nova import db from nova import exception from nova.i18n import _ from nova import quota from nova import utils QUOTAS = quota.QUOTAS # Quotas that are only enabled by specific extensions EXTENDED_QUOTAS = {"server_groups": "os-server-group-quotas", "server_group_members": "os-server-group-quotas"} authorize = extensions.extension_authorizer("compute", "quota_classes") class QuotaClassSetsController(wsgi.Controller): supported_quotas = [] def __init__(self, ext_mgr): self.ext_mgr = ext_mgr self.supported_quotas = QUOTAS.resources for resource, extension in EXTENDED_QUOTAS.items(): if not self.ext_mgr.is_loaded(extension): self.supported_quotas.remove(resource) def _format_quota_set(self, quota_class, quota_set): """Convert the quota object to a result dict."""
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import webob.exc from nova.api.openstack import extensions from nova import db from nova import exception from nova.openstack.common import log as logging LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'fixed_ips') class FixedIPController(object): def show(self, req, id): """Return data about the given fixed ip.""" context = req.environ['nova.context'] authorize(context) try: fixed_ip = db.fixed_ip_get_by_address_detailed(context, id) except exception.FixedIpNotFoundForAddress as ex: raise webob.exc.HTTPNotFound(explanation=ex.format_message()) fixed_ip_info = {"fixed_ip": {}} if not fixed_ip[1]:
cfg.StrOpt('use_neutron_default_nets', default="False", help='Control for checking for default networks'), cfg.StrOpt('neutron_default_tenant_id', default="default", help='Default tenant id when creating neutron ' 'networks'), cfg.IntOpt('quota_networks', default=3, help='Number of private networks allowed per project'), ] CONF.register_opts(os_network_opts) QUOTAS = quota.QUOTAS LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'os-tenant-networks') def network_dict(network): # NOTE(danms): Here, network should be an object, which could have come # from neutron and thus be missing most of the attributes. Providing a # default to get() avoids trying to lazy-load missing attributes. return {"id": network.get("uuid", None) or network.get("id", None), "cidr": str(network.get("cidr", None)), "label": network.get("label", None)} class NetworkController(object): def __init__(self, network_api=None): self.network_api = nova.network.API() self._default_networks = []
import six.moves.urllib.parse as urlparse import webob from nova.api.openstack.compute.schemas.v3 import quota_sets from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api import validation import nova.context from nova import exception from nova.i18n import _ from nova import objects from nova import quota ALIAS = "os-quota-sets" QUOTAS = quota.QUOTAS authorize_update = extensions.extension_authorizer('compute', 'v3:%s:update' % ALIAS) authorize_show = extensions.extension_authorizer('compute', 'v3:%s:show' % ALIAS) authorize_delete = extensions.extension_authorizer('compute', 'v3:%s:delete' % ALIAS) authorize_detail = extensions.extension_authorizer('compute', 'v3:%s:detail' % ALIAS) class QuotaSetsController(wsgi.Controller): def _format_quota_set(self, project_id, quota_set): """Convert the quota object to a result dict.""" if project_id: result = dict(id=str(project_id)) else: result = {}
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import webob.exc from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute from nova import exception from nova.i18n import _ from nova import servicegroup from nova import utils ALIAS = "os-services" authorize = extensions.extension_authorizer('compute', 'v3:' + ALIAS) class ServiceController(wsgi.Controller): def __init__(self): self.host_api = compute.HostAPI() self.servicegroup_api = servicegroup.API() def _get_services(self, req): context = req.environ['nova.context'] authorize(context) services = self.host_api.service_get_all( context, set_zones=True) host = ''
from xml.dom import minidom from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova import compute from nova.compute import api as compute_api from nova import exception from nova.network.security_group import openstack_driver from nova.network.security_group import quantum_driver from nova.openstack.common import log as logging from nova.virt import netutils LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'security_groups') softauth = extensions.soft_extension_authorizer('compute', 'security_groups') def make_rule(elem): elem.set('id') elem.set('parent_group_id') proto = xmlutil.SubTemplateElement(elem, 'ip_protocol') proto.text = 'ip_protocol' from_port = xmlutil.SubTemplateElement(elem, 'from_port') from_port.text = 'from_port' to_port = xmlutil.SubTemplateElement(elem, 'to_port') to_port.text = 'to_port'
from nova.api.openstack import wsgi from nova.cloudpipe import pipelib from nova import compute from nova.compute import utils as compute_utils from nova.compute import vm_states from nova import exception from nova.i18n import _ from nova import network from nova.openstack.common import fileutils from nova import utils CONF = cfg.CONF CONF.import_opt("keys_path", "nova.crypto") ALIAS = "os-cloudpipe" authorize = extensions.extension_authorizer("compute", "v3:" + ALIAS) class CloudpipeController(wsgi.Controller): """Handle creating and listing cloudpipe instances.""" def __init__(self): self.compute_api = compute.API() self.network_api = network.API() self.cloudpipe = pipelib.CloudPipe() self.setup() def setup(self): """Ensure the keychains and folders exist.""" # NOTE(vish): One of the drawbacks of doing this in the api is # the keys will only be on the api node that launched
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """The shelved mode extension.""" import webob from webob import exc from nova.api.openstack import common from nova.api.openstack import extensions as exts from nova.api.openstack import wsgi from nova import compute from nova import exception ALIAS = 'os-shelve' auth_shelve = exts.extension_authorizer('compute', 'v3:%s:shelve' % ALIAS) auth_shelve_offload = exts.extension_authorizer('compute', 'v3:%s:shelve_offload' % ALIAS) auth_unshelve = exts.extension_authorizer('compute', 'v3:%s:unshelve' % ALIAS) class ShelveController(wsgi.Controller): def __init__(self, *args, **kwargs): super(ShelveController, self).__init__(*args, **kwargs) self.compute_api = compute.API() @exts.expected_errors((404, 409)) @wsgi.action('shelve') def _shelve(self, req, id, body): """Move an instance into shelved mode.""" context = req.environ["nova.context"]