class SelectPolicyRuleSetAction(workflows.Action):
    provided_policy_rule_set = fields.TransferTableField(
        label=_("Provided Policy Rule Set"),
        help_text=_("Choose a policy rule set for an Group."),
        add_item_link=POLICY_RULE_SET_URL,
        required=False)
    consumed_policy_rule_set = fields.TransferTableField(
        label=_("Consumed Policy Rule Set"),
        help_text=_("Select consumed policy rule set for Group."),
        add_item_link=POLICY_RULE_SET_URL,
        required=False)

    class Meta(object):
        name = _("Application Policy")
        help_text = _("Select Policy Rule Set for Group.")

    def _policy_rule_set_list(self, request):
        policy_rule_sets = client.policy_rule_set_list(
            request, tenant_id=request.user.tenant_id)
        for c in policy_rule_sets:
            c.set_id_as_name_if_empty()
        policy_rule_sets = sorted(policy_rule_sets, key=lambda rule: rule.name)
        return [(c.id, c.name) for c in policy_rule_sets]

    def populate_provided_policy_rule_set_choices(self, request, context):
        policy_rule_set_list = []
        try:
            policy_rule_set_list = self._policy_rule_set_list(request)
        except Exception as e:
            msg = _('Unable to retrieve policy rule set. %s.') % (str(e))
            exceptions.handle(request, msg)
        return policy_rule_set_list

    def populate_consumed_policy_rule_set_choices(self, request, context):
        policy_rule_set_list = []
        try:
            policy_rule_set_list = self._policy_rule_set_list(request)
        except Exception as e:
            msg = _('Unable to retrieve policy rule set. %s.') % (str(e))
            exceptions.handle(request, msg)
        return policy_rule_set_list
class UpdatePolicyRuleForm(BaseUpdateForm):
    name = forms.CharField(max_length=80, label=_("Name"), required=False)
    description = forms.CharField(label=_("Description"), required=False)
    policy_classifier_id = forms.ChoiceField(label=_("Policy Classifier"))
    policy_actions = fields.TransferTableField(
        label=_("Policy Actions"),
        required=False,
    )

    shared = forms.BooleanField(label=_("Shared"), required=False)

    def __init__(self, request, *args, **kwargs):
        super(UpdatePolicyRuleForm, self).__init__(request, *args, **kwargs)
        try:
            policyrule_id = self.initial['policyrule_id']
            rule = client.policyrule_get(request, policyrule_id)

            for item in ['name', 'description',
                         'policy_classifier_id', 'policy_actions', 'shared']:
                self.fields[item].initial = getattr(rule, item)

            actions = client.policyaction_list(request,
                tenant_id=request.user.tenant_id)
            for action in actions:
                action.set_id_as_name_if_empty()
            actions = sorted(actions, key=lambda action: action.name)
            action_list = [(a.id, a.name) for a in actions]
            self.fields['policy_actions'].choices = action_list

            classifiers = client.policyclassifier_list(request,
                tenant_id=request.user.tenant_id)
            classifier_list = [(c.id, c.name) for c in classifiers]
            self.fields['policy_classifier_id'].choices = classifier_list
        except Exception:
            exceptions.handle(
                request, _("Unable to retrive policy rule details."))

    def handle(self, request, context):
        url = reverse('horizon:project:application_policy:index')
        try:
            prid = self.initial['policyrule_id']
            if context.get('name'):
                context['name'] = html.escape(context['name'])
            if context.get('description'):
                context['description'] = html.escape(context['description'])
            client.policyrule_update(request, prid, **context)
            messages.success(request, _('Policy rule successfully updated.'))
            return http.HttpResponseRedirect(url)
        except Exception as e:
            msg = _("Unable to update policy rule. %s") % (str(e))
            exceptions.handle(request, msg, redirect=url)
class UpdatePolicyRuleSetForm(BaseUpdateForm):
    name = forms.CharField(label=_("Name"))
    description = forms.CharField(label=_("Description"), required=False)
    policy_rules = fields.TransferTableField(label=_("Policy Rules"), )
    shared = forms.BooleanField(label=_("Shared"), required=False)

    def __init__(self, request, *args, **kwargs):
        super(UpdatePolicyRuleSetForm, self).__init__(request, *args, **kwargs)
        rules = []
        try:
            items = client.policyrule_list(request,
                tenant_id=request.user.tenant_id)
            rules = [(p.id, p.name) for p in items]
            policy_rule_set = client.policy_rule_set_get(
                request, self.initial['policy_rule_set_id'])
            if policy_rule_set:
                self.fields['name'].initial = policy_rule_set.name
                self.fields[
                    'description'].initial = policy_rule_set.description
                self.fields['shared'].initial = policy_rule_set.shared
                existing = [item for item in policy_rule_set.policy_rules]
                self.fields['policy_rules'].initial = existing
        except Exception:
            exceptions.handle(request, _('Unable to retrieve policy rules'))
        self.fields['policy_rules'].choices = rules

    def handle(self, request, context):
        try:
            policy_rule_set_id = self.initial['policy_rule_set_id']
            if context.get('name'):
                context['name'] = html.escape(context['name'])
            if context.get('description'):
                context['description'] = html.escape(context['description'])
            client.policy_rule_set_update(request,
                                          policy_rule_set_id,
                                          **context
                                          )
            messages.success(request, _('PolicyRuleSet successfully updated.'))
            url = reverse('horizon:project:application_policy:index')
            return http.HttpResponseRedirect(url)
        except Exception:
            redirect = reverse('horizon:project:policy_rule_sets:index')
            exceptions.handle(
                request, _("Unable to update policy_rule_set."),
                redirect=redirect)
class CreateServicePolicyForm(forms.SelfHandlingForm):
    name = forms.CharField(max_length=80, label=_("Name"))
    description = forms.CharField(max_length=80,
                                  label=_("Description"),
                                  required=False)
    network_service_params = fields.TransferTableField(
        label=_("Network Service Parameters"),
        add_item_link=NETWORK_PARAM_URL,
        required=False)
    shared = forms.BooleanField(label=_("Shared"),
                                initial=False,
                                required=False)

    def handle(self, request, context):
        url = reverse("horizon:project:network_policy:index")
        try:
            params = context['network_service_params']
            p = []
            if len(params) > 0:
                for item in params:
                    values = [i.split(":")[1] for i in item.split(",")]
                    values = {
                        'type': values[0],
                        'name': values[1],
                        'value': values[2]
                    }
                    p.append(values)
            context['network_service_params'] = p
            if context.get('name'):
                context['name'] = html.escape(context['name'])
            if context.get('description'):
                context['description'] = html.escape(context['description'])
            client.create_networkservice_policy(request, **context)
            msg = _("Service policy created successfully!")
            LOG.debug(msg)
            return http.HttpResponseRedirect(url)
        except Exception as e:
            msg = _("Failed to create service policy. %s") % (str(e))
            LOG.error(msg)
            exceptions.handle(request, msg, redirect=url)
Exemple #5
0
class UpdatePolicyTargetForm(forms.SelfHandlingForm):
    name = forms.CharField(max_length=80, label=_("Name"), required=False)
    description = forms.CharField(max_length=80,
                                  label=_("Description"),
                                  required=False)
    provided_policy_rule_sets = fields.TransferTableField(
        label=_("Provided Policy Rule Set"), required=False)
    consumed_policy_rule_sets = fields.TransferTableField(
        label=_("Consumed Policy Rule Set"), required=False)
    l2_policy_id = forms.ChoiceField(
        label=_("Network Policy"),
        required=False,
        help_text=_("Select network policy for Group."))
    network_service_policy_id = forms.ChoiceField(
        label=_("Network Services Policy"),
        required=False,
        help_text=_("Select network services policy for Group."))
    shared = forms.BooleanField(label=_("Shared"), required=False)
    failure_url = 'horizon:project:policytargets:index'

    def __init__(self, request, *args, **kwargs):
        super(UpdatePolicyTargetForm, self).__init__(request, *args, **kwargs)
        try:
            policy_target_id = self.initial['policy_target_id']
            policy_target = client.policy_target_get(request, policy_target_id)
            policy_rule_sets = client.policy_rule_set_list(
                request, tenant_id=request.user.tenant_id)
            for c in policy_rule_sets:
                c.set_id_as_name_if_empty()
            policy_rule_sets = sorted(policy_rule_sets,
                                      key=lambda rule: rule.name)
            policy_rule_set_list = [(c.id, c.name) for c in policy_rule_sets]
            self.fields[
                'provided_policy_rule_sets'].choices = policy_rule_set_list
            self.fields[
                'consumed_policy_rule_sets'].choices = policy_rule_set_list
            provided_init = []
            consumed_init = []
            for item in policy_rule_set_list:
                if item[0] in policy_target.provided_policy_rule_sets:
                    provided_init.append(item[0])
                if item[0] in policy_target.consumed_policy_rule_sets:
                    consumed_init.append(item[0])
            self.fields['provided_policy_rule_sets'].initial = provided_init
            self.fields['consumed_policy_rule_sets'].initial = consumed_init
            n_policies = client.l2policy_list(request,
                                              tenant_id=request.user.tenant_id)
            ns_policies = client.networkservicepolicy_list(
                request, tenant_id=request.user.tenant_id)
            n_policies = [(item.id, item.name) for item in n_policies]
            ns_policies = [(item.id, item.name) for item in ns_policies]
            ns_policies.insert(0, ('None', 'None'))
            self.fields['l2_policy_id'].choices = n_policies
            self.fields['network_service_policy_id'].choices = ns_policies
            for i in [
                    'name', 'description', 'l2_policy_id',
                    'network_service_policy_id', 'shared'
            ]:
                self.fields[i].initial = getattr(policy_target, i)
        except Exception as e:
            msg = _('Unable to retrieve policy_rule_set details. %s') % (
                str(e))
            exceptions.handle(request, msg)
            pass

    def clean(self):
        cleaned_data = super(UpdatePolicyTargetForm, self).clean()
        updated_data = {
            d: cleaned_data[d]
            for d in cleaned_data if d in self.changed_data
        }
        return updated_data

    def handle(self, request, context):
        policy_target_id = self.initial['policy_target_id']
        name_or_id = context.get('name') or policy_target_id
        try:
            if 'provided_policy_rule_sets' in context:
                if context.get('provided_policy_rule_sets'):
                    context['provided_policy_rule_sets'] = dict([
                        (i, 'string')
                        for i in context['provided_policy_rule_sets']
                    ])
                else:
                    context['provided_policy_rule_sets'] = None
            if 'consumed_policy_rule_sets' in context:
                if context.get('consumed_policy_rule_sets'):
                    context['consumed_policy_rule_sets'] = dict([
                        (i, 'string')
                        for i in context['consumed_policy_rule_sets']
                    ])
                else:
                    context['consumed_policy_rule_sets'] = None
            if context.get('network_service_policy_id') == 'None':
                context['network_service_policy_id'] = None
            if context.get('name'):
                context['name'] = html.escape(context['name'])
            if context.get('description'):
                context['description'] = html.escape(context['description'])
            policy_target = client.policy_target_update(
                request, policy_target_id, **context)
            msg = _('Group %s was successfully updated.') % name_or_id
            LOG.debug(msg)
            messages.success(request, msg)
            return policy_target
        except Exception as e:
            msg = _('Failed to update Group %(name)s. %(reason)s') % {
                'name': name_or_id,
                'reason': str(e)
            }
            LOG.error(msg)
            redirect = reverse(self.failure_url)
            exceptions.handle(request, msg, redirect=redirect)
class CreateExternalConnectivityForm(forms.SelfHandlingForm):
    name = forms.CharField(max_length=80, label=_("Name"))
    description = forms.CharField(max_length=80,
                                  label=_("Description"),
                                  required=False)
    ip_version = forms.ChoiceField(
        choices=[(4, 'IPv4'), (6, 'IPv6')],
        widget=forms.Select(attrs={
            'class': 'switchable',
            'data-slug': 'ipversion',
        }),
        label=_("IP Version"))
    cidr = forms.IPField(label=_("CIDR"),
                         initial="",
                         required=False,
                         help_text=_("Network address in CIDR format "
                                     "(e.g. 192.168.0.0/24,"
                                     "2001:DB8::/48)"),
                         version=forms.IPv4 | forms.IPv6,
                         mask=True)
    external_routes = fields.TransferTableField(label=_("External Routes"),
                                                add_item_link=ROUTE_URL,
                                                required=False)
    subnet_id = forms.ChoiceField(label=_("Subnet ID"), required=False)
    port_address_translation = forms.BooleanField(
        label=_("Port Address Translation"), initial=False, required=False)
    shared = forms.BooleanField(label=_("Shared"),
                                initial=False,
                                required=False)

    def __init__(self, request, *args, **kwargs):
        super(CreateExternalConnectivityForm,
              self).__init__(request, *args, **kwargs)
        net_id_list = []
        dic = {"router:external": True}
        try:
            net_list = api.neutron.network_list(request, **dic)
            subnet_list = api.neutron.subnet_list(request)
            net_id_list = [net.id for net in net_list]
            self.fields['subnet_id'].choices = [('', 'Select')] + \
                [(subnet.id, subnet.name) for subnet in subnet_list
                if subnet.network_id in net_id_list]
        except Exception:
            msg = _("Failed to get Subnet ID list.")
            exceptions.handle(request, msg)

    def handle(self, request, context):
        try:
            if context['subnet_id'] == '':
                del context['subnet_id']
            if context['cidr'] == '':
                del context['cidr']
            routes = context['external_routes']
            p = []
            if len(routes) > 0:
                for item in routes:
                    values = [i.split(":")[1] for i in item.split(",")]
                    values = {'destination': values[0], 'nexthop': values[1]}
                    p.append(values)
            context['external_routes'] = p
            external_segment = client.create_externalconnectivity(
                request, **context)
            msg = _('External Connectivity successfully created.')
            LOG.debug(msg)
            messages.success(request, msg)
            return external_segment
        except Exception as e:
            msg = str(e)
            LOG.error(msg)
            exceptions.handle(request, msg, redirect=shortcuts.redirect)
class AddL3PolicyForm(forms.SelfHandlingForm):
    name = forms.CharField(max_length=80, label=_("Name"))
    description = forms.CharField(max_length=80,
                                  label=_("Description"),
                                  required=False)
    ip_version = forms.ChoiceField(
        choices=[(4, 'IPv4'), (6, 'IPv6')],
        widget=forms.Select(attrs={
            'class': 'switchable',
            'data-slug': 'ipversion',
        }),
        label=_("IP Version"))
    ip_pool = forms.IPField(label=_("IP Pool"),
                            initial="",
                            help_text=_("Network address in CIDR format "
                                        "(e.g. 192.168.0.0/24,"
                                        "2001:DB8::/48)"),
                            version=forms.IPv4 | forms.IPv6,
                            mask=True)
    subnet_prefix_length = forms.CharField(
        max_length=80,
        label=_("Subnet Prefix Length"),
        help_text=_("Between 2 - 30 for IP4"
                    "and 2-127 for IP6."),
    )
    external_segments = fields.TransferTableField(
        label=_("External Segments"),
        add_item_link=EXT_SEG_PARAM_URL,
        required=False)
    shared = forms.BooleanField(label=_("Shared"),
                                initial=False,
                                required=False)

    def __init__(self, request, *args, **kwargs):
        super(AddL3PolicyForm, self).__init__(request, *args, **kwargs)

    def clean(self):
        cleaned_data = super(AddL3PolicyForm, self).clean()
        if self.is_valid():
            ipversion = int(cleaned_data['ip_version'])
            subnet_prefix_length = int(cleaned_data['subnet_prefix_length'])
            msg = _("Subnet prefix out of range.")
            if ipversion == 4 and subnet_prefix_length not in range(2, 31):
                raise forms.ValidationError(msg)
            if ipversion == 6 and subnet_prefix_length not in range(2, 128):
                raise forms.ValidationError(msg)
        return cleaned_data

    def handle(self, request, context):
        url = reverse("horizon:project:network_policy:index")
        external_segment_dic = {}
        try:
            if context['external_segments']:
                dic = {}
                for external_segment in context['external_segments']:
                    values = [
                        i.split(":")[1] for i in external_segment.split(",")
                    ]
                    dic[values[0]] = [values[1]]
                    external_segment_dic.update(dic)
                context['external_segments'] = external_segment_dic
            else:
                context['external_segments'] = {}
            if context.get('name'):
                context['name'] = html.escape(context['name'])
            if context.get('description'):
                context['description'] = html.escape(context['description'])
            client.l3policy_create(request, **context)
            msg = _("L3 Policy Created Successfully!")
            LOG.debug(msg)
            return http.HttpResponseRedirect(url)
        except Exception as e:
            exceptions.handle(request, str(e), redirect=url)