示例#1
0
    def find(self, res_class):
        """Return the inventory record from the list of Inventory records that
        matches the supplied resource class, or None.

        :param res_class: An integer or string representing a resource
                          class. If the value is a string, the method first
                          looks up the resource class identifier from the
                          string.
        """
        if isinstance(res_class, six.string_types):
            try:
                res_class = fields.ResourceClass.index(res_class)
            except ValueError:
                raise exception.NotFound("No such resource class '%s'" %
                                         res_class)

        for inv_rec in self.objects:
            if fields.ResourceClass.index(inv_rec.resource_class) == res_class:
                return inv_rec
示例#2
0
def update_vm_stat(params, remote_address):
    """
    NOTE(hzyangtk):
    params:
        state: 1 means live, others mean error,
    """
    ctxt = context.get_admin_context()
    try:
        fixed_ip = db.fixed_ip_get_by_address(ctxt, remote_address)
    except exception.FixedIpNotFoundForAddress:
        LOG.exception(_("fixed ip not found with address %s") % remote_address)
        raise
    instance_uuid = fixed_ip['instance_uuid']

    # NOTE(hzyangtk): determine if let all VMs store state in DB
    #                 when only HA vm record state, check db table
    #                 instance_metadata has key 'HA' or not.
    HA_key = 'HA'
    record_state = False
    if not FLAGS.record_all_vms_heartbeat:
        instance_metadata = db.instance_metadata_get(ctxt, instance_uuid)
        record_state = HA_key in instance_metadata
    else:
        record_state = True
    if record_state:
        cache_key = str(instance_uuid + '_heart')
        cache_value = timeutils.utcnow().strftime('%Y-%m-%d %H:%M:%S')
        memcache_client = get_memcache_client()
        if memcache_client is not None:
            result = memcache_client.set(cache_key, cache_value)
            if not result:
                LOG.exception(
                    _("Memcache insert error. Key: %(cache_key)s, "
                      "value: %(cache_value)s"), {
                          'cache_key': cache_key,
                          'cache_value': cache_value
                      })
                raise exception.NovaException()
            return json.dumps({cache_key: cache_value})
        else:
            LOG.exception(_("Memcache connection failed"))
            raise exception.NovaException()
    raise exception.NotFound()
示例#3
0
 def modify_project(self, project_id, manager_uid=None, description=None):
     """Modify an existing project"""
     if not manager_uid and not description:
         return
     attr = []
     if manager_uid:
         if not self.__user_exists(manager_uid):
             raise exception.NotFound(
                 _("Project can't be modified because "
                   "manager %s doesn't exist") % manager_uid)
         manager_dn = self.__uid_to_dn(manager_uid)
         attr.append((self.ldap.MOD_REPLACE, LdapDriver.project_attribute,
                      manager_dn))
     if description:
         attr.append((self.ldap.MOD_REPLACE, 'description', description))
     dn = self.__project_to_dn(project_id)
     self.conn.modify_s(dn, attr)
     if not self.is_in_project(manager_uid, project_id):
         self.add_to_project(manager_uid, project_id)
 def test_event_finish_with_failure_serialized(self, mock_format,
                                               mock_pack):
     mock_format.return_value = 'traceback'
     mock_pack.side_effect = test.TestingException
     exc = exception.NotFound()
     self.assertRaises(
         test.TestingException,
         instance_action.InstanceActionEvent.event_finish_with_failure,
         self.context,
         'fake-uuid',
         'fake-event',
         exc_val=exc,
         exc_tb=mock.sentinel.exc_tb)
     mock_pack.assert_called_once_with(self.context,
                                       'fake-uuid',
                                       'fake-event',
                                       exc_val=exc.format_message(),
                                       exc_tb='traceback')
     mock_format.assert_called_once_with(mock.sentinel.exc_tb)
示例#5
0
    def test_scatter_gather_cells_exception(self, mock_get_inst,
                                            mock_log_exception):
        # This is needed because we're mocking get_by_filters.
        self.useFixture(nova_fixtures.SpawnIsSynchronousFixture())
        ctxt = context.get_context()
        mapping0 = objects.CellMapping(database_connection='fake://db0',
                                       transport_url='none:///',
                                       uuid=objects.CellMapping.CELL0_UUID)
        mapping1 = objects.CellMapping(database_connection='fake://db1',
                                       transport_url='fake://mq1',
                                       uuid=uuids.cell1)
        mappings = objects.CellMappingList(objects=[mapping0, mapping1])

        # Simulate cell1 raising an exception.
        mock_get_inst.side_effect = [
            mock.sentinel.instances,
            test.TestingException()
        ]

        filters = {'deleted': False}
        results = context.scatter_gather_cells(
            ctxt, mappings, 30, objects.InstanceList.get_by_filters, filters)
        self.assertEqual(2, len(results))
        self.assertIn(mock.sentinel.instances, results.values())
        self.assertIsInstance(results[mapping1.uuid], Exception)
        # non-NovaException gets logged
        self.assertTrue(mock_log_exception.called)

        # Now run it again with a NovaException to see it's not logged.
        mock_log_exception.reset_mock()
        mock_get_inst.side_effect = [
            mock.sentinel.instances,
            exception.NotFound()
        ]

        results = context.scatter_gather_cells(
            ctxt, mappings, 30, objects.InstanceList.get_by_filters, filters)
        self.assertEqual(2, len(results))
        self.assertIn(mock.sentinel.instances, results.values())
        self.assertIsInstance(results[mapping1.uuid], exception.NovaException)
        # NovaExceptions are not logged, the caller should handle them.
        mock_log_exception.assert_not_called()
示例#6
0
文件: vmops.py 项目: septimius/nova
    def unrescue(self, instance, callback):
        """Unrescue the specified instance
            - unplug the instance VM's disk from the rescue VM
            - teardown the rescue VM
            - release the bootlock to allow the instance VM to start

        """
        rescue_vm_ref = VMHelper.lookup(self._session,
                                        instance.name + "-rescue")

        if not rescue_vm_ref:
            raise exception.NotFound(
                _("Instance is not in Rescue Mode: %s" % instance.name))

        original_vm_ref = self._get_vm_opaque_ref(instance)
        vbd_refs = self._session.get_xenapi().VM.get_VBDs(rescue_vm_ref)

        instance._rescue = False

        for vbd_ref in vbd_refs:
            _vbd_ref = self._session.get_xenapi().VBD.get_record(vbd_ref)
            if _vbd_ref["userdevice"] == "1":
                VMHelper.unplug_vbd(self._session, vbd_ref)
                VMHelper.destroy_vbd(self._session, vbd_ref)

        task1 = self._session.call_xenapi("Async.VM.hard_shutdown",
                                          rescue_vm_ref)
        self._session.wait_for_task(task1, instance.id)

        vdi_refs = VMHelper.lookup_vm_vdis(self._session, rescue_vm_ref)
        for vdi_ref in vdi_refs:
            try:
                task = self._session.call_xenapi('Async.VDI.destroy', vdi_ref)
                self._session.wait_for_task(task, instance.id)
            except self.XenAPI.Failure:
                continue

        task2 = self._session.call_xenapi('Async.VM.destroy', rescue_vm_ref)
        self._session.wait_for_task(task2, instance.id)

        self._release_bootlock(original_vm_ref)
        self._start(instance, original_vm_ref)
示例#7
0
    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')
示例#8
0
def _update_inventory_for_provider(conn, rp, inv_list, to_update):
    """Updates existing inventory records for the supplied resource provider.

    :param conn: DB connection to use.
    :param rp: Resource provider on which to update inventory.
    :param inv_list: InventoryList object
    :param to_update: set() containing resource class IDs to search inv_list
                      for updating in resource provider.
    :returns: A list of (uuid, class) tuples that have exceeded their
              capacity after this inventory update.
    """
    exceeded = []
    for res_class in to_update:
        inv_record = inv_list.find(res_class)
        if inv_record.capacity <= 0:
            raise exception.InvalidInventoryCapacity(
                resource_class=fields.ResourceClass.from_index(res_class),
                resource_provider=rp.uuid)
        allocation_query = sa.select(
            [func.sum(_ALLOC_TBL.c.used).label('usage')]).\
            where(sa.and_(
                _ALLOC_TBL.c.resource_provider_id == rp.id,
                _ALLOC_TBL.c.resource_class_id == res_class))
        allocations = conn.execute(allocation_query).first()
        if allocations and allocations['usage'] > inv_record.capacity:
            exceeded.append(
                (rp.uuid, fields.ResourceClass.from_index(res_class)))
        upd_stmt = _INV_TBL.update().where(
            sa.and_(_INV_TBL.c.resource_provider_id == rp.id,
                    _INV_TBL.c.resource_class_id == res_class)).values(
                        total=inv_record.total,
                        reserved=inv_record.reserved,
                        min_unit=inv_record.min_unit,
                        max_unit=inv_record.max_unit,
                        step_size=inv_record.step_size,
                        allocation_ratio=inv_record.allocation_ratio)
        res = conn.execute(upd_stmt)
        if not res.rowcount:
            raise exception.NotFound(
                'No inventory of class %s found for update' %
                fields.ResourceClass.from_index(res_class))
    return exceeded
示例#9
0
文件: common.py 项目: septimius/nova
def get_image_id_from_image_hash(image_service, context, image_hash):
    """Given an Image ID Hash, return an objectstore Image ID.

    image_service - reference to objectstore compatible image service.
    context - security context for image service requests.
    image_hash - hash of the image ID.
    """

    # FIX(sandy): This is terribly inefficient. It pulls all images
    # from objectstore in order to find the match. ObjectStore
    # should have a numeric counterpart to the string ID.
    try:
        items = image_service.detail(context)
    except NotImplementedError:
        items = image_service.index(context)
    for image in items:
        image_id = image['id']
        if abs(hash(image_id)) == int(image_hash):
            return image_id
    raise exception.NotFound(image_hash)
示例#10
0
    def _service_start_mocks(self):
        service_create = {
            'host': self.host,
            'binary': self.binary,
            'topic': self.topic,
            'report_count': 0
        }
        service_ref = {
            'host': self.host,
            'binary': self.binary,
            'topic': self.topic,
            'report_count': 0,
            'id': 1
        }

        db.service_get_by_args(mox.IgnoreArg(), self.host,
                               self.binary).AndRaise(exception.NotFound())
        db.service_create(mox.IgnoreArg(),
                          service_create).AndReturn(service_ref)
        return service_ref
示例#11
0
def fake_get_instance_type_by_flavor_id(flavorid):
    if flavorid == "failtest":
        raise exception.NotFound("Not found sucka!")

    return {
        'root_gb': 1,
        'ephemeral_gb': 1,
        'name': u'frob',
        'deleted': False,
        'created_at': datetime.datetime(2012, 1, 19, 18, 49, 30, 877329),
        'updated_at': None,
        'memory_mb': 256,
        'vcpus': 1,
        'flavorid': flavorid,
        'swap': 0,
        'rxtx_factor': 1.0,
        'extra_specs': {},
        'deleted_at': None,
        'vcpu_weight': None,
        'id': 7
    }
示例#12
0
    def delete_volume(self, volume):

        vol_rec = self.db.sm_volume_get(self.ctxt, volume['id'])
        if not vol_rec:
            raise exception.NotFound(_("Volume %s does not exist"),
                                     volume['id'])
        try:
            # If compute runs on this node, detach could have disconnected SR
            backend_ref = self.db.sm_backend_conf_get(self.ctxt,
                                                      vol_rec['backend_id'])
            self._create_storage_repo(self.ctxt, backend_ref)
            self._volumeops.delete_volume_for_sm(vol_rec['vdi_uuid'])
        except Exception as ex:
            LOG.exception(ex)
            raise exception.NovaException(_("Failed to delete vdi"))

        try:
            self.db.sm_volume_delete(self.ctxt, volume['id'])
        except Exception as ex:
            LOG.exception(ex)
            raise exception.NovaException(_("Failed to delete volume in db"))
示例#13
0
文件: fake.py 项目: septimius/nova
    def get_info(self, instance_name):
        """
        Get a block of information about the given instance.  This is returned
        as a dictionary containing 'state': The power_state of the instance,
        'max_mem': The maximum memory for the instance, in KiB, 'mem': The
        current memory the instance has, in KiB, 'num_cpu': The current number
        of virtual CPUs the instance has, 'cpu_time': The total CPU time used
        by the instance, in nanoseconds.

        This method should raise exception.NotFound if the hypervisor has no
        knowledge of the instance
        """
        if instance_name not in self.instances:
            raise exception.NotFound(_("Instance %s Not Found")
                                     % instance_name)
        i = self.instances[instance_name]
        return {'state': i._state,
                'max_mem': 0,
                'mem': 0,
                'num_cpu': 2,
                'cpu_time': 0}
示例#14
0
    def test_live_migration_compute_src_not_exist(self):
        """Raise exception when src compute node is does not exist."""

        self.mox.StubOutWithMock(servicegroup.API, 'service_is_up')
        self.mox.StubOutWithMock(db, 'service_get_all_compute_by_host')

        dest = 'fake_host2'
        block_migration = False
        disk_over_commit = False
        instance = self._live_migration_instance()

        # Compute down
        db.service_get_all_compute_by_host(self.context,
                instance['host']).AndRaise(
                                       exception.NotFound())

        self.mox.ReplayAll()
        self.assertRaises(exception.ComputeServiceUnavailable,
                self.driver.schedule_live_migration, self.context,
                instance=instance, dest=dest,
                block_migration=block_migration,
                disk_over_commit=disk_over_commit)
示例#15
0
    def test_live_migration_compute_dest_not_exist(self):
        # Raise exception when dest compute node does not exist.

        self.mox.StubOutWithMock(self.driver, '_live_migration_src_check')
        self.mox.StubOutWithMock(db, 'service_get_by_compute_host')

        dest = 'fake_host2'
        block_migration = False
        disk_over_commit = False
        instance = self._live_migration_instance()

        self.driver._live_migration_src_check(self.context, instance)
        # Compute down
        db.service_get_by_compute_host(self.context,
                            dest).AndRaise(exception.NotFound())

        self.mox.ReplayAll()
        self.assertRaises(exception.ComputeServiceUnavailable,
                self.driver.schedule_live_migration, self.context,
                instance=instance, dest=dest,
                block_migration=block_migration,
                disk_over_commit=disk_over_commit)
示例#16
0
文件: vmops.py 项目: septimius/nova
    def _destroy_kernel_ramdisk(self, instance, vm_ref):
        """
        Three situations can occur:

            1. We have neither a ramdisk nor a kernel, in which case we are a
               RAW image and can omit this step

            2. We have one or the other, in which case, we should flag as an
               error

            3. We have both, in which case we safely remove both the kernel
               and the ramdisk.
        """
        instance_id = instance.id
        if not instance.kernel_id and not instance.ramdisk_id:
            # 1. No kernel or ramdisk
            LOG.debug(
                _("Instance %(instance_id)s using RAW or VHD, "
                  "skipping kernel and ramdisk deletion") % locals())
            return

        if not (instance.kernel_id and instance.ramdisk_id):
            # 2. We only have kernel xor ramdisk
            raise exception.NotFound(
                _("Instance %(instance_id)s has a kernel or ramdisk but not "
                  "both" % locals()))

        # 3. We have both kernel and ramdisk
        (kernel,
         ramdisk) = VMHelper.lookup_kernel_ramdisk(self._session, vm_ref)

        LOG.debug(_("Removing kernel/ramdisk files"))

        args = {'kernel-file': kernel, 'ramdisk-file': ramdisk}
        task = self._session.async_call_plugin('glance',
                                               'remove_kernel_ramdisk', args)
        self._session.wait_for_task(task, instance.id)

        LOG.debug(_("kernel/ramdisk files removed"))
示例#17
0
文件: dom.py 项目: kiall/nova
    def destroy_domain(self, name):
        """
        Removes domain from domains list and deactivates node.
        """
        fd = self.find_domain(name)
        if fd == []:
            LOG.debug(_("destroy_domain: no such domain"))
            msg = _("No such domain %s")
            raise exception.NotFound(msg % name)

        try:
            self.baremetal_nodes.deactivate_node(fd['node_id'])

            self.domains.remove(fd)
            msg = _("Domains: %s")
            LOG.debug(msg % (self.domains))
            self.store_domain()
            msg = _("After storing domains: %s")
            LOG.debug(msg % (self.domains))
        except Exception:
            LOG.debug(_("deactivation/removing domain failed"))
            raise
示例#18
0
    def confirm_resize(self, context, instance_id):
        """Confirms a migration/resize, deleting the 'old' instance in the
        process."""
        context = context.elevated()
        migration_ref = self.db.migration_get_by_instance_and_status(
            context, instance_id, 'finished')
        if not migration_ref:
            raise exception.NotFound(
                _("No finished migrations found for "
                  "instance"))
        instance_ref = self.db.instance_get(context, instance_id)
        params = {'migration_id': migration_ref['id']}
        self._cast_compute_message('confirm_resize',
                                   context,
                                   instance_id,
                                   migration_ref['source_compute'],
                                   params=params)

        self.db.migration_update(context, migration_ref['id'],
                                 {'status': 'confirmed'})
        self.db.instance_update(context, instance_id, {
            'host': migration_ref['dest_compute'],
        })
示例#19
0
    def test_report_state_newly_connected(self):
        host = 'foo'
        binary = 'bar'
        topic = 'test'
        service_create = {
            'host': host,
            'binary': binary,
            'topic': topic,
            'report_count': 0,
            'availability_zone': 'nova'
        }
        service_ref = {
            'host': host,
            'binary': binary,
            'topic': topic,
            'report_count': 0,
            'availability_zone': 'nova',
            'id': 1
        }

        service.db.service_get_by_args(mox.IgnoreArg(), host,
                                       binary).AndRaise(exception.NotFound())
        service.db.service_create(mox.IgnoreArg(),
                                  service_create).AndReturn(service_ref)
        service.db.service_get(mox.IgnoreArg(),
                               service_ref['id']).AndReturn(service_ref)
        service.db.service_update(mox.IgnoreArg(), service_ref['id'],
                                  mox.ContainsKeyValue('report_count', 1))

        self.mox.ReplayAll()
        serv = service.Service(host, binary, topic,
                               'nova.tests.test_service.FakeManager')
        serv.start()
        serv.model_disconnected = True
        serv.report_state()

        self.assert_(not serv.model_disconnected)
示例#20
0
文件: vmops.py 项目: septimius/nova
    def _get_vm_opaque_ref(self, instance_or_vm):
        """Refactored out the common code of many methods that receive either
        a vm name or a vm instance, and want a vm instance in return.
        """
        # if instance_or_vm is a string it must be opaque ref or instance name
        if isinstance(instance_or_vm, basestring):
            obj = None
            try:
                # check for opaque ref
                obj = self._session.get_xenapi().VM.get_record(instance_or_vm)
                return instance_or_vm
            except self.XenAPI.Failure:
                # wasn't an opaque ref, must be an instance name
                instance_name = instance_or_vm

        # if instance_or_vm is an int/long it must be instance id
        elif isinstance(instance_or_vm, (int, long)):
            ctx = context.get_admin_context()
            try:
                instance_obj = db.instance_get(ctx, instance_or_vm)
                instance_name = instance_obj.name
            except exception.NotFound:
                # The unit tests screw this up, as they use an integer for
                # the vm name. I'd fix that up, but that's a matter for
                # another bug report. So for now, just try with the passed
                # value
                instance_name = instance_or_vm

        # otherwise instance_or_vm is an instance object
        else:
            instance_name = instance_or_vm.name
        vm_ref = VMHelper.lookup(self._session, instance_name)
        if vm_ref is None:
            raise exception.NotFound(
                _('Instance not present %s') % instance_name)
        return vm_ref
示例#21
0
    def test_safe_exception_translated(self, mock_translate):
        msg = gettextutils.Message('Should be translated.', domain='nova')
        safe_exception = exception.NotFound()
        safe_exception.msg_fmt = msg
        safe_exception.safe = True
        safe_exception.code = 404

        req = webob.Request.blank('/')

        def fake_translate(mesg, locale):
            if mesg == "Should be translated.":
                return "I've been translated!"
            return mesg

        mock_translate.side_effect = fake_translate

        def raiser(*args, **kwargs):
            raise safe_exception

        wrapper = nova.api.openstack.FaultWrapper(raiser)
        response = req.get_response(wrapper)

        self.assertIn("I've been translated!", unicode(response.body))
        mock_translate.assert_any_call(u'Should be translated.', None)
示例#22
0
 def delete_user(self, uid):
     """Delete a user"""
     if not self.__user_exists(uid):
         raise exception.NotFound(_("User %s doesn't exist") % uid)
     self.__remove_from_all(uid)
     if FLAGS.ldap_user_modify_only:
         # Delete attributes
         attr = []
         # Retrieve user by name
         user = self.__get_ldap_user(uid)
         if 'secretKey' in user.keys():
             attr.append(
                 (self.ldap.MOD_DELETE, 'secretKey', user['secretKey']))
         if 'accessKey' in user.keys():
             attr.append(
                 (self.ldap.MOD_DELETE, 'accessKey', user['accessKey']))
         if LdapDriver.isadmin_attribute in user.keys():
             attr.append(
                 (self.ldap.MOD_DELETE, LdapDriver.isadmin_attribute,
                  user[LdapDriver.isadmin_attribute]))
         self.conn.modify_s(self.__uid_to_dn(uid), attr)
     else:
         # Delete entry
         self.conn.delete_s(self.__uid_to_dn(uid))
示例#23
0
    def get_pool_info(self):
        # NOTE(melwitt): We're executing 'ceph df' here instead of calling
        # the RADOSClient.get_cluster_stats python API because we need
        # access to the MAX_AVAIL stat, which reports the available bytes
        # taking replication into consideration. The global available stat
        # from the RADOSClient.get_cluster_stats python API does not take
        # replication size into consideration and will simply return the
        # available storage per OSD, added together across all OSDs. The
        # MAX_AVAIL stat will divide by the replication size when doing the
        # calculation.
        args = ['ceph', 'df', '--format=json'] + self.ceph_args()

        try:
            out, _ = processutils.execute(*args)
        except processutils.ProcessExecutionError:
            LOG.exception('Could not determine disk usage')
            raise exception.StorageError(
                reason='Could not determine disk usage')

        stats = jsonutils.loads(out)

        # Find the pool for which we are configured.
        pool_stats = None
        for pool in stats['pools']:
            if pool['name'] == self.pool:
                pool_stats = pool['stats']
                break

        if pool_stats is None:
            raise exception.NotFound('Pool %s could not be found.' % self.pool)

        return {
            'total': stats['stats']['total_bytes'],
            'free': pool_stats['max_avail'],
            'used': pool_stats['bytes_used']
        }
示例#24
0
    def host_maintenance_mode(self, host, mode):
        """Start/Stop host maintenance window. On start, it triggers
        guest VMs evacuation."""
        if not mode:
            return 'off_maintenance'
        host_list = [
            host_ref for host_ref in self._session.call_xenapi('host.get_all')
            if host_ref != self._session.get_xenapi_host()
        ]
        migrations_counter = vm_counter = 0
        ctxt = context.get_admin_context()
        for vm_ref, vm_rec in vm_utils.list_vms(self._session):
            for host_ref in host_list:
                try:
                    # Ensure only guest instances are migrated
                    uuid = vm_rec['other_config'].get('nova_uuid')
                    if not uuid:
                        name = vm_rec['name_label']
                        uuid = _uuid_find(self._virtapi, ctxt, host, name)
                        if not uuid:
                            msg = _('Instance %(name)s running on %(host)s'
                                    ' could not be found in the database:'
                                    ' assuming it is a worker VM and skip'
                                    ' ping migration to a new host')
                            LOG.info(msg % locals())
                            continue
                    instance = self._virtapi.instance_get_by_uuid(ctxt, uuid)
                    vm_counter = vm_counter + 1

                    aggregate = self._virtapi.aggregate_get_by_host(
                        ctxt, host, key=pool_states.POOL_FLAG)
                    if not aggregate:
                        msg = _('Aggregate for host %(host)s count not be'
                                ' found.') % dict(host=host)
                        raise exception.NotFound(msg)

                    dest = _host_find(ctxt, self._session, aggregate[0],
                                      host_ref)
                    (old_ref, new_ref) = self._virtapi.instance_update(
                        ctxt, instance['uuid'], {
                            'host': dest,
                            'task_state': task_states.MIGRATING
                        })
                    notifications.send_update(ctxt, old_ref, new_ref)

                    self._session.call_xenapi('VM.pool_migrate', vm_ref,
                                              host_ref, {})
                    migrations_counter = migrations_counter + 1

                    (old_ref, new_ref) = self._virtapi.instance_update(
                        ctxt, instance['uuid'], {'vm_state': vm_states.ACTIVE})
                    notifications.send_update(ctxt, old_ref, new_ref)

                    break
                except self._session.XenAPI.Failure:
                    LOG.exception('Unable to migrate VM %(vm_ref)s'
                                  'from %(host)s' % locals())
                    (old_ref, new_ref) = self._virtapi.instance_update(
                        ctxt, instance['uuid'], {
                            'host': host,
                            'vm_state': vm_states.ACTIVE
                        })
                    notifications.send_update(ctxt, old_ref, new_ref)

        if vm_counter == migrations_counter:
            return 'on_maintenance'
        else:
            raise exception.NoValidHost(reason='Unable to find suitable '
                                        'host for VMs evacuation')
示例#25
0
 def remove_entry(self, name):
     entry = self.subentry_with_name(name)
     if not entry:
         raise exception.NotFound()
     entry.remove_name(name)
     self.update_soa()
示例#26
0
    def host_maintenance_mode(self, host, mode):
        """Start/Stop host maintenance window. On start, it triggers
        guest VMs evacuation.
        """
        if not mode:
            return 'off_maintenance'
        host_list = [
            host_ref for host_ref in self._session.host.get_all()
            if host_ref != self._session.host_ref
        ]
        migrations_counter = vm_counter = 0
        ctxt = context.get_admin_context()
        for vm_ref, vm_rec in vm_utils.list_vms(self._session):
            for host_ref in host_list:
                try:
                    # Ensure only guest instances are migrated
                    uuid = vm_rec['other_config'].get('nova_uuid')
                    if not uuid:
                        name = vm_rec['name_label']
                        uuid = _uuid_find(ctxt, host, name)
                        if not uuid:
                            LOG.info(
                                _LI('Instance %(name)s running on '
                                    '%(host)s could not be found in '
                                    'the database: assuming it is a '
                                    'worker VM and skip ping migration '
                                    'to a new host'), {
                                        'name': name,
                                        'host': host
                                    })
                            continue
                    instance = objects.Instance.get_by_uuid(ctxt, uuid)
                    vm_counter = vm_counter + 1

                    aggregate = objects.AggregateList.get_by_host(
                        ctxt, host, key=pool_states.POOL_FLAG)
                    if not aggregate:
                        msg = _('Aggregate for host %(host)s count not be'
                                ' found.') % dict(host=host)
                        raise exception.NotFound(msg)

                    dest = _host_find(ctxt, self._session, aggregate[0],
                                      host_ref)
                    instance.host = dest
                    instance.task_state = task_states.MIGRATING
                    instance.save()

                    self._session.VM.pool_migrate(vm_ref, host_ref,
                                                  {"live": "true"})
                    migrations_counter = migrations_counter + 1

                    instance.vm_state = vm_states.ACTIVE
                    instance.save()

                    break
                except XenAPI.Failure:
                    LOG.exception(
                        _LE('Unable to migrate VM %(vm_ref)s '
                            'from %(host)s'), {
                                'vm_ref': vm_ref,
                                'host': host
                            })
                    instance.host = host
                    instance.vm_state = vm_states.ACTIVE
                    instance.save()

        if vm_counter == migrations_counter:
            return 'on_maintenance'
        else:
            raise exception.NoValidHost(reason=_('Unable to find suitable '
                                                 'host for VMs evacuation'))
示例#27
0
def return_non_existing_address(*args, **kwarg):
    raise exception.NotFound()
示例#28
0
def fake_get_not_found(*args, **kwargs):
    raise exception.NotFound()
示例#29
0
def return_server_not_found(*arg, **kwarg):
    raise exception.NotFound()
示例#30
0
文件: vmutils.py 项目: BigFire/nova-1
 def _lookup_vm_check(self, vm_name):
     vm = self._lookup_vm(vm_name)
     if not vm:
         raise exception.NotFound(_('VM not found: %s') % vm_name)
     return vm