Exemple #1
0
 def __init__(self):
     super(HostAPI, self).__init__(rpcapi=ComputeRPCProxyAPI())
     self.cells_rpcapi = cells_rpcapi.CellsAPI()
Exemple #2
0
 def __init__(self):
     super(InstanceActionAPI, self).__init__()
     self.cells_rpcapi = cells_rpcapi.CellsAPI()
Exemple #3
0
 def _handle_cell_update_from_api():
     cells_api = cells_rpcapi.CellsAPI()
     cells_api.instance_update_from_api(context, stale_instance,
                                        expected_vm_state,
                                        expected_task_state,
                                        admin_state_reset)
Exemple #4
0
 def __init__(self):
     self.compute_api = compute.API()
     self.cells_rpcapi = cells_rpcapi.CellsAPI()
 def setUp(self):
     super(CellsAPITestCase, self).setUp()
     self.fake_topic = 'fake_topic'
     self.fake_context = 'fake_context'
     self.flags(topic=self.fake_topic, enable=True, group='cells')
     self.cells_rpcapi = cells_rpcapi.CellsAPI()
Exemple #6
0
    def save(self,
             context,
             expected_vm_state=None,
             expected_task_state=None,
             admin_state_reset=False):
        """Save updates to this instance

        Column-wise updates will be made based on the result of
        self.what_changed(). If expected_task_state is provided,
        it will be checked against the in-database copy of the
        instance before updates are made.

        :param:context: Security context
        :param:expected_task_state: Optional tuple of valid task states
        for the instance to be in
        :param:expected_vm_state: Optional tuple of valid vm states
        for the instance to be in
        :param admin_state_reset: True if admin API is forcing setting
        of task_state/vm_state

        """

        cell_type = cells_opts.get_cell_type()
        if cell_type == 'api' and self.cell_name:
            # NOTE(comstud): We need to stash a copy of ourselves
            # before any updates are applied.  When we call the save
            # methods on nested objects, we will lose any changes to
            # them.  But we need to make sure child cells can tell
            # what is changed.
            #
            # We also need to nuke any updates to vm_state and task_state
            # unless admin_state_reset is True.  compute cells are
            # authoritative for their view of vm_state and task_state.
            stale_instance = self.obj_clone()

            def _handle_cell_update_from_api():
                cells_api = cells_rpcapi.CellsAPI()
                cells_api.instance_update_from_api(context, stale_instance,
                                                   expected_vm_state,
                                                   expected_task_state,
                                                   admin_state_reset)
        else:
            stale_instance = None

        updates = {}
        changes = self.obj_what_changed()
        for field in self.fields:
            if (self.obj_attr_is_set(field)
                    and isinstance(self[field], base.NovaObject)):
                try:
                    getattr(self, '_save_%s' % field)(context)
                except AttributeError:
                    LOG.exception(_('No save handler for %s') % field,
                                  instance=self)
            elif field in changes:
                updates[field] = self[field]

        if not updates:
            if stale_instance:
                _handle_cell_update_from_api()
            return

        # Cleaned needs to be turned back into an int here
        if 'cleaned' in updates:
            if updates['cleaned']:
                updates['cleaned'] = 1
            else:
                updates['cleaned'] = 0

        if expected_task_state is not None:
            if (self.VERSION == '1.9'
                    and expected_task_state == 'image_snapshot'):
                # NOTE(danms): Icehouse introduced a pending state which
                # Havana doesn't know about. If we're an old instance,
                # tolerate the pending state as well
                expected_task_state = [
                    expected_task_state, 'image_snapshot_pending'
                ]
            updates['expected_task_state'] = expected_task_state
        if expected_vm_state is not None:
            updates['expected_vm_state'] = expected_vm_state

        expected_attrs = [
            attr for attr in _INSTANCE_OPTIONAL_JOINED_FIELDS
            if self.obj_attr_is_set(attr)
        ]
        # NOTE(alaski): We need to pull system_metadata for the
        # notification.send_update() below.  If we don't there's a KeyError
        # when it tries to extract the flavor.
        if 'system_metadata' not in expected_attrs:
            expected_attrs.append('system_metadata')
        old_ref, inst_ref = db.instance_update_and_get_original(
            context,
            self.uuid,
            updates,
            update_cells=False,
            columns_to_join=_expected_cols(expected_attrs))

        if stale_instance:
            _handle_cell_update_from_api()
        elif cell_type == 'compute':
            cells_api = cells_rpcapi.CellsAPI()
            cells_api.instance_update_at_top(context, inst_ref)

        self._from_db_object(context, self, inst_ref, expected_attrs)
        notifications.send_update(context, old_ref, inst_ref)
        self.obj_reset_changes()
 def __init__(self, *args, **kwargs):
     super(ComputeRPCProxyAPI, self).__init__(*args, **kwargs)
     self.cells_rpcapi = cells_rpcapi.CellsAPI()
Exemple #8
0
    def _save_test_helper(self, cell_type, save_kwargs):
        """Common code for testing save() for cells/non-cells."""
        if cell_type:
            self.flags(enable=True, cell_type=cell_type, group='cells')
        else:
            self.flags(enable=False, group='cells')

        ctxt = context.get_admin_context()
        old_ref = dict(self.fake_instance,
                       host='oldhost',
                       user_data='old',
                       vm_state='old',
                       task_state='old')
        fake_uuid = old_ref['uuid']

        expected_updates = dict(vm_state='meow',
                                task_state='wuff',
                                user_data='new')

        new_ref = dict(old_ref, host='newhost', **expected_updates)
        exp_vm_state = save_kwargs.get('expected_vm_state')
        exp_task_state = save_kwargs.get('expected_task_state')
        admin_reset = save_kwargs.get('admin_state_reset', False)
        if exp_vm_state:
            expected_updates['expected_vm_state'] = exp_vm_state
        if exp_task_state:
            expected_updates['expected_task_state'] = exp_task_state
        self.mox.StubOutWithMock(db, 'instance_get_by_uuid')
        self.mox.StubOutWithMock(db, 'instance_update_and_get_original')
        self.mox.StubOutWithMock(db, 'instance_info_cache_update')
        cells_api_mock = self.mox.CreateMock(cells_rpcapi.CellsAPI)
        self.mox.StubOutWithMock(cells_api_mock, 'instance_update_at_top')
        self.mox.StubOutWithMock(cells_api_mock, 'instance_update_from_api')
        self.mox.StubOutWithMock(cells_rpcapi,
                                 'CellsAPI',
                                 use_mock_anything=True)
        db.instance_get_by_uuid(ctxt, fake_uuid,
                                columns_to_join=[]).AndReturn(old_ref)
        db.instance_update_and_get_original(ctxt,
                                            fake_uuid,
                                            expected_updates,
                                            update_cells=False).AndReturn(
                                                (old_ref, new_ref))
        if cell_type == 'api':
            cells_rpcapi.CellsAPI().AndReturn(cells_api_mock)
            cells_api_mock.instance_update_from_api(ctxt,
                                                    mox.IsA(instance.Instance),
                                                    exp_vm_state,
                                                    exp_task_state,
                                                    admin_reset)
        elif cell_type == 'compute':
            cells_rpcapi.CellsAPI().AndReturn(cells_api_mock)
            cells_api_mock.instance_update_at_top(ctxt, new_ref)

        self.mox.ReplayAll()

        inst = instance.Instance.get_by_uuid(ctxt, old_ref['uuid'])
        self.assertEqual('old', inst.task_state)
        self.assertEqual('old', inst.vm_state)
        self.assertEqual('old', inst.user_data)
        inst.vm_state = 'meow'
        inst.task_state = 'wuff'
        inst.user_data = 'new'
        inst.save(**save_kwargs)
        self.assertEqual('newhost', inst.host)
        self.assertEqual('meow', inst.vm_state)
        self.assertEqual('wuff', inst.task_state)
        self.assertEqual('new', inst.user_data)
        self.assertEqual(set([]), inst.obj_what_changed())
 def __init__(self, ext_mgr):
     self.cells_rpcapi = cells_rpcapi.CellsAPI()
     self.ext_mgr = ext_mgr
Exemple #10
0
    def _metadata_as_json(self, version, path):
        metadata = {'uuid': self.uuid}
        if self.launch_metadata:
            metadata['meta'] = self.launch_metadata
        if self.files:
            metadata['files'] = self.files
        if self.extra_md:
            metadata.update(self.extra_md)
        if self.network_config:
            metadata['network_config'] = self.network_config

        if self.instance.key_name:
            if cells_opts.get_cell_type() == 'compute':
                cells_api = cells_rpcapi.CellsAPI()
                try:
                    keypair = cells_api.get_keypair_at_top(
                        context.get_admin_context(), self.instance.user_id,
                        self.instance.key_name)
                except exception.KeypairNotFound:
                    # NOTE(lpigueir): If keypair was deleted, treat
                    # it like it never had any
                    keypair = None
            else:
                keypairs = self.instance.keypairs
                # NOTE(mriedem): It's possible for the keypair to be deleted
                # before it was migrated to the instance_extra table, in which
                # case lazy-loading instance.keypairs will handle the 404 and
                # just set an empty KeyPairList object on the instance.
                keypair = keypairs[0] if keypairs else None

            if keypair:
                metadata['public_keys'] = {
                    keypair.name: keypair.public_key,
                }

                metadata['keys'] = [{
                    'name': keypair.name,
                    'type': keypair.type,
                    'data': keypair.public_key
                }]
            else:
                LOG.debug(
                    "Unable to find keypair for instance with "
                    "key name '%s'.",
                    self.instance.key_name,
                    instance=self.instance)

        metadata['hostname'] = self._get_hostname()
        metadata['name'] = self.instance.display_name
        metadata['launch_index'] = self.instance.launch_index
        metadata['availability_zone'] = self.availability_zone

        if self._check_os_version(GRIZZLY, version):
            metadata['random_seed'] = base64.encode_as_text(os.urandom(512))

        if self._check_os_version(LIBERTY, version):
            metadata['project_id'] = self.instance.project_id

        if self._check_os_version(NEWTON_ONE, version):
            metadata['devices'] = self._get_device_metadata(version)

        self.set_mimetype(MIME_TYPE_APPLICATION_JSON)
        return jsonutils.dump_as_bytes(metadata)
Exemple #11
0
 def __init__(self):
     self.cells_rpcapi = cells_rpcapi.CellsAPI()