Beispiel #1
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced, Settings
        from freenasUI.middleware.client import client

        view = appPool.hook_app_index('freeadmin', request)
        view = [_f for _f in view if _f]
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].get_hostname()
        except:
            hostname = None

        try:
            settings = Settings.objects.all().order_by('-id')[0]
            wizard = not settings.stg_wizardshown
            if settings.stg_wizardshown is False:
                settings.stg_wizardshown = True
                settings.save()
        except:
            wizard = False
        sw_version = get_sw_version()
        sw_version_footer = get_sw_version(strip_build_num=True).split('-',
                                                                       1)[-1]

        try:
            with client as c:
                middleware_token = c.call('auth.generate_token', timeout=10)
        except Exception:
            middleware_token = None
            extra_log_files = (('/var/log/middlewared.log',
                                'middlewared_log'), )
            self.trace.rollbar_report(sys.exc_info(), request, sw_version,
                                      extra_log_files)

        return render(
            request, 'freeadmin/index.html', {
                'consolemsg': console,
                'hostname': hostname,
                'sw_name': get_sw_name(),
                'sw_version': sw_version,
                'sw_version_footer': sw_version_footer,
                'cache_hash': hashlib.md5(
                    sw_version.encode('utf8')).hexdigest(),
                'css_hook': appPool.get_base_css(request),
                'js_hook': appPool.get_base_js(request),
                'menu_hook': appPool.get_top_menu(request),
                'wizard': wizard,
                'middleware_token': middleware_token,
            })
Beispiel #2
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced, Settings

        view = appPool.hook_app_index('freeadmin', request)
        view = [_f for _f in view if _f]
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].get_hostname()
        except:
            hostname = None

        try:
            settings = Settings.objects.all().order_by('-id')[0]
            wizard = not settings.stg_wizardshown
            if settings.stg_wizardshown is False:
                settings.stg_wizardshown = True
                settings.save()
        except:
            wizard = False
        sw_version = get_sw_version()
        version = get_sw_version(strip_build_num=True)
        sw_version_footer = version.split('-', 1)[-1]
        sw_version_major = version.split('-')[1]

        return render(
            request, 'freeadmin/index.html', {
                'consolemsg': console,
                'hostname': hostname,
                'sw_name': get_sw_name(),
                'sw_year': get_sw_year(),
                'sw_version': sw_version,
                'sw_version_footer': sw_version_footer,
                'sw_version_major': sw_version_major,
                'cache_hash': hashlib.md5(
                    sw_version.encode('utf8')).hexdigest(),
                'css_hook': appPool.get_base_css(request),
                'js_hook': appPool.get_base_js(request),
                'menu_hook': appPool.get_top_menu(request),
                'wizard': wizard,
            })
Beispiel #3
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced

        view = appPool.hook_app_index('freeadmin', request)
        view = filter(None, view)
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].gc_hostname
        except:
            hostname = None
        sw_version = get_sw_version()
        return render(
            request, 'freeadmin/index.html', {
                'consolemsg': console,
                'hostname': hostname,
                'sw_name': get_sw_name(),
                'sw_version': sw_version,
                'cache_hash': hashlib.md5(sw_version).hexdigest(),
                'css_hook': appPool.get_base_css(request),
                'js_hook': appPool.get_base_js(request),
                'menu_hook': appPool.get_top_menu(request),
            })
Beispiel #4
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced

        view = appPool.hook_app_index('freeadmin', request)
        view = filter(None, view)
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].gc_hostname
        except:
            hostname = None
        sw_version = get_sw_version()
        return render(request, 'freeadmin/index.html', {
            'consolemsg': console,
            'hostname': hostname,
            'sw_name': get_sw_name(),
            'sw_version': sw_version,
            'cache_hash': hashlib.md5(sw_version).hexdigest(),
            'css_hook': appPool.get_base_css(request),
            'js_hook': appPool.get_base_js(request),
            'menu_hook': appPool.get_top_menu(request),
        })
Beispiel #5
0
def server_error(request, *args, **kwargs):
    # Save exc info before next exception occurs
    exc_info = sys.exc_info()
    trace_rollbar = logger.Rollbar()
    try:
        tb = Advanced.objects.all().latest('id').adv_traceback
    except:
        tb = True

    # Report error to Rollbar.
    sw_version = get_sw_version()
    extra_log_files = [
        ('/var/log/debug.log', 'debug_log'),
        ('/data/update.failed', 'update_failed'),
    ]
    # If the exception comes from middleware client lets append the log
    # since middlewared itself might be stuck
    if issubclass(exc_info[0], ClientException):
        extra_log_files.insert(0,
                               ('/var/log/middlewared.log', 'middlewared_log'))
    trace_rollbar.rollbar_report(exc_info, request, sw_version,
                                 extra_log_files)

    try:
        if tb:
            reporter = ExceptionReporter(request, *exc_info)
            html = reporter.get_traceback_html()
            return HttpResponse(html, content_type='text/html')
        else:
            raise
    except Exception:
        return debug.technical_500_response(request, *exc_info)
Beispiel #6
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced, Settings
        from freenasUI.middleware.client import client

        view = appPool.hook_app_index('freeadmin', request)
        view = filter(None, view)
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].get_hostname()
        except:
            hostname = None

        try:
            settings = Settings.objects.all().order_by('-id')[0]
            wizard = not settings.stg_wizardshown
            if settings.stg_wizardshown is False:
                settings.stg_wizardshown = True
                settings.save()
        except:
            wizard = False
        sw_version = get_sw_version()

        try:
            with client as c:
                middleware_token = c.call('auth.generate_token', timeout=10)
        except Exception:
            middleware_token = None
            extra_data = {
                'sw_version': sw_version,
            }
            if os.path.exists('/var/log/middlewared.log'):
                with open('/var/log/middlewared.log', 'r') as f:
                    extra_data['middlewaredlog'] = f.read()[-10240:]
            rollbar.report_exc_info(
                sys.exc_info(),
                request,
                extra_data=extra_data,
            )

        return render(
            request, 'freeadmin/index.html', {
                'consolemsg': console,
                'hostname': hostname,
                'sw_name': get_sw_name(),
                'sw_version': sw_version,
                'cache_hash': hashlib.md5(sw_version).hexdigest(),
                'css_hook': appPool.get_base_css(request),
                'js_hook': appPool.get_base_js(request),
                'menu_hook': appPool.get_top_menu(request),
                'wizard': wizard,
                'middleware_token': middleware_token,
            })
Beispiel #7
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced

        view = appPool.hook_app_index("freeadmin", request)
        view = filter(None, view)
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by("-id")[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by("-id")[0].gc_hostname
        except:
            hostname = None
        sw_version = get_sw_version()
        return render(
            request,
            "freeadmin/index.html",
            {
                "consolemsg": console,
                "hostname": hostname,
                "sw_name": get_sw_name(),
                "sw_version": sw_version,
                "cache_hash": hashlib.md5(sw_version).hexdigest(),
                "css_hook": appPool.get_base_css(request),
                "js_hook": appPool.get_base_js(request),
                "menu_hook": appPool.get_top_menu(request),
            },
        )
Beispiel #8
0
def server_error(request, *args, **kwargs):
    # Save exc info before next exception occurs
    exc_info = sys.exc_info()
    try:
        tb = Advanced.objects.all().latest('id').adv_traceback
    except:
        tb = True

    try:
        # Allow rollbar to be disabled via sentinel file or environment var
        if (not os.path.exists('/tmp/.rollbar_disabled')
                and 'ROLLBAR_DISABLED' not in os.environ):
            extra_data = {
                'sw_version': get_sw_version(),
            }
            for path, name in (
                ('/data/update.failed', 'update_failed'),
                ('/var/log/debug.log', 'debug_log'),
            ):
                if os.path.exists(path):
                    with open(path, 'r') as f:
                        extra_data[name] = f.read()[-10240:]
            rollbar.report_exc_info(exc_info, request, extra_data=extra_data)
    except:
        log.warn('Failed to report error', exc_info=True)
    try:
        if tb:
            reporter = ExceptionReporter(request, *exc_info)
            html = reporter.get_traceback_html()
            return HttpResponse(html, content_type='text/html')
        else:
            raise
    except Exception:
        return debug.technical_500_response(request, *exc_info)
Beispiel #9
0
def server_error(request, *args, **kwargs):
    # Save exc info before next exception occurs
    exc_info = sys.exc_info()
    trace_rollbar = logger.Rollbar()
    try:
        tb = Advanced.objects.all().latest('id').adv_traceback
    except:
        tb = True

    # Report error to Rollbar.
    sw_version = get_sw_version()
    extra_log_files = (
        ('/data/update.failed', 'update_failed'),
        ('/var/log/debug.log', 'debug_log'),
    )
    trace_rollbar.rollbar_report(exc_info, request, sw_version,
                                 extra_log_files)

    try:
        if tb:
            reporter = ExceptionReporter(request, *exc_info)
            html = reporter.get_traceback_html()
            return HttpResponse(html, content_type='text/html')
        else:
            raise
    except Exception:
        return debug.technical_500_response(request, *exc_info)
Beispiel #10
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced, Settings
        from freenasUI.middleware.client import client

        view = appPool.hook_app_index('freeadmin', request)
        view = filter(None, view)
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].get_hostname()
        except:
            hostname = None

        try:
            settings = Settings.objects.all().order_by('-id')[0]
            wizard = not settings.stg_wizardshown
            if settings.stg_wizardshown is False:
                settings.stg_wizardshown = True
                settings.save()
        except:
            wizard = False
        sw_version = get_sw_version()

        try:
            with client as c:
                middleware_token = c.call('auth.generate_token', timeout=10)
        except Exception:
            middleware_token = None
            extra_data = {
                'sw_version': sw_version,
            }
            if os.path.exists('/var/log/middlewared.log'):
                with open('/var/log/middlewared.log', 'r') as f:
                    extra_data['middlewaredlog'] = f.read()[-10240:]
            rollbar.report_exc_info(
                sys.exc_info(),
                request,
                extra_data=extra_data,
            )

        return render(request, 'freeadmin/index.html', {
            'consolemsg': console,
            'hostname': hostname,
            'sw_name': get_sw_name(),
            'sw_version': sw_version,
            'cache_hash': hashlib.md5(sw_version).hexdigest(),
            'css_hook': appPool.get_base_css(request),
            'js_hook': appPool.get_base_js(request),
            'menu_hook': appPool.get_top_menu(request),
            'wizard': wizard,
            'middleware_token': middleware_token,
        })
Beispiel #11
0
    def ticket(self, support, alerts):
        node = alert_node()
        dismisseds = [a.message_id for a in mAlert.objects.filter(node=node)]
        msgs = []
        for alert in alerts:
            if alert.getId() not in dismisseds:
                msgs.append(str(alert))
        if len(msgs) == 0:
            return

        serial = subprocess.Popen(
            ['/usr/local/sbin/dmidecode', '-s', 'system-serial-number'],
            stdout=subprocess.PIPE,
            encoding='utf8',
        ).communicate()[0].split('\n')[0].upper()

        license, reason = get_license()
        if license:
            company = license.customer_name.decode()
        else:
            company = 'Unknown'

        for name, verbose_name in (
            ('name', 'Contact Name'),
            ('title', 'Contact Title'),
            ('email', 'Contact E-mail'),
            ('phone', 'Contact Phone'),
            ('secondary_name', 'Secondary Contact Name'),
            ('secondary_title', 'Secondary Contact Title'),
            ('secondary_email', 'Secondary Contact E-mail'),
            ('secondary_phone', 'Secondary Contact Phone'),
        ):
            value = getattr(support, name)
            if value:
                msgs += ['', '{}: {}'.format(verbose_name, value)]

        with client as c:
            try:
                rv = c.call('support.new_ticket', {
                    'title': 'Automatic alert (%s)' % serial,
                    'body': '\n'.join(msgs),
                    'version': get_sw_version().split('-', 1)[-1],
                    'debug': False,
                    'company': company,
                    'serial': serial,
                    'department': 20,
                    'category': 'Hardware',
                    'criticality': 'Loss of Functionality',
                    'environment': 'Production',
                    'name': 'Automatic Alert',
                    'email': '*****@*****.**',
                    'phone': '-',
                },
                            job=True)
                log.debug(
                    f'Automatic alert ticket successfully created: {rv["url"]}'
                )
            except ClientException as e:
                log.error(f'Failed to create a support ticket: {e.error}')
Beispiel #12
0
def login_wrapper(
    request,
    template_name='registration/login.html',
    redirect_field_name=REDIRECT_FIELD_NAME,
    authentication_form=ExtendedAuthForm,
    current_app=None, extra_context=None,
):
    """
    Wrapper to login to do not allow login and redirect to
    shutdown, reboot or logout pages,
    instead redirect to /
    """

    auth_token = request.GET.get('auth_token')
    if auth_token:
        user = authenticate(auth_token=auth_token)
        if user:
            auth_login(request, user, 'freenasUI.middleware.auth.AuthTokenBackend')

    # Overload hook_app_index to shortcut passive node
    # Doing that in another layer will use too many reasources
    view = appPool.hook_app_index('account_login', request)
    view = [_f for _f in view if _f]
    if view:
        return view[0]

    if extra_context is None:
        extra_context = {}
    extra_context.update({
        'sw_login_version': get_sw_login_version(),
        'sw_version_footer': get_sw_version(strip_build_num=True).split('-', 1)[-1],
        'sw_name': get_sw_name(),
        'sw_year': get_sw_year(),
    })
    if not models.bsdUsers.has_root_password():
        authentication_form = forms.NewPasswordForm
        extra_context.update({
            'reset_password': True,
        })
    response = login(
        request,
        template_name='registration/login.html',
        redirect_field_name=redirect_field_name,
        authentication_form=authentication_form,
        current_app=current_app,
        extra_context=extra_context,
    )
    if response.status_code in (301, 302) and response._headers.get(
        'location', ('', '')
    )[1] in (
        reverse('system_reboot'),
        reverse('system_shutdown'),
        reverse('account_logout'),
    ):
        response._headers['location'] = ('Location', '/legacy/')
    elif request.user.is_authenticated:
        return HttpResponseRedirect('/legacy/')
    return response
Beispiel #13
0
def reboot(request):
    """ reboots the system """
    if not request.session.get("allow_reboot"):
        return HttpResponseRedirect('/')
    request.session.pop("allow_reboot")
    return render(request, 'system/reboot.html', {
        'sw_name': get_sw_name(),
        'sw_version': get_sw_version(),
    })
Beispiel #14
0
def shutdown(request):
    """ shuts down the system and powers off the system """
    if not request.session.get("allow_shutdown"):
        return HttpResponseRedirect('/')
    request.session.pop("allow_shutdown")
    return render(request, 'system/shutdown.html', {
        'sw_name': get_sw_name(),
        'sw_version': get_sw_version(),
    })
Beispiel #15
0
def reboot(request):
    """ reboots the system """
    if not request.session.get("allow_reboot"):
        return HttpResponseRedirect('/')
    request.session.pop("allow_reboot")
    return render(request, 'system/reboot.html', {
        'sw_name': get_sw_name(),
        'sw_version': get_sw_version(),
    })
Beispiel #16
0
def shutdown(request):
    """ shuts down the system and powers off the system """
    if not request.session.get("allow_shutdown"):
        return HttpResponseRedirect('/')
    request.session.pop("allow_shutdown")
    return render(request, 'system/shutdown.html', {
        'sw_name': get_sw_name(),
        'sw_version': get_sw_version(),
    })
Beispiel #17
0
def login_wrapper(
    request,
    template_name='registration/login.html',
    redirect_field_name=REDIRECT_FIELD_NAME,
    authentication_form=ExtendedAuthForm,
    current_app=None, extra_context=None,
):
    """
    Wrapper to login to do not allow login and redirect to
    shutdown, reboot or logout pages,
    instead redirect to /
    """

    auth_token = request.GET.get('auth_token')
    if auth_token:
        user = authenticate(auth_token=auth_token)
        if user:
            auth_login(request, user, 'freenasUI.middleware.auth.AuthTokenBackend')

    # Overload hook_app_index to shortcut passive node
    # Doing that in another layer will use too many reasources
    view = appPool.hook_app_index('account_login', request)
    view = [_f for _f in view if _f]
    if view:
        return view[0]

    if extra_context is None:
        extra_context = {}
    extra_context.update({
        'sw_login_version': get_sw_login_version(),
        'sw_version_footer': get_sw_version(strip_build_num=True).split('-', 1)[-1],
        'sw_name': get_sw_name(),
    })
    if not models.bsdUsers.has_root_password():
        authentication_form = forms.NewPasswordForm
        extra_context.update({
            'reset_password': True,
        })
    response = login(
        request,
        template_name='registration/login.html',
        redirect_field_name=redirect_field_name,
        authentication_form=authentication_form,
        current_app=current_app,
        extra_context=extra_context,
    )
    if response.status_code in (301, 302) and response._headers.get(
        'location', ('', '')
    )[1] in (
        reverse('system_reboot'),
        reverse('system_shutdown'),
        reverse('account_logout'),
    ):
        response._headers['location'] = ('Location', '/')
    elif request.user.is_authenticated:
        return HttpResponseRedirect('/')
    return response
Beispiel #18
0
    def ticket(self, support, alerts):
        node = alert_node()
        dismisseds = [a.message_id for a in mAlert.objects.filter(node=node)]
        msgs = []
        for alert in alerts:
            if alert.getId() not in dismisseds:
                msgs.append(str(alert))
        if len(msgs) == 0:
            return

        serial = subprocess.Popen(
            ['/usr/local/sbin/dmidecode', '-s', 'system-serial-number'],
            stdout=subprocess.PIPE,
            encoding='utf8',
        ).communicate()[0].split('\n')[0].upper()

        license, reason = get_license()
        if license:
            company = license.customer_name.decode()
        else:
            company = 'Unknown'

        for name, verbose_name in (
            ('name', 'Contact Name'),
            ('title', 'Contact Title'),
            ('email', 'Contact E-mail'),
            ('phone', 'Contact Phone'),
            ('secondary_name', 'Secondary Contact Name'),
            ('secondary_title', 'Secondary Contact Title'),
            ('secondary_email', 'Secondary Contact E-mail'),
            ('secondary_phone', 'Secondary Contact Phone'),
        ):
            value = getattr(support, name)
            if value:
                msgs += ['', '{}: {}'.format(verbose_name, value)]

        with client as c:
            try:
                rv = c.call('support.new_ticket', {
                    'title': 'Automatic alert (%s)' % serial,
                    'body': '\n'.join(msgs),
                    'version': get_sw_version().split('-', 1)[-1],
                    'debug': False,
                    'company': company,
                    'serial': serial,
                    'department': 20,
                    'category': 'Hardware',
                    'criticality': 'Loss of Functionality',
                    'environment': 'Production',
                    'name': 'Automatic Alert',
                    'email': '*****@*****.**',
                    'phone': '-',
                }, job=True)
                log.debug(f'Automatic alert ticket successfully created: {rv["url"]}')
            except ClientException as e:
                log.error(f'Failed to create a support ticket: {e.error}')
Beispiel #19
0
    def adminInterface(self, request):
        from freenasUI.network.models import GlobalConfiguration
        from freenasUI.system.models import Advanced, Settings

        view = appPool.hook_app_index('freeadmin', request)
        view = [_f for _f in view if _f]
        if view:
            return view[0]

        try:
            console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
        except:
            console = False
        try:
            hostname = GlobalConfiguration.objects.order_by(
                '-id')[0].get_hostname()
        except:
            hostname = None

        try:
            settings = Settings.objects.all().order_by('-id')[0]
            wizard = not settings.stg_wizardshown
            if settings.stg_wizardshown is False:
                settings.stg_wizardshown = True
                settings.save()
        except:
            wizard = False
        sw_version = get_sw_version()
        sw_version_footer = get_sw_version(strip_build_num=True).split('-', 1)[-1]

        return render(request, 'freeadmin/index.html', {
            'consolemsg': console,
            'hostname': hostname,
            'sw_name': get_sw_name(),
            'sw_year': get_sw_year(),
            'sw_version': sw_version,
            'sw_version_footer': sw_version_footer,
            'cache_hash': hashlib.md5(sw_version.encode('utf8')).hexdigest(),
            'css_hook': appPool.get_base_css(request),
            'js_hook': appPool.get_base_js(request),
            'menu_hook': appPool.get_top_menu(request),
            'wizard': wizard,
        })
Beispiel #20
0
    def ticket(self, alerts):
        node = alert_node()
        dismisseds = [
            a.message_id
            for a in mAlert.objects.filter(dismiss=True, node=node)
        ]
        msgs = []
        for alert in alerts:
            if alert.getId() not in dismisseds:
                msgs.append(unicode(alert).encode('utf8'))
        if len(msgs) == 0:
            return

        serial = subprocess.Popen(
            ['/usr/local/sbin/dmidecode', '-s', 'system-serial-number'],
            stdout=subprocess.PIPE).communicate()[0].split('\n')[0].upper()

        license, reason = get_license()
        if license:
            company = license.customer_name
        else:
            company = 'Unknown'

        success, msg, ticketnum = new_ticket({
            'title':
            'Automatic alert (%s)' % serial,
            'body':
            '\n'.join(msgs),
            'version':
            get_sw_version().split('-', 1)[-1],
            'debug':
            False,
            'company':
            company,
            'serial':
            serial,
            'department':
            20,
            'category':
            'Hardware',
            'criticality':
            'Loss of Functionality',
            'environment':
            'Production',
            'name':
            'Automatic Alert',
            'email':
            '*****@*****.**',
            'phone':
            '-',
        })
        if not success:
            log.error("Failed to create a support ticket: %s", msg)
        else:
            log.debug("Automatic alert ticket successfully created: %s", msg)
Beispiel #21
0
def eula(request):
    eula = None
    if os.path.exists('/usr/local/share/truenas/eula.html'):
        with open('/usr/local/share/truenas/eula.html', 'r', encoding='utf8') as f:
            eula = f.read()

    return render(request, 'eula.html', {
        'sw_name': get_sw_name(),
        'sw_version': get_sw_version(),
        'eula': eula,
        'hide_buttons': True,
    })
Beispiel #22
0
    def get_traceback_html(self):
        """
        Copied from debug.ExceptionReporter
        The Template was replaced to use 500_freenas.html instead
        of the hard-coded one

        Return HTML code for traceback."
        """

        t = get_template("500_freenas.html")
        data = self.get_traceback_data()
        data.update({
            'sw_version': get_sw_version(),
        })
        c = Context(data)
        return t.render(c)
Beispiel #23
0
    def get_traceback_html(self):
        """
        Copied from debug.ExceptionReporter
        The Template was replaced to use 500_freenas.html instead
        of the hard-coded one

        Return HTML code for traceback."
        """

        t = get_template("500_freenas.html")
        data = self.get_traceback_data()
        data.update({
            'sw_version': get_sw_version(),
        })
        c = Context(data)
        return t.render(c)
Beispiel #24
0
 def adminInterface(self, request):
     from freenasUI.network.models import GlobalConfiguration
     from freenasUI.system.models import Advanced
     try:
         console = Advanced.objects.all().order_by('-id')[0].adv_consolemsg
     except:
         console = False
     try:
         hostname = GlobalConfiguration.objects.order_by(
             '-id')[0].gc_hostname
     except:
         hostname = None
     sw_version = get_sw_version()
     return render(request, 'freeadmin/index.html', {
         'consolemsg': console,
         'hostname': hostname,
         'sw_name': get_sw_name(),
         'sw_version': sw_version,
         'cache_hash': hashlib.md5(sw_version).hexdigest(),
     })
Beispiel #25
0
    def ticket(self, alerts):
        node = alert_node()
        dismisseds = [a.message_id
                      for a in mAlert.objects.filter(dismiss=True, node=node)]
        msgs = []
        for alert in alerts:
            if alert.getId() not in dismisseds:
                msgs.append(unicode(alert).encode('utf8'))
        if len(msgs) == 0:
            return

        serial = subprocess.Popen(
            ['/usr/local/sbin/dmidecode', '-s', 'system-serial-number'],
            stdout=subprocess.PIPE
        ).communicate()[0].split('\n')[0].upper()

        license, reason = get_license()
        if license:
            company = license.customer_name
        else:
            company = 'Unknown'

        success, msg, ticketnum = new_ticket({
            'title': 'Automatic alert (%s)' % serial,
            'body': '\n'.join(msgs),
            'version': get_sw_version().split('-', 1)[-1],
            'debug': False,
            'company': company,
            'serial': serial,
            'department': 20,
            'category': 'Hardware',
            'criticality': 'Loss of Functionality',
            'environment': 'Production',
            'name': 'Automatic Alert',
            'email': '*****@*****.**',
            'phone': '-',
        })
        if not success:
            log.error("Failed to create a support ticket: %s", msg)
        else:
            log.debug("Automatic alert ticket successfully created: %s", msg)
Beispiel #26
0
def server_error(request, *args, **kwargs):
    # Save exc info before next exception occurs
    exc_info = sys.exc_info()
    try:
        tb = Advanced.objects.all().latest('id').adv_traceback
    except:
        tb = True

    try:
        # Allow rollbar to be disabled via sentinel file or environment var
        if (
            not os.path.exists('/tmp/.rollbar_disabled') and
            'ROLLBAR_DISABLED' not in os.environ
        ):
            extra_data = {
                'sw_version': get_sw_version(),
            }
            for path, name in (
                ('/data/update.failed', 'update_failed'),
                ('/var/log/debug.log', 'debug_log'),
            ):
                if os.path.exists(path):
                    with open(path, 'r') as f:
                        extra_data[name] = f.read()[-10240:]
            rollbar.report_exc_info(exc_info, request, extra_data=extra_data)
    except:
        log.warn('Failed to report error', exc_info=True)
    try:
        if tb:
            reporter = ExceptionReporter(request, *exc_info)
            html = reporter.get_traceback_html()
            return HttpResponse(html, content_type='text/html')
        else:
            raise
    except Exception:
        return debug.technical_500_response(request, *exc_info)
Beispiel #27
0
def ticket(request):

    step = 2 if request.FILES.getlist('attachment') else 1

    files = []
    if request.POST.get('debug') == 'on':
        debug = True
        with open(TICKET_PROGRESS, 'w') as f:
            f.write(json.dumps({'indeterminate': True, 'step': step}))
        step += 1

        mntpt, direc, dump = debug_get_settings()
        debug_run(direc)
        files.append(File(open(dump, 'rb'), name=os.path.basename(dump)))
    else:
        debug = False

    with open(TICKET_PROGRESS, 'w') as f:
        f.write(json.dumps({'indeterminate': True, 'step': step}))
    step += 1

    data = {
        'title': request.POST.get('subject'),
        'body': request.POST.get('desc'),
        'version': get_sw_version().split('-', 1)[-1],
        'category': request.POST.get('category'),
        'debug': debug,
    }

    if get_sw_name().lower() == 'freenas':
        data.update({
            'user': request.POST.get('username'),
            'password': request.POST.get('password'),
            'type': request.POST.get('type'),
        })
    else:

        serial = subprocess.Popen(
            ['/usr/local/sbin/dmidecode', '-s', 'system-serial-number'],
            stdout=subprocess.PIPE
        ).communicate()[0].split('\n')[0].upper()

        license, reason = utils.get_license()
        if license:
            company = license.customer_name
        else:
            company = 'Unknown'

        data.update({
            'phone': request.POST.get('phone'),
            'name': request.POST.get('name'),
            'company': company,
            'email': request.POST.get('email'),
            'criticality': request.POST.get('criticality'),
            'environment': request.POST.get('environment'),
            'serial': serial,
        })

    success, msg, tid = utils.new_ticket(data)

    with open(TICKET_PROGRESS, 'w') as f:
        f.write(json.dumps({'indeterminate': True, 'step': step}))
    step += 1

    data = {'message': msg, 'error': not success}

    if not success:
        pass
    else:

        files.extend(request.FILES.getlist('attachment'))
        for f in files:
            success, attachmsg = utils.ticket_attach({
                'user': request.POST.get('username'),
                'password': request.POST.get('password'),
                'ticketnum': tid,
            }, f)

    data = (
        '<html><body><textarea>%s</textarea></boby></html>' % (
            json.dumps(data),
        )
    )
    return HttpResponse(data)
Beispiel #28
0
 def __init__(self, *args, **kwargs):
     from django.db import connection
     from freenasUI.common.system import get_sw_version
     self._version = get_sw_version()
     self._conn = connection
Beispiel #29
0
def shutdown(request):
    """ shuts down the system and powers off the system """
    if not request.session.get("allow_shutdown"):
        return HttpResponseRedirect("/")
    request.session.pop("allow_shutdown")
    return render(request, "system/shutdown.html", {"sw_name": get_sw_name(), "sw_version": get_sw_version()})
Beispiel #30
0
def reboot(request):
    """ reboots the system """
    if not request.session.get("allow_reboot"):
        return HttpResponseRedirect("/")
    request.session.pop("allow_reboot")
    return render(request, "system/reboot.html", {"sw_name": get_sw_name(), "sw_version": get_sw_version()})
Beispiel #31
0
def ticket(request):

    step = 2 if request.FILES.getlist('attachment') else 1

    files = []
    if request.POST.get('debug') == 'on':
        debug = True
        with open(TICKET_PROGRESS, 'w') as f:
            f.write(json.dumps({'indeterminate': True, 'step': step}))
        step += 1

        mntpt, direc, dump = debug_get_settings()
        debug_generate()

        _n = notifier()
        if not _n.is_freenas() and _n.failover_licensed():
            debug_file = '%s/debug.tar' % direc
            debug_name = 'debug-%s.tar' % time.strftime('%Y%m%d%H%M%S')
        else:
            gc = GlobalConfiguration.objects.all().order_by('-id')[0]
            debug_file = dump
            debug_name = 'debug-%s-%s.txz' % (
                gc.gc_hostname.encode('utf-8'),
                time.strftime('%Y%m%d%H%M%S'),
            )

        files.append(File(open(debug_file, 'rb'), name=debug_name))
    else:
        debug = False

    with open(TICKET_PROGRESS, 'w') as f:
        f.write(json.dumps({'indeterminate': True, 'step': step}))
    step += 1

    data = {
        'title': request.POST.get('subject'),
        'body': request.POST.get('desc'),
        'version': get_sw_version().split('-', 1)[-1],
        'category': request.POST.get('category'),
        'debug': debug,
    }

    if get_sw_name().lower() == 'freenas':
        data.update({
            'user': request.POST.get('username'),
            'password': request.POST.get('password'),
            'type': request.POST.get('type'),
        })
    else:

        serial = subprocess.Popen(
            ['/usr/local/sbin/dmidecode', '-s', 'system-serial-number'],
            stdout=subprocess.PIPE
        ).communicate()[0].split('\n')[0].upper()

        license, reason = utils.get_license()
        if license:
            company = license.customer_name
        else:
            company = 'Unknown'

        data.update({
            'phone': request.POST.get('phone'),
            'name': request.POST.get('name'),
            'company': company,
            'email': request.POST.get('email'),
            'criticality': request.POST.get('criticality'),
            'environment': request.POST.get('environment'),
            'serial': serial,
        })

    success, msg, tid = utils.new_ticket(data)

    with open(TICKET_PROGRESS, 'w') as f:
        f.write(json.dumps({'indeterminate': True, 'step': step}))
    step += 1

    data = {'message': msg, 'error': not success}

    if not success:
        pass
    else:

        files.extend(request.FILES.getlist('attachment'))
        for f in files:
            success, attachmsg = utils.ticket_attach({
                'user': request.POST.get('username'),
                'password': request.POST.get('password'),
                'ticketnum': tid,
            }, f)

    data = (
        '<html><body><textarea>%s</textarea></boby></html>' % (
            json.dumps(data),
        )
    )
    return HttpResponse(data)
Beispiel #32
0
 def __init__(self, *args, **kwargs):
     from django.db import connection
     from freenasUI.common.system import get_sw_version
     self._version = get_sw_version()
     self._conn = connection
Beispiel #33
0
def ticket(request):

    step = 2 if request.FILES.getlist("attachment") else 1

    files = []
    if request.POST.get("debug") == "on":
        debug = True
        with open(TICKET_PROGRESS, "w") as f:
            f.write(json.dumps({"indeterminate": True, "step": step}))
        step += 1

        mntpt, direc, dump = debug_get_settings()
        debug_run(direc)
        files.append(File(open(dump, "rb"), name=os.path.basename(dump)))
    else:
        debug = False

    with open(TICKET_PROGRESS, "w") as f:
        f.write(json.dumps({"indeterminate": True, "step": step}))
    step += 1

    data = {
        "title": request.POST.get("subject"),
        "body": request.POST.get("desc"),
        "version": get_sw_version().split("-", 1)[-1],
        "category": request.POST.get("category"),
        "debug": debug,
    }

    if get_sw_name().lower() == "freenas":
        data.update(
            {
                "user": request.POST.get("username"),
                "password": request.POST.get("password"),
                "type": request.POST.get("type"),
            }
        )
    else:

        serial = (
            subprocess.Popen(["/usr/local/sbin/dmidecode", "-s", "system-serial-number"], stdout=subprocess.PIPE)
            .communicate()[0]
            .split("\n")[0]
            .upper()
        )

        license, reason = utils.get_license()
        if license:
            company = license.customer_name
        else:
            company = "Unknown"

        data.update(
            {
                "phone": request.POST.get("phone"),
                "name": request.POST.get("name"),
                "company": company,
                "email": request.POST.get("email"),
                "criticality": request.POST.get("criticality"),
                "environment": request.POST.get("environment"),
                "serial": serial,
            }
        )

    success, msg, tid = utils.new_ticket(data)

    with open(TICKET_PROGRESS, "w") as f:
        f.write(json.dumps({"indeterminate": True, "step": step}))
    step += 1

    data = {"message": msg, "error": not success}

    if not success:
        pass
    else:

        files.extend(request.FILES.getlist("attachment"))
        for f in files:
            success, attachmsg = utils.ticket_attach(
                {"user": request.POST.get("username"), "password": request.POST.get("password"), "ticketnum": tid}, f
            )

    data = "<html><body><textarea>%s</textarea></boby></html>" % (json.dumps(data),)
    return HttpResponse(data)
Beispiel #34
0
def ticket(request):

    step = 2 if request.FILES.getlist('attachment') else 1

    files = []
    if request.POST.get('debug') == 'on':
        debug = True
        with open(TICKET_PROGRESS, 'w') as f:
            f.write(json.dumps({'indeterminate': True, 'step': step}))
        step += 1

        mntpt, direc, dump = debug_get_settings()
        debug_run(direc)
        files.append(File(open(dump, 'rb'), name=os.path.basename(dump)))
    else:
        debug = False

    with open(TICKET_PROGRESS, 'w') as f:
        f.write(json.dumps({'indeterminate': True, 'step': step}))
    step += 1

    data = {
        'title': request.POST.get('subject'),
        'body': request.POST.get('desc'),
        'version': get_sw_version().split('-', 1)[-1],
        'category': request.POST.get('category'),
        'debug': debug,
    }

    if get_sw_name().lower() == 'freenas':
        data.update({
            'user': request.POST.get('username'),
            'password': request.POST.get('password'),
            'type': request.POST.get('type'),
        })
    else:

        serial = subprocess.Popen(
            ['/usr/local/sbin/dmidecode', '-s', 'system-serial-number'],
            stdout=subprocess.PIPE).communicate()[0].split('\n')[0].upper()

        license, reason = utils.get_license()
        if license:
            company = license.customer_name
        else:
            company = 'Unknown'

        data.update({
            'phone': request.POST.get('phone'),
            'name': request.POST.get('name'),
            'company': company,
            'email': request.POST.get('email'),
            'criticality': request.POST.get('criticality'),
            'environment': request.POST.get('environment'),
            'serial': serial,
        })

    success, msg, tid = utils.new_ticket(data)

    with open(TICKET_PROGRESS, 'w') as f:
        f.write(json.dumps({'indeterminate': True, 'step': step}))
    step += 1

    data = {'message': msg, 'error': not success}

    if not success:
        pass
    else:

        files.extend(request.FILES.getlist('attachment'))
        for f in files:
            success, attachmsg = utils.ticket_attach(
                {
                    'user': request.POST.get('username'),
                    'password': request.POST.get('password'),
                    'ticketnum': tid,
                }, f)

    data = ('<html><body><textarea>%s</textarea></boby></html>' %
            (json.dumps(data), ))
    return HttpResponse(data)
Beispiel #35
0
def ticket(request):

    step = 2 if request.FILES.getlist('attachment') else 1

    files = []
    if request.POST.get('debug') == 'on':
        debug = True
        with open(TICKET_PROGRESS, 'w') as f:
            f.write(json.dumps({'indeterminate': True, 'step': step}))
        step += 1

        mntpt, direc, dump = debug_get_settings()
        debug_generate()

        _n = notifier()
        if not _n.is_freenas() and _n.failover_licensed():
            debug_file = '%s/debug.tar' % direc
            debug_name = 'debug-%s.tar' % time.strftime('%Y%m%d%H%M%S')
        else:
            gc = GlobalConfiguration.objects.all().order_by('-id')[0]
            debug_file = dump
            debug_name = 'debug-%s-%s.txz' % (
                gc.gc_hostname.encode('utf-8'),
                time.strftime('%Y%m%d%H%M%S'),
            )

        files.append(File(open(debug_file, 'rb'), name=debug_name))
    else:
        debug = False

    with open(TICKET_PROGRESS, 'w') as f:
        f.write(json.dumps({'indeterminate': True, 'step': step}))
    step += 1

    data = {
        'title': request.POST.get('subject'),
        'body': request.POST.get('desc'),
        'version': get_sw_version().split('-', 1)[-1],
        'category': request.POST.get('category'),
        'debug': debug,
    }

    if get_sw_name().lower() == 'freenas':
        data.update({
            'user': request.POST.get('username'),
            'password': request.POST.get('password'),
            'type': request.POST.get('type'),
        })
    else:

        serial = subprocess.Popen(
            ['/usr/local/sbin/dmidecode', '-s', 'system-serial-number'],
            stdout=subprocess.PIPE).communicate()[0].split('\n')[0].upper()

        license, reason = utils.get_license()
        if license:
            company = license.customer_name
        else:
            company = 'Unknown'

        data.update({
            'phone': request.POST.get('phone'),
            'name': request.POST.get('name'),
            'company': company,
            'email': request.POST.get('email'),
            'criticality': request.POST.get('criticality'),
            'environment': request.POST.get('environment'),
            'serial': serial,
        })

    success, msg, tid = utils.new_ticket(data)

    with open(TICKET_PROGRESS, 'w') as f:
        f.write(json.dumps({'indeterminate': True, 'step': step}))
    step += 1

    data = {'message': msg, 'error': not success}

    if not success:
        pass
    else:

        files.extend(request.FILES.getlist('attachment'))
        for f in files:
            success, attachmsg = utils.ticket_attach(
                {
                    'user': request.POST.get('username'),
                    'password': request.POST.get('password'),
                    'ticketnum': tid,
                }, f)

    data = ('<html><body><textarea>%s</textarea></boby></html>' %
            (json.dumps(data), ))
    return HttpResponse(data)