示例#1
0
    def _find_pool_info(self):
        root = huawei_utils.parse_xml_file(self.xml_conf)
        pool_name = root.findtext('LUN/StoragePool')
        if not pool_name:
            err_msg = _("Invalid resource pool: %s") % pool_name
            LOG.error(err_msg)
            raise exception.InvalidInput(err_msg)

        url = self.url + "/storagepool"
        result = self.call(url, None)
        self._assert_rest_result(result, 'Query resource pool error')

        poolinfo = {}
        if "data" in result:
            for item in result['data']:
                if pool_name.strip() == item['NAME']:
                    poolinfo['ID'] = item['ID']
                    poolinfo['CAPACITY'] = item['USERFREECAPACITY']
                    poolinfo['TOTALCAPACITY'] = item['USERTOTALCAPACITY']
                    break

        if not poolinfo:
            msg = (_('Get pool info error, pool name is:%s') % pool_name)
            LOG.error(msg)
            raise exception.CinderException(msg)

        return poolinfo
示例#2
0
 def reboot_vapp(self, vapp_name):
     the_vapp = self._get_vcloud_vapp(vapp_name)
     task = self._invoke_vapp_api(the_vapp, "reboot")
     if not task:
         raise exception.CinderException("reboot vapp failed, task: %s" %
                                         task)
     self._session.wait_for_task(task)
示例#3
0
    def test_create_from_image_cache_miss_error_downloading(
            self, mock_qemu_info, mock_get_internal_context,
            mock_create_from_img_dl, mock_create_from_src,
            mock_handle_bootable, mock_fetch_img):
        mock_fetch_img.return_value = mock.MagicMock()
        image_info = imageutils.QemuImgInfo()
        image_info.virtual_size = '2147483648'
        mock_qemu_info.return_value = image_info
        self.mock_driver.clone_image.return_value = (None, False)
        self.mock_cache.get_entry.return_value = None

        volume = fake_volume.fake_volume_obj(self.ctxt,
                                             size=10,
                                             host='foo@bar#pool')
        image_volume = fake_volume.fake_db_volume(size=2)
        self.mock_db.volume_create.return_value = image_volume

        mock_create_from_img_dl.side_effect = exception.CinderException()

        def update_volume(ctxt, id, updates):
            volume.update(updates)
            return volume

        self.mock_db.volume_update.side_effect = update_volume

        image_location = 'someImageLocationStr'
        image_id = 'c7a8b8d4-e519-46c7-a0df-ddf1b9b9fff2'
        image_meta = mock.MagicMock()

        manager = create_volume_manager.CreateVolumeFromSpecTask(
            self.mock_volume_manager,
            self.mock_db,
            self.mock_driver,
            image_volume_cache=self.mock_cache)

        self.assertRaises(exception.CinderException,
                          manager._create_from_image, self.ctxt, volume,
                          image_location, image_id, image_meta,
                          self.mock_image_service)

        # Make sure clone_image is always called
        self.assertTrue(self.mock_driver.clone_image.called)

        # The image download should happen if clone fails and
        # we get a cache miss
        mock_create_from_img_dl.assert_called_once_with(
            self.ctxt, mock.ANY, image_location, image_id,
            self.mock_image_service)

        # The volume size should be reduced to virtual_size and then put back,
        # especially if there is an exception while creating the volume.
        self.assertEqual(2, self.mock_db.volume_update.call_count)
        self.mock_db.volume_update.assert_any_call(self.ctxt, volume['id'],
                                                   {'size': 2})
        self.mock_db.volume_update.assert_any_call(self.ctxt, volume['id'],
                                                   {'size': 10})

        # Make sure we didn't try and create a cache entry
        self.assertFalse(self.mock_cache.ensure_space.called)
        self.assertFalse(self.mock_cache.create_cache_entry.called)
示例#4
0
    def create_volume(self,
                      context,
                      topic,
                      volume_id,
                      snapshot_id=None,
                      image_id=None,
                      request_spec=None,
                      filter_properties=None,
                      volume=None):

        self._wait_for_scheduler()

        # FIXME(thangp): Remove this in v2.0 of RPC API.
        if volume is None:
            # For older clients, mimic the old behavior and look up the
            # volume by its volume_id.
            volume = objects.Volume.get_by_id(context, volume_id)

        try:
            flow_engine = create_volume.get_flow(context, db, self.driver,
                                                 request_spec,
                                                 filter_properties, volume,
                                                 snapshot_id, image_id)
        except Exception:
            msg = _("Failed to create scheduler manager volume flow")
            LOG.exception(msg)
            raise exception.CinderException(msg)

        with flow_utils.DynamicLogListener(flow_engine, logger=LOG):
            flow_engine.run()
示例#5
0
 def _assert_rest_result(self, result, err_str):
     error_code = result['error']['code']
     if error_code != 0:
         msg = _('%(err)s\nresult: %(res)s') % {'err': err_str,
                                                'res': result}
         LOG.error(msg)
         raise exception.CinderException(msg)
示例#6
0
def return_get_qos_associations(context, id):
    if id == "111":
        raise exception.QoSSpecsNotFound(specs_id=id)
    elif id == "222":
        raise exception.CinderException()

    return stub_qos_associates(id)
示例#7
0
def get_blkdev_major_minor(path: str,
                           lookup_for_file: bool = True) -> Optional[str]:
    """Get 'major:minor' number of block device.

    Get the device's 'major:minor' number of a block device to control
    I/O ratelimit of the specified path.
    If lookup_for_file is True and the path is a regular file, lookup a disk
    device which the file lies on and returns the result for the device.
    """
    st = os.stat(path)
    if stat.S_ISBLK(st.st_mode):
        path, st = _get_disk_of_partition(path, st)
        return '%d:%d' % (os.major(st.st_rdev), os.minor(st.st_rdev))
    elif stat.S_ISCHR(st.st_mode):
        # No I/O ratelimit control is provided for character devices
        return None
    elif lookup_for_file:
        # lookup the mounted disk which the file lies on
        out, _err = execute('df', path)
        devpath = out.split("\n")[1].split()[0]
        if devpath[0] != '/':
            # the file is on a network file system
            return None
        return get_blkdev_major_minor(devpath, False)
    else:
        msg = _("Unable to get a block device for file \'%s\'") % path
        raise exception.CinderException(msg)
示例#8
0
    def create_cloned_volume(self, volume, src_vref):
        """Creates a clone of the specified volume."""
        vol_size = volume.size
        src_vol_size = src_vref.size
        self._clone_volume(src_vref.name, volume.name, src_vref.id)
        share = self._get_volume_location(src_vref.id)
        volume['provider_location'] = share
        path = self.local_path(volume)

        if self._discover_file_till_timeout(path):
            self._set_rw_permissions(path)
            if vol_size != src_vol_size:
                try:
                    self.extend_volume(volume, vol_size)
                except Exception as e:
                    LOG.error(_LE("Resizing %s failed. Cleaning volume."),
                              volume.name)
                    self._execute('rm',
                                  path,
                                  run_as_root=self._execute_as_root)
                    raise e
        else:
            raise exception.CinderException(
                _("NFS file %s not discovered.") % volume['name'])

        return {'provider_location': volume['provider_location']}
示例#9
0
    def create(self,
               context,
               size,
               name,
               description,
               snapshot=None,
               image_id=None,
               volume_type=None,
               metadata=None,
               availability_zone=None,
               source_volume=None,
               scheduler_hints=None,
               backup_source_volume=None):
        def check_volume_az_zone(availability_zone):
            try:
                return self._valid_availabilty_zone(availability_zone)
            except exception.CinderException:
                LOG.exception(
                    _("Unable to query if %s is in the "
                      "availability zone set"), availability_zone)
                return False

        create_what = {
            'size': size,
            'name': name,
            'description': description,
            'snapshot': snapshot,
            'image_id': image_id,
            'volume_type': volume_type,
            'metadata': metadata,
            'availability_zone': availability_zone,
            'source_volume': source_volume,
            'scheduler_hints': scheduler_hints,
            'key_manager': self.key_manager,
            'backup_source_volume': backup_source_volume,
        }
        (flow, uuid) = create_volume.get_api_flow(self.scheduler_rpcapi,
                                                  self.volume_rpcapi, self.db,
                                                  self.image_service,
                                                  check_volume_az_zone,
                                                  create_what)

        assert flow, _('Create volume flow not retrieved')
        flow.run(context)
        if flow.state != states.SUCCESS:
            raise exception.CinderException(
                _("Failed to successfully complete"
                  " create volume workflow"))

        # Extract the volume information from the task uuid that was specified
        # to produce said information.
        volume = None
        try:
            volume = flow.results[uuid]['volume']
        except KeyError:
            pass

        # Raise an error, nobody provided it??
        assert volume, _('Expected volume result not found')
        return volume
示例#10
0
    def test_create_consistencygroup_exceptions(self):
        with mock.patch.object(filter_scheduler.FilterScheduler,
                               'schedule_create_consistencygroup') as mock_cg:
            original_driver = self.manager.driver
            consistencygroup_obj = \
                fake_consistencygroup.fake_consistencyobject_obj(self.context)
            self.manager.driver = filter_scheduler.FilterScheduler
            LOG = self.mock_object(manager, 'LOG')
            self.stubs.Set(db, 'consistencygroup_update', mock.Mock())

            ex = exception.CinderException('test')
            mock_cg.side_effect = ex
            group_id = '1'
            self.assertRaises(exception.CinderException,
                              self.manager.create_consistencygroup,
                              self.context, 'volume', consistencygroup_obj)
            self.assertTrue(LOG.exception.call_count > 0)
            db.consistencygroup_update.assert_called_once_with(
                self.context, group_id, {'status': 'error'})

            mock_cg.reset_mock()
            LOG.exception.reset_mock()
            db.consistencygroup_update.reset_mock()

            mock_cg.side_effect = exception.NoValidHost(
                reason="No weighed hosts available")
            self.manager.create_consistencygroup(self.context, 'volume',
                                                 consistencygroup_obj)
            self.assertTrue(LOG.error.call_count > 0)
            db.consistencygroup_update.assert_called_once_with(
                self.context, group_id, {'status': 'error'})

            self.manager.driver = original_driver
示例#11
0
    def test_create_consistencygroup_exceptions(self):
        with mock.patch.object(filter_scheduler.FilterScheduler,
                               'schedule_create_consistencygroup') as mock_cg:
            original_driver = self.manager.driver
            consistencygroup_obj = \
                fake_consistencygroup.fake_consistencyobject_obj(self.context)
            self.manager.driver = filter_scheduler.FilterScheduler
            LOG = self.mock_object(manager, 'LOG')
            self.mock_object(db, 'consistencygroup_update')

            ex = exception.CinderException('test')
            mock_cg.side_effect = ex
            group_id = fake.CONSISTENCY_GROUP_ID
            self.assertRaises(exception.CinderException,
                              self.manager.create_consistencygroup,
                              self.context, 'volume', consistencygroup_obj)
            self.assertGreater(LOG.exception.call_count, 0)
            db.consistencygroup_update.assert_called_once_with(
                self.context, group_id,
                {'status': (fields.ConsistencyGroupStatus.ERROR)})

            mock_cg.reset_mock()
            LOG.exception.reset_mock()
            db.consistencygroup_update.reset_mock()

            mock_cg.side_effect = exception.NoValidHost(
                reason="No weighed hosts available")
            self.manager.create_consistencygroup(self.context, 'volume',
                                                 consistencygroup_obj)
            self.assertGreater(LOG.error.call_count, 0)
            db.consistencygroup_update.assert_called_once_with(
                self.context, group_id,
                {'status': (fields.ConsistencyGroupStatus.ERROR)})

            self.manager.driver = original_driver
示例#12
0
    def create_volume(self,
                      context,
                      volume_id,
                      request_spec=None,
                      filter_properties=None,
                      allow_reschedule=True,
                      snapshot_id=None,
                      image_id=None,
                      source_volid=None):
        """Creates and exports the volume."""

        flow = create_volume.get_manager_flow(
            self.db,
            self.driver,
            self.scheduler_rpcapi,
            self.host,
            volume_id,
            request_spec=request_spec,
            filter_properties=filter_properties,
            allow_reschedule=allow_reschedule,
            snapshot_id=snapshot_id,
            image_id=image_id,
            source_volid=source_volid,
            reschedule_context=context.deepcopy())

        assert flow, _('Manager volume flow not retrieved')

        flow.run(context.elevated())
        if flow.state != states.SUCCESS:
            raise exception.CinderException(
                _("Failed to successfully complete"
                  " manager volume workflow"))

        self._reset_stats()
        return volume_id
示例#13
0
文件: nfs.py 项目: cdwertmann/cinder
    def _clone_volume(self, volume_name, clone_name, volume_id):
        """Clones mounted volume with OnCommand proxy API."""
        host_id = self._get_host_id(volume_id)
        export_path = self._get_full_export_path(volume_id, host_id)

        request = self._client.factory.create('Request')
        request.Name = 'clone-start'

        clone_start_args = ('<source-path>%s/%s</source-path>'
                            '<destination-path>%s/%s</destination-path>')

        request.Args = text.Raw(clone_start_args % (export_path,
                                                    volume_name,
                                                    export_path,
                                                    clone_name))

        resp = self._client.service.ApiProxy(Target=host_id,
                                             Request=request)

        if (resp.Status == 'passed' and
                self.configuration.synchronous_snapshot_create):
            clone_id = resp.Results['clone-id'][0]
            clone_id_info = clone_id['clone-id-info'][0]
            clone_operation_id = int(clone_id_info['clone-op-id'][0])

            self._wait_for_clone_finished(clone_operation_id, host_id)
        elif resp.Status == 'failed':
            raise exception.CinderException(resp.Reason)
示例#14
0
    def test_create_snapshot_metadata_update_failure_generates_user_message(
            self, fake_notify, fake_init, fake_msg_create):
        manager = vol_manager.VolumeManager()

        fake_driver = mock.MagicMock()
        fake_driver.create_snapshot.return_value = False
        manager.driver = fake_driver

        fake_vol_ref = mock.MagicMock()
        fake_vol_ref.bootable.return_value = True
        fake_db = mock.MagicMock()
        fake_db.volume_get.return_value = fake_vol_ref
        fake_exp = exception.CinderException()
        fake_db.volume_glance_metadata_copy_to_snapshot.side_effect = fake_exp
        manager.db = fake_db

        fake_snapshot = mock.MagicMock(id='86')
        fake_context = mock.MagicMock()
        fake_context.elevated.return_value = fake_context

        self.assertRaises(exception.CinderException, manager.create_snapshot,
                          fake_context, fake_snapshot)

        # make sure a user message was generated
        fake_msg_create.assert_called_once_with(
            fake_context,
            action=message_field.Action.SNAPSHOT_CREATE,
            resource_type=message_field.Resource.VOLUME_SNAPSHOT,
            resource_uuid=fake_snapshot['id'],
            exception=fake_exp,
            detail=message_field.Detail.SNAPSHOT_UPDATE_METADATA_FAILED)
示例#15
0
def return_get_qos_associations(context, id):
    if id == fake.WILL_NOT_BE_FOUND_ID:
        raise exception.QoSSpecsNotFound(specs_id=id)
    elif id == fake.RAISE_ID:
        raise exception.CinderException()

    return stub_qos_associates(id)
示例#16
0
    def create_volume_from_snapshot(self, volume, snapshot):
        """Creates a volume from a snapshot."""
        vol_size = volume.size
        snap_size = snapshot.volume_size

        self._clone_volume(snapshot.name, volume.name, snapshot.volume_id)
        share = self._get_volume_location(snapshot.volume_id)
        volume['provider_location'] = share
        path = self.local_path(volume)
        run_as_root = self._execute_as_root

        if self._discover_file_till_timeout(path):
            self._set_rw_permissions(path)
            if vol_size != snap_size:
                try:
                    self.extend_volume(volume, vol_size)
                except Exception:
                    with excutils.save_and_reraise_exception():
                        LOG.error(_LE("Resizing %s failed. Cleaning volume."),
                                  volume.name)
                        self._execute('rm', path, run_as_root=run_as_root)
        else:
            raise exception.CinderException(
                _("NFS file %s not discovered.") % volume['name'])

        return {'provider_location': volume['provider_location']}
示例#17
0
    def _get_lun_conf_params(self):
        """Get parameters from config file for creating lun."""
        # Default lun set information
        lunsetinfo = {'LUNType': 'Thick',
                      'StripUnitSize': '64',
                      'WriteType': '1',
                      'MirrorSwitch': '1',
                      'PrefetchType': '3',
                      'PrefetchValue': '0',
                      'PrefetchTimes': '0'}

        root = huawei_utils.parse_xml_file(self.xml_conf)
        luntype = root.findtext('LUN/LUNType')
        if luntype:
            if luntype.strip() in ['Thick', 'Thin']:
                lunsetinfo['LUNType'] = luntype.strip()
                if luntype.strip() == 'Thick':
                    lunsetinfo['LUNType'] = 0
                if luntype.strip() == 'Thin':
                    lunsetinfo['LUNType'] = 1

            elif luntype is not '' and luntype is not None:
                err_msg = (_('Config file is wrong. LUNType must be "Thin"'
                             ' or "Thick". LUNType:%(fetchtype)s')
                           % {'fetchtype': luntype})
                LOG.error(err_msg)
                raise exception.VolumeBackendAPIException(data=err_msg)

        stripunitsize = root.findtext('LUN/StripUnitSize')
        if stripunitsize is not None:
            lunsetinfo['StripUnitSize'] = stripunitsize.strip()
        writetype = root.findtext('LUN/WriteType')
        if writetype is not None:
            lunsetinfo['WriteType'] = writetype.strip()
        mirrorswitch = root.findtext('LUN/MirrorSwitch')
        if mirrorswitch is not None:
            lunsetinfo['MirrorSwitch'] = mirrorswitch.strip()

        prefetch = root.find('LUN/Prefetch')
        fetchtype = prefetch.attrib['Type']
        if prefetch is not None and prefetch.attrib['Type']:
            if fetchtype in ['0', '1', '2', '3']:
                lunsetinfo['PrefetchType'] = fetchtype.strip()
                typevalue = prefetch.attrib['Value'].strip()
                if lunsetinfo['PrefetchType'] == '1':
                    lunsetinfo['PrefetchValue'] = typevalue
                elif lunsetinfo['PrefetchType'] == '2':
                    lunsetinfo['PrefetchValue'] = typevalue
            else:
                err_msg = (_('PrefetchType config is wrong. PrefetchType'
                             ' must in 1,2,3,4. fetchtype is:%(fetchtype)s')
                           % {'fetchtype': fetchtype})
                LOG.error(err_msg)
                raise exception.CinderException(err_msg)
        else:
            LOG.debug('Use default prefetch fetchtype. '
                      'Prefetch fetchtype:Intelligent.')

        return lunsetinfo
示例#18
0
def start_transfer(context, timeout_secs, read_file_handle, max_data_size,
                   write_file_handle=None, image_service=None, image_id=None,
                   image_meta=None):
    """Start the data transfer from the reader to the writer.

    Reader writes to the pipe and the writer reads from the pipe. This means
    that the total transfer time boils down to the slower of the read/write
    and not the addition of the two times.
    """

    if not image_meta:
        image_meta = {}

    # The pipe that acts as an intermediate store of data for reader to write
    # to and writer to grab from.
    thread_safe_pipe = io_util.ThreadSafePipe(QUEUE_BUFFER_SIZE, max_data_size)
    # The read thread. In case of glance it is the instance of the
    # GlanceFileRead class. The glance client read returns an iterator
    # and this class wraps that iterator to provide datachunks in calls
    # to read.
    read_thread = io_util.IOThread(read_file_handle, thread_safe_pipe)

    # In case of Glance - VMware transfer, we just need a handle to the
    # HTTP Connection that is to send transfer data to the VMware datastore.
    if write_file_handle:
        write_thread = io_util.IOThread(thread_safe_pipe, write_file_handle)
    # In case of VMware - Glance transfer, we relinquish VMware HTTP file read
    # handle to Glance Client instance, but to be sure of the transfer we need
    # to be sure of the status of the image on glance changing to active.
    # The GlanceWriteThread handles the same for us.
    elif image_service and image_id:
        write_thread = io_util.GlanceWriteThread(context, thread_safe_pipe,
                                                 image_service, image_id,
                                                 image_meta)
    # Start the read and write threads.
    read_event = read_thread.start()
    write_event = write_thread.start()
    timer = timeout.Timeout(timeout_secs)
    try:
        # Wait on the read and write events to signal their end
        read_event.wait()
        write_event.wait()
    except (timeout.Timeout, Exception) as exc:
        # In case of any of the reads or writes raising an exception,
        # stop the threads so that we un-necessarily don't keep the other one
        # waiting.
        read_thread.stop()
        write_thread.stop()

        # Log and raise the exception.
        LOG.exception(exc)
        raise exception.CinderException(exc)
    finally:
        timer.cancel()
        # No matter what, try closing the read and write handles, if it so
        # applies.
        read_file_handle.close()
        if write_file_handle:
            write_file_handle.close()
示例#19
0
    def test_create_snapshot(self, mock_create, mock_get):
        mock_get.return_value = True
        self.driver.create_snapshot(self.snapshot)

        mock_create.side_effect = exception.CinderException(
            'create snapshot failed')
        self.assertRaises(exception.CinderException,
                          self.driver.create_snapshot, self.snapshot)

        mock_get.side_effect = [
            False, exception.CinderException('get volume failed')]
        self.assertRaises(exception.CinderException,
                          self.driver.create_snapshot,
                          self.snapshot)
        self.assertRaises(exception.CinderException,
                          self.driver.create_snapshot,
                          self.snapshot)
示例#20
0
    def replication_enable(self, context, volume):
        if volume['replication_status'] == 'invalid_status_val':
            raise exception.CinderException()

        volume_model_update = {}
        volume_model_update['replication_driver_data'] = FAKE_DRIVER_DATA

        return volume_model_update
示例#21
0
 def _detach_disk_from_vm(self, the_vapp, disk_ref):
     task = the_vapp.detach_disk_from_vm(the_vapp.name, disk_ref)
     if not task:
         raise exception.CinderException(
             "Unable to detach disk from vm %s" % the_vapp.name)
     else:
         self._session._wait_for_task(task)
         return True
示例#22
0
    def create_context(self, user_id):
        try:
            details = self.context_details[user_id]
        except KeyError:
            msg = ('No context details defined for user_id "%s".' % (user_id))
            raise exception.CinderException(message=msg)

        return cinder_context.RequestContext(user_id=user_id, **details)
示例#23
0
    def create(self, context, size, name, description, snapshot=None,
               image_id=None, volume_type=None, metadata=None,
               availability_zone=None, source_volume=None,
               scheduler_hints=None, backup_source_volume=None):

        if source_volume and volume_type:
            if volume_type['id'] != source_volume['volume_type_id']:
                msg = _("Invalid volume_type provided (requested type "
                        "must match source volume, or be omitted). "
                        "You should omit the argument.")
                raise exception.InvalidInput(reason=msg)

        if snapshot and volume_type:
            if volume_type['id'] != snapshot['volume_type_id']:
                msg = _("Invalid volume_type provided (requested type "
                        "must match source snapshot, or be omitted). "
                        "You should omit the argument.")
                raise exception.InvalidInput(reason=msg)

        def check_volume_az_zone(availability_zone):
            try:
                return self._valid_availability_zone(availability_zone)
            except exception.CinderException:
                LOG.exception(_("Unable to query if %s is in the "
                                "availability zone set"), availability_zone)
                return False

        create_what = {
            'context': context,
            'raw_size': size,
            'name': name,
            'description': description,
            'snapshot': snapshot,
            'image_id': image_id,
            'raw_volume_type': volume_type,
            'metadata': metadata,
            'raw_availability_zone': availability_zone,
            'source_volume': source_volume,
            'scheduler_hints': scheduler_hints,
            'key_manager': self.key_manager,
            'backup_source_volume': backup_source_volume,
        }

        try:
            flow_engine = create_volume.get_flow(self.scheduler_rpcapi,
                                                 self.volume_rpcapi,
                                                 self.db,
                                                 self.image_service,
                                                 check_volume_az_zone,
                                                 create_what)
        except Exception:
            LOG.exception(_("Failed to create api volume flow"))
            raise exception.CinderException(
                _("Failed to create api volume flow"))

        flow_engine.run()
        volume = flow_engine.storage.fetch('volume')
        return volume
示例#24
0
        def _inner():
            """Function to do the image data transfer through an update
            and thereon checks if the state is 'active'.
            """
            try:
                self.image_service.update(self.context,
                                          self.image_id,
                                          self.image_meta,
                                          data=self.input)
                self._running = True
            except exception.ImageNotAuthorized as exc:
                self.done.send_exception(exc)

            while self._running:
                try:
                    image_meta = self.image_service.show(
                        self.context, self.image_id)
                    image_status = image_meta.get("status")
                    if image_status == "active":
                        self.stop()
                        self.done.send(True)
                    # If the state is killed, then raise an exception.
                    elif image_status == "killed":
                        self.stop()
                        msg = (_("Glance image %s is in killed state") %
                               self.image_id)
                        LOG.error(msg)
                        self.done.send_exception(
                            exception.CinderException(msg))
                    elif image_status in ["saving", "queued"]:
                        greenthread.sleep(GLANCE_POLL_INTERVAL)
                    else:
                        self.stop()
                        msg = _("Glance image "
                                "%(image_id)s is in unknown state "
                                "- %(state)s") % {
                                    "image_id": self.image_id,
                                    "state": image_status
                                }
                        LOG.error(msg)
                        self.done.send_exception(
                            exception.CinderException(msg))
                except Exception as exc:
                    self.stop()
                    self.done.send_exception(exc)
示例#25
0
    def _update_stats(self):
        if self._helper:
            storage_pools = self._helper.get_pools()
            if not len(storage_pools):
                msg = _('No pools found - make sure san_clustername '
                        'is defined in the config file and that the '
                        'pools exist on the storage.')
                LOG.error(msg)
                raise exception.CinderException(message=msg)
        else:
            msg = (_('Backend %s is not initialized.') %
                   self.configuration.volume_backend_name)
            raise exception.CinderException(data=msg)

        stats = {
            "volume_backend_name":
            self.configuration.volume_backend_name,
            "serial_number":
            self._helper.backend['storage_unit'],
            "extent_pools":
            self._helper.backend['pools_str'],
            "vendor_name":
            'IBM',
            "driver_version":
            self.full_version,
            "storage_protocol":
            self._helper.get_connection_type(),
            "total_capacity_gb":
            self._b2gb(sum(p['cap'] for p in storage_pools.values())),
            "free_capacity_gb":
            self._b2gb(sum(p['capavail'] for p in storage_pools.values())),
            "reserved_percentage":
            self.configuration.reserved_percentage,
            "consistencygroup_support":
            True,
            "consistent_group_snapshot_enabled":
            True,
            "multiattach":
            False
        }

        if self._replication_enabled:
            stats['replication_enabled'] = self._replication_enabled

        self.meta['stat'] = stats
示例#26
0
        def _inner():
            """Initiate write thread.

            Function to do the image data transfer through an update
            and thereon checks if the state is 'active'.
            """
            LOG.debug(_("Initiating image service update on image: %(image)s "
                        "with meta: %(meta)s") % {'image': self.image_id,
                                                  'meta': self.image_meta})
            self.image_service.update(self.context,
                                      self.image_id,
                                      self.image_meta,
                                      data=self.input_file)
            self._running = True
            while self._running:
                try:
                    image_meta = self.image_service.show(self.context,
                                                         self.image_id)
                    image_status = image_meta.get('status')
                    if image_status == 'active':
                        self.stop()
                        LOG.debug(_("Glance image: %s is now active.") %
                                  self.image_id)
                        self.done.send(True)
                    # If the state is killed, then raise an exception.
                    elif image_status == 'killed':
                        self.stop()
                        msg = (_("Glance image: %s is in killed state.") %
                               self.image_id)
                        LOG.error(msg)
                        excep = exception.CinderException(msg)
                        self.done.send_exception(excep)
                    elif image_status in ['saving', 'queued']:
                        greenthread.sleep(GLANCE_POLL_INTERVAL)
                    else:
                        self.stop()
                        msg = _("Glance image %(id)s is in unknown state "
                                "- %(state)s") % {'id': self.image_id,
                                                  'state': image_status}
                        LOG.error(msg)
                        excep = exception.CinderException(msg)
                        self.done.send_exception(excep)
                except Exception as exc:
                    self.stop()
                    self.done.send_exception(exc)
示例#27
0
def convert_version_to_int(version):
    try:
        if isinstance(version, six.string_types):
            version = convert_version_to_tuple(version)
        if isinstance(version, tuple):
            return six.moves.reduce(lambda x, y: (x * 1000) + y, version)
    except Exception:
        msg = _("Version %s is invalid.") % version
        raise exception.CinderException(msg)
示例#28
0
文件: xtremio.py 项目: suman-d/cinder
    def create_cloned_volume(self, volume, src_vref):
        """Creates a clone of the specified volume."""
        vol = self.client.req('volumes', name=src_vref['id'])['content']
        ctxt = context.get_admin_context()
        cache = self.db.image_volume_cache_get_by_volume_id(
            ctxt, src_vref['id'])
        limit = self.configuration.safe_get('xtremio_volumes_per_glance_cache')
        if cache and limit and limit > 0 and limit <= vol['num-of-dest-snaps']:
            raise exception.CinderException('Exceeded the configured limit of '
                                            '%d snapshots per volume' % limit)
        try:
            self.client.create_snapshot(src_vref['id'], volume['id'])
        except exception.XtremIOSnapshotsLimitExceeded as e:
            raise exception.CinderException(e.message)

        if volume.get('consistencygroup_id') and self.client is XtremIOClient4:
            self.client.add_vol_to_cg(volume['id'],
                                      volume['consistencygroup_id'])
示例#29
0
 def is_authorized(self, user_id, authorized_users, unauthorized_users):
     if user_id in authorized_users:
         return True
     elif user_id in unauthorized_users:
         return False
     else:
         msg = ('"%s" must be either an authorized or unauthorized user.' %
                (user_id))
         raise exception.CinderException(message=msg)
示例#30
0
 def extend_volume(self, volume, new_size):
     dev_path = self.local_path(volume)
     total_size = self._get_devices_sizes([dev_path])
     # Convert from Megabytes to Gigabytes
     size = total_size[dev_path] / units.Ki
     if size < new_size:
         msg = _("Insufficient free space available to extend volume.")
         LOG.error(msg, resource=volume)
         raise exception.CinderException(msg)