Esempio n. 1
0
class PowerConnectionCSVForm(forms.Form):
    pdu = FlexibleModelChoiceField(queryset=Device.objects.filter(device_type__is_pdu=True), to_field_name='name',
                                   error_messages={'invalid_choice': 'PDU not found.'})
    power_outlet = forms.CharField()
    device = FlexibleModelChoiceField(queryset=Device.objects.all(), to_field_name='name',
                                      error_messages={'invalid_choice': 'Device not found'})
    power_port = forms.CharField()
    status = forms.ChoiceField(choices=[('planned', 'Planned'), ('connected', 'Connected')])

    def clean(self):

        # Validate power outlet
        if self.cleaned_data.get('pdu'):
            try:
                power_outlet = PowerOutlet.objects.get(device=self.cleaned_data['pdu'],
                                                       name=self.cleaned_data['power_outlet'])
                if PowerPort.objects.filter(power_outlet=power_outlet):
                    raise forms.ValidationError("Power outlet is already occupied (by {} {})"
                                                .format(power_outlet.connected_port.device,
                                                        power_outlet.connected_port))
            except PowerOutlet.DoesNotExist:
                raise forms.ValidationError("Invalid PDU port ({} {})"
                                            .format(self.cleaned_data['pdu'], self.cleaned_data['power_outlet']))

        # Validate power port
        if self.cleaned_data.get('device'):
            try:
                power_port = PowerPort.objects.get(device=self.cleaned_data['device'],
                                                   name=self.cleaned_data['power_port'])
                if power_port.power_outlet:
                    raise forms.ValidationError("Power port is already connected (to {} {})"
                                                .format(power_port.power_outlet.device, power_port.power_outlet))
            except PowerPort.DoesNotExist:
                raise forms.ValidationError("Invalid power port ({} {})"
                                            .format(self.cleaned_data['device'], self.cleaned_data['power_port']))
Esempio n. 2
0
class ConsoleConnectionCSVForm(forms.Form):
    console_server = FlexibleModelChoiceField(queryset=Device.objects.filter(device_type__is_console_server=True),
                                              to_field_name='name',
                                              error_messages={'invalid_choice': 'Console server not found'})
    cs_port = forms.CharField()
    device = FlexibleModelChoiceField(queryset=Device.objects.all(), to_field_name='name',
                                      error_messages={'invalid_choice': 'Device not found'})
    console_port = forms.CharField()
    status = forms.ChoiceField(choices=[('planned', 'Planned'), ('connected', 'Connected')])

    def clean(self):

        # Validate console server port
        if self.cleaned_data.get('console_server'):
            try:
                cs_port = ConsoleServerPort.objects.get(device=self.cleaned_data['console_server'],
                                                        name=self.cleaned_data['cs_port'])
                if ConsolePort.objects.filter(cs_port=cs_port):
                    raise forms.ValidationError("Console server port is already occupied (by {} {})"
                                                .format(cs_port.connected_console.device, cs_port.connected_console))
            except ConsoleServerPort.DoesNotExist:
                raise forms.ValidationError("Invalid console server port ({} {})"
                                            .format(self.cleaned_data['console_server'], self.cleaned_data['cs_port']))

        # Validate console port
        if self.cleaned_data.get('device'):
            try:
                console_port = ConsolePort.objects.get(device=self.cleaned_data['device'],
                                                       name=self.cleaned_data['console_port'])
                if console_port.cs_port:
                    raise forms.ValidationError("Console port is already connected (to {} {})"
                                                .format(console_port.cs_port.device, console_port.cs_port))
            except ConsolePort.DoesNotExist:
                raise forms.ValidationError("Invalid console port ({} {})"
                                            .format(self.cleaned_data['device'], self.cleaned_data['console_port']))
Esempio n. 3
0
class InterfaceConnectionCSVForm(forms.Form):
    device_a = FlexibleModelChoiceField(
        queryset=Device.objects.all(),
        to_field_name='name',
        error_messages={'invalid_choice': 'Device A not found.'})
    interface_a = forms.CharField()
    device_b = FlexibleModelChoiceField(
        queryset=Device.objects.all(),
        to_field_name='name',
        error_messages={'invalid_choice': 'Device B not found.'})
    interface_b = forms.CharField()
    status = forms.ChoiceField(choices=[('planned',
                                         'Planned'), ('connected',
                                                      'Connected')])

    def clean(self):

        # Validate interface A
        if self.cleaned_data.get('device_a'):
            try:
                interface_a = Interface.objects.get(
                    device=self.cleaned_data['device_a'],
                    name=self.cleaned_data['interface_a'])
            except Interface.DoesNotExist:
                raise forms.ValidationError("Invalid interface ({} {})".format(
                    self.cleaned_data['device_a'],
                    self.cleaned_data['interface_a']))
            try:
                InterfaceConnection.objects.get(
                    Q(interface_a=interface_a) | Q(interface_b=interface_a))
                raise forms.ValidationError(
                    "{} {} is already connected".format(
                        self.cleaned_data['device_a'],
                        self.cleaned_data['interface_a']))
            except InterfaceConnection.DoesNotExist:
                pass

        # Validate interface B
        if self.cleaned_data.get('device_b'):
            try:
                interface_b = Interface.objects.get(
                    device=self.cleaned_data['device_b'],
                    name=self.cleaned_data['interface_b'])
            except Interface.DoesNotExist:
                raise forms.ValidationError("Invalid interface ({} {})".format(
                    self.cleaned_data['device_b'],
                    self.cleaned_data['interface_b']))
            try:
                InterfaceConnection.objects.get(
                    Q(interface_a=interface_b) | Q(interface_b=interface_b))
                raise forms.ValidationError(
                    "{} {} is already connected".format(
                        self.cleaned_data['device_b'],
                        self.cleaned_data['interface_b']))
            except InterfaceConnection.DoesNotExist:
                pass
Esempio n. 4
0
class SecretCSVForm(CustomFieldModelCSVForm):
    device = FlexibleModelChoiceField(queryset=Device.objects.all(),
                                      to_field_name='name',
                                      help_text='Device name or ID',
                                      error_messages={
                                          'invalid_choice':
                                          'Device not found.',
                                      })
    role = forms.ModelChoiceField(queryset=SecretRole.objects.all(),
                                  to_field_name='name',
                                  help_text='Name of assigned role',
                                  error_messages={
                                      'invalid_choice': 'Invalid secret role.',
                                  })
    plaintext = forms.CharField(help_text='Plaintext secret data')

    class Meta:
        model = Secret
        fields = Secret.csv_headers
        help_texts = {
            'name': 'Name or username',
        }

    def save(self, *args, **kwargs):
        s = super().save(*args, **kwargs)
        s.plaintext = str(self.cleaned_data['plaintext'])
        return s
Esempio n. 5
0
class ServiceCSVForm(CustomFieldModelCSVForm):
    device = FlexibleModelChoiceField(queryset=Device.objects.all(),
                                      required=False,
                                      to_field_name='name',
                                      help_text='Name or ID of device',
                                      error_messages={
                                          'invalid_choice':
                                          'Device not found.',
                                      })
    virtual_machine = FlexibleModelChoiceField(
        queryset=VirtualMachine.objects.all(),
        required=False,
        to_field_name='name',
        help_text='Name or ID of virtual machine',
        error_messages={
            'invalid_choice': 'Virtual machine not found.',
        })
    protocol = CSVChoiceField(choices=ServiceProtocolChoices,
                              help_text='IP protocol')

    class Meta:
        model = Service
        fields = Service.csv_headers
        help_texts = {}
Esempio n. 6
0
class IPAddressCSVForm(forms.ModelForm):
    vrf = forms.ModelChoiceField(
        queryset=VRF.objects.all(),
        required=False,
        to_field_name='rd',
        help_text='Route distinguisher of the assigned VRF',
        error_messages={
            'invalid_choice': 'VRF not found.',
        })
    tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(),
                                    to_field_name='name',
                                    required=False,
                                    help_text='Name of the assigned tenant',
                                    error_messages={
                                        'invalid_choice': 'Tenant not found.',
                                    })
    status = CSVChoiceField(choices=IPADDRESS_STATUS_CHOICES,
                            help_text='Operational status')
    role = CSVChoiceField(choices=IPADDRESS_ROLE_CHOICES,
                          required=False,
                          help_text='Functional role')
    device = FlexibleModelChoiceField(
        queryset=Device.objects.all(),
        required=False,
        to_field_name='name',
        help_text='Name or ID of assigned device',
        error_messages={
            'invalid_choice': 'Device not found.',
        })
    virtual_machine = forms.ModelChoiceField(
        queryset=VirtualMachine.objects.all(),
        required=False,
        to_field_name='name',
        help_text='Name of assigned virtual machine',
        error_messages={
            'invalid_choice': 'Virtual machine not found.',
        })
    interface_name = forms.CharField(help_text='Name of assigned interface',
                                     required=False)
    is_primary = forms.BooleanField(
        help_text='Make this the primary IP for the assigned device',
        required=False)

    class Meta:
        model = IPAddress
        fields = IPAddress.csv_headers

    def clean(self):

        super(IPAddressCSVForm, self).clean()

        device = self.cleaned_data.get('device')
        virtual_machine = self.cleaned_data.get('virtual_machine')
        interface_name = self.cleaned_data.get('interface_name')
        is_primary = self.cleaned_data.get('is_primary')

        # Validate interface
        if interface_name and device:
            try:
                self.instance.interface = Interface.objects.get(
                    device=device, name=interface_name)
            except Interface.DoesNotExist:
                raise forms.ValidationError(
                    "Invalid interface {} for device {}".format(
                        interface_name, device))
        elif interface_name and virtual_machine:
            try:
                self.instance.interface = Interface.objects.get(
                    virtual_machine=virtual_machine, name=interface_name)
            except Interface.DoesNotExist:
                raise forms.ValidationError(
                    "Invalid interface {} for virtual machine {}".format(
                        interface_name, virtual_machine))
        elif interface_name:
            raise forms.ValidationError(
                "Interface given ({}) but parent device/virtual machine not specified"
                .format(interface_name))
        elif device:
            raise forms.ValidationError(
                "Device specified ({}) but interface missing".format(device))
        elif virtual_machine:
            raise forms.ValidationError(
                "Virtual machine specified ({}) but interface missing".format(
                    virtual_machine))

        # Validate is_primary
        if is_primary and not device and not virtual_machine:
            raise forms.ValidationError(
                "No device or virtual machine specified; cannot set as primary IP"
            )

    def save(self, *args, **kwargs):

        # Set interface
        if self.cleaned_data['device'] and self.cleaned_data['interface_name']:
            self.instance.interface = Interface.objects.get(
                device=self.cleaned_data['device'],
                name=self.cleaned_data['interface_name'])
        elif self.cleaned_data['virtual_machine'] and self.cleaned_data[
                'interface_name']:
            self.instance.interface = Interface.objects.get(
                virtual_machine=self.cleaned_data['virtual_machine'],
                name=self.cleaned_data['interface_name'])

        ipaddress = super(IPAddressCSVForm, self).save(*args, **kwargs)

        # Set as primary for device/VM
        if self.cleaned_data['is_primary']:
            parent = self.cleaned_data['device'] or self.cleaned_data[
                'virtual_machine']
            if self.instance.address.version == 4:
                parent.primary_ip4 = ipaddress
            elif self.instance.address.version == 6:
                parent.primary_ip6 = ipaddress
            parent.save()

        return ipaddress
Esempio n. 7
0
class PrefixCSVForm(forms.ModelForm):
    vrf = FlexibleModelChoiceField(
        queryset=VRF.objects.all(),
        to_field_name='rd',
        required=False,
        help_text='Route distinguisher of parent VRF (or {ID})',
        error_messages={
            'invalid_choice': 'VRF not found.',
        })
    tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(),
                                    required=False,
                                    to_field_name='name',
                                    help_text='Name of assigned tenant',
                                    error_messages={
                                        'invalid_choice': 'Tenant not found.',
                                    })
    site = forms.ModelChoiceField(queryset=Site.objects.all(),
                                  required=False,
                                  to_field_name='name',
                                  help_text='Name of parent site',
                                  error_messages={
                                      'invalid_choice': 'Site not found.',
                                  })
    vlan_group = forms.CharField(help_text='Group name of assigned VLAN',
                                 required=False)
    vlan_vid = forms.IntegerField(help_text='Numeric ID of assigned VLAN',
                                  required=False)
    status = CSVChoiceField(choices=PrefixStatusChoices,
                            help_text='Operational status')
    role = forms.ModelChoiceField(queryset=Role.objects.all(),
                                  required=False,
                                  to_field_name='name',
                                  help_text='Functional role',
                                  error_messages={
                                      'invalid_choice': 'Invalid role.',
                                  })

    class Meta:
        model = Prefix
        fields = Prefix.csv_headers

    def clean(self):

        super().clean()

        site = self.cleaned_data.get('site')
        vlan_group = self.cleaned_data.get('vlan_group')
        vlan_vid = self.cleaned_data.get('vlan_vid')

        # Validate VLAN
        if vlan_group and vlan_vid:
            try:
                self.instance.vlan = VLAN.objects.get(site=site,
                                                      group__name=vlan_group,
                                                      vid=vlan_vid)
            except VLAN.DoesNotExist:
                if site:
                    raise forms.ValidationError(
                        "VLAN {} not found in site {} group {}".format(
                            vlan_vid, site, vlan_group))
                else:
                    raise forms.ValidationError(
                        "Global VLAN {} not found in group {}".format(
                            vlan_vid, vlan_group))
            except MultipleObjectsReturned:
                raise forms.ValidationError(
                    "Multiple VLANs with VID {} found in group {}".format(
                        vlan_vid, vlan_group))
        elif vlan_vid:
            try:
                self.instance.vlan = VLAN.objects.get(site=site,
                                                      group__isnull=True,
                                                      vid=vlan_vid)
            except VLAN.DoesNotExist:
                if site:
                    raise forms.ValidationError(
                        "VLAN {} not found in site {}".format(vlan_vid, site))
                else:
                    raise forms.ValidationError(
                        "Global VLAN {} not found".format(vlan_vid))
            except MultipleObjectsReturned:
                raise forms.ValidationError(
                    "Multiple VLANs with VID {} found".format(vlan_vid))
Esempio n. 8
0
class IPAddressCSVForm(forms.ModelForm):
    vrf = forms.ModelChoiceField(
        queryset=VRF.objects.all(),
        required=False,
        to_field_name='rd',
        help_text='Route distinguisher of the assigned VRF',
        error_messages={
            'invalid_choice': 'VRF not found.',
        })
    tenant = forms.ModelChoiceField(queryset=Tenant.objects.all(),
                                    to_field_name='name',
                                    required=False,
                                    help_text='Name of the assigned tenant',
                                    error_messages={
                                        'invalid_choice': 'Tenant not found.',
                                    })
    status = CSVChoiceField(choices=PREFIX_STATUS_CHOICES,
                            help_text='Operational status')
    device = FlexibleModelChoiceField(
        queryset=Device.objects.all(),
        required=False,
        to_field_name='name',
        help_text='Name or ID of assigned device',
        error_messages={
            'invalid_choice': 'Device not found.',
        })
    interface_name = forms.CharField(help_text='Name of assigned interface',
                                     required=False)
    is_primary = forms.BooleanField(
        help_text='Make this the primary IP for the assigned device',
        required=False)

    class Meta:
        model = IPAddress
        fields = [
            'address', 'vrf', 'tenant', 'status', 'device', 'interface_name',
            'is_primary', 'description'
        ]

    def clean(self):

        super(IPAddressCSVForm, self).clean()

        device = self.cleaned_data.get('device')
        interface_name = self.cleaned_data.get('interface_name')
        is_primary = self.cleaned_data.get('is_primary')

        # Validate interface
        if device and interface_name:
            try:
                self.instance.interface = Interface.objects.get(
                    device=device, name=interface_name)
            except Interface.DoesNotExist:
                raise forms.ValidationError(
                    "Invalid interface {} for device {}".format(
                        interface_name, device))
        elif device and not interface_name:
            raise forms.ValidationError(
                "Device set ({}) but interface missing".format(device))
        elif interface_name and not device:
            raise forms.ValidationError(
                "Interface set ({}) but device missing or invalid".format(
                    interface_name))

        # Validate is_primary
        if is_primary and not device:
            raise forms.ValidationError(
                "No device specified; cannot set as primary IP")

    def save(self, *args, **kwargs):

        # Set interface
        if self.cleaned_data['device'] and self.cleaned_data['interface_name']:
            self.instance.interface = Interface.objects.get(
                device=self.cleaned_data['device'],
                name=self.cleaned_data['interface_name'])
        # Set as primary for device
        if self.cleaned_data['is_primary']:
            if self.instance.address.version == 4:
                self.instance.primary_ip4_for = self.cleaned_data['device']
            elif self.instance.address.version == 6:
                self.instance.primary_ip6_for = self.cleaned_data['device']

        return super(IPAddressCSVForm, self).save(*args, **kwargs)