Ejemplo n.º 1
0
def view_system_info(request):
    return_dict = {}
    try:
        if "ack" in request.GET:
            if request.GET["ack"] == "system_time_set":
                return_dict['ack_message'] = "Time successfully updated"
            elif request.GET["ack"] == "system_date_set":
                return_dict['ack_message'] = "Date successfully updated"
            elif request.GET["ack"] == "system_datetime_set":
                return_dict[
                    'ack_message'] = "Date and time successfully updated"
            elif request.GET["ack"] == 'system_timezone_set':
                return_dict['ack_message'] = "Timezone successfully updated"
            elif request.GET['ack'] == 'system_date_timezone_set':
                return_dict[
                    'ack_message'] = 'Date and timezone successfully updated'
            elif request.GET['ack'] == 'system_time_timezone_set':
                return_dict[
                    'ack_message'] = 'Time and timezone successfully updated'
            elif request.GET['ack'] == 'system_datetimetz_set':
                return_dict[
                    'ack_message'] = 'Date, time and timezone successfully updated'

        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        now = datetime.datetime.now()
        milliseconds = int(time.mktime(time.localtime()) * 1000)
        system_timezone, err = system_date_time.get_current_timezone()
        if err:
            raise Exception(err)
        return_dict['date_str'] = now.strftime("%A %d %B %Y")
        return_dict['time'] = now
        return_dict['milliseconds'] = milliseconds
        return_dict['system_timezone'] = system_timezone['system_timezone']
        print return_dict['system_timezone']
        return_dict['system_info'] = si
        if "from" in request.GET:
            frm = request.GET["from"]
            return_dict['frm'] = frm
        return_dict['node'] = si[si.keys()[0]]
        return django.shortcuts.render_to_response(
            "view_system_info.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "system_base.html"
        return_dict["page_title"] = 'System configuration'
        return_dict['tab'] = 'node_info_tab'
        return_dict["error"] = 'Error loading system configuration'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            'logged_in_error.html',
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Ejemplo n.º 2
0
def api_get_status(request):
    si = {}
    err = None
    try:
        si, err = system_info.load_system_config()
        # print si
        if err:
            raise Exception(err)
    except Exception, e:
        # print str(e)
        return JsonResponse({'error': str(e)})
Ejemplo n.º 3
0
def api_get_status(request):
    si = {}
    err = None
    try:
        si, err = system_info.load_system_config()
        # print si
        if err:
            raise Exception(err)
    except Exception, e:
        # print str(e)
        return JsonResponse({'error': str(e)})
def view_disks(request):
    return_dict = {}
    type = 'data'
    try:
        if "ack" in request.GET:
            if request.GET["ack"] == "blink":
                return_dict['ack_message'] = "Disk identification LED successfully activated"
            elif request.GET["ack"] == "unblink":
                return_dict['ack_message'] = "Disk identification LED successfully de-activated"
        ret, err = django_utils.get_request_parameter_values(
            request, ['type'])
        if err:
            raise Exception(err)
        if ('type' not in ret) or ret['type'] not in ['data', 'os']:
            type = 'data'
        else:
            type = ret['type']
        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        if not si:
            raise Exception('Error loading system configuration')
        hw_platform, err = config.get_hardware_platform()
        if hw_platform:
            return_dict['hw_platform'] = hw_platform
            if hw_platform == 'dell':
                from integralstor.platforms import dell
                idrac_url, err = dell.get_idrac_addr()
                if idrac_url:
                    return_dict['idrac_url'] = idrac_url
        if type == 'os':
            os_disk_stats, err = disks.get_os_partition_stats()
            if err:
                raise Exception(err)
            return_dict['os_disk_stats'] = os_disk_stats
        return_dict['node'] = si
        return_dict['system_info'] = si
        return_dict["disk_status"] = si['disks']
        # print si['disks']
        return_dict['node_name'] = si['fqdn']
        if type == 'os':
            return django.shortcuts.render_to_response('view_os_disks.html', return_dict, context_instance=django.template.context.RequestContext(request))
        else:
            return django.shortcuts.render_to_response('view_data_disks.html', return_dict, context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "storage_base.html"
        return_dict["page_title"] = 'Disks'
        return_dict['tab'] = 'view_%s_disks_tab' % type
        return_dict["error"] = 'Error loading disk information'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
Ejemplo n.º 5
0
def view_disks(request):
    return_dict = {}
    try:
        if "ack" in request.GET:
            if request.GET["ack"] == "blink":
                return_dict[
                    'ack_message'] = "Disk identification LED successfully activated"
            elif request.GET["ack"] == "unblink":
                return_dict[
                    'ack_message'] = "Disk identification LED successfully de-activated"
        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        if not si:
            raise Exception('Error loading system configuration')
        hw_platform, err = config.get_hardware_platform()
        if hw_platform:
            return_dict['hw_platform'] = hw_platform
            if hw_platform == 'dell':
                from integralstor_utils.platforms import dell
                idrac_url, err = dell.get_idrac_addr()
                if idrac_url:
                    return_dict['idrac_url'] = idrac_url
        return_dict['node'] = si[si.keys()[0]]
        return_dict['system_info'] = si
        return_dict["disk_status"] = si[si.keys()[0]]['disks']
        return_dict['node_name'] = si.keys()[0]
        return django.shortcuts.render_to_response(
            'view_disks.html',
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "storage_base.html"
        return_dict["page_title"] = 'Disks'
        return_dict['tab'] = 'view_disks_tab'
        return_dict["error"] = 'Error loading disk information'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Ejemplo n.º 6
0
def view_disks(request):
    return_dict = {}
    type = 'data'
    try:
        if "ack" in request.GET:
            if request.GET["ack"] == "blink":
                return_dict[
                    'ack_message'] = "Disk identification LED successfully activated"
            elif request.GET["ack"] == "unblink":
                return_dict[
                    'ack_message'] = "Disk identification LED successfully de-activated"
        ret, err = django_utils.get_request_parameter_values(request, ['type'])
        if err:
            raise Exception(err)
        if ('type' not in ret) or ret['type'] not in ['data', 'os']:
            type = 'data'
        else:
            type = ret['type']
        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        if not si:
            raise Exception('Error loading system configuration')
        hw_platform, err = config.get_hardware_platform()
        if hw_platform:
            return_dict['hw_platform'] = hw_platform
            if hw_platform == 'dell':
                from integralstor.platforms import dell
                idrac_url, err = dell.get_idrac_addr()
                if idrac_url:
                    return_dict['idrac_url'] = idrac_url
        if type == 'os':
            os_disk_stats, err = disks.get_os_partition_stats()
            if err:
                raise Exception(err)
            return_dict['os_disk_stats'] = os_disk_stats
        return_dict['node'] = si
        return_dict['system_info'] = si
        return_dict["disk_status"] = si['disks']
        # print si['disks']
        return_dict['node_name'] = si['fqdn']
        if type == 'os':
            return django.shortcuts.render_to_response(
                'view_os_disks.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            return django.shortcuts.render_to_response(
                'view_data_disks.html',
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
    except Exception, e:
        return_dict['base_template'] = "storage_base.html"
        return_dict["page_title"] = 'Disks'
        return_dict['tab'] = 'view_%s_disks_tab' % type
        return_dict["error"] = 'Error loading disk information'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Ejemplo n.º 7
0
def replace_disk(request):

    return_dict = {}
    try:
        form = None

        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        if not si:
            raise Exception('Error loading system config')

        return_dict['system_config_list'] = si

        template = 'logged_in_error.html'
        use_salt, err = config.use_salt()
        if err:
            raise Exception(err)

        if request.method == "GET":
            raise Exception("Incorrect access method. Please use the menus")
        else:
            if 'node' in request.POST:
                node = request.POST["node"]
            else:
                node = si['fqdn']
            serial_number = request.POST["serial_number"]

            if "conf" in request.POST:
                if "node" not in request.POST or "serial_number" not in request.POST:
                    raise Exception(
                        "Incorrect access method. Please use the menus")
                elif request.POST["node"] != si['fqdn']:
                    raise Exception("Unknown node. Please use the menus")
                elif "step" not in request.POST:
                    raise Exception("Incomplete request. Please use the menus")
                elif request.POST["step"] not in [
                        "replace_method", "select_replacement_disk",
                        "offline_disk", "scan_for_new_disk", "online_new_disk"
                ]:
                    raise Exception("Incomplete request. Please use the menus")
                else:
                    step = request.POST["step"]

                    # Which step of the replace disk are we in?

                    if step == "offline_disk":

                        # get the pool corresponding to the disk
                        # zpool offline pool disk
                        # send a screen asking them to replace the disk

                        if 'replacement_method' not in request.POST or request.POST[
                                'replacement_method'] not in [
                                    'use_existing_disk', 'swap_out_disk'
                                ]:
                            raise Exception('Invalid request')
                        return_dict['replacement_method'] = request.POST[
                            'replacement_method']
                        if request.POST[
                                'replacement_method'] == 'use_existing_disk':
                            # Then we should have landed here after already
                            # selecting the new disk so get and record the new
                            # disk details
                            if 'new_serial_number' not in request.POST:
                                raise Exception(
                                    'Incomplete request. Please try again')
                            new_serial_number = request.POST[
                                'new_serial_number']
                            all_disks, err = disks.get_disk_info_status_all(
                                rescan=False)
                            if new_serial_number not in all_disks:
                                raise Exception('Invalid disk selection')
                            # print new_serial_number
                            # print all_disks[new_serial_number]['id']
                            return_dict[
                                'new_serial_number'] = new_serial_number
                            return_dict['new_id'] = all_disks[
                                new_serial_number]['id']

                        pool = None
                        if serial_number in si["disks"]:
                            disk = si["disks"][serial_number]
                            if "pool" in disk:
                                pool = disk["pool"]
                            disk_id = disk["id"]
                        if not pool:
                            raise Exception(
                                "Could not find the storage pool on that disk. Please use the menus"
                            )
                        else:
                            cmd_to_run = 'zpool offline %s %s' % (pool,
                                                                  disk_id)
                            # print 'Running %s'%cmd_to_run
                            #assert False
                            ret, err = command.get_command_output(cmd_to_run)
                            if err:
                                raise Exception(err)
                            audit_str = "Replace disk - Disk with serial number %s brought offline" % serial_number
                            audit.audit("replace_disk_offline_disk", audit_str,
                                        request)
                            return_dict["serial_number"] = serial_number
                            return_dict["node"] = node
                            return_dict["pool"] = pool
                            return_dict["old_id"] = disk_id
                            template = "replace_disk_offlined_conf.html"

                    elif step == "replace_method":
                        return_dict["node"] = node
                        return_dict["serial_number"] = serial_number
                        template = "replace_disk_method.html"

                    elif step == "select_replacement_disk":
                        if 'replacement_method' not in request.POST or request.POST[
                                'replacement_method'] not in [
                                    'use_existing_disk', 'swap_out_disk'
                                ]:
                            raise Exception('Invalid request')
                        return_dict['replacement_method'] = request.POST[
                            'replacement_method']
                        return_dict["node"] = node
                        return_dict["serial_number"] = serial_number
                        free_disks, err = zfs.get_free_disks()
                        if err:
                            raise Exception(err)
                        if not free_disks:
                            raise Exception(
                                'There are no unused disks presently')
                        return_dict['free_disks'] = free_disks
                        template = "replace_disk_choose_disk.html"

                    elif step == "scan_for_new_disk":

                        # they have replaced the disk so scan for the new disk
                        # and prompt for a confirmation of the new disk serial
                        # number

                        pool = request.POST["pool"]
                        old_id = request.POST["old_id"]
                        return_dict["node"] = node
                        return_dict["serial_number"] = serial_number
                        return_dict["pool"] = pool
                        return_dict["old_id"] = old_id
                        old_disks = si["disks"].keys()
                        result = False
                        new_disks, err = disks.get_disk_info_status_all(
                            rescan=True)
                        if err:
                            raise Exception(err)
                        '''
                        rc, err = manifest_status.get_disk_info_and_status()
                        if err:
                            raise Exception(err)
                        if rc:
                            result = True
                            new_disks = rc
                        if result:
                        '''
                        if new_disks:
                            # print new_disks.keys()
                            # print old_disks
                            for disk in new_disks.keys():
                                # print disk
                                if disk not in old_disks:
                                    # print 'new disk : ', disk
                                    return_dict[
                                        "inserted_disk_serial_number"] = disk
                                    return_dict["new_id"] = new_disks[disk][
                                        "id"]
                                    break
                            if "inserted_disk_serial_number" not in return_dict:
                                raise Exception(
                                    "Could not detect any new disk. Please check the new disk is inserted and give the system a few seconds to detect the drive and refresh the page to try again."
                                )
                            else:
                                template = "replace_disk_confirm_new_disk.html"
                        else:
                            raise Exception('No disks were found!')
                    elif step == "online_new_disk":

                        pool = request.POST["pool"]
                        old_id = request.POST["old_id"]
                        new_id = request.POST["new_id"]
                        new_serial_number = request.POST["new_serial_number"]
                        python_scripts_path, err = config.get_python_scripts_path(
                        )
                        if err:
                            raise Exception(err)
                        cmd_list = []
                        cmd_list.append({
                            'Replace old disk':
                            'zpool replace -f %s %s %s' %
                            (pool, old_id, new_id)
                        })
                        cmd_list.append({
                            'Online the new disk':
                            'zpool online -e %s %s' % (pool, new_id)
                        })
                        cmd_list.append({
                            'Regenerate the system configuration':
                            '%s/generate_manifest.py' % python_scripts_path
                        })
                        ret, err = tasks_utils.create_task('Disk replacement',
                                                           cmd_list,
                                                           task_type_id=1,
                                                           attempts=1)
                        if err:
                            raise Exception(err)
                        if not ret:
                            raise Exception(
                                'Error scheduling disk replacement tasks')
                        audit_str = "Replace disk - Scheduled a task for replacing the old disk with serial number %s with the new disk with serial number %s" % (
                            serial_number, new_serial_number)
                        audit.audit("replace_disk_replaced_disk", audit_str,
                                    request)
                        return_dict["node"] = node
                        return_dict["old_serial_number"] = serial_number
                        return_dict["new_serial_number"] = new_serial_number
                        template = "replace_disk_success.html"
                    return django.shortcuts.render_to_response(
                        template,
                        return_dict,
                        context_instance=django.template.context.
                        RequestContext(request))

            else:
                if "serial_number" not in request.POST:
                    raise Exception(
                        "Incorrect access method. Please use the menus")
                else:
                    if 'node' in request.POST:
                        return_dict["node"] = request.POST["node"]
                    else:
                        node = si['fqdn']
                    return_dict["serial_number"] = request.POST[
                        "serial_number"]
                    template = "replace_disk_conf.html"
        return django.shortcuts.render_to_response(
            template,
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "storage_base.html"
        return_dict["page_title"] = 'Replace a disk in a ZFS pool'
        return_dict['tab'] = 'view_data_disks_tab'
        return_dict["error"] = 'Error replacing a disk in a ZFS pool'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            "logged_in_error.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
Ejemplo n.º 8
0
def view_dashboard(request, page = None):
    return_dict = {}
    try:
        return_dict["page_title"] = 'Overall system health'
        return_dict['tab'] = 'system_health_tab'
        return_dict["error"] = 'Error loading system health data'

        if request.method != 'GET':
            raise Exception('Invalid access method. Please use the menus')

        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        if not si:
            raise Exception('Error loading system configuration')

        #node_name = si.keys()[0]
        #node = si[node_name]
        return_dict['node'] = si
        # print node.keys()

        # By default show error page
        template = "logged_in_error.html"

        # Chart specific declarations
        # will return 02, instead of 2.
        end_epoch, err = datetime_utils.get_epoch(when='now')
        if err:
            raise Exception(err)
        start_epoch = end_epoch - 3 * 60 * 60
        start, err = datetime_utils.convert_from_epoch(
            start_epoch, return_format='str', str_format='%H:%M:%S', to='local')
        if err:
            raise Exception(err)
        end, err = datetime_utils.convert_from_epoch(
            end_epoch, return_format='str', str_format='%H:%M:%S', to='local')
        if err:
            raise Exception(err)

        todays_date = (datetime.date.today()).strftime('%02d')

        value_list = []
        time_list = []

        num_bad_disks = 0
        num_hw_raid_bad_disks = 0
        num_hw_raid_ctrl_disks = 0
        num_smart_ctrl_disks = 0
        num_disks = len(si['disks'])
        disks_ok = True
        for sn, disk in si['disks'].items():
            if 'status' in disk:
                if 'hw_raid' in disk:
                    if not disk['hw_raid']:
                        num_smart_ctrl_disks += 1
                        if (disk['status'] is not None and disk['status'].upper() not in ['PASSED', 'OK']):
                            num_bad_disks += 1
                            disks_ok = False
                    else:
                        num_hw_raid_ctrl_disks += 1
                        if (disk['status'] is not None and disk['status'].upper() != 'OK'):
                            num_hw_raid_bad_disks += 1
                            disks_ok = False
                else:
                    # Assume its a non raid disk
                    num_smart_ctrl_disks += 1
                    if (disk['status'] is not None and disk['status'].upper() not in ['PASSED', 'OK']):
                        num_bad_disks += 1
                        disks_ok = False

        return_dict['num_disks'] = num_disks
        return_dict['num_bad_disks'] = num_bad_disks
        return_dict['disks_ok'] = disks_ok
        return_dict['num_hw_raid_bad_disks'] = num_hw_raid_bad_disks
        return_dict['num_hw_raid_ctrl_disks'] = num_hw_raid_ctrl_disks
        return_dict['num_smart_ctrl_disks'] = num_smart_ctrl_disks

        if 'ipmi_status' in si:
            num_sensors = len(si['ipmi_status'])
            num_bad_sensors = 0
            ipmi_ok = True
            for sensor in si['ipmi_status']:
                if sensor['status'] in ['ok', 'nr', 'na']:
                    continue
                else:
                    num_bad_sensors += 1
                    ipmi_ok = False
            return_dict['num_sensors'] = num_sensors
            return_dict['num_bad_sensors'] = num_bad_sensors
            return_dict['ipmi_ok'] = ipmi_ok

        services_dict, err = services_management.get_sysd_services_status()
        if err:
            raise Exception(err)

        num_services = len(services_dict)
        num_failed_services = 0
        num_active_services = 0
        num_inactive_services = 0
        services_ok = True

        if services_dict:
            for service, service_d in services_dict.items():
                if service_d["info"]["status"]["status_str"] == "Active":
                    num_active_services += 1
                elif service_d["info"]["status"]["status_str"] == "Inactive":
                    num_inactive_services += 1
                elif service_d["info"]["status"]["status_str"] == "Failed":
                    num_failed_services += 1
                    services_ok = False
                elif service_d["info"]["status"]["status_str"] == "Unknown State":
                    num_failed_services += 1
                    services_ok = False
            return_dict['num_services'] = num_services
            return_dict['num_active_services'] = num_active_services
            return_dict['num_inactive_services'] = num_inactive_services
            return_dict['num_failed_services'] = num_failed_services
            return_dict['services_ok'] = services_ok
        else:
            raise Exception('Error retrieving services status')

        pools, err = zfs.get_pools()
        if err:
            raise Exception(err)

        num_pools = len(pools)
        num_bad_pools = 0
        num_degraded_pools = 0
        num_high_usage_pools = 0
        for pool in pools:
            if pool['usage']['used_percent'] > 75:
                num_high_usage_pools += 1
            if pool['config']['pool']['root']['status']['state'] == 'ONLINE':
                pass
            elif pool['config']['pool']['root']['status']['state'] == 'DEGRADED':
                num_degraded_pools += 1
            else:
                num_bad_pools += 1
        return_dict['num_pools'] = num_pools
        return_dict['num_bad_pools'] = num_bad_pools
        return_dict['num_degraded_pools'] = num_degraded_pools
        return_dict['num_high_usage_pools'] = num_high_usage_pools

        load_avg_ok = True
        if (si["load_avg"]["5_min"] > si["load_avg"]["cpu_cores"]) or (si["load_avg"]["15_min"] > si["load_avg"]["cpu_cores"]):
            load_avg_ok = False
        return_dict['load_avg_ok'] = load_avg_ok

        shares_list, err = cifs.get_shares_list()
        if err:
            raise Exception(err)
        return_dict['num_cifs_shares'] = len(shares_list)

        exports_list, err = nfs.load_exports_list()
        if err:
            raise Exception(err)
        return_dict['num_nfs_exports'] = len(exports_list)

        target_list, err = iscsi_stgt.get_targets()
        if err:
            raise Exception(err)
        return_dict['num_iscsi_targets'] = len(target_list)

        with open('/proc/uptime', 'r') as f:
            uptime_seconds = float(f.readline().split()[0])
            uptime_str = '%s hours' % (
                ':'.join(str(datetime.timedelta(seconds=uptime_seconds)).split(':')[:2]))
            return_dict['uptime_str'] = uptime_str

        # CPU status
        if not page:
            page = "sys_health"
        if page == "cpu":
            return_dict["page_title"] = 'CPU statistics'
            return_dict['tab'] = 'cpu_tab'
            return_dict["error"] = 'Error loading CPU statistics'
            cpu, err = stats.get_system_stats(todays_date, start, end, "cpu")
            if err:
                raise Exception(err)
            value_dict = {}
            if cpu:
                for key in cpu.keys():
                    value_list = []
                    time_list = []
                    if key == "date":
                        pass
                    else:
                        if cpu[key]:
                            for a in cpu[key]:
                                time_list.append(a[0])
                                value_list.append(a[1])
                        value_dict[key] = value_list
            return_dict["data_dict"] = value_dict
            queue, err = stats.get_system_stats(
                todays_date, start, end, "queue")
            if err:
                raise Exception(err)
            value_dict = {}
            if queue:
                for key in queue.keys():
                    value_list = []
                    time_list = []
                    if key == "date":
                        pass
                    else:
                        for a in queue[key]:
                            time_list.append(a[0])
                            value_list.append(a[1])
                        value_dict[key] = value_list
            return_dict["data_dict_queue"] = value_dict
            return_dict['node'] = si
            d = {}
            template = "view_cpu_stats.html"
        elif page == "sys_health":
            return_dict["page_title"] = 'Overall system health'
            return_dict['tab'] = 'system_health_tab'
            return_dict["error"] = 'Error loading system health data'
            template = "view_dashboard.html"
            hw_platform, err = config.get_hardware_platform()
            if hw_platform:
                return_dict['hw_platform'] = hw_platform
                if hw_platform == 'dell':
                    from integralstor.platforms import dell
                    idrac_url, err = dell.get_idrac_addr()
                    if idrac_url:
                        return_dict['idrac_url'] = idrac_url
        # Memory
        elif page == "memory":
            return_dict["page_title"] = 'Memory statistics'
            return_dict['tab'] = 'memory_tab'
            return_dict["error"] = 'Error loading memory statistics'
            mem, err = stats.get_system_stats(
                todays_date, start, end, "memory")
            if err:
                raise Exception(err)
            if mem:
                for a in mem["memused"]:
                    time_list.append(a[0])
                    value_list.append((a[1] / (1024 * 1024)))
            return_dict['memory_status'] = si['memory']
            template = "view_memory_stats.html"
        # Network
        elif page == "network":
            return_dict["page_title"] = 'Network statistics'
            return_dict['tab'] = 'network_tab'
            return_dict["error"] = 'Error loading Network statistics'
            network, err = stats.get_system_stats(
                todays_date, start, end, "network")
            if err:
                raise Exception(err)
            value_dict = {}
            if network:
                for key in network.keys():
                    value_list = []
                    time_list = []
                    if key == "date" or key == "lo":
                        pass
                    else:
                        for a in network[key]["ifutil-percent"]:
                            time_list.append(a[0])
                            value_list.append(a[1])
                        value_dict[key] = value_list

            return_dict["data_dict"] = value_dict
            return_dict["network_status"] = si['interfaces']
            template = "view_network_stats.html"
        return_dict["labels"] = time_list
        return_dict["data"] = value_list
        return django.shortcuts.render_to_response(template, return_dict, context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "monitoring_base.html"
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
def view_system_info(request):
    return_dict = {}
    try:
        if "ack" in request.GET:
            if request.GET["ack"] == "system_time_set":
                return_dict['ack_message'] = "Time successfully updated"
            elif request.GET["ack"] == "system_date_set":
                return_dict['ack_message'] = "Date successfully updated"
            elif request.GET["ack"] == "system_datetime_set":
                return_dict[
                    'ack_message'] = "Date and time successfully updated"
            elif request.GET["ack"] == 'system_timezone_set':
                return_dict['ack_message'] = "Timezone successfully updated"
            elif request.GET['ack'] == 'system_date_timezone_set':
                return_dict[
                    'ack_message'] = 'Date and timezone successfully updated'
            elif request.GET['ack'] == 'system_time_timezone_set':
                return_dict[
                    'ack_message'] = 'Time and timezone successfully updated'
            elif request.GET['ack'] == 'system_datetimetz_set':
                return_dict[
                    'ack_message'] = 'Date, time and timezone successfully updated'
            elif request.GET['ack'] == 'config_uploaded':
                return_dict[
                    'ack_message'] = 'Configuration information successfully uploaded'
            elif request.GET['ack'] == 'update_org_info_ok':
                return_dict[
                    'ack_message'] = 'Updated orgnazation information successfully'

        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        org_info, err = system_info.get_org_info()
        if err:
            raise Exception(err)
        return_dict['org_info'] = org_info

        now_epoch, err = datetime_utils.get_epoch(when='now',
                                                  num_previous_days=0)
        if err:
            raise Exception(err)
        now, err = datetime_utils.convert_from_epoch(now_epoch,
                                                     return_format='datetime',
                                                     to='local')
        if err:
            raise Exception(err)
        milliseconds = int(now_epoch * 1000)
        if err:
            raise Exception(err)
        system_timezone, err = datetime_utils.get_system_timezone()
        if err:
            raise Exception(err)
        return_dict['date_str'] = now.strftime("%A %d %B %Y")
        return_dict['time'] = now
        return_dict['milliseconds'] = milliseconds
        return_dict['system_timezone'] = system_timezone['system_timezone']
        # print return_dict['system_timezone']
        return_dict['system_info'] = si
        if "from" in request.GET:
            frm = request.GET["from"]
            return_dict['frm'] = frm
        return_dict['node'] = si
        return django.shortcuts.render_to_response(
            "view_system_info.html",
            return_dict,
            context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "system_base.html"
        return_dict["page_title"] = 'System configuration'
        return_dict['tab'] = 'node_info_tab'
        return_dict["error"] = 'Error loading system configuration'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response(
            'logged_in_error.html',
            return_dict,
            context_instance=django.template.context.RequestContext(request))
def view_system_info(request):
    return_dict = {}
    try:
        if "ack" in request.GET:
            if request.GET["ack"] == "system_time_set":
                return_dict['ack_message'] = "Time successfully updated"
            elif request.GET["ack"] == "system_date_set":
                return_dict['ack_message'] = "Date successfully updated"
            elif request.GET["ack"] == "system_datetime_set":
                return_dict['ack_message'] = "Date and time successfully updated"
            elif request.GET["ack"] == 'system_timezone_set':
                return_dict['ack_message'] = "Timezone successfully updated"
            elif request.GET['ack'] == 'system_date_timezone_set':
                return_dict['ack_message'] = 'Date and timezone successfully updated'
            elif request.GET['ack'] == 'system_time_timezone_set':
                return_dict['ack_message'] = 'Time and timezone successfully updated'
            elif request.GET['ack'] == 'system_datetimetz_set':
                return_dict['ack_message'] = 'Date, time and timezone successfully updated'
            elif request.GET['ack'] == 'config_uploaded':
                return_dict['ack_message'] = 'Configuration information successfully uploaded'
            elif request.GET['ack'] == 'update_org_info_ok':
                return_dict['ack_message'] = 'Updated orgnazation information successfully'

        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        org_info, err = system_info.get_org_info()
        if err:
            raise Exception(err)
        return_dict['org_info'] = org_info

        now_epoch, err = datetime_utils.get_epoch(
            when='now', num_previous_days=0)
        if err:
            raise Exception(err)
        now, err = datetime_utils.convert_from_epoch(
            now_epoch, return_format='datetime', to='local')
        if err:
            raise Exception(err)
        milliseconds = int(now_epoch * 1000)
        if err:
            raise Exception(err)
        system_timezone, err = datetime_utils.get_system_timezone()
        if err:
            raise Exception(err)
        return_dict['date_str'] = now.strftime("%A %d %B %Y")
        return_dict['time'] = now
        return_dict['milliseconds'] = milliseconds
        return_dict['system_timezone'] = system_timezone['system_timezone']
        # print return_dict['system_timezone']
        return_dict['system_info'] = si
        if "from" in request.GET:
            frm = request.GET["from"]
            return_dict['frm'] = frm
        return_dict['node'] = si
        return django.shortcuts.render_to_response("view_system_info.html", return_dict, context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "system_base.html"
        return_dict["page_title"] = 'System configuration'
        return_dict['tab'] = 'node_info_tab'
        return_dict["error"] = 'Error loading system configuration'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response('logged_in_error.html', return_dict, context_instance=django.template.context.RequestContext(request))
Ejemplo n.º 11
0
def update_ntp_settings(request):

    return_dict = {}
    try:
        if request.method == "GET":
            ntp_servers, err = ntp.get_ntp_servers()
            if err:
                raise Exception(err)
            if not ntp_servers:
                form = common_forms.ConfigureNTPForm()
            else:
                form = common_forms.ConfigureNTPForm(
                    initial={'server_list': ','.join(ntp_servers)})
            url = "update_ntp_settings.html"
        else:
            form = common_forms.ConfigureNTPForm(request.POST)
            if form.is_valid():
                iv_logging.debug("Got valid request to change NTP settings")
                cd = form.cleaned_data
                si, err = system_info.load_system_config()
                if err:
                    raise Exception(err)
                server_list = cd["server_list"]
                if ',' in server_list:
                    slist = server_list.split(',')
                else:
                    slist = server_list.split(' ')
                with open('/tmp/ntp.conf', 'w') as temp:
                    # First create the ntp.conf file for the primary and
                    # secondary nodes
                    temp.write("driftfile /var/lib/ntp/drift\n")
                    temp.write(
                        "restrict default kod nomodify notrap nopeer noquery\n")
                    temp.write(
                        "restrict -6 default kod nomodify notrap nopeer noquery\n")
                    temp.write("logfile /var/log/ntp.log\n")
                    temp.write("\n")
                    for server in slist:
                        temp.write("server %s iburst\n" % server)
                    temp.flush()
                    temp.close()
                shutil.move('/tmp/ntp.conf', '/etc/ntp.conf')
                #ret, err = ntp.restart_ntp_service()
                ret, err = services_management.update_service_status(
                    'ntpd', 'restart')
                if err:
                    raise Exception(err)
                return django.http.HttpResponseRedirect("/view_ntp_settings?ack=saved")
            else:
                # invalid form
                iv_logging.debug("Got invalid request to change NTP settings")
                url = "update_ntp_settings.html"
        return_dict["form"] = form
        return django.shortcuts.render_to_response(url, return_dict, context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "services_base.html"
        return_dict["page_title"] = 'Modify NTP notifications settings'
        return_dict['tab'] = 'ntp_settings_tab'
        return_dict["error"] = 'Error modifying NTP notifications settings'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))
def replace_disk(request):

    return_dict = {}
    try:
        form = None

        si, err = system_info.load_system_config()
        if err:
            raise Exception(err)
        if not si:
            raise Exception('Error loading system config')

        return_dict['system_config_list'] = si

        template = 'logged_in_error.html'
        use_salt, err = config.use_salt()
        if err:
            raise Exception(err)

        if request.method == "GET":
            raise Exception("Incorrect access method. Please use the menus")
        else:
            if 'node' in request.POST:
                node = request.POST["node"]
            else:
                node = si['fqdn']
            serial_number = request.POST["serial_number"]

            if "conf" in request.POST:
                if "node" not in request.POST or "serial_number" not in request.POST:
                    raise Exception(
                        "Incorrect access method. Please use the menus")
                elif request.POST["node"] != si['fqdn']:
                    raise Exception("Unknown node. Please use the menus")
                elif "step" not in request.POST:
                    raise Exception("Incomplete request. Please use the menus")
                elif request.POST["step"] not in ["replace_method", "select_replacement_disk", "offline_disk", "scan_for_new_disk", "online_new_disk"]:
                    raise Exception("Incomplete request. Please use the menus")
                else:
                    step = request.POST["step"]

                    # Which step of the replace disk are we in?

                    if step == "offline_disk":

                        # get the pool corresponding to the disk
                        # zpool offline pool disk
                        # send a screen asking them to replace the disk

                        if 'replacement_method' not in request.POST or request.POST['replacement_method'] not in ['use_existing_disk', 'swap_out_disk']:
                            raise Exception('Invalid request')
                        return_dict['replacement_method'] = request.POST['replacement_method']
                        if request.POST['replacement_method'] == 'use_existing_disk':
                            # Then we should have landed here after already
                            # selecting the new disk so get and record the new
                            # disk details
                            if 'new_serial_number' not in request.POST:
                                raise Exception(
                                    'Incomplete request. Please try again')
                            new_serial_number = request.POST['new_serial_number']
                            all_disks, err = disks.get_disk_info_status_all(
                                rescan=False)
                            if new_serial_number not in all_disks:
                                raise Exception('Invalid disk selection')
                            # print new_serial_number
                            # print all_disks[new_serial_number]['id']
                            return_dict['new_serial_number'] = new_serial_number
                            return_dict['new_id'] = all_disks[new_serial_number]['id']

                        pool = None
                        if serial_number in si["disks"]:
                            disk = si["disks"][serial_number]
                            if "pool" in disk:
                                pool = disk["pool"]
                            disk_id = disk["id"]
                        if not pool:
                            raise Exception(
                                "Could not find the storage pool on that disk. Please use the menus")
                        else:
                            cmd_to_run = 'zpool offline %s %s' % (
                                pool, disk_id)
                            # print 'Running %s'%cmd_to_run
                            #assert False
                            ret, err = command.get_command_output(cmd_to_run)
                            if err:
                                raise Exception(err)
                            audit_str = "Replace disk - Disk with serial number %s brought offline" % serial_number
                            audit.audit("replace_disk_offline_disk",
                                        audit_str, request)
                            return_dict["serial_number"] = serial_number
                            return_dict["node"] = node
                            return_dict["pool"] = pool
                            return_dict["old_id"] = disk_id
                            template = "replace_disk_offlined_conf.html"

                    elif step == "replace_method":
                        return_dict["node"] = node
                        return_dict["serial_number"] = serial_number
                        template = "replace_disk_method.html"

                    elif step == "select_replacement_disk":
                        if 'replacement_method' not in request.POST or request.POST['replacement_method'] not in ['use_existing_disk', 'swap_out_disk']:
                            raise Exception('Invalid request')
                        return_dict['replacement_method'] = request.POST['replacement_method']
                        return_dict["node"] = node
                        return_dict["serial_number"] = serial_number
                        free_disks, err = zfs.get_free_disks()
                        if err:
                            raise Exception(err)
                        if not free_disks:
                            raise Exception(
                                'There are no unused disks presently')
                        return_dict['free_disks'] = free_disks
                        template = "replace_disk_choose_disk.html"

                    elif step == "scan_for_new_disk":

                        # they have replaced the disk so scan for the new disk
                        # and prompt for a confirmation of the new disk serial
                        # number

                        pool = request.POST["pool"]
                        old_id = request.POST["old_id"]
                        return_dict["node"] = node
                        return_dict["serial_number"] = serial_number
                        return_dict["pool"] = pool
                        return_dict["old_id"] = old_id
                        old_disks = si["disks"].keys()
                        result = False
                        new_disks, err = disks.get_disk_info_status_all(
                            rescan=True)
                        if err:
                            raise Exception(err)
                        '''
                        rc, err = manifest_status.get_disk_info_and_status()
                        if err:
                            raise Exception(err)
                        if rc:
                            result = True
                            new_disks = rc
                        if result:
                        '''
                        if new_disks:
                            # print new_disks.keys()
                            # print old_disks
                            for disk in new_disks.keys():
                                # print disk
                                if disk not in old_disks:
                                    # print 'new disk : ', disk
                                    return_dict["inserted_disk_serial_number"] = disk
                                    return_dict["new_id"] = new_disks[disk]["id"]
                                    break
                            if "inserted_disk_serial_number" not in return_dict:
                                raise Exception(
                                    "Could not detect any new disk. Please check the new disk is inserted and give the system a few seconds to detect the drive and refresh the page to try again.")
                            else:
                                template = "replace_disk_confirm_new_disk.html"
                        else:
                            raise Exception('No disks were found!')
                    elif step == "online_new_disk":

                        pool = request.POST["pool"]
                        old_id = request.POST["old_id"]
                        new_id = request.POST["new_id"]
                        new_serial_number = request.POST["new_serial_number"]
                        python_scripts_path, err = config.get_python_scripts_path()
                        if err:
                            raise Exception(err)
                        cmd_list = []
                        cmd_list.append(
                            {'Replace old disk': 'zpool replace -f %s %s %s' % (pool, old_id, new_id)})
                        cmd_list.append(
                            {'Online the new disk': 'zpool online -e %s %s' % (pool, new_id)})
                        cmd_list.append(
                            {'Regenerate the system configuration': '%s/generate_manifest.py' % python_scripts_path})
                        ret, err = tasks_utils.create_task(
                            'Disk replacement', cmd_list, task_type_id=1, attempts=1)
                        if err:
                            raise Exception(err)
                        if not ret:
                            raise Exception(
                                'Error scheduling disk replacement tasks')
                        audit_str = "Replace disk - Scheduled a task for replacing the old disk with serial number %s with the new disk with serial number %s" % (
                            serial_number, new_serial_number)
                        audit.audit("replace_disk_replaced_disk",
                                    audit_str, request)
                        return_dict["node"] = node
                        return_dict["old_serial_number"] = serial_number
                        return_dict["new_serial_number"] = new_serial_number
                        template = "replace_disk_success.html"
                    return django.shortcuts.render_to_response(template, return_dict, context_instance=django.template.context.RequestContext(request))

            else:
                if "serial_number" not in request.POST:
                    raise Exception(
                        "Incorrect access method. Please use the menus")
                else:
                    if 'node' in request.POST:
                        return_dict["node"] = request.POST["node"]
                    else:
                        node = si['fqdn']
                    return_dict["serial_number"] = request.POST["serial_number"]
                    template = "replace_disk_conf.html"
        return django.shortcuts.render_to_response(template, return_dict, context_instance=django.template.context.RequestContext(request))
    except Exception, e:
        return_dict['base_template'] = "storage_base.html"
        return_dict["page_title"] = 'Replace a disk in a ZFS pool'
        return_dict['tab'] = 'view_data_disks_tab'
        return_dict["error"] = 'Error replacing a disk in a ZFS pool'
        return_dict["error_details"] = str(e)
        return django.shortcuts.render_to_response("logged_in_error.html", return_dict, context_instance=django.template.context.RequestContext(request))