def __init__(self, virtapi, scheme="https"): super(VMwareVCDriver, self).__init__(virtapi) if (CONF.vmware.host_ip is None or CONF.vmware.host_username is None or CONF.vmware.host_password is None): raise Exception( _("Must specify host_ip, host_username and " "host_password to use vmwareapi.VMwareVCDriver")) self._datastore_regex = None if CONF.vmware.datastore_regex: try: self._datastore_regex = re.compile(CONF.vmware.datastore_regex) except re.error: raise exception.InvalidInput( reason=_("Invalid Regular Expression %s") % CONF.vmware.datastore_regex) self._session = VMwareAPISession(scheme=scheme) self._check_min_version() # Update the PBM location if necessary if CONF.vmware.pbm_enabled: self._update_pbm_location() self._validate_configuration() self._cluster_name = CONF.vmware.cluster_name self._cluster_ref = vm_util.get_cluster_ref_by_name( self._session, self._cluster_name) if self._cluster_ref is None: raise exception.NotFound( _("The specified cluster '%s' was not " "found in vCenter") % self._cluster_name) self._vcenter_uuid = self._get_vcenter_uuid() self._nodename = self._create_nodename(self._cluster_ref.value) self._volumeops = volumeops.VMwareVolumeOps(self._session, self._cluster_ref) self._vmops = vmops.VMwareVMOps(self._session, virtapi, self._volumeops, self._cluster_ref, datastore_regex=self._datastore_regex) self._vc_state = host.VCState(self._session, self._nodename, self._cluster_ref, self._datastore_regex) # Register the OpenStack extension self._register_openstack_extension()
def allocate_for_instance(self, context, instance, **kwargs): """Allocate all network resources for the instance.""" LOG.debug(_('allocate_for_instance() for %s'), instance['display_name']) search_opts = {} if instance['project_id']: search_opts.update({"tenant_id": instance['project_id']}) else: msg = _('empty project id for instance %s') raise exception.InvalidInput(reason=msg % instance['display_name']) # If user has specified to attach instance only to specific # networks, add them to **search_opts # Tenant-only network only allowed so far requested_networks = kwargs.get('requested_networks') if requested_networks: net_ids = [net_id for (net_id, _i) in requested_networks] search_opts['id'] = net_ids data = quantumv2.get_client(context).list_networks(**search_opts) nets = data.get('networks', []) created_port_ids = [] for network in nets: port_req_body = { 'port': { 'network_id': network['id'], 'admin_state_up': True, 'device_id': instance['uuid'], 'tenant_id': instance['project_id'] }, } try: created_port_ids.append( quantumv2.get_client(context).create_port(port_req_body) ['port']['id']) except Exception: with excutils.save_and_reraise_exception(): for port_id in created_port_ids: try: quantumv2.get_client(context).delete_port(port_id) except Exception as ex: msg = _("Fail to delete port %(portid)s with" " failure: %(exception)s") LOG.debug(msg, { 'portid': port_id, 'exception': ex }) return self.get_instance_nw_info(context, instance, networks=nets)
def is_all_tenants(search_opts): """Checks to see if the all_tenants flag is in search_opts :param dict search_opts: The search options for a request :returns: boolean indicating if all_tenants are being requested or not """ all_tenants = search_opts.get('all_tenants') if all_tenants: try: all_tenants = strutils.bool_from_string(all_tenants, True) except ValueError as err: raise exception.InvalidInput(six.text_type(err)) else: # The empty string is considered enabling all_tenants all_tenants = 'all_tenants' in search_opts return all_tenants
def wrapper(self, ctx, *args, **kwargs): try: res = method(self, ctx, *args, **kwargs) except (cinder_exception.ConnectionError, keystone_exception.ConnectionError): exc_type, exc_value, exc_trace = sys.exc_info() _reraise( exception.CinderConnectionFailed( reason=six.text_type(exc_value))) except (keystone_exception.BadRequest, cinder_exception.BadRequest): exc_type, exc_value, exc_trace = sys.exc_info() _reraise(exception.InvalidInput(reason=six.text_type(exc_value))) except (keystone_exception.Forbidden, cinder_exception.Forbidden): exc_type, exc_value, exc_trace = sys.exc_info() _reraise(exception.Forbidden(six.text_type(exc_value))) return res
def wrapper(self, ctx, *args, **kwargs): try: res = method(self, ctx, *args, **kwargs) except (cinder_exception.ConnectionError, keystone_exception.ConnectionError) as exc: err_msg = encodeutils.exception_to_unicode(exc) _reraise(exception.CinderConnectionFailed(reason=err_msg)) except (keystone_exception.BadRequest, cinder_exception.BadRequest) as exc: err_msg = encodeutils.exception_to_unicode(exc) _reraise(exception.InvalidInput(reason=err_msg)) except (keystone_exception.Forbidden, cinder_exception.Forbidden) as exc: err_msg = encodeutils.exception_to_unicode(exc) _reraise(exception.Forbidden(err_msg)) return res
def wrapper(self, ctx, volume_id, *args, **kwargs): try: res = method(self, ctx, volume_id, *args, **kwargs) except cinder_exception.ClientException: exc_type, exc_value, exc_trace = sys.exc_info() if isinstance(exc_value, cinder_exception.NotFound): exc_value = exception.VolumeNotFound(volume_id=volume_id) elif isinstance(exc_value, cinder_exception.BadRequest): exc_value = exception.InvalidInput(reason=exc_value.message) raise exc_value, None, exc_trace except cinder_exception.ConnectionError: exc_type, exc_value, exc_trace = sys.exc_info() exc_value = exception.CinderConnectionFailed( reason=exc_value.message) raise exc_value, None, exc_trace return res
def __init__(self, name, loader=None, use_ssl=False, max_url_len=None): """Initialize, but do not start the WSGI server. :param name: The name of the WSGI server given to the loader. :param loader: Loads the WSGI application using the given name. :returns: None """ self.name = name # NOTE(danms): Name can be metadata, osapi_compute, per # nova.service's enabled_apis self.binary = 'nova-%s' % name LOG.warning('Running %s using eventlet is deprecated. Deploy with ' 'a WSGI server such as uwsgi or mod_wsgi.', self.binary) self.topic = None self.manager = self._get_manager() self.loader = loader or api_wsgi.Loader() self.app = self.loader.load_app(name) # inherit all compute_api worker counts from osapi_compute if name.startswith('openstack_compute_api'): wname = 'osapi_compute' else: wname = name self.host = getattr(CONF, '%s_listen' % name, "0.0.0.0") self.port = getattr(CONF, '%s_listen_port' % name, 0) self.workers = (getattr(CONF, '%s_workers' % wname, None) or processutils.get_worker_count()) if self.workers and self.workers < 1: worker_name = '%s_workers' % name msg = (_("%(worker_name)s value of %(workers)s is invalid, " "must be greater than 0") % {'worker_name': worker_name, 'workers': str(self.workers)}) raise exception.InvalidInput(msg) self.use_ssl = use_ssl self.server = wsgi.Server(name, self.app, host=self.host, port=self.port, use_ssl=self.use_ssl, max_url_len=max_url_len) # Pull back actual port used self.port = self.server.port self.backdoor_port = None setup_profiler(name, self.host)
def _get_neutron_network(session, cluster, vif): if vif['type'] == model.VIF_TYPE_OVS: _check_ovs_supported_version(session) # Check if this is the NSX-MH plugin is used if CONF.vmware.integration_bridge: net_id = CONF.vmware.integration_bridge use_external_id = False network_type = 'opaque' else: # The NSX|V3 plugin will pass the nsx-logical-switch-id as part # of the port details. This will enable the VC to connect to # that specific opaque network net_id = (vif.get('details') and vif['details'].get('nsx-logical-switch-id')) if not net_id: # Make use of the original one, in the event that the # plugin does not pass the aforementioned id LOG.info( _LI('NSX Logical switch ID is not present. ' 'Using network ID to attach to the ' 'opaque network.')) net_id = vif['network']['id'] use_external_id = True network_type = 'nsx.LogicalSwitch' network_ref = { 'type': 'OpaqueNetwork', 'network-id': net_id, 'network-type': network_type, 'use-external-id': use_external_id } elif vif['type'] == model.VIF_TYPE_DVS: # Port binding for DVS VIF types may pass the name # of the port group, so use it if present network_id = vif.get('details', {}).get('dvs_port_group_name') if network_id is None: # Make use of the original one, in the event that the # port binding does not provide this key in VIF details network_id = vif['network']['bridge'] network_ref = network_util.get_network_with_the_name( session, network_id, cluster) if not network_ref: raise exception.NetworkNotFoundForBridge(bridge=network_id) else: reason = _('vif type %s not supported') % vif['type'] # noqa raise exception.InvalidInput(reason=reason) return network_ref
def __init__(self, name, app, host='0.0.0.0', port=0, pool_size=None, protocol=eventlet.wsgi.HttpProtocol, backlog=128, use_ssl=False, max_url_len=None): """Initialize, but do not start, a WSGI server. :param name: Pretty name for logging. :param app: The WSGI application to serve. :param host: IP address to serve the application. :param port: Port number to server the application. :param pool_size: Maximum number of eventlets to spawn concurrently. :param backlog: Maximum number of queued connections. :param max_url_len: Maximum length of permitted URLs. :returns: None :raises: nova.exception.InvalidInput """ self.name = name self.app = app self._server = None self._protocol = protocol self._pool = eventlet.GreenPool(pool_size or self.default_pool_size) self._logger = logging.getLogger("nova.%s.wsgi.server" % self.name) self._wsgi_logger = logging.WritableLogger(self._logger) self._use_ssl = use_ssl self._max_url_len = max_url_len if backlog < 1: raise exception.InvalidInput( reason='The backlog must be more than 1') bind_addr = (host, port) # TODO(dims): eventlet's green dns/socket module does not actually # support IPv6 in getaddrinfo(). We need to get around this in the # future or monitor upstream for a fix try: info = socket.getaddrinfo(bind_addr[0], bind_addr[1], socket.AF_UNSPEC, socket.SOCK_STREAM)[0] family = info[0] bind_addr = info[-1] except Exception: family = socket.AF_INET self._socket = eventlet.listen(bind_addr, family, backlog=backlog) (self.host, self.port) = self._socket.getsockname()[0:2] LOG.info(_("%(name)s listening on %(host)s:%(port)s") % self.__dict__)
def delete_entry(self, name, domain): if name is None: raise exception.InvalidInput(_("Invalid name")) deleted = False outfile = tempfile.NamedTemporaryFile('w', delete=False) with open(self.filename, 'r') as infile: for line in infile: entry = self.parse_line(line) if (not entry or entry['name'] != self.qualify(name, domain)): outfile.write(line) else: deleted = True outfile.close() shutil.move(outfile.name, self.filename) if not deleted: LOG.warning('Cannot delete entry |%s|', self.qualify(name, domain)) raise exception.NotFound
def __init__(self, virtapi, read_only=False, scheme="https"): super(VMwareVCDriver, self).__init__(virtapi) # Get the list of clusters to be used self._cluster_names = CONF.vmware.cluster_name self.dict_mors = vm_util.get_all_cluster_refs_by_name( self._session, self._cluster_names) if not self.dict_mors: raise exception.NotFound( _("All clusters specified %s were not" " found in the vCenter") % self._cluster_names) # Check if there are any clusters that were specified in the nova.conf # but are not in the vCenter, for missing clusters log a warning. clusters_found = [v.get('name') for k, v in self.dict_mors.iteritems()] missing_clusters = set(self._cluster_names) - set(clusters_found) if missing_clusters: LOG.warn( _("The following clusters could not be found in the" " vCenter %s") % list(missing_clusters)) self._datastore_regex = None if CONF.vmware.datastore_regex: try: self._datastore_regex = re.compile(CONF.vmware.datastore_regex) except re.error: raise exception.InvalidInput( reason=_("Invalid Regular Expression %s") % CONF.vmware.datastore_regex) # The _resources is used to maintain the vmops, volumeops and vcstate # objects per cluster self._resources = {} self._resource_keys = set() self._virtapi = virtapi self._update_resources() # The following initialization is necessary since the base class does # not use VC state. first_cluster = self._resources.keys()[0] self._vmops = self._resources.get(first_cluster).get('vmops') self._volumeops = self._resources.get(first_cluster).get('volumeops') self._vc_state = self._resources.get(first_cluster).get('vcstate')
def delete_entry(self, name, domain): if name is None: raise exception.InvalidInput(_("Invalid name")) deleted = False keeps = [] self.file.seek(0) for line in self.file: entry = self.parse_line(line) if (not entry or entry['name'] != self.qualify(name, domain)): keeps.append(line) else: deleted = True self.file.truncate(0) self.file.seek(0) self.file.write(''.join(keeps)) self.file.flush() if not deleted: LOG.warning('Cannot delete entry |%s|', self.qualify(name, domain)) raise exception.NotFound
def _get_neutron_network(session, cluster, vif): opaque = _get_opaque_network(session, cluster) LOG.info("#" * 80) LOG.info(opaque) LOG.info(vif) LOG.info("#" * 80) if not opaque: network_name = (vif['network']['bridge'] or CONF.vmwaredummy.integration_bridge) ridge = network_name network_ref = network_util.get_network_with_the_name( session, network_name, cluster) return network_ref if vif['type'] == model.VIF_TYPE_OVS: _check_ovs_supported_version(session) # Check if this is the NSX-MH plugin is used if CONF.vmwaredummy.integration_bridge: net_id = CONF.vmwaredummy.integration_bridge use_external_id = False network_type = 'opaque' else: net_id = vif['network']['id'] use_external_id = True network_type = 'nsx.LogicalSwitch' network_ref = { 'type': 'OpaqueNetwork', 'network-id': net_id, 'network-type': network_type, 'use-external-id': use_external_id } elif vif['type'] == model.VIF_TYPE_DVS: network_id = vif['network']['bridge'] network_ref = network_util.get_network_with_the_name( session, network_id, cluster) if not network_ref: raise exception.NetworkNotFoundForBridge(bridge=network_id) else: reason = _('vif type %s not supported') % vif['type'] raise exception.InvalidInput(reason=reason) return network_ref
def _connect_to_ssh(self): ssh = paramiko.SSHClient() #TODO(justinsb): We need a better SSH key policy ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if FLAGS.san_password: ssh.connect(FLAGS.san_ip, port=FLAGS.san_ssh_port, username=FLAGS.san_login, password=FLAGS.san_password) elif FLAGS.san_private_key: privatekeyfile = os.path.expanduser(FLAGS.san_private_key) # It sucks that paramiko doesn't support DSA keys privatekey = paramiko.RSAKey.from_private_key_file(privatekeyfile) ssh.connect(FLAGS.san_ip, port=FLAGS.san_ssh_port, username=FLAGS.san_login, pkey=privatekey) else: msg = _("Specify san_password or san_private_key") raise exception.InvalidInput(reason=msg) return ssh
def wrapper(self, ctx, volume_id, *args, **kwargs): try: res = method(self, ctx, volume_id, *args, **kwargs) except (cinder_exception.ClientException, keystone_exception.ClientException): exc_type, exc_value, exc_trace = sys.exc_info() if isinstance(exc_value, (keystone_exception.NotFound, cinder_exception.NotFound)): exc_value = exception.VolumeNotFound(volume_id=volume_id) elif isinstance(exc_value, (keystone_exception.BadRequest, cinder_exception.BadRequest)): exc_value = exception.InvalidInput( reason=six.text_type(exc_value)) six.reraise(exc_value, None, exc_trace) except (cinder_exception.ConnectionError, keystone_exception.ConnectionError): exc_type, exc_value, exc_trace = sys.exc_info() exc_value = exception.CinderConnectionFailed( reason=six.text_type(exc_value)) six.reraise(exc_value, None, exc_trace) return res
def create(self, context, size, name, description, snapshot=None, image_id=None, volume_type=None, metadata=None, availability_zone=None): client = cinderclient(context) if snapshot is not None: snapshot_id = snapshot['id'] else: snapshot_id = None kwargs = dict(snapshot_id=snapshot_id, volume_type=volume_type, user_id=context.user_id, project_id=context.project_id, availability_zone=availability_zone, metadata=metadata, imageRef=image_id) if isinstance(client, v1_client.Client): kwargs['display_name'] = name kwargs['display_description'] = description else: kwargs['name'] = name kwargs['description'] = description try: item = client.volumes.create(size, **kwargs) return _untranslate_volume_summary_view(context, item) except cinder_exception.OverLimit: raise exception.OverQuota(overs='volumes') except (cinder_exception.BadRequest, keystone_exception.BadRequest) as e: raise exception.InvalidInput(reason=e)
def test_attach_volume_with_invalid_input(self, mock_attach): mock_attach.side_effect = exception.InvalidInput( reason='Invalid volume') body = { 'volumeAttachment': { 'volumeId': FAKE_UUID_A, 'device': '/dev/fake' } } req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments') req.method = 'POST' req.body = jsonutils.dump_as_bytes({}) req.headers['content-type'] = 'application/json' req.environ['nova.context'] = self.context self.assertRaises(exc.HTTPBadRequest, self.attachments.create, req, FAKE_UUID, body=body)
def get_cell_type(): """Return the cell type, 'api', 'compute', or None (if cells is disabled). This call really exists just to support the deprecated compute_api_class config option. Otherwise, one could just access CONF.cells.enable and CONF.cells.cell_type directly. """ if not CONF.cells.enable: return cell_type = CONF.cells.cell_type if cell_type: if cell_type == 'api' or cell_type == 'compute': return cell_type msg = _("cell_type must be configured as 'api' or 'compute'") raise exception.InvalidInput(reason=msg) LOG.deprecated( _("The compute_api_class is now deprecated and " "will be removed in next release. Please set the" " cell_type option to 'api' or 'compute'")) if CONF.compute_api_class == 'nova.compute.cells_api.ComputeCellsAPI': return 'api' return 'compute'
def create(self, context, size, name, description, snapshot=None, image_id=None, volume_type=None, metadata=None, availability_zone=None): if snapshot is not None: snapshot_id = snapshot['id'] else: snapshot_id = None kwargs = dict(snapshot_id=snapshot_id, volume_type=volume_type, user_id=context.user_id, project_id=context.project_id, availability_zone=availability_zone, metadata=metadata, imageRef=image_id) version = get_cinder_client_version(context) if version == '1': kwargs['display_name'] = name kwargs['display_description'] = description elif version == '2': kwargs['name'] = name kwargs['description'] = description try: item = cinderclient(context).volumes.create(size, **kwargs) return _untranslate_volume_summary_view(context, item) except cinder_exception.OverLimit: raise exception.OverQuota(overs='volumes') except cinder_exception.BadRequest as e: raise exception.InvalidInput(reason=unicode(e))
def __init__(self, name, loader=None, use_ssl=False, max_url_len=None): """Initialize, but do not start the WSGI server. :param name: The name of the WSGI server given to the loader. :param loader: Loads the WSGI application using the given name. :returns: None """ self.name = name self.manager = self._get_manager() self.loader = loader or wsgi.Loader() self.app = self.loader.load_app(name) # inherit all compute_api worker counts from osapi_compute if name.startswith('openstack_compute_api'): wname = 'osapi_compute' else: wname = name self.host = getattr(CONF, '%s_listen' % name, "0.0.0.0") self.port = getattr(CONF, '%s_listen_port' % name, 0) self.workers = (getattr(CONF, '%s_workers' % wname, None) or processutils.get_worker_count()) if self.workers and self.workers < 1: worker_name = '%s_workers' % name msg = (_("%(worker_name)s value of %(workers)s is invalid, " "must be greater than 0") % { 'worker_name': worker_name, 'workers': str(self.workers) }) raise exception.InvalidInput(msg) self.use_ssl = use_ssl self.server = wsgi.Server(name, self.app, host=self.host, port=self.port, use_ssl=self.use_ssl, max_url_len=max_url_len) # Pull back actual port used self.port = self.server.port self.backdoor_port = None
def _get_neutron_network(session, cluster, vif): if vif['type'] == model.VIF_TYPE_OVS: _check_ovs_supported_version(session) # Check if this is the NSX-MH plugin is used if CONF.vmware.integration_bridge: net_id = CONF.vmware.integration_bridge use_external_id = False network_type = 'opaque' else: net_id = vif['network']['id'] use_external_id = True network_type = 'nsx.LogicalSwitch' network_ref = { 'type': 'OpaqueNetwork', 'network-id': net_id, 'network-type': network_type, 'use-external-id': use_external_id } elif vif['type'] == model.VIF_TYPE_DVS: # Port binding for DVS VIF types may pass the name # of the port group, so use it if present network_id = vif.get('details', {}).get('dvs_port_group_name') if network_id is None: # Make use of the original one, in the event that the # port binding does not provide this key in VIF details #network_id = vif['network']['bridge'] network_id = (CONF.vmware.integration_bridge or "br-int") network_ref = network_util.get_network_with_the_name( session, network_id, cluster) if not network_ref: raise exception.NetworkNotFoundForBridge(bridge=network_id) if vif.get('details') and vif['details'].get('dvs_port_key'): network_ref['dvs_port_key'] = vif['details']['dvs_port_key'] else: reason = _('vif type %s not supported') % vif['type'] raise exception.InvalidInput(reason=reason) return network_ref
def fake_attachment_update( _self, context, attachment_id, connector, mountpoint=None, ): # Ensure the attachment exists volume_id, attachment, attachments = _find_attachment( attachment_id) # Cinder will only allow one "connected" attachment per # non-multiattach volume at a time. if volume_id != self.MULTIATTACH_VOL: for _attachment in attachments.values(): if _attachment['connector'] is not None: raise exception.InvalidInput( 'Volume %s is already connected with attachment ' '%s on host %s' % (volume_id, _attachment['id'], _attachment['connector'].get('host'))) # If the mountpoint was provided stash it in the connector as we do # within nova.volume.cinder.API.attachment_update before calling # c-api and then stash the connector in the attachment record. if mountpoint: connector['device'] = mountpoint attachment['connector'] = connector LOG.info('Updating volume attachment: %s', attachment_id) attachment_ref = { 'id': attachment_id, 'connection_info': _find_connection_info(volume_id, attachment_id) } if attachment_id == self.SWAP_ERR_ATTACH_ID: # This intentionally triggers a TypeError for the # instance.volume_swap.error versioned notification tests. attachment_ref = {'connection_info': ()} return attachment_ref
def fake_attachment_update( _self, context, attachment_id, connector, mountpoint=None, ): # Ensure the attachment exists volume_id, attachment, attachments = _find_attachment( attachment_id) # Cinder will only allow one "connected" attachment per # non-multiattach volume at a time. if volume_id != self.MULTIATTACH_VOL: for _attachment in attachments.values(): if _attachment['connector'] is not None: raise exception.InvalidInput( 'Volume %s is already connected with attachment ' '%s on host %s' % (volume_id, _attachment['id'], _attachment['connector'].get('host'))) attachment['connector'] = connector LOG.info('Updating volume attachment: %s', attachment_id) attachment_ref = { 'id': attachment_id, 'connection_info': { 'driver_volume_type': 'fake', 'data': { 'foo': 'bar', 'target_lun': '1' } } } if attachment_id == self.SWAP_ERR_ATTACH_ID: # This intentionally triggers a TypeError for the # instance.volume_swap.error versioned notification tests. attachment_ref = {'connection_info': ()} return attachment_ref
def __init__(self, name, loader=None, use_ssl=False, max_url_len=None): """Initialize, but do not start the WSGI server. :param name: The name of the WSGI server given to the loader. :param loader: Loads the WSGI application using the given name. :returns: None """ self.name = name self.manager = self._get_manager() #并没有传入loader self.loader = loader or wsgi.Loader() #根据名字加载/etc/nova/api-paste.ini中定义的对应app self.app = self.loader.load_app(name) #监听ip self.host = getattr(CONF, '%s_listen' % name, "0.0.0.0") #监听端口,openstack的api默认8774,就在本文件的上面定义 self.port = getattr(CONF, '%s_listen_port' % name, 0) self.workers = (getattr(CONF, '%s_workers' % name, None) or processutils.get_worker_count()) if self.workers and self.workers < 1: worker_name = '%s_workers' % name msg = (_("%(worker_name)s value of %(workers)s is invalid, " "must be greater than 0") % {'worker_name': worker_name, 'workers': str(self.workers)}) raise exception.InvalidInput(msg) self.use_ssl = use_ssl self.server = wsgi.Server(name, self.app, host=self.host, port=self.port, use_ssl=self.use_ssl, max_url_len=max_url_len) # Pull back actual port used self.port = self.server.port self.backdoor_port = None
def __init__(self, virtapi, read_only=False, scheme="https"): super(VMwareESXDriver, self).__init__(virtapi) self._do_deprecation_warning() self._host_ip = CONF.vmware.host_ip if not (self._host_ip or CONF.vmware.host_username is None or CONF.vmware.host_password is None): raise Exception( _("Must specify host_ip, " "host_username " "and host_password to use " "compute_driver=vmwareapi.VMwareESXDriver or " "vmwareapi.VMwareVCDriver")) self._datastore_regex = None if CONF.vmware.datastore_regex: try: self._datastore_regex = re.compile(CONF.vmware.datastore_regex) except re.error: raise exception.InvalidInput( reason=_("Invalid Regular Expression %s") % CONF.vmware.datastore_regex) self._session = VMwareAPISession(scheme=scheme) self._volumeops = volumeops.VMwareVolumeOps(self._session) self._vmops = vmops.VMwareVMOps(self._session, self.virtapi, self._volumeops, datastore_regex=self._datastore_regex) self._host = host.Host(self._session) self._host_state = None #TODO(hartsocks): back-off into a configuration test module. if CONF.vmware.use_linked_clone is None: raise error_util.UseLinkedCloneConfigurationFault()
def create(self, context, size, name, description, snapshot=None, image_id=None, volume_type=None, metadata=None, availability_zone=None): if snapshot is not None: snapshot_id = snapshot['id'] else: snapshot_id = None kwargs = dict(snapshot_id=snapshot_id, display_name=name, display_description=description, volume_type=volume_type, user_id=context.user_id, project_id=context.project_id, availability_zone=availability_zone, metadata=metadata, imageRef=image_id) try: item = cinderclient(context).volumes.create(size, **kwargs) return _untranslate_volume_summary_view(context, item) except cinder_exception.BadRequest as e: raise exception.InvalidInput(reason=unicode(e))
def spawn(self, context, instance, image_meta, injected_files, admin_password, allocations, network_info=None, block_device_info=None, power_on=True): LOG.info("Spawning new instance %s on zVM hypervisor", instance.name, instance=instance) if self._hypervisor.guest_exists(instance): raise exception.InstanceExists(name=instance.name) os_distro = image_meta.properties.get('os_distro') if os_distro is None or len(os_distro) == 0: reason = _("The `os_distro` image metadata property is required") raise exception.InvalidInput(reason=reason) try: spawn_start = time.time() transportfiles = zvmutils.generate_configdrive( context, instance, injected_files, network_info, admin_password) spawn_image_name = self._get_image_info(context, image_meta.id, os_distro) disk_list, eph_list = self._set_disk_list(instance, spawn_image_name, block_device_info) # Create the guest vm self._hypervisor.guest_create(instance.name, instance.vcpus, instance.memory_mb, disk_list) # Deploy image to the guest vm self._hypervisor.guest_deploy(instance.name, spawn_image_name, transportfiles=transportfiles) # Handle ephemeral disks if eph_list: self._hypervisor.guest_config_minidisks( instance.name, eph_list) # Setup network for z/VM instance self._wait_vif_plug_events(instance.name, os_distro, network_info, instance) self._hypervisor.guest_start(instance.name) spawn_time = time.time() - spawn_start LOG.info("Instance spawned successfully in %s seconds", spawn_time, instance=instance) except Exception as err: with excutils.save_and_reraise_exception(): LOG.error( "Deploy instance %(instance)s " "failed with reason: %(err)s", { 'instance': instance.name, 'err': err }, instance=instance) try: self.destroy(context, instance, network_info, block_device_info) except Exception: LOG.exception("Failed to destroy instance", instance=instance)
def fake_volume_create(self, context, size, name, description, snapshot, **param): raise exception.InvalidInput(reason="bad request data")
def allocate_for_instance(self, context, instance, **kwargs): """Allocate all network resources for the instance.""" quantum = quantumv2.get_client(context) LOG.debug(_('allocate_for_instance() for %s'), instance['display_name']) if not instance['project_id']: msg = _('empty project id for instance %s') raise exception.InvalidInput(reason=msg % instance['display_name']) requested_networks = kwargs.get('requested_networks') ports = {} fixed_ips = {} net_ids = [] if requested_networks: for network_id, fixed_ip, port_id in requested_networks: if port_id: port = quantum.show_port(port_id).get('port') network_id = port['network_id'] ports[network_id] = port elif fixed_ip: fixed_ips[network_id] = fixed_ip net_ids.append(network_id) nets = self._get_available_networks(context, instance['project_id'], net_ids) touched_port_ids = [] created_port_ids = [] for network in nets: network_id = network['id'] zone = 'compute:%s' % CONF.node_availability_zone port_req_body = { 'port': { 'device_id': instance['uuid'], 'device_owner': zone } } try: port = ports.get(network_id) if port: quantum.update_port(port['id'], port_req_body) touched_port_ids.append(port['id']) else: if fixed_ips.get(network_id): port_req_body['port']['fixed_ip'] = fixed_ip port_req_body['port']['network_id'] = network_id port_req_body['port']['admin_state_up'] = True port_req_body['port']['tenant_id'] = instance['project_id'] created_port_ids.append( quantum.create_port(port_req_body)['port']['id']) except Exception: with excutils.save_and_reraise_exception(): for port_id in touched_port_ids: port_in_server = quantum.show_port(port_id).get('port') if not port_in_server: raise Exception(_('Port not found')) port_req_body = {'port': {'device_id': None}} quantum.update_port(port_id, port_req_body) for port_id in created_port_ids: try: quantum.delete_port(port_id) except Exception as ex: msg = _("Fail to delete port %(portid)s with" " failure: %(exception)s") LOG.debug(msg, { 'portid': port_id, 'exception': ex }) self.trigger_security_group_members_refresh(context, instance) self.trigger_instance_add_security_group_refresh(context, instance) return self.get_instance_nw_info(context, instance, networks=nets)
def _new_ingress_rule(ip_protocol, from_port, to_port, group_id=None, cidr=None): values = {} if group_id: values['group_id'] = group_id # Open everything if an explicit port range or type/code are not # specified, but only if a source group was specified. ip_proto_upper = ip_protocol.upper() if ip_protocol else '' if (ip_proto_upper == 'ICMP' and from_port is None and to_port is None): from_port = -1 to_port = -1 elif (ip_proto_upper in ['TCP', 'UDP'] and from_port is None and to_port is None): from_port = 1 to_port = 65535 elif cidr: values['cidr'] = cidr if ip_protocol and from_port is not None and to_port is not None: ip_protocol = str(ip_protocol) try: # Verify integer conversions from_port = int(from_port) to_port = int(to_port) except ValueError: if ip_protocol.upper() == 'ICMP': raise exception.InvalidInput( reason=_("Type and" " Code must be integers for ICMP protocol type")) else: raise exception.InvalidInput(reason=_("To and From ports " "must be integers")) if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']: raise exception.InvalidIpProtocol(protocol=ip_protocol) # Verify that from_port must always be less than # or equal to to_port if (ip_protocol.upper() in ['TCP', 'UDP'] and (from_port > to_port)): raise exception.InvalidPortRange(from_port=from_port, to_port=to_port, msg="Former value cannot" " be greater than the later") # Verify valid TCP, UDP port ranges if (ip_protocol.upper() in ['TCP', 'UDP'] and (from_port < 1 or to_port > 65535)): raise exception.InvalidPortRange(from_port=from_port, to_port=to_port, msg="Valid %s ports should" " be between 1-65535" % ip_protocol.upper()) # Verify ICMP type and code if (ip_protocol.upper() == "ICMP" and (from_port < -1 or from_port > 255 or to_port < -1 or to_port > 255)): raise exception.InvalidPortRange(from_port=from_port, to_port=to_port, msg="For ICMP, the" " type:code must be valid") values['protocol'] = ip_protocol values['from_port'] = from_port values['to_port'] = to_port else: # If cidr based filtering, protocol and ports are mandatory if cidr: return None return values