Beispiel #1
0
    def save(self):
        try:
            jc = JailsConfiguration.objects.order_by("-id")[0]
        except Exception as e:
            raise MiddlewareError(e.message)

        if not jc.jc_path:
            raise MiddlewareError(_("No jail root configured."))

        jail_host = self.cleaned_data.get('jail_host')
        jail_ipv4 = self.cleaned_data.get('jail_ipv4')
        jail_ipv6 = self.cleaned_data.get('jail_ipv6')

        jail_flags = WARDEN_FLAGS_NONE
        jail_create_args = {}
        jail_create_args['jail'] = jail_host

        w = Warden()

        if self.cleaned_data['jail_32bit']:
            jail_flags |= WARDEN_CREATE_FLAGS_32BIT


#        if self.cleaned_data['jail_source']:
#            jail_flags |= WARDEN_CREATE_FLAGS_SRC
#        if self.cleaned_data['jail_ports']:
#            jail_flags |= WARDEN_CREATE_FLAGS_PORTS
        if self.cleaned_data['jail_vanilla']:
            jail_flags |= WARDEN_CREATE_FLAGS_VANILLA

        template_create_args = {}

        jail_type = self.cleaned_data['jail_type']
        template = JailTemplate.objects.get(jt_name=jail_type)
        template_create_args['nick'] = template.jt_name
        template_create_args['tar'] = template.jt_url
        template_create_args['flags'] = WARDEN_TEMPLATE_FLAGS_CREATE | \
            WARDEN_TEMPLATE_CREATE_FLAGS_NICK | \
            WARDEN_TEMPLATE_CREATE_FLAGS_TAR

        template = None
        template_list_flags = {}
        template_list_flags['flags'] = WARDEN_TEMPLATE_FLAGS_LIST
        templates = w.template(**template_list_flags)
        for t in templates:
            if t['nick'] == template_create_args['nick']:
                template = t
                break

        createfile = "/var/tmp/.templatecreate"
        if not template:
            try:
                cf = open(createfile, "a+")
                cf.close()
                w.template(**template_create_args)

            except Exception as e:
                self.errors['__all__'] = self.error_class([_(e.message)])
                if os.path.exists(createfile):
                    os.unlink(createfile)
                return

            template_list_flags = {}
            template_list_flags['flags'] = WARDEN_TEMPLATE_FLAGS_LIST
            templates = w.template(**template_list_flags)
            for t in templates:
                if t['nick'] == template_create_args['nick']:
                    template = t
                    break

        if not template:
            self.errors['__all__'] = self.error_class(
                [_('Unable to find template!')])
            return

        if template['type'] == 'Linux':
            jail_flags |= WARDEN_CREATE_FLAGS_LINUXJAIL
        if template['arch'] == 'i386':
            jail_flags |= WARDEN_CREATE_FLAGS_32BIT

        jail_flags |= WARDEN_CREATE_FLAGS_TEMPLATE
        jail_create_args['template'] = template_create_args['nick']

        if jail_ipv4:
            jail_flags |= WARDEN_CREATE_FLAGS_IPV4
            jail_create_args['ipv4'] = jail_ipv4

        if jail_ipv6:
            jail_flags |= WARDEN_CREATE_FLAGS_IPV6
            jail_create_args['ipv6'] = jail_ipv6

        jail_flags |= WARDEN_CREATE_FLAGS_LOGFILE
        jail_flags |= WARDEN_CREATE_FLAGS_SYSLOG

        jail_create_args['logfile'] = self.logfile
        jail_create_args['flags'] = jail_flags

        createfile = "/var/tmp/.jailcreate"
        try:
            cf = open(createfile, "a+")
            cf.close()
            w.create(**jail_create_args)

        except Exception as e:
            self.errors['__all__'] = self.error_class([_(e.message)])
            if os.path.exists(createfile):
                os.unlink(createfile)
            return

        if os.path.exists(createfile):
            os.unlink(createfile)

        for key in ('jail_bridge_ipv4', 'jail_bridge_ipv6',
                    'jail_defaultrouter_ipv4', 'jail_defaultrouter_ipv6',
                    'jail_mac'):
            jail_set_args = {}
            jail_set_args['jail'] = jail_host
            jail_flags = WARDEN_FLAGS_NONE
            val = self.cleaned_data.get(key, None)
            if val:
                if key == 'jail_bridge_ipv4':
                    jail_flags |= WARDEN_SET_FLAGS_BRIDGE_IPV4
                    jail_set_args['bridge-ipv4'] = val

                elif key == 'jail_bridge_ipv6':
                    jail_flags |= WARDEN_SET_FLAGS_BRIDGE_IPV6
                    jail_set_args['bridge-ipv6'] = val

                elif key == 'jail_defaultrouter_ipv4':
                    jail_flags |= WARDEN_SET_FLAGS_DEFAULTROUTER_IPV4
                    jail_set_args['defaultrouter-ipv4'] = val

                elif key == 'jail_defaultrouter_ipv6':
                    jail_flags |= WARDEN_SET_FLAGS_DEFAULTROUTER_IPV6
                    jail_set_args['defaultrouter-ipv6'] = val

                elif key == 'jail_mac':
                    jail_flags |= WARDEN_SET_FLAGS_MAC
                    jail_set_args['mac'] = val

                jail_set_args['flags'] = jail_flags
                try:
                    w.set(**jail_set_args)
                except Exception as e:
                    self.errors['__all__'] = self.error_class([_(e.message)])
                    return

        jail_nat = self.cleaned_data.get('jail_nat', None)
        jail_vnet = self.cleaned_data.get('jail_vnet', None)

        jail_set_args = {}
        jail_set_args['jail'] = jail_host
        jail_flags = WARDEN_FLAGS_NONE
        if jail_nat:
            jail_flags |= WARDEN_SET_FLAGS_NAT_ENABLE
        else:
            jail_flags |= WARDEN_SET_FLAGS_NAT_DISABLE

        jail_set_args['flags'] = jail_flags
        try:
            w.set(**jail_set_args)
        except Exception as e:
            self.errors['__all__'] = self.error_class([_(e.message)])
            return

        jail_set_args = {}
        jail_set_args['jail'] = jail_host
        jail_flags = WARDEN_FLAGS_NONE
        if jail_vnet:
            # XXXX if NOT LINUX XXXX (revisit this)
            if (not self.cleaned_data['jail_32bit']):
                jail_flags |= WARDEN_SET_FLAGS_VNET_ENABLE
            else:
                jail_flags |= WARDEN_SET_FLAGS_VNET_DISABLE

            jail_set_args['flags'] = jail_flags
            try:
                w.set(**jail_set_args)
            except Exception as e:
                self.errors['__all__'] = self.error_class([_(e.message)])
                return

        if self.cleaned_data['jail_autostart']:
            try:
                w.auto(jail=jail_host)
            except Exception as e:
                self.errors['__all__'] = self.error_class([_(e.message)])
                return

        try:
            w.start(jail=jail_host)
        except Exception as e:
            self.errors['__all__'] = self.error_class([_(e.message)])
            return
Beispiel #2
0
    def save(self):
        jc = self.jc

        if not jc.jc_path:
            raise MiddlewareError(_("No jail root configured."))

        jc_ipv4_netmask = 24
        if jc.jc_ipv4_network:
            parts = jc.jc_ipv4_network.split('/')
            if len(parts) > 1:
                jc_ipv4_netmask = parts[1]

        jc_ipv6_prefix = 64
        if jc.jc_ipv6_network:
            parts = jc.jc_ipv6_network.split('/')
            if len(parts) > 1:
                jc_ipv6_prefix = parts[1]

        jail_host = self.cleaned_data.get('jail_host')
        jail_ipv4_dhcp = self.cleaned_data.get('jail_ipv4_dhcp')
        jail_ipv4 = self.cleaned_data.get('jail_ipv4')
        jail_ipv4_netmask = self.cleaned_data.get('jail_ipv4_netmask',
                                                  jc_ipv4_netmask)

        jail_ipv6_autoconf = self.cleaned_data.get('jail_ipv6_autoconf')
        jail_ipv6 = self.cleaned_data.get('jail_ipv6')
        jail_ipv6_prefix = self.cleaned_data.get('jail_ipv6_prefix',
                                                 jc_ipv6_prefix)

        jail_flags = WARDEN_FLAGS_NONE
        jail_flags |= WARDEN_CREATE_FLAGS_VANILLA

        jail_create_args = {}
        jail_create_args['jail'] = jail_host

        w = Warden()

        template_create_args = {}
        jail_type = self.cleaned_data['jail_type']
        if not jail_type:
            jail_type = 'standard'
        template = JailTemplate.objects.get(jt_name=jail_type)
        template_create_args['nick'] = template.jt_name
        template_create_args['tar'] = template.jt_url
        template_create_args['flags'] = WARDEN_TEMPLATE_FLAGS_CREATE | \
            WARDEN_TEMPLATE_CREATE_FLAGS_NICK | \
            WARDEN_TEMPLATE_CREATE_FLAGS_TAR
        if template.jt_mtree:
            template_create_args['mtree'] = template.jt_mtree
            template_create_args['flags'] = template_create_args['flags'] | \
                WARDEN_TEMPLATE_CREATE_FLAGS_MTREE

        saved_template = template
        template = None
        template_list_flags = {}
        template_list_flags['flags'] = WARDEN_TEMPLATE_FLAGS_LIST
        templates = w.template(**template_list_flags)
        for t in templates:
            if t['nick'] == template_create_args['nick']:
                template = t
                break

        createfile = "/var/tmp/.templatecreate"
        if not template:
            try:
                cf = open(createfile, "a+")
                cf.close()
                w.template(**template_create_args)

            except Exception as e:
                self.errors['__all__'] = self.error_class([_(e.message)])
                if os.path.exists(createfile):
                    os.unlink(createfile)
                return

            template_list_flags = {}
            template_list_flags['flags'] = WARDEN_TEMPLATE_FLAGS_LIST
            templates = w.template(**template_list_flags)
            for t in templates:
                if t['nick'] == template_create_args['nick']:
                    template = t
                    break

        if not template:
            self.errors['__all__'] = self.error_class(
                [_('Unable to find template!')])
            return

        if template['type'] == 'Linux':
            jail_flags |= WARDEN_CREATE_FLAGS_LINUXJAIL
        if template['arch'] == 'i386' and self.arch == 'x64':
            jail_flags |= WARDEN_CREATE_FLAGS_32BIT

        jail_flags |= WARDEN_CREATE_FLAGS_TEMPLATE
        jail_create_args['template'] = template_create_args['nick']

        if jail_ipv4_dhcp:
            jail_ipv4 = "DHCP"

        if jail_ipv4:
            if jail_ipv4 != "DHCP":
                jail_ipv4 = "%s/%s" % (jail_ipv4, jail_ipv4_netmask)

            jail_flags |= WARDEN_CREATE_FLAGS_IPV4
            jail_create_args['ipv4'] = jail_ipv4

        if jail_ipv6_autoconf:
            jail_ipv6 = "AUTOCONF"

        if jail_ipv6:
            if jail_ipv6 != "AUTOCONF":
                jail_ipv6 = "%s/%s" % (jail_ipv6, jail_ipv6_prefix)

            jail_flags |= WARDEN_CREATE_FLAGS_IPV6
            jail_create_args['ipv6'] = jail_ipv6

        jail_flags |= WARDEN_CREATE_FLAGS_LOGFILE
        jail_flags |= WARDEN_CREATE_FLAGS_SYSLOG

        jail_create_args['logfile'] = self.logfile
        jail_create_args['flags'] = jail_flags

        createfile = "/var/tmp/.jailcreate"
        try:
            cf = open(createfile, "a+")
            cf.close()
            w.create(**jail_create_args)

        except Exception as e:
            self.errors['__all__'] = self.error_class([_(e.message)])
            if os.path.exists(createfile):
                os.unlink(createfile)
            return

        if os.path.exists(createfile):
            os.unlink(createfile)

        for key in ('jail_bridge_ipv4', 'jail_bridge_ipv6',
                    'jail_defaultrouter_ipv4', 'jail_defaultrouter_ipv6',
                    'jail_mac', 'jail_iface', 'jail_flags'):
            jail_set_args = {}
            jail_set_args['jail'] = jail_host
            jail_flags = WARDEN_FLAGS_NONE
            val = self.cleaned_data.get(key, None)
            if val:
                if key == 'jail_bridge_ipv4':
                    mask = self.cleaned_data.get('jail_bridge_ipv4_netmask',
                                                 jc_ipv4_netmask)
                    jail_flags |= WARDEN_SET_FLAGS_BRIDGE_IPV4
                    jail_set_args['bridge-ipv4'] = "%s/%s" % (val, mask)

                elif key == 'jail_bridge_ipv6':
                    prefix = self.cleaned_data.get('jail_bridge_ipv6_prefix',
                                                   jc_ipv6_prefix)
                    jail_flags |= WARDEN_SET_FLAGS_BRIDGE_IPV6
                    jail_set_args['bridge-ipv6'] = "%s/%s" % (val, prefix)

                elif key == 'jail_defaultrouter_ipv4':
                    jail_flags |= WARDEN_SET_FLAGS_DEFAULTROUTER_IPV4
                    jail_set_args['defaultrouter-ipv4'] = val

                elif key == 'jail_defaultrouter_ipv6':
                    jail_flags |= WARDEN_SET_FLAGS_DEFAULTROUTER_IPV6
                    jail_set_args['defaultrouter-ipv6'] = val

                elif key == 'jail_mac':
                    jail_flags |= WARDEN_SET_FLAGS_MAC
                    jail_set_args['mac'] = val

                elif key == 'jail_iface':
                    jail_flags |= WARDEN_SET_FLAGS_IFACE
                    jail_set_args['iface'] = val

                elif key == 'jail_flags':
                    jail_flags |= WARDEN_SET_FLAGS_FLAGS
                    jail_set_args['jflags'] = val

            elif key == 'jail_mac':
                jail_mac_list = [jail.jail_mac for jail in Jails.objects.all()]
                mac_address = generate_randomMAC()
                while mac_address in jail_mac_list:
                    mac_address = generate_randomMAC()

                jail_flags |= WARDEN_SET_FLAGS_MAC
                jail_set_args['mac'] = mac_address

            jail_set_args['flags'] = jail_flags
            try:
                w.set(**jail_set_args)
            except Exception as e:
                self.errors['__all__'] = self.error_class([_(e.message)])
                return

        jail_nat = self.cleaned_data.get('jail_nat', None)
        jail_vnet = self.cleaned_data.get('jail_vnet', None)
        if jc.jc_ipv4_dhcp or jc.jc_ipv6_autoconf:
            jail_vnet = True

        jail_set_args = {}
        jail_set_args['jail'] = jail_host
        jail_flags = WARDEN_FLAGS_NONE
        if jail_nat:
            jail_flags |= WARDEN_SET_FLAGS_NAT_ENABLE
        else:
            jail_flags |= WARDEN_SET_FLAGS_NAT_DISABLE

        jail_set_args['flags'] = jail_flags
        try:
            w.set(**jail_set_args)
        except Exception as e:
            self.errors['__all__'] = self.error_class([_(e.message)])
            return

        jail_set_args = {}
        jail_set_args['jail'] = jail_host
        jail_flags = WARDEN_FLAGS_NONE
        if jail_vnet:
            # XXXX if NOT LINUX XXXX (revisit this)
            if (saved_template.jt_arch != 'x86'
                    and saved_template.jt_os != 'Linux'):
                jail_flags |= WARDEN_SET_FLAGS_VNET_ENABLE
            else:
                jail_flags |= WARDEN_SET_FLAGS_VNET_DISABLE

            jail_set_args['flags'] = jail_flags
            try:
                w.set(**jail_set_args)
            except Exception as e:
                self.errors['__all__'] = self.error_class([_(e.message)])
                return

        if self.cleaned_data['jail_autostart']:
            try:
                w.auto(jail=jail_host)
            except Exception as e:
                self.errors['__all__'] = self.error_class([_(e.message)])
                return

        try:
            w.start(jail=jail_host)
        except Exception as e:
            self.errors['__all__'] = self.error_class([_(e.message)])
            return

        # Requery instance so we have everything up-to-date after save
        # See #14686
        self.instance = Jails.objects.get(jail_host=jail_host)
        if self.instance:
            add_media_user_and_group(self.instance.jail_path)
Beispiel #3
0
def perftest(request):

    systemdataset, volume, basename = notifier().system_dataset_settings()

    if request.method == 'GET':
        p1 = subprocess.Popen([
            '/usr/local/bin/perftests-nas',
            '-t',
        ],
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)
        tests = p1.communicate()[0].strip('\n').split('\n')
        return render(request, 'system/perftest.html', {
            'tests': tests,
        })

    if not basename:
        raise MiddlewareError(
            _('System dataset is required to perform this action.'))

    dump = os.path.join(notifier().system_dataset_path(), 'perftest.txz')
    perftestdataset = '%s/perftest' % basename
    perftestdir = os.path.join(notifier().system_dataset_path(), 'perftest')

    with mntlock(mntpt=notifier().system_dataset_path()):

        _n = notifier()

        rv, errmsg = _n.create_zfs_dataset(
            path=perftestdataset,
            props={
                'primarycache': 'metadata',
                'secondarycache': 'metadata',
                'mountpoint': 'legacy',
                'compression': 'off',
            },
            _restart_collectd=False,
        )

        currdir = os.getcwd()

    if not os.path.isdir(perftestdir):
        os.mkdir(perftestdir)
        os.chdir(perftestdir)

    os.system('/sbin/mount -t zfs %s %s' % (perftestdataset, perftestdir))

    p1 = subprocess.Popen([
        '/usr/local/bin/perftests-nas',
        '-o',
        perftestdataset.encode('utf8'),
        '-s',
        str(PERFTEST_SIZE),
    ],
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT)
    p1.communicate()

    os.chdir('..')

    p1 = pipeopen('tar -cJf %s perftest' % dump)
    p1.communicate()

    os.chdir(currdir)

    os.system('/sbin/umount -f %s' % perftestdataset)
    os.rmdir(perftestdir)
    _n.destroy_zfs_dataset(perftestdataset)

    return JsonResp(
        request,
        message='Performance test has completed.',
        events=[
            'window.location=\'%s\'' % reverse('system_perftest_download'),
        ],
    )
Beispiel #4
0
        self.fields['destination'].widget.attrs['root'] = jail_path

        self.fields['mpjc_path'].widget = forms.widgets.HiddenInput()
        self.fields['mpjc_path'].initial = self.jc.jc_path

        if self.instance.id:
            self.fields['mounted'].initial = self.instance.mounted
        else:
            self.fields['mounted'].widget = forms.widgets.HiddenInput()

    def save(self, *args, **kwargs):
        obj = super(NullMountPointForm, self).save(*args, **kwargs)
        mounted = self.cleaned_data.get("mounted")
        if mounted == obj.mounted:
            return obj
        if mounted:
            try:
                obj.mount()
            except ValueError, e:
                raise MiddlewareError(
                    _("The path could not be mounted %s: %s") % (
                        obj.source,
                        e,
                    ))
        elif obj.umount():
            #FIXME better error handling, show the user why
            raise MiddlewareError(
                _("The path could not be umounted %s") % (obj.source, ))

        return obj
Beispiel #5
0
        p = os.popen(". /etc/rc.freenas; jail_update_fstab '%s';" %
                     self.cleaned_data.get('jail'))
        p.close()

        mounted = self.cleaned_data.get("mounted")
        if mounted == obj.mounted:
            return obj
        if mounted:
            try:
                obj.mount()
            except ValueError, e:
                raise MiddlewareError(
                    _("The path could not be mounted %(source)s: %(error)s") %
                    {
                        'source': obj.source,
                        'error': e,
                    })
        else:
            try:
                obj.umount()
            except ValueError, e:
                raise MiddlewareError(
                    _("The path could not be umounted %(source)s: %(error)s" %
                      {
                          'source': obj.source,
                          'error': e,
                      }))

        return obj
Beispiel #6
0
 def save(self):
     try:
         super(ActiveDirectoryForm, self).save()
     except Exception as e:
         raise MiddlewareError(e)
Beispiel #7
0
def jail_auto_configure():
    import platform
    """
    Auto configure the jail settings

    The first ZFS volume found will be selected.
    A dataset called jails will be created, if it already exists then
    append "_N" where N 2..100 until a dataset is not found.
    """

    vol_fstype = 'ZFS'
    volume = Volume.objects.filter(vol_fstype='ZFS')
    if not volume.exists():
        log.warn("ZFS is recommended for plugins!")
        volume = Volume.objects.filter(vol_fstype='UFS')
        if not volume.exists():
            raise MiddlewareError(_("You need to create a volume to proceed!"))
        vol_fstype = 'UFS'

    volume = volume[0]
    basename = "%s/jails" % volume.vol_name

    if vol_fstype == 'ZFS':
        name = basename
        for i in xrange(2, 100):
            datasets = list_datasets(
                path="/mnt/%s" % name,
                recursive=False,
            )
            if not datasets:
                break
            else:
                name = "%s_%d" % (basename, i)
        rv, err = notifier().create_zfs_dataset(name)
        if rv != 0:
            raise MiddlewareError(
                _("Failed to create dataset %(name)s: %(error)s") % {
                    'name': name,
                    'error': err,
                })

    elif vol_fstype == 'UFS':
        name = "/mnt/%s" % basename
        if os.path.exists(name):
            max = 1
            dirs = glob.glob("%s_*" % name)
            if dirs:
                for d in dirs:
                    parts = d.split('_')
                    if len(parts) > 1 and re.match('^[0-9]+$', parts[1]):
                        num = int(parts[1])
                        if num > max:
                            max = num

            name = "%s_%d" % (name, max + 1)

        name = name.replace('/mnt/', '')
        try:
            os.makedirs("/mnt/%s" % name)

        except Exception as e:
            raise MiddlewareError(
                _("Failed to create directory %(name)s: %(error)s") % {
                    'name': name,
                    'error': e
                })

    try:
        jail = JailsConfiguration.objects.latest('id')
    except JailsConfiguration.DoesNotExist:
        jail = JailsConfiguration()
    jail.jc_path = "/mnt/%s" % name
    jail.save()

    w = warden.Warden()
    w.wtmp = jail.jc_path
    w.jdir = jail.jc_path
    w.release = platform.release().strip()
    w.save()
Beispiel #8
0
def install_available(request, oid):

    try:
        jc = JailsConfiguration.objects.all()[0]
    except IndexError:
        jc = JailsConfiguration.objects.create()

    try:
        if not jail_path_configured():
            jail_auto_configure()

        if not jc.jc_ipv4_dhcp:
            addrs = guess_addresses()
            if not addrs['high_ipv4']:
                raise MiddlewareError(_("No available IP addresses"))

    except MiddlewareError as e:
        return render(request, "plugins/install_error.html", {
            'error': e.value,
        })

    if os.path.exists("/tmp/.plugin_upload_update"):
        os.unlink("/tmp/.plugin_upload_update")
    if os.path.exists(PROGRESS_FILE):
        os.unlink(PROGRESS_FILE)

    plugin = None
    for p in availablePlugins.get_remote(cache=True):
        if p.id == oid:
            plugin = p
            break

    if not plugin:
        raise MiddlewareError(_("Invalid plugin"))

    if request.method == "POST":

        plugin_upload_path = notifier().get_plugin_upload_path()
        notifier().change_upload_location(plugin_upload_path)

        if not plugin.download("/var/tmp/firmware/pbifile.pbi"):
            raise MiddlewareError(_("Failed to download plugin"))

        try:
            jail = new_default_plugin_jail(plugin.unixname)
        except IOError as e:
            raise MiddlewareError(str(e))
        except MiddlewareError as e:
            raise e
        except Exception as e:
            raise MiddlewareError(str(e))

        newplugin = []
        if notifier().install_pbi(jail.jail_host, newplugin):
            newplugin = newplugin[0]
            notifier()._restart_plugins(
                jail=newplugin.plugin_jail,
                plugin=newplugin.plugin_name,
            )
        else:
            jail.delete()

        return JsonResp(
            request,
            message=_("Plugin successfully installed"),
            events=['reloadHttpd()'],
        )

    return render(request, "plugins/available_install.html", {
        'plugin': plugin,
    })
Beispiel #9
0
    def save(self):
        enable = self.cleaned_data.get("ad_enable")
        enable_monitoring = self.cleaned_data.get("ad_enable_monitor")
        monit_frequency = self.cleaned_data.get("ad_monitor_frequency")
        monit_retry = self.cleaned_data.get("ad_recover_retry")
        fqdn = self.cleaned_data.get("ad_domainname")
        sm = None

        if self.__original_changed():
            notifier().clear_activedirectory_config()

        started = notifier().started(
            "activedirectory",
            timeout=_fs().directoryservice.activedirectory.timeout.started)
        obj = super(ActiveDirectoryForm, self).save()

        try:
            utils.get_idmap_object(obj.ds_type, obj.id, obj.ad_idmap_backend)
        except ObjectDoesNotExist:
            log.debug(
                'IDMAP backend {} entry does not exist, creating one.'.format(
                    obj.ad_idmap_backend))
            utils.get_idmap(obj.ds_type, obj.id, obj.ad_idmap_backend)

        self.cifs.cifs_srv_netbiosname = self.cleaned_data.get(
            "ad_netbiosname_a")
        self.cifs.cifs_srv_netbiosname_b = self.cleaned_data.get(
            "ad_netbiosname_b")
        self.cifs.cifs_srv_netbiosalias = self.cleaned_data.get(
            "ad_netbiosalias")
        self.cifs.save()

        if enable:
            if started is True:
                timeout = _fs(
                ).directoryservice.activedirectory.timeout.restart
                try:
                    started = notifier().restart("activedirectory",
                                                 timeout=timeout)
                except Exception as e:
                    raise MiddlewareError(
                        _("Active Directory restart timed out after %d seconds."
                          % timeout), )

            if started is False:
                timeout = _fs().directoryservice.activedirectory.timeout.start
                try:
                    started = notifier().start("activedirectory",
                                               timeout=timeout)
                except Exception as e:
                    raise MiddlewareError(
                        _("Active Directory start timed out after %d seconds."
                          % timeout), )
            if started is False:
                self.instance.ad_enable = False
                super(ActiveDirectoryForm, self).save()
                raise MiddlewareError(
                    _("Active Directory failed to reload."), )
        else:
            if started is True:
                timeout = _fs().directoryservice.activedirectory.timeout.stop
                try:
                    started = notifier().stop("activedirectory",
                                              timeout=timeout)
                except Exception as e:
                    raise MiddlewareError(
                        _("Active Directory stop timed out after %d seconds." %
                          timeout), )

        sm_name = 'activedirectory'
        try:
            sm = ServiceMonitor.objects.get(sm_name=sm_name)
        except Exception as e:
            log.debug("XXX: Unable to find ServiceMonitor: %s", e)
            pass

        #
        # Ports can be specified in the UI but there doesn't appear to be a way to
        # override them via SRV records. This should be fixed.
        #
        dcport = self.get_dcport()
        # gcport = self.get_gcport()

        if not sm:
            try:
                log.debug(
                    "XXX: fqdn=%s dcport=%s frequency=%s retry=%s enable=%s",
                    fqdn, dcport, monit_frequency, monit_retry,
                    enable_monitoring)

                sm = ServiceMonitor.objects.create(
                    sm_name=sm_name,
                    sm_host=fqdn,
                    sm_port=dcport,
                    sm_frequency=monit_frequency,
                    sm_retry=monit_retry,
                    sm_enable=enable_monitoring)
            except Exception as e:
                log.debug("XXX: Unable to create ServiceMonitor: %s", e)
                raise MiddlewareError(
                    _("Unable to create ServiceMonitor: %s" % e), )

        else:
            sm.sm_name = sm_name
            if fqdn != sm.sm_host:
                sm.sm_host = fqdn
            if dcport != sm.sm_port:
                sm.sm_port = dcport
            if monit_frequency != sm.sm_frequency:
                sm.sm_frequency = monit_frequency
            if monit_retry != sm.sm_retry:
                sm.sm_retry = monit_retry
            if enable_monitoring != sm.sm_enable:
                sm.sm_enable = enable_monitoring

            try:
                sm.save(force_update=True)
            except Exception as e:
                log.debug("XXX: Unable to create ServiceMonitor: %s", e)
                raise MiddlewareError(
                    _("Unable to save ServiceMonitor: %s" % e), )

        with client as c:
            if enable_monitoring and enable:
                log.debug(
                    "[ServiceMonitoring] Add %s service, frequency: %d, retry: %d"
                    % ('activedirectory', monit_frequency, monit_retry))
                c.call('servicemonitor.restart')
            else:
                log.debug(
                    "[ServiceMonitoring] Remove %s service, frequency: %d, retry: %d"
                    % ('activedirectory', monit_frequency, monit_retry))
                c.call('servicemonitor.restart')

        return obj
Beispiel #10
0
def plugin_update(request, oid):
    host = get_base_url(request)

    jc = JailsConfiguration.objects.order_by("-id")[0]
    logfile = '%s/warden.log' % jc.jc_path
    if os.path.exists(logfile):
        os.unlink(logfile)
    if os.path.exists(WARDEN_EXTRACT_STATUS_FILE):
        os.unlink(WARDEN_EXTRACT_STATUS_FILE)
    if os.path.exists("/tmp/.plugin_upload_install"):
        os.unlink("/tmp/.plugin_upload_install")
    if os.path.exists("/tmp/.jailcreate"):
        os.unlink("/tmp/.jailcreate")
    if os.path.exists(PROGRESS_FILE):
        os.unlink(PROGRESS_FILE)

    iplugin = models.Plugins.objects.filter(id=oid)
    if not iplugin:
        raise MiddlewareError(_("Plugin not installed"))
    iplugin = iplugin[0]

    rplugin = None
    for rp in availablePlugins.get_remote(cache=True):
        if rp.name.lower() == iplugin.plugin_name.lower():
            rplugin = rp
            break

    if not rplugin:
        raise MiddlewareError(_("Invalid plugin"))

    (p, js, jail_status) = get_plugin_status([iplugin, host, request])
    if js and js['status'] == 'RUNNING':
        (p, js, jail_status) = get_plugin_stop([iplugin, host, request])

    if request.method == "POST":
        plugin_upload_path = notifier().get_plugin_upload_path()
        notifier().change_upload_location(plugin_upload_path)

        if not rplugin.download("/var/tmp/firmware/pbifile.pbi"):
            raise MiddlewareError(_("Failed to download plugin"))

        jail = Jails.objects.filter(jail_host=iplugin.plugin_jail)
        if not jail:
            raise MiddlewareError(_("Jail does not exist"))

        if notifier().update_pbi(plugin=iplugin):
            notifier()._start_plugins(
                jail=iplugin.plugin_jail,
                plugin=iplugin.plugin_name,
            )

        else:
            raise MiddlewareError(_("Failed to update plugin"))

        return JsonResp(
            request,
            message=_("Plugin successfully updated"),
            events=['reloadHttpd()'],
        )

    return render(request, "plugins/plugin_update.html", {
        'plugin': rplugin,
    })
Beispiel #11
0
 def zfs_online_disk(self, volume, label):
     try:
         with client as c:
             c.call('pool.online', volume.id, {'label': label})
     except Exception as e:
         raise MiddlewareError(f'Disk online failed: {str(e)}')
Beispiel #12
0
 def geli_delkey(self, volume):
     try:
         with client as c:
             c.call('pool.recoverykey_rm', volume.id)
     except Exception as e:
         raise MiddlewareError(f'Failed to remove recovery key: {str(e)}')
Beispiel #13
0
 def save(self):
     try:
         super(LDAPForm, self).save()
     except Exception as e:
         raise MiddlewareError(e)
Beispiel #14
0
    def __init__(self, *args, **kwargs):
        super(JailsEditForm, self).__init__(*args, **kwargs)
        self.__myfields = [
            'jail_autostart',
            'jail_ipv4',
            'jail_ipv4_netmask',
            'jail_alias_ipv4',
            'jail_bridge_ipv4',
            'jail_bridge_ipv4_netmask',
            'jail_alias_bridge_ipv4',
            'jail_defaultrouter_ipv4',
            'jail_ipv6',
            'jail_ipv6_prefix',
            'jail_alias_ipv6',
            'jail_bridge_ipv6',
            'jail_bridge_ipv6_prefix',
            'jail_alias_bridge_ipv6',
            'jail_defaultrouter_ipv6',
            'jail_mac',
            'jail_iface',
            'jail_vnet',
            'jail_nat',
            'jail_flags',
        ]
        try:
            self.jc = JailsConfiguration.objects.order_by("-id")[0]
        except Exception as e:
            raise MiddlewareError(e.message)

        jail_ipv4_dhcp = False
        jail_ipv6_autoconf = False

        if self.jc.jc_ipv4_dhcp:
            jail_ipv4_dhcp = True
        if self.jc.jc_ipv6_autoconf:
            jail_ipv6_autoconf = True

        if self.instance:
            if (self.instance.jail_ipv4
                    and self.instance.jail_ipv4.startswith("DHCP")):
                jail_ipv4_dhcp = True
            if (self.instance.jail_ipv6
                    and self.instance.jail_ipv6.startswith("AUTOCONF")):
                jail_ipv6_autoconf = True

        self.fields['jail_ipv4_dhcp'].initial = jail_ipv4_dhcp
        self.fields['jail_ipv6_autoconf'].initial = jail_ipv6_autoconf

        if self._api and self.instance and self.instance.id:
            self.instance = Jails.objects.get(id=self.instance.id)
        instance = getattr(self, 'instance', None)
        self.__instance_save(instance, self.__myfields)

        self.fields['jail_vnet'].widget.attrs['onChange'] = (
            "jail_vnet_toggle();")
        self.fields['jail_nat'].widget.attrs['onChange'] = (
            "jail_nat_toggle();")
        self.fields['jail_ipv4_dhcp'].widget.attrs['onChange'] = (
            "jail_ipv4_dhcp_toggle();")
        self.fields['jail_ipv6_autoconf'].widget.attrs['onChange'] = (
            "jail_ipv6_autoconf_toggle();")

        self.__set_ro(instance, 'jail_host')
        self.__set_ro(instance, 'jail_type')
Beispiel #15
0
            'error': e.value,
        })

    if os.path.exists("/tmp/.plugin_upload_update"):
        os.unlink("/tmp/.plugin_upload_update")
    if os.path.exists(PROGRESS_FILE):
        os.unlink(PROGRESS_FILE)

    plugin = None
    for p in availablePlugins.get_remote(cache=True):
        if p.id == oid:
            plugin = p
            break

    if not plugin:
        raise MiddlewareError(_("Invalid plugin"))

    if request.method == "POST":

        plugin_upload_path = notifier().get_plugin_upload_path()
        notifier().change_upload_location(plugin_upload_path)

        if not plugin.download("/var/tmp/firmware/pbifile.pbi"):
            raise MiddlewareError(_("Failed to download plugin"))

        try:
            jail = new_default_plugin_jail(plugin.unixname)
        except IOError, e:
            raise MiddlewareError(unicode(e))
        except MiddlewareError, e:
            raise e
Beispiel #16
0
    def save(self):
        jail_host = self.cleaned_data.get('jail_host')

        instance = getattr(self, 'instance', None)
        if self.__instance_diff(instance, self.__myfields):
            self.__instance_changed_fields(instance, self.__myfields)

        changed_fields = self.__instance_changed_fields(
            instance, self.__myfields)

        try:
            jc = JailsConfiguration.objects.order_by("-id")[0]
        except Exception as e:
            raise MiddlewareError(e.message)

        if not jc.jc_path:
            raise MiddlewareError(_("No jail root configured."))

        jc_ipv4_netmask = 24
        if jc.jc_ipv4_network:
            parts = jc.jc_ipv4_network.split('/')
            if len(parts) > 1:
                jc_ipv4_netmask = parts[1]

        jc_ipv6_prefix = 64
        if jc.jc_ipv6_network:
            parts = jc.jc_ipv6_network.split('/')
            if len(parts) > 1:
                jc_ipv6_prefix = parts[1]

        jail_ipv4_dhcp = self.cleaned_data.get('jail_ipv4_dhcp', False)
        jail_ipv6_autoconf = self.cleaned_data.get('jail_ipv6_autoconf', False)

        for cf in changed_fields:
            if cf == 'jail_autostart':
                Warden().auto(jail=jail_host)
            else:
                args = {}
                flags = WARDEN_FLAGS_NONE

                if cf == 'jail_ipv4' or cf == 'jail_ipv4_netmask':
                    ipv4 = self.cleaned_data.get('jail_ipv4')
                    mask = self.cleaned_data.get('jail_ipv4_netmask',
                                                 jc_ipv4_netmask)
                    if jail_ipv4_dhcp:
                        jail_ipv4 = ipv4
                    else:
                        jail_ipv4 = "%s/%s" % (ipv4, mask)

                    flags |= WARDEN_SET_FLAGS_IPV4
                    args['ipv4'] = jail_ipv4

                elif cf == 'jail_ipv6' or cf == 'jail_ipv6_prefix':
                    ipv6 = self.cleaned_data.get('jail_ipv6')
                    prefix = self.cleaned_data.get('jail_ipv6_prefix',
                                                   jc_ipv6_prefix)
                    if jail_ipv6_autoconf:
                        jail_ipv6 = ipv6
                    else:
                        jail_ipv6 = "%s/%s" % (ipv6, prefix)

                    flags |= WARDEN_SET_FLAGS_IPV6
                    args['ipv6'] = jail_ipv6

                elif cf == 'jail_alias_ipv4':
                    flags |= WARDEN_SET_FLAGS_ALIAS_IPV4
                    args['alias-ipv4'] = self.cleaned_data.get(cf)

                elif cf == 'jail_alias_ipv6':
                    flags |= WARDEN_SET_FLAGS_ALIAS_IPV6
                    args['alias-ipv6'] = self.cleaned_data.get(cf)

                elif (cf == 'jail_bridge_ipv4'
                      or cf == 'jail_bridge_ipv4_netmask'):
                    bridge_ipv4 = self.cleaned_data.get('jail_bridge_ipv4')
                    mask = self.cleaned_data.get('jail_bridge_ipv4_netmask',
                                                 jc_ipv4_netmask)
                    jail_bridge_ipv4 = "%s/%s" % (bridge_ipv4, mask)

                    flags |= WARDEN_SET_FLAGS_BRIDGE_IPV4
                    args['bridge-ipv4'] = jail_bridge_ipv4

                elif (cf == 'jail_bridge_ipv6'
                      or cf == 'jail_bridge_ipv6_prefix'):
                    bridge_ipv6 = self.cleaned_data.get('jail_bridge_ipv6')
                    prefix = self.cleaned_data.get('jail_bridge_ipv6_prefix',
                                                   jc_ipv6_prefix)
                    jail_bridge_ipv6 = "%s/%s" % (bridge_ipv6, prefix)

                    flags |= WARDEN_SET_FLAGS_BRIDGE_IPV6
                    args['bridge-ipv6'] = jail_bridge_ipv6

                elif cf == 'jail_alias_bridge_ipv4':
                    flags |= WARDEN_SET_FLAGS_ALIAS_BRIDGE_IPV4
                    args['alias-bridge-ipv4'] = self.cleaned_data.get(cf)

                elif cf == 'jail_alias_bridge_ipv6':
                    flags |= WARDEN_SET_FLAGS_ALIAS_BRIDGE_IPV6
                    args['alias-bridge-ipv6'] = self.cleaned_data.get(cf)

                elif cf == 'jail_defaultrouter_ipv4':
                    flags |= WARDEN_SET_FLAGS_DEFAULTROUTER_IPV4
                    args['defaultrouter-ipv4'] = self.cleaned_data.get(cf)

                elif cf == 'jail_defaultrouter_ipv6':
                    flags |= WARDEN_SET_FLAGS_DEFAULTROUTER_IPV6
                    args['defaultrouter-ipv6'] = self.cleaned_data.get(cf)

                elif cf == 'jail_mac':
                    flags |= WARDEN_SET_FLAGS_MAC
                    args['mac'] = self.cleaned_data.get(cf)

                elif cf == 'jail_iface':
                    flags |= WARDEN_SET_FLAGS_IFACE
                    args['iface'] = self.cleaned_data.get(cf)

                elif cf == 'jail_vnet':
                    if (self.cleaned_data.get(cf)):
                        flags |= WARDEN_SET_FLAGS_VNET_ENABLE
                        args['vnet-enable'] = self.cleaned_data.get(cf)
                    else:
                        flags |= WARDEN_SET_FLAGS_VNET_DISABLE
                        args['vnet-disable'] = self.cleaned_data.get(cf)

                elif cf == 'jail_nat':
                    if self.cleaned_data.get(cf):
                        flags |= WARDEN_SET_FLAGS_NAT_ENABLE
                        args['nat-enable'] = self.cleaned_data.get(cf)
                    else:
                        flags |= WARDEN_SET_FLAGS_NAT_DISABLE
                        args['nat-disable'] = self.cleaned_data.get(cf)

                elif cf == 'jail_flags':
                    flags |= WARDEN_SET_FLAGS_FLAGS
                    args['jflags'] = self.cleaned_data.get(cf)

                args['jail'] = jail_host
                args['flags'] = flags

                Warden().set(**args)
Beispiel #17
0
def new_default_plugin_jail(basename):
    jc = JailsConfiguration.objects.order_by("-id")[0]
    logfile = "%s/warden.log" % jc.jc_path

    if not jc.jc_ipv4_dhcp or not jc.jc_ipv6_autoconf:
        addrs = guess_addresses()

    if not jc.jc_ipv4_dhcp:
        if not addrs['high_ipv4']:
            raise MiddlewareError(_("Unable to determine IPv4 for plugin"))

    if (jc.jc_ipv6_autoconf or jc.jc_ipv6_network):
        if not jc.jc_ipv6_autoconf:
            if not addrs['high_ipv6']:
                raise MiddlewareError(_("Unable to determine IPv6 for plugin"))

    jailname = None
    for i in xrange(1, 1000):
        tmpname = "%s_%d" % (basename, i)
        jails = Jails.objects.filter(jail_host=tmpname)
        if not jails:
            jailname = tmpname
            break

    w = warden.Warden()
    template_create_args = {}

    template = JailTemplate.objects.get(jt_name='pluginjail')
    template_create_args['nick'] = template.jt_name
    template_create_args['tar'] = template.jt_url
    template_create_args['flags'] = warden.WARDEN_TEMPLATE_FLAGS_CREATE | \
        warden.WARDEN_TEMPLATE_CREATE_FLAGS_NICK | \
        warden.WARDEN_TEMPLATE_CREATE_FLAGS_TAR

    template = None
    template_list_flags = {}
    template_list_flags['flags'] = warden.WARDEN_TEMPLATE_FLAGS_LIST
    templates = w.template(**template_list_flags)
    for t in templates:
        if t['nick'] == template_create_args['nick']:
            template = t
            break

    os.environ[
        'EXTRACT_TARBALL_STATUSFILE'] = warden.WARDEN_EXTRACT_STATUS_FILE
    createfile = "/var/tmp/.templatecreate"
    if not template:
        try:
            cf = open(createfile, "a+")
            cf.close()
            w.template(**template_create_args)

        except Exception as e:
            if os.path.exists(createfile):
                os.unlink(createfile)
            raise MiddlewareError(e.message)

        template_list_flags = {}
        template_list_flags['flags'] = warden.WARDEN_TEMPLATE_FLAGS_LIST
        templates = w.template(**template_list_flags)
        for t in templates:
            if t['nick'] == template_create_args['nick']:
                template = t
                break

    if not template:
        raise MiddlewareError(_('Unable to find template!'))

    try:
        high_ipv4 = "DHCP"
        if not jc.jc_ipv4_dhcp:
            high_ipv4 = addrs['high_ipv4']

        high_ipv6 = "AUTOCONF"
        if not jc.jc_ipv6_autoconf:
            high_ipv6 = addrs['high_ipv6']

        create_args = {
            'jail':
            jailname,
            'ipv4':
            high_ipv4,
            'ipv6':
            high_ipv6,
            'flags': (warden.WARDEN_CREATE_FLAGS_LOGFILE
                      | warden.WARDEN_CREATE_FLAGS_TEMPLATE
                      | warden.WARDEN_CREATE_FLAGS_VANILLA
                      | warden.WARDEN_CREATE_FLAGS_SYSLOG
                      | warden.WARDEN_CREATE_FLAGS_IPV4
                      | warden.WARDEN_CREATE_FLAGS_IPV6),
            'template':
            'pluginjail',
            'logfile':
            logfile
        }

        w.create(**create_args)

    except Exception, e:
        raise MiddlewareError(_("Failed to install plugin: %s") % e)
Beispiel #18
0
def upload(request, jail_id=-1):
    try:
        jc = JailsConfiguration.objects.all()[0]
    except:
        jc = None

    # FIXME: duplicated code with available_install
    try:
        if not jail_path_configured():
            jail_auto_configure()

        if not jc:
            jc = JailsConfiguration.objects.all()[0]

        if not jc.jc_ipv4_dhcp:
            addrs = guess_addresses()
            if not addrs['high_ipv4']:
                raise MiddlewareError(_("No available IP addresses"))

    except MiddlewareError as e:
        return render(request, "plugins/install_error.html", {
            'error': e.value,
        })

    plugin_upload_path = notifier().get_plugin_upload_path()
    notifier().change_upload_location(plugin_upload_path)

    jail = None
    if jail_id > 0:
        try:
            jail = Jails.objects.filter(pk=jail_id)[0]

        except Exception as e:
            log.debug("Failed to get jail %d: %s", jail_id, repr(e))
            jail = None

    if request.method == "POST":
        jc = JailsConfiguration.objects.order_by("-id")[0]
        logfile = '%s/warden.log' % jc.jc_path
        if os.path.exists(logfile):
            os.unlink(logfile)
        if os.path.exists(WARDEN_EXTRACT_STATUS_FILE):
            os.unlink(WARDEN_EXTRACT_STATUS_FILE)
        if os.path.exists("/tmp/.plugin_upload_install"):
            os.unlink("/tmp/.plugin_upload_install")
        if os.path.exists("/tmp/.jailcreate"):
            os.unlink("/tmp/.jailcreate")

        form = forms.PBIUploadForm(request.POST, request.FILES, jail=jail)
        if form.is_valid():
            form.done()
            return JsonResp(
                request,
                message=_('Plugin successfully installed'),
                events=['reloadHttpd()'],
            )
        else:
            resp = render(request, "plugins/upload.html", {
                'form': form,
            })
            resp.content = ("<html><body><textarea>" + resp.content +
                            "</textarea></boby></html>")
            return resp
    else:
        form = forms.PBIUploadForm(jail=jail)

    return render(request, "plugins/upload.html", {
        'form': form,
    })
Beispiel #19
0
def update_check(request):

    try:
        updateobj = models.Update.objects.order_by('-id')[0]
    except IndexError:
        updateobj = models.Update.objects.create()

    if request.method == 'POST':
        uuid = request.GET.get('uuid')
        if request.POST.get('apply') == '1':
            apply_ = True
        else:
            apply_ = False
        handler = UpdateHandler(uuid=uuid, apply_=apply_)
        if not uuid:
            #FIXME: ugly
            pid = os.fork()
            if pid != 0:
                return HttpResponse(handler.uuid, status=202)
            else:
                handler.pid = os.getpid()
                handler.dump()
                path = notifier().system_dataset_path()
                if not path:
                    raise MiddlewareError(_('System dataset not configured'))
                try:
                    if handler.apply:
                        Update(
                            train=updateobj.get_train(),
                            get_handler=handler.get_handler,
                            install_handler=handler.install_handler,
                            cache_dir='%s/update' % path,
                        )
                    else:
                        DownloadUpdate(
                            updateobj.get_train(),
                            '%s/update' % path,
                            check_handler=handler.get_handler,
                            get_handler=handler.get_file_handler,
                        )
                except Exception, e:
                    from freenasUI.common.log import log_traceback
                    log_traceback(log=log)
                    handler.error = unicode(e)
                handler.finished = True
                handler.dump()
                os.kill(handler.pid, 9)
        else:
            if handler.error is not False:
                raise MiddlewareError(handler.error)
            if not handler.finished:
                return HttpResponse(handler.uuid, status=202)
            handler.exit()
            if handler.apply:
                request.session['allow_reboot'] = True
                return render(request, 'system/done.html')
            else:
                return JsonResp(
                    request,
                    message=_('Packages downloaded'),
                )
Beispiel #20
0
    def __init__(self, *args, **kwargs):
        super(JailCreateForm, self).__init__(*args, **kwargs)

        if not jail_path_configured():
            jail_auto_configure()

        try:
            self.jc = JailsConfiguration.objects.order_by("-id")[0]
        except Exception as e:
            raise MiddlewareError(e)

        self.logfile = "/var/tmp/warden.log"
        self.statusfile = "/var/tmp/status"
        try:
            os.unlink(self.logfile)
        except:
            pass
        try:
            os.unlink(self.statusfile)
        except:
            pass

        arch = platform.architecture()
        if arch[0] == '64bit':
            arch = 'x64'
        else:
            arch = 'x86'
        self.arch = arch

        os.environ['EXTRACT_TARBALL_STATUSFILE'] = self.statusfile
        self.fields['jail_type'].choices = choices.JAIL_TEMPLATE_CHOICES()
        self.fields['jail_type'].widget.attrs['onChange'] = (
            "jail_type_toggle();")
        self.fields['jail_vnet'].widget.attrs['onChange'] = (
            "jail_vnet_toggle();")
        self.fields['jail_nat'].widget.attrs['onChange'] = (
            "jail_nat_toggle();")
        self.fields['jail_ipv4_dhcp'].widget.attrs['onChange'] = (
            "jail_ipv4_dhcp_toggle();")
        self.fields['jail_ipv6_autoconf'].widget.attrs['onChange'] = (
            "jail_ipv6_autoconf_toggle();")

        if not self.jc.jc_ipv4_dhcp:
            ipv4_addrs = guess_ipv4_addresses()
            if ipv4_addrs['high_ipv4']:
                parts = str(ipv4_addrs['high_ipv4']).split('/')
                self.fields['jail_ipv4'].initial = parts[0]
                if len(parts) > 1:
                    self.fields['jail_ipv4_netmask'].initial = parts[1]

            if ipv4_addrs['bridge_ipv4']:
                parts = str(ipv4_addrs['bridge_ipv4']).split('/')
                self.fields['jail_bridge_ipv4'].initial = parts[0]
                if len(parts) > 1:
                    self.fields['jail_bridge_ipv4_netmask'].initial = parts[1]
        else:
            self.fields['jail_ipv4_dhcp'].initial = True

        if not self.jc.jc_ipv6_autoconf:
            ipv6_addrs = guess_ipv6_addresses()
            if ipv6_addrs['high_ipv6']:
                parts = str(ipv6_addrs['high_ipv6']).split('/')
                self.fields['jail_ipv6'].initial = parts[0]
                if len(parts) > 1:
                    self.fields['jail_ipv6_prefix'].initial = parts[1]

            if ipv6_addrs['bridge_ipv6']:
                parts = str(ipv6_addrs['bridge_ipv6']).split('/')
                self.fields['jail_bridge_ipv6'].initial = parts[0]
                if len(parts) > 1:
                    self.fields['jail_bridge_ipv6_prefix'].initial = parts[1]
        else:
            self.fields['jail_ipv6_autoconf'].initial = True
Beispiel #21
0
def new_default_plugin_jail(basename):
    jc = JailsConfiguration.objects.order_by("-id")[0]
    logfile = "%s/warden.log" % jc.jc_path

    if not jc.jc_ipv4_dhcp or not jc.jc_ipv6_autoconf:
        addrs = guess_addresses()

    if not jc.jc_ipv4_dhcp:
        if not addrs['high_ipv4']:
            raise MiddlewareError(_("Unable to determine IPv4 for plugin"))

    if (jc.jc_ipv6_autoconf or jc.jc_ipv6_network):
        if not jc.jc_ipv6_autoconf:
            if not addrs['high_ipv6']:
                raise MiddlewareError(_("Unable to determine IPv6 for plugin"))

    jailname = None
    for i in range(1, 1000):
        tmpname = "%s_%d" % (basename, i)
        jails = Jails.objects.filter(jail_host=tmpname)
        if not jails:
            jailname = tmpname
            break

    w = warden.Warden()
    template_create_args = {}

    template = JailTemplate.objects.get(jt_name='pluginjail')
    template_create_args['nick'] = template.jt_name
    template_create_args['tar'] = template.jt_url
    template_create_args['flags'] = warden.WARDEN_TEMPLATE_FLAGS_CREATE | \
        warden.WARDEN_TEMPLATE_CREATE_FLAGS_NICK | \
        warden.WARDEN_TEMPLATE_CREATE_FLAGS_TAR
    if template.jt_mtree:
        template_create_args['mtree'] = template.jt_mtree
        template_create_args['flags'] = template_create_args['flags'] | \
            warden.WARDEN_TEMPLATE_CREATE_FLAGS_MTREE

    template = None
    template_list_flags = {}
    template_list_flags['flags'] = warden.WARDEN_TEMPLATE_FLAGS_LIST
    templates = w.template(**template_list_flags)
    for t in templates:
        if t['nick'] == template_create_args['nick']:
            template = t
            break

    os.environ['EXTRACT_TARBALL_STATUSFILE'] = warden.WARDEN_EXTRACT_STATUS_FILE
    createfile = "/var/tmp/.templatecreate"
    if not template:

        # If for some reason warden does not list the template but the path
        # exists, we shall try to nuke it
        template_path = '{}/.warden-template-pluginjail'.format(jc.jc_path)
        if os.path.exists(template_path):
            try:
                notifier().destroy_zfs_dataset(template_path.replace('/mnt/', ''))
            except:
                pass
            try:
                shutil.rmtree(template_path)
            except OSError:
                pass

        try:
            cf = open(createfile, "a+")
            cf.close()
            w.template(**template_create_args)

        except Exception as e:
            if os.path.exists(createfile):
                os.unlink(createfile)
            raise MiddlewareError(e)

        template_list_flags = {}
        template_list_flags['flags'] = warden.WARDEN_TEMPLATE_FLAGS_LIST
        templates = w.template(**template_list_flags)
        for t in templates:
            if t['nick'] == template_create_args['nick']:
                template = t
                break

    if not template:
        raise MiddlewareError(_('Unable to find template!'))

    try:
        high_ipv4 = "DHCP"
        if not jc.jc_ipv4_dhcp:
            high_ipv4 = addrs['high_ipv4']

        high_ipv6 = "AUTOCONF"
        if not jc.jc_ipv6_autoconf:
            high_ipv6 = addrs['high_ipv6']

        create_args = {
            'jail': jailname,
            'ipv4': high_ipv4,
            'ipv6': high_ipv6,
            'flags': (
                warden.WARDEN_CREATE_FLAGS_LOGFILE |
                warden.WARDEN_CREATE_FLAGS_TEMPLATE |
                warden.WARDEN_CREATE_FLAGS_VANILLA |
                warden.WARDEN_CREATE_FLAGS_SYSLOG |
                warden.WARDEN_CREATE_FLAGS_IPV4 |
                warden.WARDEN_CREATE_FLAGS_IPV6
            ),
            'template': 'pluginjail',
            'logfile': logfile
        }

        w.create(**create_args)

    except Exception as e:
        raise MiddlewareError(_("Failed to install plugin: %s") % e)

    jaildir = "%s/%s" % (jc.jc_path, jailname)
    with open('%s/.plugins/PLUGIN' % jaildir, 'w') as f:
        f.close()

    w.auto(jail=jailname)
    w.set(
        jail=jailname,
        flags=(
            warden.WARDEN_SET_FLAGS_VNET_ENABLE
        )
    )
    w.start(jail=jailname)

    obj = Jails.objects.get(jail_host=jailname)
    add_media_user_and_group(obj.jail_path)
    return obj