예제 #1
0
 def __init__(self, *args, **kwargs):
     super(InterfacesForm, self).__init__(*args, **kwargs)
     self.fields['int_interface'].choices = choices.NICChoices()
     self.fields['int_dhcp'].widget.attrs['onChange'] = (
         'javascript:toggleGeneric("id_int_dhcp", ["id_int_ipv4address", '
         '"id_int_v4netmaskbit"]);')
     self.fields['int_ipv6auto'].widget.attrs['onChange'] = (
         'javascript:toggleGeneric("id_int_ipv6auto", '
         '["id_int_ipv6address", "id_int_v6netmaskbit"]);')
     dhcp = False
     ipv6auto = False
     if self.data:
         if self.data.get("int_dhcp"):
             dhcp = True
         if self.data.get("int_ipv6auto"):
             ipv6auto = True
     elif self.instance.id:
         if self.instance.int_dhcp:
             dhcp = True
         if self.instance.int_ipv6auto:
             ipv6auto = True
     if dhcp:
         self.fields['int_ipv4address'].widget.attrs['disabled'] = (
             'disabled')
         self.fields['int_v4netmaskbit'].widget.attrs['disabled'] = (
             'disabled')
     if ipv6auto:
         self.fields['int_ipv6address'].widget.attrs['disabled'] = (
             'disabled')
         self.fields['int_v6netmaskbit'].widget.attrs['disabled'] = (
             'disabled')
예제 #2
0
파일: forms.py 프로젝트: vanloswang/freenas
 def __init__(self, *args, **kwargs):
     super(LAGGInterfaceForm, self).__init__(*args, **kwargs)
     self.fields['lagg_interfaces'].choices = list(
         choices.NICChoices(nolagg=True))
     # Remove empty option (e.g. -------)
     self.fields['lagg_protocol'].choices = (
         self.fields['lagg_protocol'].choices[1:])
예제 #3
0
    def __init__(self, *args, **kwargs):
        super(InterfacesForm, self).__init__(*args, **kwargs)
        self.fields['int_interface'].choices = choices.NICChoices()
        self.fields['int_dhcp'].widget.attrs['onChange'] = (
            'javascript:toggleGeneric("id_int_dhcp", ["id_int_ipv4address", '
            '"id_int_v4netmaskbit"]);')
        self.fields['int_ipv6auto'].widget.attrs['onChange'] = (
            'javascript:toggleGeneric("id_int_ipv6auto", '
            '["id_int_ipv6address", "id_int_v6netmaskbit"]);')
        dhcp = False
        ipv6auto = False
        if self.data:
            if self.data.get("int_dhcp"):
                dhcp = True
            if self.data.get("int_ipv6auto"):
                ipv6auto = True
        elif self.instance.id:
            if self.instance.int_dhcp:
                dhcp = True
            if self.instance.int_ipv6auto:
                ipv6auto = True
        if dhcp:
            self.fields['int_ipv4address'].widget.attrs['disabled'] = (
                'disabled')
            self.fields['int_v4netmaskbit'].widget.attrs['disabled'] = (
                'disabled')
        if ipv6auto:
            self.fields['int_ipv6address'].widget.attrs['disabled'] = (
                'disabled')
            self.fields['int_v6netmaskbit'].widget.attrs['disabled'] = (
                'disabled')

        if self.instance.id:
            if self.instance.int_interface.startswith('carp'):
                self.fields['int_v4netmaskbit'].widget.attrs['readonly'] = True
                self.fields['int_v4netmaskbit'].widget.attrs['class'] = (
                    'dijitDisabled dijitSelectDisabled'
                )
                self.fields['int_v4netmaskbit'].initial = '32'
                self.instance.int_v4netmaskbit = '32'
            self.fields['int_interface'] = \
                forms.CharField(
                    label=self.fields['int_interface'].label,
                    initial=self.instance.int_interface,
                    widget=forms.TextInput(
                        attrs={
                            'readonly': True,
                            'class': (
                                'dijitDisabled dijitTextBoxDisabled'
                                ' dijitValidationTextBoxDisabled'
                            ),
                        },
                    )
                )
예제 #4
0
파일: forms.py 프로젝트: vanloswang/freenas
 def __init__(self, *args, **kwargs):
     super(LAGGInterfaceMemberForm, self).__init__(*args, **kwargs)
     if self.instance.id:
         self.fields['lagg_interfacegroup'].widget.attrs['readonly'] = True
         self.fields['lagg_interfacegroup'].widget.attrs['class'] = (
             'dijitDisabled dijitSelectDisabled')
         self.fields['lagg_physnic'].widget.attrs['readonly'] = True
         self.fields['lagg_physnic'].widget.attrs['class'] = (
             'dijitDisabled dijitSelectDisabled')
         self.fields['lagg_physnic'].choices = ((
             self.instance.lagg_physnic, self.instance.lagg_physnic), )
     else:
         self.fields['lagg_physnic'].choices = list(
             choices.NICChoices(nolagg=True, novlan=True))
예제 #5
0
    def __init__(self, *args, **kwargs):
        super(LAGGInterfaceForm, self).__init__(*args, **kwargs)
        self.fields['lagg_interfaces'].choices = list(
            choices.NICChoices(nolagg=True))

        # For HA we dont want people using failover type
        # See #25351
        if not notifier().is_freenas() and notifier().failover_licensed():
            filter_failover_type = True
        else:
            filter_failover_type = False
        # Remove empty option (e.g. -------)
        lagg_protocol = list(self.fields['lagg_protocol'].choices[1:])
        if filter_failover_type:
            lagg_protocol = filter(lambda x: x[0] != 'failover', lagg_protocol)
        self.fields['lagg_protocol'].choices = tuple(lagg_protocol)
예제 #6
0
class Jails(Model):
    objects = JailsManager()

    jail_host = models.CharField(
        max_length=120,
        verbose_name=_("Jail Name"),
    )
    jail_type = models.CharField(
        max_length=120,
        verbose_name=_("Type")
    )
    jail_ipv4 = models.CharField(
        max_length=120,
        blank=True,
        null=True,
        verbose_name=_("IPv4 address")
    )
    jail_ipv4_netmask = models.CharField(
        max_length=3,
        choices=choices.v4NetmaskBitList,
        blank=True,
        default='',
        verbose_name=_("IPv4 netmask"),
    )
    jail_alias_ipv4 = models.CharField(
        max_length=120,
        blank=True,
        null=True,
        verbose_name=_("IPv4 aliases")
    )
    jail_bridge_ipv4 = models.CharField(
        max_length=120,
        blank=True,
        null=True,
        verbose_name=_("IPv4 bridge address")
    )
    jail_bridge_ipv4_netmask = models.CharField(
        max_length=3,
        choices=choices.v4NetmaskBitList,
        blank=True,
        default='',
        verbose_name=_("IPv4 bridge netmask"),
    )
    jail_alias_bridge_ipv4 = models.CharField(
        max_length=120,
        blank=True,
        null=True,
        verbose_name=_("IPv4 bridge aliases")
    )
    jail_defaultrouter_ipv4 = models.IPAddressField(
        max_length=120,
        blank=True,
        null=True,
        verbose_name=_("IPv4 default gateway")
    )
    jail_ipv6 = models.CharField(
        max_length=120,
        blank=True,
        null=True,
        verbose_name=_("IPv6 address")
    )
    jail_ipv6_prefix = models.CharField(
        max_length=4,
        choices=choices.v6NetmaskBitList,
        blank=True,
        default='',
        verbose_name=_("IPv6 prefix length")
    )
    jail_alias_ipv6 = models.CharField(
        max_length=120,
        blank=True,
        null=True,
        verbose_name=_("IPv6 aliases")
    )
    jail_bridge_ipv6 = models.CharField(
        max_length=120,
        blank=True,
        null=True,
        verbose_name=_("IPv6 bridge address")
    )
    jail_bridge_ipv6_prefix = models.CharField(
        max_length=4,
        choices=choices.v6NetmaskBitList,
        blank=True,
        default='',
        verbose_name=_("IPv6 bridge prefix length")
    )
    jail_alias_bridge_ipv6 = models.CharField(
        max_length=120,
        blank=True,
        null=True,
        verbose_name=_("IPv6 bridge aliases")
    )
    jail_defaultrouter_ipv6 = models.GenericIPAddressField(
        max_length=120,
        blank=True,
        null=True,
        protocol='IPv6',
        verbose_name=_("IPv6 default gateway")
    )
    jail_mac = models.CharField(
        max_length=120,
        blank=True,
        null=True,
        verbose_name=_("MAC")
    )
    jail_iface = models.CharField(
        max_length=300,
        blank=True,
        default='',
        choices=choices.NICChoices(exclude_configured=False),
        verbose_name=_("NIC")
    )
    jail_flags = models.TextField(
        verbose_name=_("Sysctls"),
        blank=True,
        help_text=_("Comma delimited list of sysctl's")
    )
    jail_autostart = models.BooleanField(
        max_length=120,
        default=True,
        verbose_name=_("Autostart")
    )
    jail_status = models.CharField(
        max_length=120,
        verbose_name=_("Status")
    )
    jail_vnet = models.BooleanField(
        max_length=120,
        default=True,
        verbose_name=_("VIMAGE")
    )
    jail_nat = models.BooleanField(
        default=False,
        verbose_name=_("NAT")
    )

    @property
    def jail_ipv4_dhcp(self):
        ret = False
        jail_ipv4 = self.jail_ipv4
        if jail_ipv4 and jail_ivp4.startswith("DHCP:"):
            ret = True
        return ret

    @property
    def jail_ipv4_addr(self):
        jail_ipv4 = self.jail_ipv4
        if jail_ipv4:
            jail_ipv4 = jail_ipv4.replace("DHCP:", '')

        return jail_ipv4

    @property
    def jail_ipv6_autoconf(self):
        ret = False
        jail_ipv6 = self.jail_ipv6
        if jail_ipv6 and jail_ivp6.startswith("AUTOCONF:"):
            ret = True
        return ret

    @property
    def jail_ipv6_addr(self):
        jail_ipv6 = self.jail_ipv6
        if jail_ipv6:
            jail_ipv6 = jail_ipv6.replace("AUTOCONF:", '')

        return jail_ipv6

    @property
    def jail_path(self):
        if self.__jail_path:
            return self.__jail_path
        else:
            try:
                jc = JailsConfiguration.objects.order_by("-id")[0] 
                self.__jail_path = "%s/%s" % (jc.jc_path, self.jail_host)
            except:
                pass

        return self.__jail_path

    @property
    def jail_meta_path(self):
        if self.__jail_meta_path:
            return self.__jail_meta_path
        else:
            try:
                jc = JailsConfiguration.objects.order_by("-id")[0] 
                self.__jail_meta_path = "%s/.%s.meta" % (jc.jc_path, self.jail_host)
            except:
                pass

        return self.__jail_meta_path

    def __str__(self):
        return str(self.jail_host)

    def __unicode__(self):
        return unicode(self.jail_host)

    def __init__(self, *args, **kwargs):
        super(Jails, self).__init__(*args, **kwargs)
        self.__jail_path = None
        self.__jail_meta_path = None

        if self.jail_autostart == WARDEN_AUTOSTART_ENABLED:
            self.jail_autostart = True
        elif self.jail_autostart == WARDEN_AUTOSTART_DISABLED:
            self.jail_autostart = False

        if self.jail_vnet == WARDEN_VNET_ENABLED:
            self.jail_vnet = True
        elif self.jail_vnet == WARDEN_VNET_DISABLED:
            self.jail_vnet = False

        if self.jail_nat == WARDEN_NAT_ENABLED:
            self.jail_nat = True
        elif self.jail_nat == WARDEN_NAT_DISABLED:
            self.jail_nat = False

        #
        # XXX
        #
        # This should probably be done in forms.py.. but for some reason,
        # probably related to how this model fakes out django and doesn't
        # use a database table (just a guess), when changing the form instance
        # variable, it does not reflect in the GUI. Will return to this 
        # particular issue some other time. For now, hacky hack hacks!
        #
        # Also note, the mask/prefix is stripped here for display in the GUI,
        # and appended back on in the form save() method.
        #
        # XXX
        #
        if self.jail_ipv4:
            parts = self.jail_ipv4.split('/')
            self.jail_ipv4 = parts[0]
            if len(parts) > 1:
                self.jail_ipv4_netmask = parts[1]

        if self.jail_bridge_ipv4:
            parts = self.jail_bridge_ipv4.split('/')
            self.jail_bridge_ipv4 = parts[0]
            if len(parts) > 1:
                self.jail_bridge_ipv4_netmask = parts[1]

        if self.jail_ipv6:
            parts = self.jail_ipv6.split('/')
            self.jail_ipv6 = parts[0]
            if len(parts) > 1:
                self.jail_ipv6_prefix = parts[1]

        if self.jail_bridge_ipv6:
            parts = self.jail_bridge_ipv6.split('/')
            self.jail_bridge_ipv6 = parts[0]
            if len(parts) > 1:
                self.jail_bridge_ipv6_prefix = parts[1]

    def delete(self, force=False):
        #FIXME: Cyclic dependency
        from freenasUI.plugins.models import Plugins
        if not force:
            qs = Plugins.objects.filter(plugin_jail=self.jail_host)
            if qs.exists():
                raise MiddlewareError(
                    _("This jail is required by %d plugin(s)") % qs.count()
                )
        Warden().delete(jail=self.jail_host, flags=WARDEN_DELETE_FLAGS_CONFIRM)

    def is_linux_jail(self):
        is_linux = False

        sysctl_path = "%s/sbin/sysctl" % (self.jail_path)
        p = pipeopen("file %s" % sysctl_path, important=False)
        out = p.communicate()
        if p.returncode != 0:
            return is_linux

        try:
            out = out[0]
            parts = out.split(',')
            line = parts[4]
            parts = line.split()
            line = parts[1] 
            if re.match('(.+)?linux(.+)?', line, flags=re.I):
                is_linux = True

        except:
            is_linux = False 

        return is_linux

    class Meta:
        verbose_name = _("Jails")
        verbose_name_plural = _("Jails")
예제 #7
0
파일: forms.py 프로젝트: vanloswang/freenas
    def __init__(self, *args, **kwargs):
        super(InterfacesForm, self).__init__(*args, **kwargs)

        self._carp = False
        _n = notifier()
        if not _n.is_freenas() and _n.failover_licensed():
            from freenasUI.failover.utils import node_label_field
            self._carp = True
            node_label_field(
                _n.failover_node(),
                self.fields['int_ipv4address'],
                self.fields['int_ipv4address_b'],
            )

        if not self._carp:
            del self.fields['int_vip']
            del self.fields['int_vhid']
            del self.fields['int_critical']
            del self.fields['int_group']
            del self.fields['int_ipv4address_b']

        self.fields['int_interface'].choices = choices.NICChoices(nocarp=True)
        self.fields['int_dhcp'].widget.attrs['onChange'] = (
            'javascript:toggleGeneric("id_int_dhcp", ["id_int_ipv4address", '
            '"id_int_ipv4address_b", "id_int_v4netmaskbit"]);')
        self.fields['int_ipv6auto'].widget.attrs['onChange'] = (
            'javascript:toggleGeneric("id_int_ipv6auto", '
            '["id_int_ipv6address", "id_int_v6netmaskbit"]);')
        if 'int_critical' in self.fields:
            self.fields['int_critical'].widget.attrs['onChange'] = (
                'javascript:toggleGeneric("id_int_critical", '
                '["id_int_group"], true);')
        dhcp = False
        ipv6auto = False
        if self.data:
            if self.data.get("int_dhcp"):
                dhcp = True
            if self.data.get("int_ipv6auto"):
                ipv6auto = True
        elif self.instance.id:
            if self.instance.int_dhcp:
                dhcp = True
            if self.instance.int_ipv6auto:
                ipv6auto = True
        if dhcp:
            if 'int_ipv4address' in self.fields:
                self.fields['int_ipv4address'].widget.attrs['disabled'] = (
                    'disabled')
            if 'int_ipv4address_b' in self.fields:
                self.fields['int_ipv4address_b'].widget.attrs['disabled'] = (
                    'disabled')
            self.fields['int_v4netmaskbit'].widget.attrs['disabled'] = (
                'disabled')
        if ipv6auto:
            self.fields['int_ipv6address'].widget.attrs['disabled'] = (
                'disabled')
            self.fields['int_v6netmaskbit'].widget.attrs['disabled'] = (
                'disabled')

        if self.instance.id:
            if 'int_group' in self.fields and not self.instance.int_critical:
                self.fields['int_group'].widget.attrs['disabled'] = (
                    'disabled')
            self.fields['int_interface'] = \
                forms.CharField(
                    label=self.fields['int_interface'].label,
                    initial=self.instance.int_interface,
                    widget=forms.TextInput(
                        attrs={
                            'readonly': True,
                            'class': (
                                'dijitDisabled dijitTextBoxDisabled'
                                ' dijitValidationTextBoxDisabled'
                            ),
                        },
                    )
                )
예제 #8
0
파일: forms.py 프로젝트: vanloswang/freenas
 def __init__(self, *args, **kwargs):
     super(VLANForm, self).__init__(*args, **kwargs)
     self.fields['vlan_pint'].choices = list(
         choices.NICChoices(novlan=True, exclude_configured=False))
예제 #9
0
파일: forms.py 프로젝트: skarekrow/freenas
class DeviceForm(ModelForm):

    CDROM_path = PathField(
        label=_('CD-ROM (ISO)'),
        required=False,
        dirsonly=False,
    )
    DISK_zvol = forms.ChoiceField(
        label=_('ZVol'),
        required=False,
    )
    DISK_mode = forms.ChoiceField(
        label=_('Mode'),
        choices=choices.VM_DISKMODETYPES,
        required=False,
        initial='AHCI',
    )
    DISK_raw = PathField(
        label=_('Raw File'),
        required=False,
        dirsonly=False,
    )
    DISK_sectorsize = forms.IntegerField(
        label=_('Disk sectorsize'),
        required=False,
        initial=0,
        help_text=_("Logical and physical sector size in bytes of the emulated disk."
                    "If 0, a sector size is not set."),
    )
    NIC_type = forms.ChoiceField(
        label=_('Adapter Type'),
        choices=choices.VM_NICTYPES,
        required=False,
        initial='E1000',
    )
    NIC_attach = forms.ChoiceField(
        label=_('Nic to attach'),
        choices=choices.NICChoices(exclude_configured=False),
        required=False,
    )
    NIC_mac = forms.CharField(
        label=_('Mac Address'),
        required=False,
        help_text=_("You can specify the adapter MAC Address or let it be auto generated."),
        validators=[RegexValidator("^([0-9a-fA-F]{2}([::]?|$)){6}$", "Invalid MAC format.")],
        initial='00:a0:98:FF:FF:FF',
    )
    VNC_resolution = forms.ChoiceField(
        label=_('Resolution'),
        choices=choices.VNC_RESOLUTION,
        required=False,
        initial='1024x768',
    )
    VNC_port = forms.CharField(
        label=_('VNC port'),
        required=False,
        help_text=_("You can specify the VNC port or 0 for auto."),
        validators=[RegexValidator("^[0-9]*$", "Only integer is accepted")],
        initial=0,
    )
    VNC_bind = forms.ChoiceField(
        label=_('Bind to'),
        choices=(),
        required=False,
        initial='0.0.0.0'
    )
    VNC_wait = forms.BooleanField(
        label=_('Wait to boot'),
        required=False,
    )

    class Meta:
        fields = '__all__'
        model = models.Device

    def __init__(self, *args, **kwargs):
        super(DeviceForm, self).__init__(*args, **kwargs)
        self.fields['dtype'].widget.attrs['onChange'] = (
            "deviceTypeToggle();"
        )
        self.fields['VNC_bind'].choices = self.ipv4_list()

        diskchoices = {}
        _n = notifier()
        used_zvol = []
        for volume in Volume.objects.filter():
            zvols = _n.list_zfs_vols(volume.vol_name, sort='name')
            for zvol, attrs in zvols.items():
                if "zvol/" + zvol not in used_zvol:
                    diskchoices["zvol/" + zvol] = "%s (%s)" % (
                        zvol,
                        humanize_size(attrs['volsize']))
        self.fields['DISK_zvol'].choices = diskchoices.items()

        if self.instance.id:
            if self.instance.dtype == 'CDROM':
                self.fields['CDROM_path'].initial = self.instance.attributes.get('path', '')
            elif self.instance.dtype == 'DISK':
                self.fields['DISK_zvol'].initial = self.instance.attributes.get('path', '').replace('/dev/', '')
                self.fields['DISK_mode'].initial = self.instance.attributes.get('type')
                self.fields['DISK_sectorsize'].initial = self.instance.attributes.get('sectorsize', 0)
            elif self.instance.dtype == "RAW":
                self.fields['DISK_raw'].initial = self.instance.attributes.get('path', '')
                self.fields['DISK_mode'].initial = self.instance.attributes.get('type')
                self.fields['DISK_sectorsize'].initial = self.instance.attributes.get('sectorsize', 0)
            elif self.instance.dtype == 'NIC':
                self.fields['NIC_type'].initial = self.instance.attributes.get('type')
                self.fields['NIC_mac'].initial = self.instance.attributes.get('mac')
                self.fields['NIC_attach'].initial = self.instance.attributes.get('nic_attach')
            elif self.instance.dtype == 'VNC':
                vnc_port = self.instance.attributes.get('vnc_port')
                vnc_port = 0 if vnc_port is None else vnc_port

                self.fields['VNC_wait'].initial = self.instance.attributes.get('wait')
                self.fields['VNC_port'].initial = vnc_port
                self.fields['VNC_resolution'].initial = self.instance.attributes.get('vnc_resolution')
                self.fields['VNC_bind'].initial = self.instance.attributes.get('vnc_bind')

    def ipv4_list(self):
        choices = (('0.0.0.0', '0.0.0.0'),)
        with client as c:
            ipv4_addresses = c.call('interfaces.ipv4_in_use')
        for ipv4_addr in ipv4_addresses:
            choices = choices + ((ipv4_addr, ipv4_addr),)
        return choices

    def clean(self):
        vm = self.cleaned_data.get('vm')
        vnc_port = self.cleaned_data.get('VNC_port')
        new_vnc_port = 5900
        if vm and vnc_port == '0':
            new_vnc_port = new_vnc_port + int(vm.id)
            self.cleaned_data['VNC_port'] = str(new_vnc_port)

        return self.cleaned_data

    def save(self, *args, **kwargs):
        vm = self.cleaned_data.get('vm')
        kwargs['commit'] = False
        obj = super(DeviceForm, self).save(*args, **kwargs)
        if self.cleaned_data['dtype'] == 'DISK':
            obj.attributes = {
                'path': '/dev/' + self.cleaned_data['DISK_zvol'],
                'type': self.cleaned_data['DISK_mode'],
                'sectorsize': self.cleaned_data['DISK_sectorsize'],
            }
        elif self.cleaned_data['dtype'] == 'RAW':
            obj.attributes = {
                'path': self.cleaned_data['DISK_raw'],
                'type': self.cleaned_data['DISK_mode'],
                'sectorsize': self.cleaned_data['DISK_sectorsize'],
            }
        elif self.cleaned_data['dtype'] == 'CDROM':
            cdrom_path = self.cleaned_data['CDROM_path']
            if cdrom_path:
                obj.attributes = {
                    'path': cdrom_path,
                }
            else:
                self._errors['CDROM_path'] = self.error_class([_('Please choose an ISO file.')])
        elif self.cleaned_data['dtype'] == 'NIC':
            obj.attributes = {
                'type': self.cleaned_data['NIC_type'],
                'mac': self.cleaned_data['NIC_mac'],
                'nic_attach': self.cleaned_data['NIC_attach'],
            }
        elif self.cleaned_data['dtype'] == 'VNC':
            if vm.bootloader == 'UEFI':
                obj.attributes = {
                    'wait': self.cleaned_data['VNC_wait'],
                    'vnc_port': self.cleaned_data['VNC_port'],
                    'vnc_resolution': self.cleaned_data['VNC_resolution'],
                    'vnc_bind': self.cleaned_data['VNC_bind'],
                }
            else:
                self._errors['dtype'] = self.error_class([_('VNC is only allowed for UEFI')])
                self.cleaned_data.pop('VNC_port', None)
                self.cleaned_data.pop('VNC_wait', None)
                self.cleaned_data.pop('VNC_resolution', None)
                self.cleaned_data.pop('VNC_bind', None)
                return obj

        obj.save()
        return obj
예제 #10
0
파일: forms.py 프로젝트: jiangge/freenas
    def __init__(self, *args, **kwargs):
        super(DeviceForm, self).__init__(*args, **kwargs)
        self.fields['dtype'].widget.attrs['onChange'] = ("deviceTypeToggle();")

        self.fields['VNC_bind'].choices = self.ipv4_list()
        self.fields['NIC_attach'].choices = choices.NICChoices(
            exclude_configured=False,
            include_vlan_parent=True,
            include_lagg_parent=False,
        )

        diskchoices = {}
        with client as c:
            for zvol in c.call('pool.dataset.query',
                               [('type', '=', 'VOLUME')]):
                diskchoices[f'zvol/{zvol["name"]}'] = "%s (%s)" % (
                    zvol['name'], humanize_size(zvol['volsize']['parsed']))
        self.fields['DISK_zvol'].choices = diskchoices.items()

        if self.instance.id:
            if self.instance.dtype == 'CDROM':
                self.fields[
                    'CDROM_path'].initial = self.instance.attributes.get(
                        'path', '')
            elif self.instance.dtype == 'DISK':
                self.fields[
                    'DISK_zvol'].initial = self.instance.attributes.get(
                        'path', '').replace('/dev/', '')
                self.fields[
                    'DISK_mode'].initial = self.instance.attributes.get('type')
                self.fields[
                    'DISK_sectorsize'].initial = self.instance.attributes.get(
                        'sectorsize', 0)
            elif self.instance.dtype == 'RAW':
                self.fields['DISK_raw'].initial = self.instance.attributes.get(
                    'path', '')
                self.fields[
                    'DISK_mode'].initial = self.instance.attributes.get('type')
                self.fields[
                    'DISK_sectorsize'].initial = self.instance.attributes.get(
                        'sectorsize', 0)

                if self.instance.vm.vm_type == 'Container Provider':
                    self.fields['DISK_raw_boot'].widget = forms.CheckboxInput()
                    self.fields['DISK_raw_size'].widget = forms.TextInput()
                    self.fields['ROOT_password'].widget = forms.PasswordInput(
                        render_value=True, )

                self.fields[
                    'DISK_raw_boot'].initial = self.instance.attributes.get(
                        'boot', False)
                self.fields[
                    'DISK_raw_size'].initial = self.instance.attributes.get(
                        'size', '')
                self.fields[
                    'ROOT_password'].initial = self.instance.attributes.get(
                        'rootpwd', '')
            elif self.instance.dtype == 'NIC':
                self.fields['NIC_type'].initial = self.instance.attributes.get(
                    'type')
                self.fields['NIC_mac'].initial = self.instance.attributes.get(
                    'mac')
                self.fields[
                    'NIC_attach'].initial = self.instance.attributes.get(
                        'nic_attach')
            elif self.instance.dtype == 'VNC':
                vnc_port = self.instance.attributes.get('vnc_port')
                vnc_port = 0 if vnc_port is None else vnc_port

                self.fields['VNC_wait'].initial = self.instance.attributes.get(
                    'wait')
                self.fields['VNC_port'].initial = vnc_port
                self.fields[
                    'VNC_resolution'].initial = self.instance.attributes.get(
                        'vnc_resolution')
                self.fields['VNC_bind'].initial = self.instance.attributes.get(
                    'vnc_bind')
                self.fields[
                    'VNC_password'].initial = self.instance.attributes.get(
                        'vnc_password')
                self.fields['VNC_web'].initial = self.instance.attributes.get(
                    'vnc_web')
예제 #11
0
class DeviceForm(ModelForm):

    CDROM_path = PathField(
        label=_('CD-ROM (ISO)'),
        required=False,
        dirsonly=False,
    )
    DISK_zvol = forms.ChoiceField(
        label=_('ZVol'),
        required=False,
    )
    DISK_mode = forms.ChoiceField(
        label=_('Mode'),
        choices=choices.VM_DISKMODETYPES,
        required=False,
        initial='AHCI',
    )
    DISK_raw = PathField(
        label=_('Raw File'),
        required=False,
        dirsonly=False,
    )
    DISK_raw_boot = forms.BooleanField(
        label=_('Disk boot'),
        widget=forms.widgets.HiddenInput(),
        required=False,
        initial=False,
    )
    ROOT_password = forms.CharField(
        label=_('Password'),
        max_length=50,
        widget=forms.widgets.HiddenInput(),
        required=False,
        help_text=_("Set the password for the rancher user."),
    )
    DISK_sectorsize = forms.IntegerField(
        label=_('Disk sectorsize'),
        required=False,
        initial=0,
        help_text=_(
            "Sector size of the emulated disk in bytes. Both logical and physical sector size are set to this value."
            "If 0, a sector size is not set."),
    )
    DISK_raw_size = forms.CharField(
        label=_('Disk size'),
        widget=forms.widgets.HiddenInput(),
        required=False,
        initial=0,
        validators=[
            RegexValidator(
                "^(\d*)\s?([M|G|T]?)$",
                "Enter M, G, or T after the value to use megabytes, gigabytes or terabytes."
                " When no suffix letter is entered, the units default to gigabytes."
            )
        ],
        help_text=
        _("Resize the existing raw disk. Enter 0 to use the disk with the current size."
          ),
    )
    NIC_type = forms.ChoiceField(
        label=_('Adapter Type'),
        choices=choices.VM_NICTYPES,
        required=False,
        initial='E1000',
    )
    NIC_attach = forms.ChoiceField(
        label=_('NIC to attach'),
        choices=choices.NICChoices(exclude_configured=False),
        required=False,
    )
    NIC_mac = forms.CharField(
        label=_('MAC Address'),
        required=False,
        help_text=
        _("Specify the adapter MAC Address or leave empty to be auto generated."
          ),
        validators=[
            RegexValidator("^([0-9a-fA-F]{2}([::]?|$)){6}$",
                           "Invalid MAC format.")
        ],
        initial='00:a0:98:FF:FF:FF',
    )
    VNC_resolution = forms.ChoiceField(
        label=_('Resolution'),
        choices=choices.VNC_RESOLUTION,
        required=False,
        initial='1024x768',
    )
    VNC_port = forms.CharField(
        label=_('VNC port'),
        required=False,
        help_text=_("Specify the VNC port or set to 0 for auto."),
        validators=[RegexValidator("^[0-9]*$", "Only integers are accepted")],
        initial=0,
    )
    VNC_bind = forms.ChoiceField(label=_('Bind to'),
                                 choices=(),
                                 required=False,
                                 initial='0.0.0.0')
    VNC_wait = forms.BooleanField(
        label=_('Wait to boot'),
        required=False,
    )
    VNC_password = forms.CharField(
        label=_('Password'),
        max_length=8,
        widget=forms.PasswordInput(render_value=True, ),
        required=False,
        help_text=_("The VNC password authentication."
                    "Maximum password length is 8 characters."))
    VNC_web = forms.BooleanField(
        label=_('VNC Web'),
        required=False,
    )

    class Meta:
        fields = '__all__'
        model = models.Device

    def __init__(self, *args, **kwargs):
        super(DeviceForm, self).__init__(*args, **kwargs)
        self.fields['dtype'].widget.attrs['onChange'] = ("deviceTypeToggle();")

        self.fields['VNC_bind'].choices = self.ipv4_list()

        diskchoices = {}
        _n = notifier()
        used_zvol = []
        for volume in Volume.objects.filter():
            zvols = _n.list_zfs_vols(volume.vol_name, sort='name')
            for zvol, attrs in zvols.items():
                if "zvol/" + zvol not in used_zvol:
                    diskchoices["zvol/" + zvol] = "%s (%s)" % (
                        zvol, humanize_size(attrs['volsize']))
        self.fields['DISK_zvol'].choices = diskchoices.items()

        if self.instance.id:
            if self.instance.dtype == 'CDROM':
                self.fields[
                    'CDROM_path'].initial = self.instance.attributes.get(
                        'path', '')
            elif self.instance.dtype == 'DISK':
                self.fields[
                    'DISK_zvol'].initial = self.instance.attributes.get(
                        'path', '').replace('/dev/', '')
                self.fields[
                    'DISK_mode'].initial = self.instance.attributes.get('type')
                self.fields[
                    'DISK_sectorsize'].initial = self.instance.attributes.get(
                        'sectorsize', 0)
            elif self.instance.dtype == 'RAW':
                self.fields['DISK_raw'].initial = self.instance.attributes.get(
                    'path', '')
                self.fields[
                    'DISK_mode'].initial = self.instance.attributes.get('type')
                self.fields[
                    'DISK_sectorsize'].initial = self.instance.attributes.get(
                        'sectorsize', 0)

                if self.instance.vm.vm_type == 'Container Provider':
                    self.fields['DISK_raw_boot'].widget = forms.CheckboxInput()
                    self.fields['DISK_raw_size'].widget = forms.TextInput()
                    self.fields['ROOT_password'].widget = forms.PasswordInput(
                        render_value=True, )

                self.fields[
                    'DISK_raw_boot'].initial = self.instance.attributes.get(
                        'boot', False)
                self.fields[
                    'DISK_raw_size'].initial = self.instance.attributes.get(
                        'size', '')
                self.fields[
                    'ROOT_password'].initial = self.instance.attributes.get(
                        'rootpwd', '')
            elif self.instance.dtype == 'NIC':
                self.fields['NIC_type'].initial = self.instance.attributes.get(
                    'type')
                self.fields['NIC_mac'].initial = self.instance.attributes.get(
                    'mac')
                self.fields[
                    'NIC_attach'].initial = self.instance.attributes.get(
                        'nic_attach')
            elif self.instance.dtype == 'VNC':
                vnc_port = self.instance.attributes.get('vnc_port')
                vnc_port = 0 if vnc_port is None else vnc_port

                self.fields['VNC_wait'].initial = self.instance.attributes.get(
                    'wait')
                self.fields['VNC_port'].initial = vnc_port
                self.fields[
                    'VNC_resolution'].initial = self.instance.attributes.get(
                        'vnc_resolution')
                self.fields['VNC_bind'].initial = self.instance.attributes.get(
                    'vnc_bind')
                self.fields[
                    'VNC_password'].initial = self.instance.attributes.get(
                        'vnc_password')
                self.fields['VNC_web'].initial = self.instance.attributes.get(
                    'vnc_web')

    def ipv4_list(self):
        choices = (('0.0.0.0', '0.0.0.0'), )
        with client as c:
            ipv4_addresses = c.call('interfaces.ipv4_in_use')
        for ipv4_addr in ipv4_addresses:
            choices = choices + ((ipv4_addr, ipv4_addr), )
        return choices

    def clean(self):
        vm = self.cleaned_data.get('vm')
        vnc_port = self.cleaned_data.get('VNC_port')
        new_vnc_port = 5900
        if vm and vnc_port == '0':
            new_vnc_port = new_vnc_port + int(vm.id)
            self.cleaned_data['VNC_port'] = str(new_vnc_port)

        return self.cleaned_data

    def is_container(self, vm_type):
        if vm_type == 'Container Provider':
            return True
        else:
            return False

    def save(self, *args, **kwargs):
        vm = self.cleaned_data.get('vm')
        kwargs['commit'] = False
        obj = super(DeviceForm, self).save(*args, **kwargs)

        if self.cleaned_data['dtype'] == 'DISK':
            obj.attributes = {
                'path': '/dev/' + self.cleaned_data['DISK_zvol'],
                'type': self.cleaned_data['DISK_mode'],
                'sectorsize': self.cleaned_data['DISK_sectorsize'],
            }
        elif self.cleaned_data['dtype'] == 'RAW':
            if self.is_container(vm.vm_type):
                if self.cleaned_data['DISK_mode'] == 'VIRTIO':
                    self._errors['dtype'] = self.error_class(
                        [_('Containers require AHCI mode.')])
            obj.attributes = {
                'path': self.cleaned_data['DISK_raw'],
                'type': self.cleaned_data['DISK_mode'],
                'sectorsize': self.cleaned_data['DISK_sectorsize'],
                'boot': self.cleaned_data['DISK_raw_boot'],
                'size': self.cleaned_data['DISK_raw_size'],
                'rootpwd': self.cleaned_data['ROOT_password'],
            }
        elif self.cleaned_data['dtype'] == 'CDROM':
            cdrom_path = self.cleaned_data['CDROM_path']
            if cdrom_path:
                obj.attributes = {
                    'path': cdrom_path,
                }
            else:
                self._errors['CDROM_path'] = self.error_class(
                    [_('Please choose an ISO file.')])
        elif self.cleaned_data['dtype'] == 'NIC':
            obj.attributes = {
                'type': self.cleaned_data['NIC_type'],
                'mac': self.cleaned_data['NIC_mac'],
                'nic_attach': self.cleaned_data['NIC_attach'],
            }
        elif self.cleaned_data['dtype'] == 'VNC':
            if vm.bootloader == 'UEFI' and self.is_container(
                    vm.vm_type) is False:
                obj.attributes = {
                    'wait': self.cleaned_data['VNC_wait'],
                    'vnc_port': self.cleaned_data['VNC_port'],
                    'vnc_resolution': self.cleaned_data['VNC_resolution'],
                    'vnc_bind': self.cleaned_data['VNC_bind'],
                    'vnc_password': self.cleaned_data['VNC_password'],
                    'vnc_web': self.cleaned_data['VNC_web'],
                }
            else:
                self._errors['dtype'] = self.error_class(
                    [_('VNC only works with UEFI VMs')])
                self.cleaned_data.pop('VNC_port', None)
                self.cleaned_data.pop('VNC_wait', None)
                self.cleaned_data.pop('VNC_resolution', None)
                self.cleaned_data.pop('VNC_bind', None)
                self.cleaned_data.pop('VNC_password', None)
                self.cleaned_data.pop('VNC_web', None)
                return obj

        obj.save()
        return obj
예제 #12
0
 def __init__(self, *args, **kwargs):
     super(SSHForm, self).__init__(*args, **kwargs)
     self.fields['ssh_bindiface'].choices = list(
         choices.NICChoices(exclude_configured=False,
                            exclude_unconfigured_vlan_parent=True))
예제 #13
0
 def __init__(self, *args, **kwargs):
     super(LAGGInterfaceForm, self).__init__(*args, **kwargs)
     self.fields['lagg_interfaces'].choices = list(
         choices.NICChoices(nolagg=True))
예제 #14
0
파일: forms.py 프로젝트: plitc/freenas
    def __init__(self, *args, **kwargs):
        super(InterfacesForm, self).__init__(*args, **kwargs)
        self.fields['int_interface'].choices = choices.NICChoices()
        self.fields['int_dhcp'].widget.attrs['onChange'] = (
            'javascript:toggleGeneric("id_int_dhcp", ["id_int_ipv4address", '
            '"id_int_v4netmaskbit"]);')
        self.fields['int_ipv6auto'].widget.attrs['onChange'] = (
            'javascript:toggleGeneric("id_int_ipv6auto", '
            '["id_int_ipv6address", "id_int_v6netmaskbit"]);')
        dhcp = False
        ipv6auto = False
        if self.data:
            if self.data.get("int_dhcp"):
                dhcp = True
            if self.data.get("int_ipv6auto"):
                ipv6auto = True
        elif self.instance.id:
            if self.instance.int_dhcp:
                dhcp = True
            if self.instance.int_ipv6auto:
                ipv6auto = True
        if dhcp:
            self.fields['int_ipv4address'].widget.attrs['disabled'] = (
                'disabled')
            self.fields['int_v4netmaskbit'].widget.attrs['disabled'] = (
                'disabled')
        if ipv6auto:
            self.fields['int_ipv6address'].widget.attrs['disabled'] = (
                'disabled')
            self.fields['int_v6netmaskbit'].widget.attrs['disabled'] = (
                'disabled')

        if self.instance.id:
            if self.instance.int_interface.startswith('carp'):
                self.fields['int_v4netmaskbit'].widget.attrs['readonly'] = True
                self.fields['int_v4netmaskbit'].widget.attrs['class'] = (
                    'dijitDisabled dijitSelectDisabled')
                self.fields['int_v4netmaskbit'].initial = '32'
                self.instance.int_v4netmaskbit = '32'
            self.fields['int_interface'] = \
                forms.CharField(
                    label=self.fields['int_interface'].label,
                    initial=self.instance.int_interface,
                    widget=forms.TextInput(
                        attrs={
                            'readonly': True,
                            'class': (
                                'dijitDisabled dijitTextBoxDisabled'
                                ' dijitValidationTextBoxDisabled'
                            ),
                        },
                    )
                )
        else:
            # In case there is a CARP instance but no Interfaces instance
            if hasattr(notifier, 'failover_status'):
                from freenasUI.failover.models import CARP
                int_interfaces = [
                    o.int_interface for o in models.Interfaces.objects.all()
                ]
                for o in CARP.objects.all():
                    if o.carp_name not in int_interfaces:
                        self.fields['int_interface'].choices += [
                            (o.carp_name, o.carp_name),
                        ]