예제 #1
0
    def get_shares_data(self):
        share_nets_names = {}
        share_nets = manila.share_network_list(self.request)
        for share_net in share_nets:
            share_nets_names[share_net.id] = share_net.name
        try:
            shares = manila.share_list(self.request)
            for share in shares:
                share.share_network = (share_nets_names.get(
                    share.share_network_id) or share.share_network_id)
                share.metadata = ui_utils.metadata_to_str(share.metadata)

            snapshots = manila.share_snapshot_list(self.request, detailed=True)
            share_ids_with_snapshots = []
            for snapshot in snapshots:
                share_ids_with_snapshots.append(snapshot.to_dict()['share_id'])
            for share in shares:
                if share.to_dict()['id'] in share_ids_with_snapshots:
                    setattr(share, 'has_snapshot', True)
                else:
                    setattr(share, 'has_snapshot', False)
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve share list.'))
            return []
        # Gather our tenants to correlate against IDs
        return shares
예제 #2
0
    def get_shares_data(self):
        share_nets_names = {}
        share_nets = manila.share_network_list(self.request)
        for share_net in share_nets:
            share_nets_names[share_net.id] = share_net.name
        try:
            shares = manila.share_list(self.request)
            for share in shares:
                share.share_network = (
                    share_nets_names.get(share.share_network_id) or
                    share.share_network_id)
                share.metadata = ui_utils.metadata_to_str(share.metadata)

            snapshots = manila.share_snapshot_list(self.request, detailed=True)
            share_ids_with_snapshots = []
            for snapshot in snapshots:
                share_ids_with_snapshots.append(snapshot.to_dict()['share_id'])
            for share in shares:
                if share.to_dict()['id'] in share_ids_with_snapshots:
                    setattr(share, 'has_snapshot', True)
                else:
                    setattr(share, 'has_snapshot', False)
        except Exception:
            exceptions.handle(
                self.request, _('Unable to retrieve share list.'))
            return []
        # Gather our tenants to correlate against IDs
        return shares
예제 #3
0
    def test_share_snapshot_list(self, kwargs):
        result = api.share_snapshot_list(self.request, **kwargs)

        self.assertEqual(
            self.manilaclient.share_snapshots.list.return_value, result)
        self.manilaclient.share_snapshots.list.assert_called_once_with(
            detailed=kwargs.get("detailed", True),
            search_opts=kwargs.get("search_opts"),
            sort_key=kwargs.get("sort_key"),
            sort_dir=kwargs.get("sort_dir"),
        )
예제 #4
0
 def get_share_snapshots_data(self):
     try:
         snapshots = manila.share_snapshot_list(self.request)
         shares = manila.share_list(self.request)
         share_names = dict([(share.id, share.name or share.id)
                             for share in shares])
         for snapshot in snapshots:
             snapshot.share = share_names.get(snapshot.share_id)
     except Exception:
         msg = _("Unable to retrieve share snapshots list.")
         exceptions.handle(self.request, msg)
         return []
     # Gather our tenants to correlate against IDs
     return snapshots
예제 #5
0
 def get_share_snapshots_data(self):
     try:
         snapshots = manila.share_snapshot_list(self.request)
         shares = manila.share_list(self.request)
         share_names = dict([(share.id, share.name or share.id)
                             for share in shares])
         for snapshot in snapshots:
             snapshot.share = share_names.get(snapshot.share_id)
     except Exception:
         msg = _("Unable to retrieve share snapshots list.")
         exceptions.handle(self.request, msg)
         return []
     # Gather our tenants to correlate against IDs
     return snapshots
예제 #6
0
def tenant_quota_usages(f, request, tenant_id=None):

    usages = f(request, tenant_id)

    if 'shares' not in _get_manila_disabled_quotas(request):
        shares = manila.share_list(request)
        snapshots = manila.share_snapshot_list(request)
        sn_l = manila.share_network_list(request)
        gig_s = sum([int(v.size) for v in shares])
        gig_ss = sum([int(v.size) for v in snapshots])
        usages.tally('gigabytes', gig_s + gig_ss)
        usages.tally('shares', len(shares))
        usages.tally('snapshots', len(snapshots))
        usages.tally('share_networks', len(sn_l))

    return usages
예제 #7
0
def tenant_quota_usages(f, request, tenant_id=None):

    usages = f(request, tenant_id)

    if 'shares' not in _get_manila_disabled_quotas(request):
        shares = manila.share_list(request)
        snapshots = manila.share_snapshot_list(request)
        sn_l = manila.share_network_list(request)
        gig_s = sum([int(v.size) for v in shares])
        gig_ss = sum([int(v.size) for v in snapshots])
        usages.tally('gigabytes', gig_s + gig_ss)
        usages.tally('shares', len(shares))
        usages.tally('snapshots', len(snapshots))
        usages.tally('share_networks', len(sn_l))

    return usages
예제 #8
0
 def __init__(self, req, *args, **kwargs):
     super(self.__class__, self).__init__(req, *args, **kwargs)
     # NOTE(vponomaryov): manila client does not allow to filter snapshots
     # using "created_at" field, so, we need to get all snapshots of a share
     # and do filtering here.
     search_opts = {'share_id': self.initial['share_id']}
     snapshots = manila.share_snapshot_list(req, search_opts=search_opts)
     amount_of_snapshots = len(snapshots)
     if amount_of_snapshots < 1:
         self.fields['snapshot'].choices = [("", "")]
     else:
         snapshot = snapshots[0]
         if amount_of_snapshots > 1:
             for s in snapshots[1:]:
                 if s.created_at > snapshot.created_at:
                     snapshot = s
         self.fields['snapshot'].choices = [
             (snapshot.id, snapshot.name or snapshot.id)]
예제 #9
0
    def get_snapshots_data(self):
        snapshots = []
        try:
            snapshots = manila.share_snapshot_list(
                self.request, search_opts={'all_tenants': True})
            shares = manila.share_list(self.request)
            share_names = dict([(share.id, share.name or share.id)
                                for share in shares])
            for snapshot in snapshots:
                snapshot.share = share_names.get(snapshot.share_id)
        except Exception:
            msg = _("Unable to retrieve snapshot list.")
            exceptions.handle(self.request, msg)

        # Gather our tenants to correlate against IDs
        utils.set_tenant_name_to_objects(self.request, snapshots)

        return snapshots
예제 #10
0
    def get_snapshots_data(self):
        snapshots = []
        try:
            snapshots = manila.share_snapshot_list(
                self.request, search_opts={'all_tenants': True})
            shares = manila.share_list(self.request)
            share_names = dict([(share.id, share.name or share.id)
                                for share in shares])
            for snapshot in snapshots:
                snapshot.share = share_names.get(snapshot.share_id)
        except Exception:
            msg = _("Unable to retrieve snapshot list.")
            exceptions.handle(self.request, msg)

        # Gather our projects to correlate against IDs
        utils.set_project_name_to_objects(self.request, snapshots)

        return snapshots
예제 #11
0
 def __init__(self, req, *args, **kwargs):
     super(self.__class__, self).__init__(req, *args, **kwargs)
     # NOTE(vponomaryov): manila client does not allow to filter snapshots
     # using "created_at" field, so, we need to get all snapshots of a share
     # and do filtering here.
     search_opts = {'share_id': self.initial['share_id']}
     snapshots = manila.share_snapshot_list(req, search_opts=search_opts)
     amount_of_snapshots = len(snapshots)
     if amount_of_snapshots < 1:
         self.fields['snapshot'].choices = [("", "")]
     else:
         snapshot = snapshots[0]
         if amount_of_snapshots > 1:
             for s in snapshots[1:]:
                 if s.created_at > snapshot.created_at:
                     snapshot = s
         self.fields['snapshot'].choices = [(snapshot.id, snapshot.name
                                             or snapshot.id)]
예제 #12
0
def tenant_limit_usages(f, request):

    limits = f(request)

    if base.is_service_enabled(request, 'share'):
        try:
            limits.update(manila.tenant_absolute_limits(request))
            shares = manila.share_list(request)
            snapshots = manila.share_snapshot_list(request)
            total_s_size = sum([getattr(share, 'size', 0) for share in shares])
            total_ss_size = sum([getattr(ss, 'size', 0) for ss in snapshots])
            limits['totalGigabytesUsed'] = total_s_size + total_ss_size
            limits['totalSharesUsed'] = len(shares)
            limits['totalSnapshotsUsed'] = len(snapshots)
        except Exception:
            msg = _("Unable to retrieve share limit information.")
            horizon.exceptions.handle(request, msg)

    return limits
예제 #13
0
def tenant_limit_usages(f, request):

    limits = f(request)

    if base.is_service_enabled(request, 'share'):
        try:
            limits.update(manila.tenant_absolute_limits(request))
            shares = manila.share_list(request)
            snapshots = manila.share_snapshot_list(request)
            total_s_size = sum([getattr(share, 'size', 0) for share in shares])
            total_ss_size = sum([getattr(ss, 'size', 0) for ss in snapshots])
            limits['totalGigabytesUsed'] = total_s_size + total_ss_size
            limits['totalSharesUsed'] = len(shares)
            limits['totalSnapshotsUsed'] = len(snapshots)
        except Exception:
            msg = _("Unable to retrieve share limit information.")
            horizon.exceptions.handle(request, msg)

    return limits
예제 #14
0
    def get_shares_data(self):
        shares = []
        try:
            shares = manila.share_list(self.request,
                                       search_opts={'all_tenants': True})
            snapshots = manila.share_snapshot_list(
                self.request, detailed=True, search_opts={'all_tenants': True})
            share_ids_with_snapshots = []
            for snapshot in snapshots:
                share_ids_with_snapshots.append(snapshot.to_dict()['share_id'])
            for share in shares:
                if share.to_dict()['id'] in share_ids_with_snapshots:
                    setattr(share, 'has_snapshot', True)
                else:
                    setattr(share, 'has_snapshot', False)
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve share list.'))

        # Gather our projects to correlate against IDs
        utils.set_project_name_to_objects(self.request, shares)

        return shares
예제 #15
0
    def get_shares_data(self):
        shares = []
        try:
            shares = manila.share_list(
                self.request, search_opts={'all_tenants': True})
            snapshots = manila.share_snapshot_list(
                self.request, detailed=True, search_opts={'all_tenants': True})
            share_ids_with_snapshots = []
            for snapshot in snapshots:
                share_ids_with_snapshots.append(snapshot.to_dict()['share_id'])
            for share in shares:
                if share.to_dict()['id'] in share_ids_with_snapshots:
                    setattr(share, 'has_snapshot', True)
                else:
                    setattr(share, 'has_snapshot', False)
        except Exception:
            exceptions.handle(
                self.request, _('Unable to retrieve share list.'))

        # Gather our projects to correlate against IDs
        utils.set_project_name_to_objects(self.request, shares)

        return shares
예제 #16
0
파일: forms.py 프로젝트: bswartz/manila-ui
    def __init__(self, request, *args, **kwargs):
        super(CreateForm, self).__init__(request, *args, **kwargs)
        share_protos = ('NFS', 'CIFS', 'GlusterFS', 'HDFS', )
        share_networks = manila.share_network_list(request)
        share_types = manila.share_type_list(request)
        self.fields['share_type'].choices = (
            [("", "")] + [(st.name, st.name) for st in share_types])
        self.fields['share_proto'].choices = [(sp, sp) for sp in share_protos]
        if "snapshot_id" in request.GET:
            try:
                snapshot = self.get_snapshot(request,
                                             request.GET["snapshot_id"])
                self.fields['name'].initial = snapshot.name
                self.fields['size'].initial = snapshot.size
                self.fields['snapshot'].choices = ((snapshot.id, snapshot),)
                try:
                    # Set the share type from the original share
                    orig_share = manila.share_get(request, snapshot.share_id)
                    self.fields['share_type'].initial = orig_share.share_type
                except Exception:
                    pass
                self.fields['size'].help_text = _(
                    'Share size must be equal to or greater than the snapshot '
                    'size (%sGB)') % snapshot.size
                del self.fields['share_source_type']
            except Exception:
                exceptions.handle(request,
                                  _('Unable to load the specified snapshot.'))
        else:
            source_type_choices = []

            try:
                snapshot_list = manila.share_snapshot_list(request)
                snapshots = [s for s in snapshot_list
                             if s.status == 'available']
                if snapshots:
                    source_type_choices.append(("snapshot",
                                                _("Snapshot")))
                    choices = [('', _("Choose a snapshot"))] + \
                              [(s.id, s) for s in snapshots]
                    self.fields['snapshot'].choices = choices
                else:
                    del self.fields['snapshot']
            except Exception:
                exceptions.handle(request, _("Unable to retrieve "
                                  "share snapshots."))

            if source_type_choices:
                choices = ([('no_source_type',
                             _("No source, empty share"))] +
                           source_type_choices)
                self.fields['share_source_type'].choices = choices
            else:
                del self.fields['share_source_type']

        self.sn_field_name_prefix = 'share-network-choices-'
        for st in share_types:
            extra_specs = st.get_keys()
            dhss = extra_specs.get('driver_handles_share_servers')
            # NOTE(vponomaryov): Set and tie share-network field only for
            # share types with enabled handling of share servers.
            if (isinstance(dhss, six.string_types) and
                    dhss.lower() in ['true', '1']):
                sn_choices = (
                    [('', '')] +
                    [(sn.id, sn.name or sn.id) for sn in share_networks])
                sn_field_name = self.sn_field_name_prefix + st.name
                sn_field = forms.ChoiceField(
                    label=_("Share Network"), required=True,
                    choices=sn_choices,
                    widget=forms.Select(attrs={
                        'class': 'switched',
                        'data-switch-on': 'sharetype',
                        'data-sharetype-%s' % st.name: _("Share Network"),
                    }))
                self.fields.insert(5, sn_field_name, sn_field)
예제 #17
0
    def __init__(self, request, *args, **kwargs):
        super(CreateForm, self).__init__(request, *args, **kwargs)
        # NOTE(vkmc): choose only those share protocols that are enabled
        # FIXME(vkmc): this should be better implemented by having a
        # capabilities endpoint on the control plane.
        manila_features = getattr(settings, 'OPENSTACK_MANILA_FEATURES', {})
        self.enabled_share_protocols = manila_features.get(
            'enabled_share_protocols',
            ['NFS', 'CIFS', 'GlusterFS', 'HDFS', 'CephFS', 'MapRFS'])
        self.enable_public_shares = manila_features.get(
            'enable_public_shares', True)
        share_networks = manila.share_network_list(request)
        share_types = manila.share_type_list(request)
        self.fields['share_type'].choices = (
            [("", "")] + [(st.name, st.name) for st in share_types])

        availability_zones = manila.availability_zone_list(request)
        self.fields['availability_zone'].choices = (
            [("", "")] + [(az.name, az.name) for az in availability_zones])

        if features.is_share_groups_enabled():
            share_groups = manila.share_group_list(request)
            self.fields['sg'] = forms.ChoiceField(
                label=_("Share Group"),
                choices=[("", "")] + [(sg.id, sg.name or sg.id)
                                      for sg in share_groups],
                required=False)

        self.sn_field_name_prefix = 'share-network-choices-'
        for st in share_types:
            extra_specs = st.get_keys()
            dhss = extra_specs.get('driver_handles_share_servers')
            # NOTE(vponomaryov): Set and tie share-network field only for
            # share types with enabled handling of share servers.
            if (isinstance(dhss, six.string_types) and
                    dhss.lower() in ['true', '1']):
                sn_choices = (
                    [('', '')] +
                    [(sn.id, sn.name or sn.id) for sn in share_networks])
                sn_field_name = self.sn_field_name_prefix + st.name
                sn_field = forms.ChoiceField(
                    label=_("Share Network"), required=True,
                    choices=sn_choices,
                    widget=forms.Select(attrs={
                        'class': 'switched',
                        'data-switch-on': 'sharetype',
                        'data-sharetype-%s' % st.name: _("Share Network"),
                    }))
                self.fields[sn_field_name] = sn_field

        self.fields['share_source_type'] = forms.ChoiceField(
            label=_("Share Source"), required=False,
            widget=forms.Select(
                attrs={'class': 'switchable', 'data-slug': 'source'}))
        self.fields['snapshot'] = forms.ChoiceField(
            label=_("Use snapshot as a source"),
            widget=forms.fields.SelectWidget(
                attrs={'class': 'switched',
                       'data-switch-on': 'source',
                       'data-source-snapshot': _('Snapshot')},
                data_attrs=('size', 'name'),
                transform=lambda x: "%s (%sGiB)" % (x.name, x.size)),
            required=False)
        self.fields['metadata'] = forms.CharField(
            label=_("Metadata"), required=False,
            widget=forms.Textarea(attrs={'rows': 4}))

        if self.enable_public_shares:
            self.fields['is_public'] = forms.BooleanField(
                label=_("Make visible for all"), required=False,
                help_text=(
                    "If set then all tenants will be able to see this share."))

        self.fields['share_proto'].choices = [(sp, sp) for sp in
                                              self.enabled_share_protocols]
        if ("snapshot_id" in request.GET or
                kwargs.get("data", {}).get("snapshot")):
            try:
                snapshot = self.get_snapshot(
                    request,
                    request.GET.get("snapshot_id",
                                    kwargs.get("data", {}).get("snapshot")))
                self.fields['name'].initial = snapshot.name
                self.fields['size'].initial = snapshot.size
                self.fields['snapshot'].choices = ((snapshot.id, snapshot),)
                try:
                    # Set the share type from the original share
                    orig_share = manila.share_get(request, snapshot.share_id)
                    # NOTE(vponomaryov): we should use share type name, not ID,
                    # because we use names in our choices above.
                    self.fields['share_type'].initial = (
                        orig_share.share_type_name)
                except Exception:
                    pass
                self.fields['size'].help_text = _(
                    'Share size must be equal to or greater than the snapshot '
                    'size (%sGiB)') % snapshot.size
                del self.fields['share_source_type']
            except Exception:
                exceptions.handle(request,
                                  _('Unable to load the specified snapshot.'))
        else:
            source_type_choices = []

            try:
                snapshot_list = manila.share_snapshot_list(request)
                snapshots = [s for s in snapshot_list
                             if s.status == 'available']
                if snapshots:
                    source_type_choices.append(("snapshot",
                                                _("Snapshot")))
                    choices = [('', _("Choose a snapshot"))] + \
                              [(s.id, s) for s in snapshots]
                    self.fields['snapshot'].choices = choices
                else:
                    del self.fields['snapshot']
            except Exception:
                exceptions.handle(request, _("Unable to retrieve "
                                             "share snapshots."))

            if source_type_choices:
                choices = ([('no_source_type',
                             _("No source, empty share"))] +
                           source_type_choices)
                self.fields['share_source_type'].choices = choices
            else:
                del self.fields['share_source_type']
예제 #18
0
    def __init__(self, request, *args, **kwargs):
        super(CreateForm, self).__init__(request, *args, **kwargs)
        # NOTE(vkmc): choose only those share protocols that are enabled
        # FIXME(vkmc): this should be better implemented by having a
        # capabilities endpoint on the control plane.
        manila_features = getattr(settings, 'OPENSTACK_MANILA_FEATURES', {})
        self.enabled_share_protocols = manila_features.get(
            'enabled_share_protocols',
            ['NFS', 'CIFS', 'GlusterFS', 'HDFS', 'CephFS', 'MapRFS'])
        self.enable_public_shares = manila_features.get(
            'enable_public_shares', True)
        share_networks = manila.share_network_list(request)
        share_types = manila.share_type_list(request)
        self.fields['share_type'].choices = (
            [("", "")] + [(utils.transform_dashed_name(st.name), st.name)
                          for st in share_types])

        availability_zones = manila.availability_zone_list(request)
        self.fields['availability_zone'].choices = (
            [("", "")] + [(az.name, az.name) for az in availability_zones])

        if features.is_share_groups_enabled():
            share_groups = manila.share_group_list(request)
            self.fields['sg'] = forms.ChoiceField(label=_("Share Group"),
                                                  choices=[("", "")] +
                                                  [(sg.id, sg.name or sg.id)
                                                   for sg in share_groups],
                                                  required=False)

        self.sn_field_name_prefix = 'share-network-choices-'
        for st in share_types:
            extra_specs = st.get_keys()
            dhss = extra_specs.get('driver_handles_share_servers')
            # NOTE(vponomaryov): Set and tie share-network field only for
            # share types with enabled handling of share servers.
            if (isinstance(dhss, str) and dhss.lower() in ['true', '1']):
                sn_choices = ([('', '')] + [(sn.id, sn.name or sn.id)
                                            for sn in share_networks])
                sn_field_name = (self.sn_field_name_prefix +
                                 utils.transform_dashed_name(st.name))
                sn_field = forms.ChoiceField(
                    label=_("Share Network"),
                    required=True,
                    choices=sn_choices,
                    widget=forms.Select(
                        attrs={
                            'class':
                            'switched',
                            'data-switch-on':
                            'sharetype',
                            'data-sharetype-%s' % utils.transform_dashed_name(st.name):
                            _("Share Network"),
                        }))
                self.fields[sn_field_name] = sn_field

        self.fields['share_source_type'] = forms.ChoiceField(
            label=_("Share Source"),
            required=False,
            widget=forms.Select(attrs={
                'class': 'switchable',
                'data-slug': 'source'
            }))
        self.fields['snapshot'] = forms.ChoiceField(
            label=_("Use snapshot as a source"),
            widget=forms.fields.SelectWidget(attrs={
                'class':
                'switched',
                'data-switch-on':
                'source',
                'data-source-snapshot':
                _('Snapshot')
            },
                                             data_attrs=('size', 'name'),
                                             transform=lambda x: "%s (%sGiB)" %
                                             (x.name, x.size)),
            required=False)
        self.fields['metadata'] = forms.CharField(
            label=_("Metadata"),
            required=False,
            widget=forms.Textarea(attrs={'rows': 4}))

        if self.enable_public_shares:
            self.fields['is_public'] = forms.BooleanField(
                label=_("Make visible to users from all projects"),
                required=False)

        self.fields['share_proto'].choices = [
            (sp, sp) for sp in self.enabled_share_protocols
        ]
        if ("snapshot_id" in request.GET
                or kwargs.get("data", {}).get("snapshot")):
            try:
                snapshot = self.get_snapshot(
                    request,
                    request.GET.get("snapshot_id",
                                    kwargs.get("data", {}).get("snapshot")))
                self.fields['name'].initial = snapshot.name
                self.fields['size'].initial = snapshot.size
                self.fields['snapshot'].choices = ((snapshot.id, snapshot), )
                try:
                    # Set the share type and az from the original share
                    orig_share = manila.share_get(request, snapshot.share_id)
                    self.fields['share_type'].initial = (
                        orig_share.share_type_name)
                    self.fields['availability_zone'].initial = (
                        orig_share.availability_zone)
                except Exception:
                    pass
                self.fields['size'].help_text = _(
                    'Share size must be equal to or greater than the snapshot '
                    'size (%sGiB)') % snapshot.size
                del self.fields['share_source_type']
            except Exception:
                exceptions.handle(request,
                                  _('Unable to load the specified snapshot.'))
        else:
            source_type_choices = []

            try:
                snapshot_list = manila.share_snapshot_list(request)
                snapshots = [
                    s for s in snapshot_list if s.status == 'available'
                ]
                if snapshots:
                    source_type_choices.append(("snapshot", _("Snapshot")))
                    choices = [('', _("Choose a snapshot"))] + \
                              [(s.id, s) for s in snapshots]
                    self.fields['snapshot'].choices = choices
                else:
                    del self.fields['snapshot']
            except Exception:
                exceptions.handle(request,
                                  _("Unable to retrieve "
                                    "share snapshots."))

            if source_type_choices:
                choices = ([('no_source_type', _("No source, empty share"))] +
                           source_type_choices)
                self.fields['share_source_type'].choices = choices
            else:
                del self.fields['share_source_type']
예제 #19
0
    def __init__(self, request, *args, **kwargs):
        super(CreateForm, self).__init__(request, *args, **kwargs)
        share_protos = ('NFS', 'CIFS', 'GlusterFS', 'HDFS', 'CephFS')
        share_networks = manila.share_network_list(request)
        share_types = manila.share_type_list(request)
        self.fields['share_type'].choices = ([("", "")] +
                                             [(st.name, st.name)
                                              for st in share_types])
        availability_zones = nova.availability_zone_list(request)
        self.fields['availability_zone'].choices = (
            [("", "")] + [(az.zoneName, az.zoneName)
                          for az in availability_zones])

        self.sn_field_name_prefix = 'share-network-choices-'
        for st in share_types:
            extra_specs = st.get_keys()
            dhss = extra_specs.get('driver_handles_share_servers')
            # NOTE(vponomaryov): Set and tie share-network field only for
            # share types with enabled handling of share servers.
            if (isinstance(dhss, six.string_types)
                    and dhss.lower() in ['true', '1']):
                sn_choices = ([('', '')] + [(sn.id, sn.name or sn.id)
                                            for sn in share_networks])
                sn_field_name = self.sn_field_name_prefix + st.name
                sn_field = forms.ChoiceField(
                    label=_("Share Network"),
                    required=True,
                    choices=sn_choices,
                    widget=forms.Select(
                        attrs={
                            'class': 'switched',
                            'data-switch-on': 'sharetype',
                            'data-sharetype-%s' % st.name: _("Share Network"),
                        }))
                self.fields[sn_field_name] = sn_field

        self.fields['share_source_type'] = forms.ChoiceField(
            label=_("Share Source"),
            required=False,
            widget=forms.Select(attrs={
                'class': 'switchable',
                'data-slug': 'source'
            }))
        self.fields['snapshot'] = forms.ChoiceField(
            label=_("Use snapshot as a source"),
            widget=forms.fields.SelectWidget(attrs={
                'class':
                'switched',
                'data-switch-on':
                'source',
                'data-source-snapshot':
                _('Snapshot')
            },
                                             data_attrs=('size', 'name'),
                                             transform=lambda x: "%s (%sGiB)" %
                                             (x.name, x.size)),
            required=False)
        self.fields['metadata'] = forms.CharField(
            label=_("Metadata"),
            required=False,
            widget=forms.Textarea(attrs={'rows': 4}))
        self.fields['is_public'] = forms.BooleanField(
            label=_("Make visible for all"),
            required=False,
            help_text=(
                "If set then all tenants will be able to see this share."))

        self.fields['share_proto'].choices = [(sp, sp) for sp in share_protos]
        if "snapshot_id" in request.GET:
            try:
                snapshot = self.get_snapshot(request,
                                             request.GET["snapshot_id"])
                self.fields['name'].initial = snapshot.name
                self.fields['size'].initial = snapshot.size
                self.fields['snapshot'].choices = ((snapshot.id, snapshot), )
                try:
                    # Set the share type from the original share
                    orig_share = manila.share_get(request, snapshot.share_id)
                    self.fields['share_type'].initial = orig_share.share_type
                except Exception:
                    pass
                self.fields['size'].help_text = _(
                    'Share size must be equal to or greater than the snapshot '
                    'size (%sGiB)') % snapshot.size
                del self.fields['share_source_type']
            except Exception:
                exceptions.handle(request,
                                  _('Unable to load the specified snapshot.'))
        else:
            source_type_choices = []

            try:
                snapshot_list = manila.share_snapshot_list(request)
                snapshots = [
                    s for s in snapshot_list if s.status == 'available'
                ]
                if snapshots:
                    source_type_choices.append(("snapshot", _("Snapshot")))
                    choices = [('', _("Choose a snapshot"))] + \
                              [(s.id, s) for s in snapshots]
                    self.fields['snapshot'].choices = choices
                else:
                    del self.fields['snapshot']
            except Exception:
                exceptions.handle(request,
                                  _("Unable to retrieve "
                                    "share snapshots."))

            if source_type_choices:
                choices = ([('no_source_type', _("No source, empty share"))] +
                           source_type_choices)
                self.fields['share_source_type'].choices = choices
            else:
                del self.fields['share_source_type']
예제 #20
0
파일: forms.py 프로젝트: ajarr/manila-ui
    def __init__(self, request, *args, **kwargs):
        super(CreateForm, self).__init__(request, *args, **kwargs)
        share_protos = ('NFS', 'CIFS', 'GlusterFS', 'HDFS', 'CephFS')
        share_networks = manila.share_network_list(request)
        share_types = manila.share_type_list(request)
        self.fields['share_type'].choices = (
            [("", "")] + [(st.name, st.name) for st in share_types])
        availability_zones = nova.availability_zone_list(request)
        self.fields['availability_zone'].choices = (
            [("", "")] +
            [(az.zoneName, az.zoneName) for az in availability_zones])

        self.sn_field_name_prefix = 'share-network-choices-'
        for st in share_types:
            extra_specs = st.get_keys()
            dhss = extra_specs.get('driver_handles_share_servers')
            # NOTE(vponomaryov): Set and tie share-network field only for
            # share types with enabled handling of share servers.
            if (isinstance(dhss, six.string_types) and
                    dhss.lower() in ['true', '1']):
                sn_choices = (
                    [('', '')] +
                    [(sn.id, sn.name or sn.id) for sn in share_networks])
                sn_field_name = self.sn_field_name_prefix + st.name
                sn_field = forms.ChoiceField(
                    label=_("Share Network"), required=True,
                    choices=sn_choices,
                    widget=forms.Select(attrs={
                        'class': 'switched',
                        'data-switch-on': 'sharetype',
                        'data-sharetype-%s' % st.name: _("Share Network"),
                    }))
                self.fields[sn_field_name] = sn_field

        self.fields['share_source_type'] = forms.ChoiceField(
            label=_("Share Source"), required=False,
            widget=forms.Select(
                attrs={'class': 'switchable', 'data-slug': 'source'}))
        self.fields['snapshot'] = forms.ChoiceField(
            label=_("Use snapshot as a source"),
            widget=forms.fields.SelectWidget(
                attrs={'class': 'switched',
                       'data-switch-on': 'source',
                       'data-source-snapshot': _('Snapshot')},
                data_attrs=('size', 'name'),
                transform=lambda x: "%s (%sGiB)" % (x.name, x.size)),
            required=False)
        self.fields['metadata'] = forms.CharField(
            label=_("Metadata"), required=False,
            widget=forms.Textarea(attrs={'rows': 4}))
        self.fields['is_public'] = forms.BooleanField(
            label=_("Make visible for all"), required=False,
            help_text=(
                "If set then all tenants will be able to see this share."))

        self.fields['share_proto'].choices = [(sp, sp) for sp in share_protos]
        if "snapshot_id" in request.GET:
            try:
                snapshot = self.get_snapshot(request,
                                             request.GET["snapshot_id"])
                self.fields['name'].initial = snapshot.name
                self.fields['size'].initial = snapshot.size
                self.fields['snapshot'].choices = ((snapshot.id, snapshot),)
                try:
                    # Set the share type from the original share
                    orig_share = manila.share_get(request, snapshot.share_id)
                    self.fields['share_type'].initial = orig_share.share_type
                except Exception:
                    pass
                self.fields['size'].help_text = _(
                    'Share size must be equal to or greater than the snapshot '
                    'size (%sGiB)') % snapshot.size
                del self.fields['share_source_type']
            except Exception:
                exceptions.handle(request,
                                  _('Unable to load the specified snapshot.'))
        else:
            source_type_choices = []

            try:
                snapshot_list = manila.share_snapshot_list(request)
                snapshots = [s for s in snapshot_list
                             if s.status == 'available']
                if snapshots:
                    source_type_choices.append(("snapshot",
                                                _("Snapshot")))
                    choices = [('', _("Choose a snapshot"))] + \
                              [(s.id, s) for s in snapshots]
                    self.fields['snapshot'].choices = choices
                else:
                    del self.fields['snapshot']
            except Exception:
                exceptions.handle(request, _("Unable to retrieve "
                                  "share snapshots."))

            if source_type_choices:
                choices = ([('no_source_type',
                             _("No source, empty share"))] +
                           source_type_choices)
                self.fields['share_source_type'].choices = choices
            else:
                del self.fields['share_source_type']