class UpdateSubnetInfoAction(CreateSubnetInfoAction): cidr = fields.IPField( label=_("Network Address"), required=False, initial="", widget=forms.TextInput(attrs={'readonly': 'readonly'}), help_text=_("Network address in CIDR format " "(e.g. 192.168.0.0/24)"), version=fields.IPv4 | fields.IPv6, mask=True) ipam = forms.DynamicTypedChoiceField(label=_("IPAM"), required=False, empty_value=None, widget=forms.HiddenInput(), help_text=_( "Choose IPAM that will be " "associated with the IP Block")) # NOTE(amotoki): When 'disabled' attribute is set for the ChoiceField # and ValidationError is raised for POST request, the initial value of # the ip_version ChoiceField is not set in the re-displayed form # As a result, 'IPv4' is displayed even when IPv6 is used if # ValidationError is detected. In addition 'required=True' check complains # when re-POST since the value of the ChoiceField is not set. # Thus now I use HiddenInput for the ip_version ChoiceField as a work # around. ip_version = forms.ChoiceField( choices=[(4, 'IPv4'), (6, 'IPv6')], #widget=forms.Select( # attrs={'disabled': 'disabled'}), widget=forms.HiddenInput(), label=_("IP Version")) gateway_ip = fields.IPField( label=_("Gateway IP (optional)"), required=False, initial="", help_text=_("IP address of Gateway (e.g. 192.168.0.254). " "You need to specify an explicit address " "to set the gateway. " "If you want to use no gateway, " "check 'Disable Gateway' below."), version=fields.IPv4 | fields.IPv6, mask=False) no_gateway = forms.BooleanField(label=_("Disable Gateway"), initial=False, required=False) class Meta: name = ("Subnet") help_text = _('You can update a subnet associated with the ' 'network. Advanced configuration are available ' 'at "Subnet Detail" tab.') def clean(self): cleaned_data = workflows.Action.clean(self) self._check_subnet_data(cleaned_data, is_create=False) return cleaned_data
class CreateSiteInfoAction(workflows.Action): with_site = forms.BooleanField( label=_("Add a remote Openstack cloud site to this VPN?"), initial=False, required=False) CHOICES = (('Data_Center_San_Jose_B', 'Enterprise Data Center in San Jose B'), ('Data_Center_Jorvas', 'Enterprise Data Center in Jorvas')) #sitechoice = forms.ChoiceField(required=False, label='Existent Enterprise Site:', choices=CHOICES) site_name = forms.CharField( max_length=255, label=_("Name of remote Openstack Site running VPN Agent:"), help_text=_("Remote Site Name. This field is " "optional."), required=False) keystone = fields.IPField( label=_("Remote Keystone IP Address:"), required=False, initial="10.126.71.249", help_text=_( "Remote Keystone Network address in IPv4 or IPv6 address format " "(e.g. 192.168.0.0)"), version=fields.IPv4 | fields.IPv6, mask=False) user = forms.CharField( max_length=255, label=_("Username in Remote site"), help_text=_( "Tenant's user LOGIN in Enterprise site. In case you do not want to provide a 24hours expiration token from your Enterprise Keystone " "each time you connect your VPN. This field is " "optional."), required=False) password = forms.CharField( label=_("Password:"******"User PASSWORD in Remote site used to generate the token. This field is " "optional."), widget=forms.PasswordInput(render_value=False), required=False) tenant = forms.CharField( label=_("and Tenant Name:"), help_text=_("Tenant's NAME in Enterprise site. This field is " "optional."), required=False) class Meta: name = ("Local and Remote Sites") help_text = _( 'You can add a Remote Openstack Provider Cloud Site as well as your Enterprise Site associated with the new ' 'VPN. You need to provide your credentials in remote site so that we generate a token on your behalf. ' ) def _check_site_data(self, cleaned_data, is_create=True): rke = cleaned_data.get('keystone') ws = cleaned_data.get('with_site') sn = cleaned_data.get('site_name') lg = cleaned_data.get('user') tn = cleaned_data.get('tenant') pw = cleaned_data.get('password') if not rke: msg = _('Specify "Enterprise Keystone IP Address" or ' 'clear "Add your Enterprise Site to this VPN" checkbox.') raise forms.ValidationError(msg) if rke: site = netaddr.IPNetwork(rke) # if site.version != ip_version: # msg = _('Keystone IP Address and IP version are inconsistent.') # raise forms.ValidationError(msg) if sn and not rke: msg = _( 'Make sure you added a keystone endpoint for you newly added site' ) raise forms.ValidationError(msg) #if sn and rke and not tk and not lg: # msg = _('Make sure you added a login if you do not provide a token for your new site') # raise forms.ValidationError(msg) if lg and not tn: msg = _('Make sure you added a tenant for the login your provided') raise forms.ValidationError(msg) if lg and not pw: msg = _( 'Make sure you added a password for the login your provided') raise forms.ValidationError(msg) def clean(self): cleaned_data = super(CreateSiteInfoAction, self).clean() with_site = cleaned_data.get('with_site') if not with_site: return cleaned_data self._check_site_data(cleaned_data) return cleaned_data
class AddRule(forms.SelfHandlingForm): id = forms.CharField(widget=forms.HiddenInput()) sequence_id = forms.ChoiceField(label=_('Sequence Id'), help_text=_("Choose the Sequence Id for " " this rule.")) simple_action = forms.ChoiceField(label=_('Action'), choices=[('pass', 'Pass'), ('deny', 'Deny')], help_text=_( "Actions that will be applied " " on the traffic that matches" " the rules")) protocol = forms.ChoiceField( label=_('IP Protocol'), choices=[('any', 'ANY'), ('tcp', 'TCP'), ('udp', 'UDP'), ('icmp', 'ICMP')], help_text=_("TCP, UDP, ICMP or All protocols")) direction = forms.ChoiceField(label=_('Direction'), choices=[('<>', '<> Bidirectional'), ('>', '> Unidirectional')], help_text=_("Direction of traffic on which" " the rule will be applied")) srctype = forms.ChoiceField(label=_('Source Type'), choices=[('srcnets', _('Source Network')), ('srccidr', _('Source CIDR')), ('srcpols', _('Source Network Policy'))], help_text=_('To specify an allowed IP ' 'range, select "CIDR". To ' 'allow access from a network ' 'select "Network". To ' 'allow access from a network ' 'policy select "Network Policy".'), widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'srctype' })) dsttype = forms.ChoiceField(label=_('Destination Type'), choices=[('dstnets', _('Destination Network')), ('dstcidr', _('Destination CIDR')), ('dstpols', _('Destination Network Policy'))], help_text=_('To specify an allowed IP ' 'range, select "CIDR". To ' 'allow access from a network ' 'select "Network". To ' 'allow access from a network ' 'policy select "Network Policy".'), widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'dsttype' })) srccidr = fields.IPField(label=_("Source CIDR"), required=False, initial="0.0.0.0/0", help_text=_("Classless Inter-Domain Routing " "(e.g. 192.168.0.0/24)"), version=fields.IPv4, mask=True, widget=forms.TextInput( attrs={ 'class': 'switched', 'data-switch-on': 'srctype', 'data-srctype-srccidr': _('Source CIDR') })) srcnets = forms.ChoiceField( label=_('Source Network'), required=False, widget=forms.Select( attrs={ 'class': 'switched', 'data-switch-on': 'srctype', 'data-srctype-srcnets': _('Source Network') })) srcpols = forms.ChoiceField( label=_('Source Network Policy'), required=False, widget=forms.Select( attrs={ 'class': 'switched', 'data-switch-on': 'srctype', 'data-srctype-srcpols': _('Source Network Policy') })) dstcidr = fields.IPField( label=_("Destination CIDR"), required=False, initial="0.0.0.0/0", help_text=_("Classless Inter-Domain Routing " "(e.g. 192.168.0.0/24)"), version=fields.IPv4, mask=True, widget=forms.TextInput( attrs={ 'class': 'switched', 'data-switch-on': 'dsttype', 'data-dsttype-dstcidr': _('Destination CIDR') })) dstnets = forms.ChoiceField( label=_('Destination Network'), required=False, widget=forms.Select( attrs={ 'class': 'switched', 'data-switch-on': 'dsttype', 'data-dsttype-dstnets': _('Destination Network') })) dstpols = forms.ChoiceField( label=_('Destination Network Policy'), required=False, widget=forms.Select( attrs={ 'class': 'switched', 'data-switch-on': 'dsttype', 'data-dsttype-dstpols': _('Destination Network Policy') })) src_ports = forms.CharField(label=_("Source Ports"), required=False, help_text=_("Originating Port list i.e. " "80 or 80,443,8080,8443-8446"), initial="any") dst_ports = forms.CharField(label=_("Destination Ports"), required=False, help_text=_("Destination Port list i.e. " "80 or 80,443,8080,8443-8446"), initial="any") def __init__(self, *args, **kwargs): policy_list = kwargs.pop('policy_list', []) network_list = kwargs.pop('network_list', []) services_list = kwargs.pop('services_list', []) super(AddRule, self).__init__(*args, **kwargs) if policy_list: policy_choices = policy_list else: policy_choices = [("", _("No network policies available"))] self.fields['srcpols'].choices = policy_choices self.fields['dstpols'].choices = policy_choices if network_list: network_choices = network_list else: network_choices = [] self.fields['srcnets'].choices = network_choices self.fields['dstnets'].choices = network_choices pol_id = kwargs['initial']['id'] sequence_id_choices = [("last", "Last Rule"), ("first", "First Rule")] try: pol_obj = policy_show(self.request, policy_id=pol_id) seq_list = [] for rule in pol_obj['entries']['policy_rule']: seq_val = "after:{0}".format(rule['rule_sequence']) seq_val_lbl = "{0}".format(rule['rule_sequence']) seq_list.append((seq_val, seq_val_lbl)) sequence_id_choices.append(('After Rule', seq_list)) except: pol_obj = {} self.fields['sequence_id'].choices = sequence_id_choices def clean(self): cleaned_data = super(AddRule, self).clean() simple_action = cleaned_data.get("simple_action", None) direction = cleaned_data.get("direction", None) protocol = cleaned_data.get("protocol", None) src_ports = cleaned_data.get("src_ports", None) dst_ports = cleaned_data.get("dst_ports", None) sequence_id = cleaned_data.get("sequence_id", None) srctype = cleaned_data.get("srctype", None) dsttype = cleaned_data.get("dsttype", None) srccidr = cleaned_data.get("srccidr", None) srcnets = cleaned_data.get("srcnets", None) srcpols = cleaned_data.get("srcpols", None) dstcidr = cleaned_data.get("dstcidr", None) dstnets = cleaned_data.get("dstnets", None) dstpols = cleaned_data.get("dstpols", None) return cleaned_data def handle(self, request, data): policy_id = data['id'] src_port_list = [] if data['src_ports'] == 'any': sport = {'end_port': -1, 'start_port': -1} src_port_list.append(sport) elif len(data['src_ports']): src_port_str = data['src_ports'].split(',') for s in src_port_str: range_str = s.split('-') if len(range_str) == 2: sport = { 'end_port': int(range_str[1]), 'start_port': int(range_str[0]) } elif len(range_str) == 1: sport = { 'end_port': int(range_str[0]), 'start_port': int(range_str[0]) } src_port_list.append(sport) dst_port_list = [] if data['dst_ports'] == 'any': dport = {'end_port': -1, 'start_port': -1} dst_port_list.append(dport) elif len(data['dst_ports']): dst_port_str = data['dst_ports'].split(',') for d in dst_port_str: drange_str = d.split('-') if len(drange_str) == 2: dport = { 'end_port': int(drange_str[1]), 'start_port': int(drange_str[0]) } elif len(drange_str) == 1: dport = { 'end_port': int(drange_str[0]), 'start_port': int(drange_str[0]) } dst_port_list.append(dport) rule = { 'direction': data['direction'], 'protocol': data['protocol'], 'action_list': { 'simple_action': data['simple_action'] }, 'src_ports': src_port_list, 'dst_ports': dst_port_list, 'application': [], 'rule_sequence': { 'major': -1, 'minor': -1 } } if data['srctype'] == 'srcnets': rule['src_addresses'] = [{ 'security_group': None, 'subnet': None, 'virtual_network': data['srcnets'], 'network_policy': None }] elif data['srctype'] == 'srccidr': ip = IPNetwork(data['srccidr']) rule['src_addresses'] = [{ 'security_group': None, 'subnet': { 'ip_prefix': str(ip.ip), 'ip_prefix_len': ip.prefixlen }, 'virtual_network': None, 'network_policy': None }] elif data['srctype'] == 'srcpols': rule['src_addresses'] = [{ 'security_group': None, 'subnet': None, 'virtual_network': None, 'network_policy': data['srcpols'] }] if data['dsttype'] == 'dstnets': rule['dst_addresses'] = [{ 'security_group': None, 'subnet': None, 'virtual_network': data['dstnets'], 'network_policy': None }] elif data['dsttype'] == 'dstcidr': ip = IPNetwork(data['dstcidr']) rule['dst_addresses'] = [{ 'security_group': None, 'subnet': { 'ip_prefix': str(ip.ip), 'ip_prefix_len': ip.prefixlen }, 'virtual_network': None, 'network_policy': None }] elif data['dsttype'] == 'dstpols': rule['dst_addresses'] = [{ 'security_group': None, 'subnet': None, 'virtual_network': None, 'network_policy': data['dstpols'] }] try: policy_obj = policy_show(request, policy_id=policy_id) if not policy_obj['entries']: policy_obj['entries'] = {} policy_obj['entries']['policy_rule'] = [] if data['sequence_id'] == 'last': policy_obj['entries']['policy_rule'].append(rule) elif data['sequence_id'] == 'first': policy_obj['entries']['policy_rule'].insert(0, rule) else: seq = int(data['sequence_id'].split(':')[1]) policy_obj['entries']['policy_rule'].insert(seq, rule) policy_update_dict = policy_obj.__dict__['_apidict']['entries'] for rule in policy_update_dict['policy_rule']: rule['rule_sequence'] = {'major': -1, 'minor': -1} policy = policy_modify(request, policy_id=policy_id, entries=policy_update_dict) messages.success( request, _('Successfully added rule to policy : %s') % policy.name) return policy except: redirect = reverse("horizon:project:networks:" "policy:detail", args=[data['id']]) exceptions.handle(request, _('Unable to add rule to policy.'), redirect=redirect)
class CreateNetworkIpam(forms.SelfHandlingForm): name = forms.CharField(label=_("Name"), error_messages={ 'required': _('This field is required.'), 'invalid': _("The string may only contain" " ASCII characters and numbers.")}, validators=[validators.validate_slug]) dnsmethod = forms.ChoiceField(label=_('DNS Method'), choices=[('default', _('Default')), ('vdns', _('Virtual DNS')), ('tenantdns', _('Tenant DNS')), ('none', _('None'))], widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'dnsmethod'})) vdns = forms.CharField(label=_("Virtual DNS"), required=False, help_text=_("FQ Name of Virtual DNS i.e. default-domain:vdns"), widget=forms.TextInput( attrs={'class': 'switched', 'data-switch-on': 'dnsmethod', 'data-dnsmethod-vdns': _('Virtual DNS')})) tenantdns = fields.IPField(label=_("Tenant DNS Server IP"), required=False, help_text=_("Tenant managed DNS Server's IP Address"), version=fields.IPv4, mask=False, widget=forms.TextInput( attrs={'class': 'switched', 'data-switch-on': 'dnsmethod', 'data-dnsmethod-tenantdns': _('Tenant DNS Server IP')})) ntpip = fields.IPField(label=_("NTP Server IP"), required=False, help_text=_("IP Address of the NTP Server"), version=fields.IPv4, mask=False, widget=forms.TextInput()) domainname = forms.CharField(label=_("Domain Name"), required=False, help_text=_("Domain Name i.e. openstack.org"), widget=forms.TextInput()) def clean(self): cleaned_data = super(CreateNetworkIpam, self).clean() name = cleaned_data.get("name") dnsmethod = cleaned_data.get("dnsmethod") vdns = cleaned_data.get("vdns") tenantdns = cleaned_data.get("tenantdns") ntpip = cleaned_data.get("ntpip") domainname = cleaned_data.get("domainname") if dnsmethod == 'vdns' and not len(vdns): msg = _('Virtual DNS : Enter a valid Virtual DNS in FQN format') raise ValidationError(msg) if dnsmethod == 'tenantdns': if not tenantdns: msg = _('Tenant DNS Server IP : Enter Tenant DNS Server IP address') raise ValidationError(msg) elif not len(tenantdns): msg = _('Tenant DNS Server IP : Enter Tenant DNS Server IP address') raise ValidationError(msg) return cleaned_data def handle(self, request, data): params = {'name': data['name'], 'mgmt': {'ipam_method': None, 'dhcp_option_list': {'dhcp_option':[]}}} if data['domainname']: params['mgmt']['dhcp_option_list']['dhcp_option'].append( {'dhcp_option_name': '15', 'dhcp_option_value': data['domainname']}) if data['ntpip']: params['mgmt']['dhcp_option_list']['dhcp_option'].append( {'dhcp_option_name': '4', 'dhcp_option_value': data['ntpip']}) params['mgmt']['ipam_dns_server'] = {} params['mgmt']['ipam_dns_server']['tenant_dns_server_address'] = {} params['mgmt']['ipam_dns_server']['virtual_dns_server_name'] = None if data['dnsmethod'] == 'default': params['mgmt']['ipam_dns_method'] = 'default-dns-server' if data['dnsmethod'] == 'none': params['mgmt']['ipam_dns_method'] = 'none' if data['dnsmethod'] == 'tenantdns': params['mgmt']['ipam_dns_method'] = 'tenant-dns-server' if data['tenantdns']: params['mgmt']['ipam_dns_server']['tenant_dns_server_address']['ip_address'] = [] params['mgmt']['ipam_dns_server']['tenant_dns_server_address']['ip_address'].append(data['tenantdns']) if data['dnsmethod'] == 'vdns': params['mgmt']['ipam_dns_method'] = 'virtual-dns-server' params['mgmt']['ipam_dns_server']['virtual_dns_server_name'] = data['vdns'] try: ipam = ipam_create(request, **params) messages.success(request, _('Successfully created network ipam: %s') % data['name']) return ipam except Exception: redirect = reverse("horizon:project:networking:index") exceptions.handle(request, _('Unable to create network ipam.'), redirect=redirect)
class UpdateIpam(forms.SelfHandlingForm): id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(label=_("Name"), widget=forms.TextInput( attrs={'readonly': 'readonly'}), validators=[validators.validate_slug]) dnsmethod = forms.ChoiceField(label=_('DNS Method'), choices=[('default', _('Default')), ('vdns', _('Virtual DNS')), ('tenantdns', _('Tenant DNS')), ('none', _('None'))], widget=forms.Select(attrs={ 'class': 'switchable', 'data-slug': 'dnsmethod'})) vdns = forms.CharField(label=_("Virtual DNS"), required=False, help_text=_("FQ Name of Virtual DNS i.e. default-domain:vdns"), widget=forms.TextInput( attrs={'class': 'switched', 'data-switch-on': 'dnsmethod', 'data-dnsmethod-vdns': _('Virtual DNS')})) tenantdns = fields.IPField(label=_("Tenant DNS Server IP"), required=False, help_text=_("Tenant managed DNS Server's IP Address"), version=fields.IPv4, mask=False, widget=forms.TextInput( attrs={'class': 'switched', 'data-switch-on': 'dnsmethod', 'data-dnsmethod-tenantdns': _('Tenant DNS Server IP')})) ntpip = fields.IPField(label=_("NTP Server IP"), required=False, help_text=_("IP Address of the NTP Server"), version=fields.IPv4, mask=False, widget=forms.TextInput()) domainname = forms.CharField(label=_("Domain Name"), required=False, help_text=_("Domain Name i.e. openstack.org"), widget=forms.TextInput()) def __init__(self, *args, **kwargs): ipam_obj = kwargs.pop('ipam_obj', {}) mgmt = ipam_obj.__dict__['_apidict']['mgmt'] super(UpdateIpam, self).__init__(*args, **kwargs) if mgmt['ipam_dns_method'] == 'default-dns-server': self.fields['dnsmethod'].initial = 'default' if mgmt['ipam_dns_method'] == 'tenant-dns-server': self.fields['dnsmethod'].initial = 'tenantdns' if 'ipam_dns_server' in mgmt and \ 'tenant_dns_server_address' in mgmt['ipam_dns_server'] and \ 'ip_address' in mgmt['ipam_dns_server']['tenant_dns_server_address'] : for ip in mgmt['ipam_dns_server']['tenant_dns_server_address']['ip_address']: self.fields['tenantdns'].initial = ip if mgmt['ipam_dns_method'] == 'virtual-dns-server': self.fields['dnsmethod'].initial = 'vdns' if 'ipam_dns_server' in mgmt and \ 'virtual_dns_server_name' in mgmt['ipam_dns_server'] and \ mgmt['ipam_dns_server']['virtual_dns_server_name'] != None : self.fields['vdns'].initial = mgmt['ipam_dns_server']['virtual_dns_server_name'] if mgmt['ipam_dns_method'] == 'none': self.fields['dnsmethod'].initial = 'none' if 'dhcp_option_list' in mgmt: dhcp_list = mgmt['dhcp_option_list'] if dhcp_list and 'dhcp_option' in dhcp_list: for entry in mgmt['dhcp_option_list']['dhcp_option']: if entry['dhcp_option_name'] == '4': self.fields['ntpip'].initial = entry['dhcp_option_value'] if entry['dhcp_option_name'] == '15': self.fields['domainname'].initial = entry['dhcp_option_value'] def clean(self): cleaned_data = super(UpdateIpam, self).clean() name = cleaned_data.get("name") dnsmethod = cleaned_data.get("dnsmethod") vdns = cleaned_data.get("vdns") tenantdns = cleaned_data.get("tenantdns") ntpip = cleaned_data.get("ntpip") domainname = cleaned_data.get("domainname") if dnsmethod == 'vdns' and not len(vdns): msg = _('Virtual DNS : Enter a valid Virtual DNS in FQN format') raise ValidationError(msg) if dnsmethod == 'tenantdns': if not tenantdns: msg = _('Tenant DNS Server IP : Enter Tenant DNS Server IP address') raise ValidationError(msg) elif not len(tenantdns): msg = _('Tenant DNS Server IP : Enter Tenant DNS Server IP address') raise ValidationError(msg) return cleaned_data def handle(self, request, data): params = {'mgmt': {'ipam_method': None, 'dhcp_option_list': {'dhcp_option':[]}}} if data['domainname']: params['mgmt']['dhcp_option_list']['dhcp_option'].append( {'dhcp_option_name': '15', 'dhcp_option_value': data['domainname']}) if data['ntpip']: params['mgmt']['dhcp_option_list']['dhcp_option'].append( {'dhcp_option_name': '4', 'dhcp_option_value': data['ntpip']}) params['mgmt']['ipam_dns_server'] = {} params['mgmt']['ipam_dns_server']['tenant_dns_server_address'] = {} params['mgmt']['ipam_dns_server']['virtual_dns_server_name'] = None if data['dnsmethod'] == 'default': params['mgmt']['ipam_dns_method'] = 'default-dns-server' if data['dnsmethod'] == 'none': params['mgmt']['ipam_dns_method'] = 'none' if data['dnsmethod'] == 'tenantdns': params['mgmt']['ipam_dns_method'] = 'tenant-dns-server' if data['tenantdns']: params['mgmt']['ipam_dns_server']['tenant_dns_server_address']['ip_address'] = [] params['mgmt']['ipam_dns_server']['tenant_dns_server_address']['ip_address'].append(data['tenantdns']) if data['dnsmethod'] == 'vdns': params['mgmt']['ipam_dns_method'] = 'virtual-dns-server' params['mgmt']['ipam_dns_server']['virtual_dns_server_name'] = data['vdns'] try: ipam = ipam_modify(request, ipam_id=data['id'], **params) messages.success(request, _('Successfully updated network ipam: %s') % data['name']) return ipam except Exception: redirect = reverse("horizon:project:networking:index") exceptions.handle(request, _('Unable to update network ipam.'), redirect=redirect)
class CreateSubnetInfoAction(workflows.Action): with_subnet = forms.BooleanField(label=_("Create Subnet"), initial=True, required=False) subnet_name = forms.CharField(max_length=255, label=_("Subnet Name"), required=False) ipam = forms.DynamicTypedChoiceField(label=_("IPAM"), required=False, empty_value=None, add_item_link=IPAM_CREATE_URL, help_text=_( "Choose IPAM that will be " "associated with the IP Block")) cidr = fields.IPField(label=_("Network Address"), required=False, initial="", help_text=_("Network address in CIDR format " "(e.g. 192.168.0.0/24)"), version=fields.IPv4 | fields.IPv6, mask=True) ip_version = forms.ChoiceField(choices=[(4, 'IPv4'), (6, 'IPv6')], label=_("IP Version")) gateway_ip = fields.IPField( label=_("Gateway IP"), required=False, initial="", help_text=_("IP address of Gateway (e.g. 192.168.0.254) " "The default value is the first IP of the " "network address (e.g. 192.168.0.1 for " "192.168.0.0/24). " "If you use the default, leave blank. " "If you want to use no gateway, " "check 'Disable Gateway' below."), version=fields.IPv4, mask=False) no_gateway = forms.BooleanField(label=_("Disable Gateway"), initial=False, required=False) def __init__(self, request, *args, **kwargs): super(CreateSubnetInfoAction, self).__init__(request, *args, **kwargs) tenant_id = self.request.user.tenant_id try: ipams = ipam_summary(self.request) if ipams: ipam_choices = [(ipam.id, "{0} ({1})".format(ipam.fq_name[2], ipam.fq_name[1])) for ipam in ipams] ipam_choices.append(('None', 'None')) else: ipam_choices = [('None', 'Create a new IPAM')] except: ipam_choices = [('None', 'None')] exceptions.handle(self.request, _('Unable to retrieve ipam list')) self.fields['ipam'].choices = ipam_choices class Meta: name = _("Subnet") help_text = _('You can create a subnet associated with the new ' 'network, in which case "Network Address" must be ' 'specified. If you wish to create a network WITHOUT a ' 'subnet, uncheck the "Create Subnet" checkbox.') def _check_subnet_data(self, cleaned_data, is_create=True): cidr = cleaned_data.get('cidr') ipam = cleaned_data.get('ipam') ip_version = int(cleaned_data.get('ip_version')) gateway_ip = cleaned_data.get('gateway_ip') no_gateway = cleaned_data.get('no_gateway') if not cidr: msg = _('Specify "Network Address" or ' 'clear "Create Subnet" checkbox.') raise forms.ValidationError(msg) if cidr: subnet = netaddr.IPNetwork(cidr) if subnet.version != ip_version: msg = _('Network Address and IP version are inconsistent.') raise forms.ValidationError(msg) if (ip_version == 4 and subnet.prefixlen == 32) or \ (ip_version == 6 and subnet.prefixlen == 128): msg = _( "The subnet in the Network Address is too small (/%s)." % subnet.prefixlen) raise forms.ValidationError(msg) if not no_gateway and gateway_ip: if netaddr.IPAddress(gateway_ip).version is not ip_version: msg = _('Gateway IP and IP version are inconsistent.') raise forms.ValidationError(msg) if not is_create and not no_gateway and not gateway_ip: msg = _('Specify IP address of gateway or ' 'check "Disable Gateway".') raise forms.ValidationError(msg) def clean(self): cleaned_data = super(CreateSubnetInfoAction, self).clean() with_subnet = cleaned_data.get('with_subnet') if not with_subnet: return cleaned_data self._check_subnet_data(cleaned_data) return cleaned_data
class CreateReachabilityTest(forms.SelfHandlingForm): name = forms.CharField(max_length="64", label=_("Name"), required=True) src_tenant_name = forms.ChoiceField( label=_("Source Tenant"), help_text=_("Test reachability for current tenant only.")) src_segment_name = forms.ChoiceField( label=_("Source Segment"), help_text=_("Select a source segment name.")) def __init__(self, request, *args, **kwargs): super(CreateReachabilityTest, self).__init__(request, *args, **kwargs) self.fields['src_tenant_name'].choices = self\ .populate_tenant_choices(request) self.fields['src_tenant_name'].widget.attrs['readonly'] = True self.fields['src_segment_name'].choices = self\ .populate_segment_choices(request) def populate_tenant_choices(self, request): return [(request.user.tenant_name, request.user.tenant_name)] def populate_segment_choices(self, request): networks = osneutron.network_list(request, tenant_id=request.user.project_id, shared=False) segment_list = [(network.name, network.name) for network in networks] if segment_list: segment_list.insert(0, ("", _("Select a Segment"))) else: segment_list.insert(0, ("", _("No segments available"))) return segment_list src_ip = fields.IPField( label=_("Source IP Address"), required=True, initial="0.0.0.0") dst_ip = fields.IPField( label=_("Destination IP Address"), required=True, initial="0.0.0.0") expected_result = forms.ChoiceField( label=_('Expected Connection Results'), required=True, choices=EXPECTATION_CHOICES, widget=forms.Select( attrs={'class': 'switchable', 'data-slug': 'expected_result'})) def clean(self): cleaned_data = super(CreateReachabilityTest, self).clean() def update_cleaned_data(key, value): cleaned_data[key] = value self.errors.pop(key, None) expected_result = cleaned_data.get('expected_result') if expected_result == 'default': msg = _('A expected connection result must be selected.') raise ValidationError(msg) return cleaned_data def handle(self, request, data): try: reachabilitytest = neutron.reachabilitytest_create(request, **data) msg = _("Reachability Test %s was successfully created") \ % data['name'] LOG.debug(msg) messages.success(request, msg) return reachabilitytest except Exception: exceptions.handle(request, _("Failed to create reachability test"))
class RunQuickTestForm(forms.SelfHandlingForm): src_tenant_name = forms.ChoiceField( label=_("Source Tenant"), help_text=_("Select a source tenant name.")) src_segment_name = forms.ChoiceField( label=_("Source Segment"), help_text=_("Select a source segment name.")) def __init__(self, request, *args, **kwargs): super(RunQuickTestForm, self).__init__(request, *args, **kwargs) self.fields['src_tenant_name'].choices = self\ .populate_tenant_choices(request) self.fields['src_segment_name'].choices = self\ .populate_segment_choices(request) def populate_tenant_choices(self, request): return [(request.user.tenant_name, request.user.tenant_name)] def populate_segment_choices(self, request): networks = osneutron.network_list(request, tenant_id=request.user.project_id, shared=False) segment_list = [(network.name, network.name) for network in networks] if segment_list: segment_list.insert(0, ("", _("Select a Segment"))) else: segment_list.insert(0, ("", _("No segments available"))) return segment_list src_ip = fields.IPField( label=_("Source IP Address"), required=True, initial="0.0.0.0") dst_ip = fields.IPField( label=_("Destination IP Address"), required=True, initial="0.0.0.0") expected_result = forms.ChoiceField( label=_('Expected Connection Results'), required=True, choices=EXPECTATION_CHOICES, widget=forms.Select( attrs={'class': 'switchable', 'data-slug': 'expected_connection'})) def clean(self): cleaned_data = super(RunQuickTestForm, self).clean() def update_cleaned_data(key, value): cleaned_data[key] = value self.errors.pop(key, None) expected_result = cleaned_data.get('expected_result') if expected_result == 'default': msg = _('A expected connection result must be selected.') raise ValidationError(msg) return cleaned_data def handle(self, request, data): data['name'] = "quicktest_" + str(request.user.project_id) try: reachabilityquicktest = neutron \ .reachabilityquicktest_get(request, request.user.project_id) # update with new fields neutron.reachabilityquicktest_update( request, request.user.project_id, **data) except Exception: # test doesn't exist, create reachabilityquicktest = neutron.reachabilityquicktest_create( request, **data) # clear dict data = {} # set run_test to true and update test to get results data['run_test'] = True reachabilityquicktest = neutron.reachabilityquicktest_update( request, reachabilityquicktest.id, **data) return reachabilityquicktest
class RunQuickTestForm(forms.SelfHandlingForm): src_tenant = forms.ChoiceField( label=_("Source Tenant"), help_text=_("Test reachability for current tenant only.")) src_segment = forms.ChoiceField( label=_("Source Segment"), help_text=_("Select a source segment.")) def __init__(self, request, *args, **kwargs): super(RunQuickTestForm, self).__init__(request, *args, **kwargs) self.fields['src_tenant'].choices = populate_tenant_choices(request) self.fields['src_tenant'].widget.attrs['readonly'] = True self.fields['src_segment'].choices = populate_segment_choices(request) src_ip = fields.IPField( label=_("Source IP Address"), required=True, initial="0.0.0.0") dst_ip = fields.IPField( label=_("Destination IP Address"), required=True, initial="0.0.0.0") expected_result = forms.ChoiceField( label=_('Expected Connection Results'), required=True, choices=EXPECTATION_CHOICES, widget=forms.Select( attrs={'class': 'switchable', 'data-slug': 'expected_connection'})) def clean(self): cleaned_data = super(RunQuickTestForm, self).clean() def update_cleaned_data(key, value): cleaned_data[key] = value self.errors.pop(key, None) expected_result = cleaned_data.get('expected_result') if expected_result == 'default': msg = _('A expected connection result must be selected.') raise ValidationError(msg) return cleaned_data def handle(self, request, data): data['name'] = "quicktest_" + str(request.user.project_id) try: extract_src_tenant_and_segment(data) reachabilityquicktest = neutron \ .reachabilityquicktest_get(request, request.user.project_id) # update with new fields neutron.reachabilityquicktest_update( request, request.user.project_id, **data) except Exception: # test doesn't exist, create reachabilityquicktest = neutron.reachabilityquicktest_create( request, **data) # clear dict data = {} # set run_test to true and update test to get results data['run_test'] = True reachabilityquicktest = neutron.reachabilityquicktest_update( request, reachabilityquicktest.id, **data) return reachabilityquicktest
class CreateReachabilityTest(forms.SelfHandlingForm): name = forms.CharField(max_length="64", label=_("Name"), required=True) src_tenant = forms.ChoiceField( label=_("Source Tenant"), help_text=_("Test reachability for current tenant only.")) src_segment = forms.ChoiceField( label=_("Source Segment"), help_text=_("Select a source segment.")) def __init__(self, request, *args, **kwargs): super(CreateReachabilityTest, self).__init__(request, *args, **kwargs) self.fields['src_tenant'].choices = populate_tenant_choices(request) self.fields['src_tenant'].widget.attrs['readonly'] = True self.fields['src_segment'].choices = populate_segment_choices(request) src_ip = fields.IPField( label=_("Source IP Address"), required=True, initial="0.0.0.0") dst_ip = fields.IPField( label=_("Destination IP Address"), required=True, initial="0.0.0.0") expected_result = forms.ChoiceField( label=_('Expected Connection Results'), required=True, choices=EXPECTATION_CHOICES, widget=forms.Select( attrs={'class': 'switchable', 'data-slug': 'expected_result'})) def clean(self): cleaned_data = super(CreateReachabilityTest, self).clean() def update_cleaned_data(key, value): cleaned_data[key] = value self.errors.pop(key, None) expected_result = cleaned_data.get('expected_result') if expected_result == 'default': msg = _('A expected connection result must be selected.') raise ValidationError(msg) return cleaned_data def handle(self, request, data): try: extract_src_tenant_and_segment(data) reachabilitytest = neutron.reachabilitytest_create(request, **data) msg = _("Reachability Test %s was successfully created") \ % data['name'] LOG.debug(msg) messages.success(request, msg) return reachabilitytest except Exception as e: exceptions.handle(request, _("Failed to create reachability test. Info: " "%s") % e.message)