Exemplo n.º 1
0
    def create_snapshot(self, context, snapshot, share_server=None):
        """Creates a snapshot."""
        model_update = {}
        volume = self._get_volume(self.admin_context, snapshot['share_id'])
        volume_snapshot_name = (
            self.configuration.volume_snapshot_name_template % snapshot['id'])
        volume_snapshot = self.volume_api.create_snapshot_force(
            self.admin_context, volume['id'], volume_snapshot_name, '')
        t = time.time()
        while time.time() - t < self.configuration.max_time_to_create_volume:
            if volume_snapshot['status'] == const.STATUS_AVAILABLE:
                break
            if volume_snapshot['status'] == const.STATUS_ERROR:
                raise exception.ManilaException(
                    _('Failed to create volume '
                      'snapshot'))
            time.sleep(1)
            volume_snapshot = self.volume_api.get_snapshot(
                self.admin_context, volume_snapshot['id'])

            # NOTE(xyang): We should look at whether we still need to save
            # volume_snapshot_id in private_storage later, now that is saved
            # in provider_location.
            self.private_storage.update(
                snapshot['id'], {'volume_snapshot_id': volume_snapshot['id']})
            # NOTE(xyang): Need to update provider_location in the db so
            # that it can be used in manage/unmanage snapshot tempest tests.
            model_update['provider_location'] = volume_snapshot['id']
        else:
            raise exception.ManilaException(
                _('Volume snapshot have not been '
                  'created in %ss. Giving up') %
                self.configuration.max_time_to_create_volume)

        return model_update
Exemplo n.º 2
0
 def do_attach(volume):
     if volume['status'] == 'in-use':
         attached_volumes = [
             vol.id for vol in self.compute_api.instance_volumes_list(
                 self.admin_context, instance_id)
         ]
         if volume['id'] in attached_volumes:
             return volume
         else:
             raise exception.ManilaException(
                 _('Volume %s is already attached to another instance')
                 % volume['id'])
     self.compute_api.instance_volume_attach(
         self.admin_context,
         instance_id,
         volume['id'],
     )
     t = time.time()
     while time.time() - t < self.configuration.max_time_to_attach:
         volume = self.volume_api.get(context, volume['id'])
         if volume['status'] == 'in-use':
             return volume
         elif volume['status'] != 'attaching':
             raise exception.ManilaException(
                 _('Failed to attach volume %s') % volume['id'])
         time.sleep(1)
     else:
         raise exception.ManilaException(
             _('Volume have not been attached in %ss. Giving up') %
             self.configuration.max_time_to_attach)
Exemplo n.º 3
0
    def wrap(self, context, *args, **kwargs):
        server = kwargs.get('share_server')

        if not self.driver_handles_share_servers:
            if not server:
                server = self.service_instance_manager.get_common_server()
                kwargs['share_server'] = server
            else:
                raise exception.ManilaException(
                    _("Share server handling is not available. "
                      "But 'share_server' was provided. '%s'. "
                      "Share network should not be used.") % server.get('id'))
        elif not server:
            raise exception.ManilaException(
                _("Share server handling is enabled. But 'share_server' "
                  "is not provided. Make sure you used 'share_network'."))

        if not server.get('backend_details'):
            raise exception.ManilaException(
                _("Share server '%s' does not have backend details.") %
                server['id'])
        if not self.service_instance_manager.ensure_service_instance(
                context, server['backend_details']):
            raise exception.ServiceInstanceUnavailable()

        return f(self, context, *args, **kwargs)
Exemplo n.º 4
0
    def _wait_for_available_volume(self,
                                   volume,
                                   timeout,
                                   msg_error,
                                   msg_timeout,
                                   expected_size=None):
        t = time.time()
        while time.time() - t < timeout:
            if volume['status'] == const.STATUS_AVAILABLE:
                if expected_size and volume['size'] != expected_size:
                    LOG.debug(
                        "The volume %(vol_id)s is available but the "
                        "volume size does not match the expected size. "
                        "A volume resize operation may be pending. "
                        "Expected size: %(expected_size)s, "
                        "Actual size: %(volume_size)s.",
                        dict(vol_id=volume['id'],
                             expected_size=expected_size,
                             volume_size=volume['size']))
                else:
                    break
            elif 'error' in volume['status'].lower():
                raise exception.ManilaException(msg_error)
            time.sleep(1)
            volume = self.volume_api.get(self.admin_context, volume['id'])
        else:
            raise exception.ManilaException(msg_timeout)

        return volume
Exemplo n.º 5
0
 def _deallocate_container(self, context, share):
     """Deletes cinder volume."""
     try:
         volume = self._get_volume(context, share['id'])
     except exception.VolumeNotFound:
         LOG.info(_LI("Volume not found. Already deleted?"))
         volume = None
     if volume:
         if volume['status'] == 'in-use':
             raise exception.ManilaException(
                 _('Volume is still in use and '
                   'cannot be deleted now.'))
         self.volume_api.delete(context, volume['id'])
         t = time.time()
         while (time.time() - t <
                self.configuration.max_time_to_create_volume):
             try:
                 volume = self.volume_api.get(context, volume['id'])
             except exception.VolumeNotFound:
                 LOG.debug('Volume was deleted successfully')
                 break
             time.sleep(1)
         else:
             raise exception.ManilaException(
                 _('Volume have not been '
                   'deleted in %ss. Giving up') %
                 self.configuration.max_time_to_create_volume)
Exemplo n.º 6
0
    def _allocate_container(self, context, share, snapshot=None):
        """Creates cinder volume, associated to share by name."""
        volume_snapshot = None
        if snapshot:
            volume_snapshot = self._get_volume_snapshot(
                context, snapshot['id'])
        volume = self.volume_api.create(
            context,
            share['size'],
            self.configuration.volume_name_template % share['id'],
            '',
            snapshot=volume_snapshot)

        t = time.time()
        while time.time() - t < self.configuration.max_time_to_create_volume:
            if volume['status'] == 'available':
                break
            if volume['status'] == 'error':
                raise exception.ManilaException(_('Failed to create volume'))
            time.sleep(1)
            volume = self.volume_api.get(context, volume['id'])
        else:
            raise exception.ManilaException(
                _('Volume have not been created '
                  'in %ss. Giving up') %
                self.configuration.max_time_to_create_volume)

        return volume
Exemplo n.º 7
0
    def do_setup(self, context):
        """Driver initialization"""
        if purity_fb is None:
            msg = _("Missing 'purity_fb' python module, ensure the library"
                    " is installed and available.")
            raise exception.ManilaException(message=msg)

        self.api = self._safe_get_from_config_or_fail("flashblade_api")
        self.management_address = self._safe_get_from_config_or_fail(
            "flashblade_mgmt_vip")
        self.data_address = self._safe_get_from_config_or_fail(
            "flashblade_data_vip")
        self._sys = purity_fb.PurityFb(self.management_address)
        self._sys.disable_verify_ssl()
        try:
            self._sys.login(self.api)
            self._sys._api_client.user_agent = self._user_agent
        except purity_fb.rest.ApiException as ex:
            msg = _("Exception when logging into the array: %s\n") % ex
            LOG.exception(msg)
            raise exception.ManilaException(message=msg)

        backend_name = self.configuration.safe_get("share_backend_name")
        self._backend_name = backend_name or self.__class__.__name__

        LOG.debug("setup complete")
Exemplo n.º 8
0
    def _verify_share_server_handling(self, driver_handles_share_servers):
        if not isinstance(self.driver_handles_share_servers, bool):
            raise exception.ManilaException(
                "Config opt 'driver_handles_share_servers' has improper "
                "value - '%s'. Please define it as boolean." %
                self.driver_handles_share_servers)
        elif isinstance(driver_handles_share_servers, bool):
            driver_handles_share_servers = [driver_handles_share_servers]
        elif not isinstance(driver_handles_share_servers, (tuple, list, set)):
            raise exception.ManilaException(
                "Improper data provided for 'driver_handles_share_servers' - "
                "%s" % driver_handles_share_servers)

        if any(not isinstance(v, bool) for v in driver_handles_share_servers):
            raise exception.ManilaException("Provided wrong data: %s" %
                                            driver_handles_share_servers)

        if (self.driver_handles_share_servers
                not in driver_handles_share_servers):
            raise exception.ManilaException(
                "Driver does not support mode 'driver_handles_share_servers="
                "%(actual)s'. It can be used only with value '%(allowed)s'." %
                {
                    'actual': self.driver_handles_share_servers,
                    'allowed': driver_handles_share_servers
                })
Exemplo n.º 9
0
        def do_attach(volume):
            if volume['status'] == 'in-use':
                attached_volumes = [vol.id for vol in
                                    self.compute_api.instance_volumes_list(
                                        self.admin_context, instance_id)]
                if volume['id'] in attached_volumes:
                    return volume
                else:
                    raise exception.ManilaException(
                        _('Volume %s is already attached to another instance')
                        % volume['id'])

            @retrying.retry(stop_max_attempt_number=3,
                            wait_fixed=2000,
                            retry_on_exception=lambda exc: True)
            def attach_volume():
                self.compute_api.instance_volume_attach(
                    self.admin_context, instance_id, volume['id'])

            attach_volume()

            t = time.time()
            while time.time() - t < self.configuration.max_time_to_attach:
                volume = self.volume_api.get(context, volume['id'])
                if volume['status'] == 'in-use':
                    return volume
                elif volume['status'] != 'attaching':
                    raise exception.ManilaException(
                        _('Failed to attach volume %s') % volume['id'])
                time.sleep(1)
            else:
                raise exception.ManilaException(
                    _('Volume have not been attached in %ss. Giving up') %
                    self.configuration.max_time_to_attach)
Exemplo n.º 10
0
    def create_snapshot(self, context, snapshot, share_server=None):
        """Creates a snapshot."""
        volume = self._get_volume(self.admin_context, snapshot['share_id'])
        volume_snapshot_name = (self.configuration.
                                volume_snapshot_name_template % snapshot['id'])
        volume_snapshot = self.volume_api.create_snapshot_force(
            self.admin_context, volume['id'], volume_snapshot_name, '')
        t = time.time()
        while time.time() - t < self.configuration.max_time_to_create_volume:
            if volume_snapshot['status'] == const.STATUS_AVAILABLE:
                break
            if volume_snapshot['status'] == const.STATUS_ERROR:
                raise exception.ManilaException(_('Failed to create volume '
                                                  'snapshot'))
            time.sleep(1)
            volume_snapshot = self.volume_api.get_snapshot(
                self.admin_context,
                volume_snapshot['id'])

            self.private_storage.update(
                snapshot['id'], {'volume_snapshot_id': volume_snapshot['id']})
        else:
            raise exception.ManilaException(
                _('Volume snapshot have not been '
                  'created in %ss. Giving up') %
                self.configuration.max_time_to_create_volume)
Exemplo n.º 11
0
    def create_export(self, server, share_name, recreate=False):
        """Create share at samba server."""
        share_path = os.path.join(self.configuration.share_mount_path,
                                  share_name)
        create_cmd = [
            'sudo',
            'net',
            'conf',
            'addshare',
            share_name,
            share_path,
            'writeable=y',
            'guest_ok=y',
        ]
        try:
            self._ssh_exec(server, [
                'sudo',
                'net',
                'conf',
                'showshare',
                share_name,
            ])
        except exception.ProcessExecutionError:
            # Share does not exist, create it
            try:
                self._ssh_exec(server, create_cmd)
            except Exception as child_e:
                msg = _("Could not create CIFS export %s.") % share_name
                LOG.exception(child_e)
                LOG.error(msg)
                raise exception.ManilaException(reason=msg)
        else:
            # Share exists
            if recreate:
                self._ssh_exec(server, [
                    'sudo',
                    'net',
                    'conf',
                    'delshare',
                    share_name,
                ])
                try:
                    self._ssh_exec(server, create_cmd)
                except Exception as e:
                    msg = _("Could not create CIFS export %s.") % share_name
                    LOG.exception(e)
                    LOG.error(msg)
                    raise exception.ManilaException(reason=msg)
            else:
                msg = _('Share section %s already defined.') % share_name
                raise exception.ShareBackendException(msg=msg)

        for param, value in self.parameters.items():
            self._ssh_exec(
                server,
                ['sudo', 'net', 'conf', 'setparm', share_name, param, value])

        return self.export_format % (server['public_address'], share_name)
Exemplo n.º 12
0
 def execute(self, name=None, cmd=None, ignore_errors=False):
     if name is None:
         raise exception.ManilaException(_("Container name not specified."))
     if cmd is None or (type(cmd) is not list):
         raise exception.ManilaException(_("Missing or malformed command."))
     LOG.debug("Executing inside a container %s.", name)
     cmd = ["docker", "exec", "-i", name] + cmd
     result = self._inner_execute(cmd, ignore_errors=ignore_errors)
     return result
Exemplo n.º 13
0
 def _verify_server_has_public_address(server):
     if 'public_address' in server:
         pass
     elif 'public_addresses' in server:
         if not isinstance(server['public_addresses'], list):
             raise exception.ManilaException(_("public_addresses must be "
                                               "a list"))
     else:
         raise exception.ManilaException(
             _("Can not get public_address(es) for generation of export."))
Exemplo n.º 14
0
 def revert_to_snapshot(
     self,
     context,
     snapshot,
     share_access_rules,
     snapshot_access_rules,
     share_server=None,
 ):
     dataset_name = self._make_source_name(snapshot)
     filt = "source_display_name='{0}' and suffix='{1}'".format(
         dataset_name, snapshot["id"])
     LOG.debug("FlashBlade filter %(name)s", {"name": filt})
     name = "{0}.{1}".format(dataset_name, snapshot["id"])
     self._get_flashblade_snapshot_by_name(filt)
     fs_attr = purity_fb.FileSystem(name=dataset_name,
                                    source=purity_fb.Reference(name=name))
     try:
         self._sys.file_systems.create_file_systems(
             overwrite=True,
             discard_non_snapshotted_data=True,
             file_system=fs_attr,
         )
     except purity_fb.rest.ApiException as ex:
         msg = _("Failed to revert snapshot: %s\n") % ex
         LOG.exception(msg)
         raise exception.ManilaException(message=msg)
Exemplo n.º 15
0
 def _update_nfs_access(self, share, access_rules):
     dataset_name = self._make_share_name(share)
     self._get_flashblade_filesystem_by_name(dataset_name)
     nfs_rules = ""
     rule_state = {}
     for access in access_rules:
         if access["access_type"] == "ip":
             line = (access["access_to"] + "(" + access["access_level"] +
                     ",no_root_squash) ")
             rule_state[access["access_id"]] = {"state": "active"}
             nfs_rules += line
         else:
             message = _(
                 'Only "ip" access type is allowed for NFS protocol.')
             LOG.error(message)
             rule_state[access["access_id"]] = {"state": "error"}
     try:
         self._sys.file_systems.update_file_systems(
             name=dataset_name,
             attributes=purity_fb.FileSystem(nfs=purity_fb.NfsRule(
                 rules=nfs_rules)),
         )
         message = "Set nfs rules %(nfs_rules)s for %(share_name)s"
         LOG.debug(message, {
             "nfs_rules": nfs_rules,
             "share_name": dataset_name
         })
     except purity_fb.rest.ApiException as ex:
         msg = _("Failed to set NFS access rules: %s\n") % ex
         LOG.exception(msg)
         raise exception.ManilaException(message=msg)
     return rule_state
Exemplo n.º 16
0
    def _get_service_port(self):
        """Find or creates service neutron port.

        This port will be used for connectivity with service instances.
        """
        ports = [port for port in self.neutron_api.
                 list_ports(device_id='manila-share')]
        if len(ports) > 1:
            raise exception.ServiceInstanceException(
                _('Error. Ambiguous service ports.'))
        elif not ports:
            try:
                stdout, stderr = self._execute('hostname')
                host = stdout.strip()
            except exception.ProcessExecutionError as e:
                msg = _('Unable to get host. %s') % e.stderr
                raise exception.ManilaException(msg)
            port = self.neutron_api.create_port(
                self.service_tenant_id,
                self.service_network_id,
                device_id='manila-share',
                device_owner='manila:share',
                host_id=host)
        else:
            port = ports[0]
        return port
Exemplo n.º 17
0
 def ensure_share(self, context, share, share_server=None):
     lcfg = self.configuration
     details = self.zfssa.get_share(lcfg.zfssa_pool, lcfg.zfssa_project,
                                    share['id'])
     if not details:
         msg = (_("Share %s doesn't exists.") % share['id'])
         raise exception.ManilaException(msg)
Exemplo n.º 18
0
 def do_detach():
     attached_volumes = [
         vol.id for vol in self.compute_api.instance_volumes_list(
             self.admin_context, instance_id)
     ]
     try:
         volume = self._get_volume(context, share['id'])
     except exception.VolumeNotFound:
         LOG.warning(
             _LW("Volume not found for share %s. "
                 "Possibly already deleted."), share['id'])
         volume = None
     if volume and volume['id'] in attached_volumes:
         self.compute_api.instance_volume_detach(
             self.admin_context, instance_id, volume['id'])
         t = time.time()
         while time.time() - t < self.configuration.max_time_to_attach:
             volume = self.volume_api.get(context, volume['id'])
             if volume['status'] in (const.STATUS_AVAILABLE,
                                     const.STATUS_ERROR):
                 break
             time.sleep(1)
         else:
             err_msg = {
                 'volume_id': volume['id'],
                 'max_time': self.configuration.max_time_to_attach
             }
             raise exception.ManilaException(
                 _('Volume %(volume_id)s has not been detached in '
                   '%(max_time)ss. Giving up.') % err_msg)
Exemplo n.º 19
0
    def test_delete_snapshot__some_error(self, post):
        snapshot = {'share_name': 'share', 'name': 'share@first'}
        post.return_value = FakeResponse()
        post.side_effect = exception.ManilaException('Some error')

        self.assertRaises(exception.ManilaException, self.drv.delete_snapshot,
                          self.ctx, snapshot)
Exemplo n.º 20
0
    def test_setup_server_with_error(self):

        mock_get_vserver_name = self.mock_object(
            self.library,
            '_get_vserver_name',
            mock.Mock(return_value=fake.VSERVER1))

        fake_exception = exception.ManilaException("fake")
        mock_create_vserver = self.mock_object(
            self.library,
            '_create_vserver',
            mock.Mock(side_effect=fake_exception))

        mock_validate_network_type = self.mock_object(
            self.library,
            '_validate_network_type')

        self.assertRaises(
            exception.ManilaException,
            self.library.setup_server,
            fake.NETWORK_INFO)

        self.assertTrue(mock_validate_network_type.called)
        self.assertTrue(mock_get_vserver_name.called)
        self.assertTrue(mock_create_vserver.called)
        self.assertDictEqual(
            {'server_details': {'vserver_name': fake.VSERVER1}},
            fake_exception.detail_data)
Exemplo n.º 21
0
    def rename_container(self, name, new_name):
        veth_name = self.find_container_veth(name)
        if not veth_name:
            raise exception.ManilaException(
                _("Could not find OVS information related to "
                  "container %s.") % name)

        try:
            self._inner_execute(["docker", "rename", name, new_name])
        except (exception.ProcessExecutionError, OSError):
            raise exception.ShareBackendException(
                msg="Could not rename container %s." % name)

        cmd = [
            "ovs-vsctl", "set", "interface", veth_name,
            "external-ids:manila-container=%s" % new_name
        ]
        try:
            self._inner_execute(cmd)
        except (exception.ProcessExecutionError, OSError):
            try:
                self._inner_execute(["docker", "rename", new_name, name])
            except (exception.ProcessExecutionError, OSError):
                msg = _("Could not rename back container %s.") % name
                LOG.exception(msg)
            raise exception.ShareBackendException(
                msg="Could not update OVS information %s." % name)

        LOG.info("Container %s has been successfully renamed.", name)
Exemplo n.º 22
0
    def do_setup(self, context):
        """Driver initialization"""
        if infinisdk is None:
            msg = _("Missing 'infinisdk' python module, ensure the library"
                    " is installed and available.")
            raise exception.ManilaException(message=msg)

        infinibox_login = self._safe_get_from_config_or_fail('infinibox_login')
        infinibox_password = (
            self._safe_get_from_config_or_fail('infinibox_password'))
        auth = (infinibox_login, infinibox_password)

        management_address = (
            self._safe_get_from_config_or_fail('infinibox_hostname'))

        self._pool_name = (
            self._safe_get_from_config_or_fail('infinidat_pool_name'))

        self._network_space_name = (
            self._safe_get_from_config_or_fail(
                'infinidat_nas_network_space_name'))

        self._system = (
            self._setup_and_get_system_object(management_address, auth))

        backend_name = self.configuration.safe_get('share_backend_name')
        self._backend_name = backend_name or self.__class__.__name__

        thin_provisioning = self.configuration.infinidat_thin_provision
        self._provtype = "THIN" if thin_provisioning else "THICK"

        LOG.debug('setup complete')
Exemplo n.º 23
0
    def create_share(self, context, share, share_server=None):
        """Create a Zadara share and export it.

        :param context: A RequestContext.
        :param share: A Share.
        :param share_server: Not used currently
        :return: The export locations dictionary.
        """
        # Check share's protocol.
        # Throw an exception immediately if it is an invalid protocol.
        self._check_share_protocol(share)
        share_name = self._get_zadara_share_template_name(share['id'])

        # Collect the share metadata provided and validate it
        metadata = self.api.get_share_metadata(context,
                                               {'id': share['share_id']})
        if not self.is_valid_metadata(metadata):
            raise manila_exception.ManilaException(
                _("Not a valid metadata provided for the share %s") %
                share['id'])

        data = self.vpsa_send_cmd('create_volume',
                                  name=share_name,
                                  size=share['size'],
                                  metadata=metadata)
        if data['status'] != 0:
            raise manila_exception.ZadaraVPSAVolumeShareFailed(
                error=data['status'])

        export_location = self._get_share_export_location(share)
        return {'path': export_location}
Exemplo n.º 24
0
    def manage_existing_snapshot(self, snapshot, driver_options):
        share = snapshot['share']
        share_name = self._get_zadara_share_template_name(share['id'])

        vpsa_volume = self.vpsa._get_vpsa_volume(share_name)
        if not vpsa_volume:
            msg = (_('Volume %(name)s could not be found. '
                     'It might be already deleted') % {
                         'name': share_name
                     })
            LOG.error(msg)
            raise manila_exception.ZadaraShareNotFound(name=share['id'])

        # Check if the provider_location is specified
        if not snapshot['provider_location']:
            msg = (_('Provider location as snap id of the VPSA backend '
                     'should be provided'))
            LOG.error(msg)
            raise manila_exception.ManilaException(msg)

        new_name = (self.configuration.zadara_share_snap_name_template %
                    snapshot['id'])
        new_snap_id = self.vpsa._get_snap_id(vpsa_volume['cg_name'], new_name)
        if new_snap_id:
            msg = (_('Snapshot with name %s already exists') % new_name)
            LOG.debug(msg)
            return

        data = self.vpsa_send_cmd('rename_snapshot',
                                  snap_id=snapshot['provider_location'],
                                  new_name=new_name)
        if data['status'] != 0:
            raise manila_exception.ZadaraVPSASnapshotManageFailed(
                snap_id=snapshot['provider_location'], error=data['status'])
Exemplo n.º 25
0
    def create(self):
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            if self.privatekey:
                pkfile = os.path.expanduser(self.privatekey)
                self.privatekey = paramiko.RSAKey.from_private_key_file(pkfile)
            elif not self.password:
                msg = _("Specify a password or private_key")
                raise exception.ManilaException(msg)
            ssh.connect(self.ip,
                        port=self.port,
                        username=self.login,
                        password=self.password,
                        pkey=self.privatekey,
                        timeout=self.conn_timeout)

            # Paramiko by default sets the socket timeout to 0.1 seconds,
            # ignoring what we set thru the sshclient. This doesn't help for
            # keeping long lived connections. Hence we have to bypass it, by
            # overriding it after the transport is initialized. We are setting
            # the sockettimeout to None and setting a keepalive packet so that,
            # the server will keep the connection open. All that does is send
            # a keepalive packet every ssh_conn_timeout seconds.
            if self.conn_timeout:
                transport = ssh.get_transport()
                transport.sock.settimeout(None)
                transport.set_keepalive(self.conn_timeout)
            return ssh
        except Exception as e:
            msg = _("Error connecting via ssh: %s") % e
            LOG.error(msg)
            raise paramiko.SSHException(msg)
Exemplo n.º 26
0
    def test_setup_server_exception_raised(self):
        # Setup required test data
        context = "fake_context"
        share_server = {
            'id': 'fake_id',
            'share_network_id': 'fake_sn_id',
        }
        share_network = {'id': 'fake_sn_id'}

        # mock required stuff
        self.stubs.Set(self.share_manager.db, 'share_network_get',
                       mock.Mock(return_value=share_network))
        self.stubs.Set(self.share_manager.driver,
                       'get_network_allocations_number',
                       mock.Mock(side_effect=exception.ManilaException()))
        self.stubs.Set(self.share_manager.db, 'share_server_update',
                       mock.Mock())
        self.stubs.Set(self.share_manager.network_api, 'deallocate_network',
                       mock.Mock())

        # execute method _setup_server
        self.assertRaises(
            exception.ManilaException,
            self.share_manager._setup_server,
            context,
            share_server,
        )
        self.share_manager.db.share_network_get.assert_called_once_with(
            context, share_server['share_network_id'])
        self.share_manager.driver.get_network_allocations_number.\
            assert_called_once_with()
        self.share_manager.db.share_server_update.assert_called_once_with(
            context, share_server['id'], {'status': constants.STATUS_ERROR})
        self.share_manager.network_api.deallocate_network.\
            assert_called_once_with(context, share_network)
Exemplo n.º 27
0
    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=e.message)
        except cinder_exception.NotFound:
            raise exception.NotFound(
                _("Error in creating cinder "
                  "volume. Cinder volume type %s not exist. Check parameter "
                  "cinder_volume_type in configuration file.") % volume_type)
        except Exception as e:
            raise exception.ManilaException(e.message)
Exemplo n.º 28
0
    def test_setup_server_with_error(self):

        mock_get_vserver_name = self.mock_object(
            self.library,
            '_get_vserver_name',
            mock.Mock(return_value=fake.VSERVER1))

        fake_exception = exception.ManilaException("fake")
        mock_create_vserver = self.mock_object(
            self.library,
            '_create_vserver',
            mock.Mock(side_effect=fake_exception))

        mock_validate_network_type = self.mock_object(
            self.library,
            '_validate_network_type')

        self.assertRaises(
            exception.ManilaException,
            self.library.setup_server,
            fake.NETWORK_INFO)

        ports = {}
        for network_allocation in fake.NETWORK_INFO['network_allocations']:
            ports[network_allocation['id']] = network_allocation['ip_address']

        self.assertTrue(mock_validate_network_type.called)
        self.assertTrue(mock_get_vserver_name.called)
        self.assertTrue(mock_create_vserver.called)
        self.assertDictEqual(
            {'server_details': {'vserver_name': fake.VSERVER1,
                                'ports': jsonutils.dumps(ports)}},
            fake_exception.detail_data)
Exemplo n.º 29
0
    def volume_client(self):
        if self._volume_client:
            return self._volume_client

        if not ceph_module_found:
            raise exception.ManilaException(
                _("Ceph client libraries not found.")
            )

        conf_path = self.configuration.safe_get('cephfs_conf_path')
        cluster_name = self.configuration.safe_get('cephfs_cluster_name')
        auth_id = self.configuration.safe_get('cephfs_auth_id')
        self._volume_client = ceph_volume_client.CephFSVolumeClient(
            auth_id, conf_path, cluster_name)
        LOG.info(_LI("[%(be)s}] Ceph client found, connecting..."),
                 {"be": self.backend_name})
        if auth_id != CEPH_DEFAULT_AUTH_ID:
            # Evict any other manila sessions.  Only do this if we're
            # using a client ID that isn't the default admin ID, to avoid
            # rudely disrupting anyone else.
            premount_evict = auth_id
        else:
            premount_evict = None
        try:
            self._volume_client.connect(premount_evict=premount_evict)
        except Exception:
            self._volume_client = None
            raise
        else:
            LOG.info(_LI("[%(be)s] Ceph client connection complete."),
                     {"be": self.backend_name})

        return self._volume_client
Exemplo n.º 30
0
    def _request(self,
                 req_body=None,
                 method=None,
                 header=constants.CONTENT_TYPE_URLENCODE):
        req = url_request.Request(self._url, req_body, header)
        if method not in (None, 'GET', 'POST'):
            req.get_method = lambda: method
        self._http_log_req(req)
        try:
            resp = self.url_opener.open(req)
            resp_body = resp.read()
            self._http_log_resp(resp, resp_body)
        except url_error.HTTPError as http_err:
            err = {
                'errorCode': -1,
                'httpStatusCode': http_err.code,
                'messages': six.text_type(http_err),
                'request': req_body
            }
            msg = (_("The request is invalid. Reason: %(reason)s") % {
                'reason': err
            })
            if '403' == six.text_type(http_err.code):
                raise exception.NotAuthorized()
            else:
                raise exception.ManilaException(message=msg)

        return resp_body