def delete_bond(request):

    return_dict = {}
    try:
        req_ret, err = django_utils.get_request_parameter_values(request, [
                                                                 'name'])
        if err:
            raise Exception(err)
        if 'name' not in req_ret:
            raise Exception('Invalid request, please use the menus')
        name = req_ret['name']
        return_dict["name"] = name

        if request.method == "GET":
            # Return the conf page
            return django.shortcuts.render_to_response("delete_bond_conf.html", return_dict, context_instance=django.template.context.RequestContext(request))
        else:
            result, err = networking.delete_bond(name)
            if not result:
                if not err:
                    raise Exception("Error removing bond")
                else:
                    raise Exception(err)

            python_scripts_path, err = config.get_python_scripts_path()
            if err:
                raise Exception(err)
            python_scripts_path, err = config.get_python_scripts_path()
            if err:
                raise Exception(err)
            status_path, err = config.get_system_status_path()
            if err:
                raise Exception(err)

            ret, err = command.get_command_output(
                "python %s/generate_manifest.py %s" % (python_scripts_path, status_path))
            if err:
                raise Exception(err)

            ret, err = command.get_command_output(
                "python %s/generate_status.py %s" % (python_scripts_path, status_path))
            if err:
                raise Exception(err)

            audit_str = "Removed network bond %s" % (name)
            audit.audit("remove_bond", audit_str, request)
            return django.http.HttpResponseRedirect('/networking/view_interfaces?ack=removed_bond')
    except Exception, e:
        return_dict['base_template'] = "networking_base.html"
        return_dict["page_title"] = 'Remove a network interface bond'
        return_dict['tab'] = 'view_interfaces_tab'
        return_dict["error"] = 'Error removing a network interface bond'
        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 update_manifest(request):
    return_dict = {}
    try:
        if request.method == "GET":
            from integralstor import manifest_status as iu
            mi, err = iu.generate_manifest_info(rescan_for_disks=True)
            # print mi, err
            if err:
                raise Exception(err)
            if not mi:
                raise Exception('Could not load new configuration')
            return_dict["mi"] = mi  # Need the hostname here.
            return django.shortcuts.render_to_response(
                "update_manifest.html",
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        elif request.method == "POST":
            python_scripts_path, err = config.get_python_scripts_path()
            if err:
                raise Exception(err)
            ss_path, err = config.get_system_status_path()
            if err:
                raise Exception(err)
            #(ret,rc), err = command.execute_with_rc("python %s/generate_manifest.py %s"%(python_scripts_path, ss_path))
            ret, err = command.get_command_output(
                "python %s/generate_manifest.py %s" %
                (python_scripts_path, ss_path))
            # print 'mani', ret, err
            if err:
                raise Exception(err)
            #(ret,rc), err = command.execute_with_rc("python %s/generate_status.py %s"%(config.get_python_scripts_path(),config.get_system_status_path()))
            ret, err = command.get_command_output(
                "python %s/generate_status.py %s" %
                (python_scripts_path, ss_path))
            # print 'stat', ret, err
            if err:
                raise Exception(err)
            audit_str = 'Reloaded system configuration after hardware scan'
            audit.audit('update_manifest', audit_str, request)
            return django.http.HttpResponseRedirect(
                "/system/view_system_info/")
    except Exception, e:
        return_dict['base_template'] = "system_base.html"
        return_dict["page_title"] = 'Reload system configuration'
        return_dict['tab'] = 'system_info_tab'
        return_dict["error"] = 'Error reloading 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 create_event_notification(schedule, event_type_id, event_subtype_id, subsystem_type_id, notification_type_id, severity_type_id, enc_id, reference_table_entries=None):
    """Create an event notification. This involves creating a trigger entry and a cron entry

    """
    audit_str = None
    try:
        psp, err = config.get_python_scripts_path()
        if err:
            raise Exception(err)
        ent_id, err = create_event_notification_trigger(
            event_type_id, event_subtype_id, subsystem_type_id, notification_type_id, severity_type_id, enc_id, -1)
        if err:
            raise Exception(err)
        if event_type_id == 1:
            cmd = 'python %s/process_alert_notifications.py %d' % (
                psp, int(ent_id))
        elif event_type_id == 2:
            cmd = 'python %s/process_audit_notifications.py %d' % (
                psp, int(ent_id))
        elif event_type_id == 3:
            cmd = 'python %s/process_report_notifications.py %d' % (
                psp, int(ent_id))
        description, err = stringify_event_notification(
            event_type_id, notification_type_id, subsystem_type_id, severity_type_id, event_subtype_id, reference_table_entries=reference_table_entries)
        if err:
            delete_event_notification_trigger(ent_id)
            raise Exception(err)
        cron_task_id, err = scheduler_utils.create_cron_task(
            cmd, description, schedule[0], schedule[1], schedule[2], schedule[3], schedule[4], task_type_id=5)
        if err:
            delete_event_notification_trigger(ent_id)
            raise Exception(err)

        ret, err = update_event_notification_trigger_cron_id(
            ent_id, cron_task_id)
        if err:
            delete_event_notification_trigger(ent_id)
            scheduler_utils.delete_cron(cron_task_id)
            raise Exception(err)

        cron_task_list, err = scheduler_utils.get_cron_tasks(cron_task_id)
        if err:
            audit_str = 'Created event notification : %s. Scheduled for <Error while retrieving schedule>' % description
        else:
            audit_str = 'Created event notification : %s. Scheduled for %s' % (
                description, cron_task_list[0]['schedule_description'])
    except Exception, e:
        return None, 'Error creating event notification : %s' % str(e)
def update_manifest(request):
    return_dict = {}
    try:
        if request.method == "GET":
            from integralstor import manifest_status as iu
            mi, err = iu.generate_manifest_info(rescan_for_disks=True)
            # print mi, err
            if err:
                raise Exception(err)
            if not mi:
                raise Exception('Could not load new configuration')
            return_dict["mi"] = mi  # Need the hostname here.
            return django.shortcuts.render_to_response("update_manifest.html", return_dict, context_instance=django.template.context.RequestContext(request))
        elif request.method == "POST":
            python_scripts_path, err = config.get_python_scripts_path()
            if err:
                raise Exception(err)
            ss_path, err = config.get_system_status_path()
            if err:
                raise Exception(err)
            #(ret,rc), err = command.execute_with_rc("python %s/generate_manifest.py %s"%(python_scripts_path, ss_path))
            ret, err = command.get_command_output(
                "python %s/generate_manifest.py %s" % (python_scripts_path, ss_path))
            # print 'mani', ret, err
            if err:
                raise Exception(err)
            #(ret,rc), err = command.execute_with_rc("python %s/generate_status.py %s"%(config.get_python_scripts_path(),config.get_system_status_path()))
            ret, err = command.get_command_output(
                "python %s/generate_status.py %s" % (python_scripts_path, ss_path))
            # print 'stat', ret, err
            if err:
                raise Exception(err)
            audit_str = 'Reloaded system configuration after hardware scan'
            audit.audit('update_manifest',
                        audit_str, request)
            return django.http.HttpResponseRedirect("/system/view_system_info/")
    except Exception, e:
        return_dict['base_template'] = "system_base.html"
        return_dict["page_title"] = 'Reload system configuration'
        return_dict['tab'] = 'system_info_tab'
        return_dict["error"] = 'Error reloading 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))
Beispiel #5
0
def create_scheduled_notification(request):
    return_dict = {}
    try:
        req_params, err = django_utils.get_request_parameter_values(
            request, ['event_type_id', 'scheduler'])
        if err:
            raise Exception(err)

        reference_table_entries, err = event_notifications.get_reference_table_entries(
            [
                'reference_event_types', 'reference_event_subtypes',
                'reference_notification_types', 'reference_severity_types',
                'reference_subsystem_types'
            ])
        if err:
            raise Exception(err)
        if 'event_type_id' not in req_params or int(
                req_params['event_type_id']
        ) not in reference_table_entries['reference_event_types'].keys():
            raise Exception('Invalid request. Please use the menus.')
        return_dict['event_type_id'] = req_params['event_type_id']
        event_type_id = int(req_params['event_type_id'])
        if request.method == "GET":
            if event_type_id == 1:
                form = monitoring_forms.AlertNotificationsForm(
                    reference_subsystem_types=reference_table_entries[
                        'reference_subsystem_types'],
                    reference_severity_types=reference_table_entries[
                        'reference_severity_types'],
                    reference_notification_types=reference_table_entries[
                        'reference_notification_types'])
                template = 'create_alert_notification.html'
            elif event_type_id == 2:
                form = monitoring_forms.AuditNotificationsForm(
                    reference_notification_types=reference_table_entries[
                        'reference_notification_types'])
                template = 'create_audit_notification.html'
            elif event_type_id == 3:
                form = monitoring_forms.LogNotificationsForm(
                    reference_notification_types=reference_table_entries[
                        'reference_notification_types'],
                    reference_event_subtypes=reference_table_entries[
                        'reference_event_subtypes'])
                template = 'create_report_notification.html'
            return_dict['form'] = form
            return django.shortcuts.render_to_response(
                template,
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))

        elif request.method == "POST":
            scheduler = req_params['scheduler']
            schedule = scheduler.split()
            if event_type_id == 1:
                form = monitoring_forms.AlertNotificationsForm(
                    request.POST,
                    reference_subsystem_types=reference_table_entries[
                        'reference_subsystem_types'],
                    reference_severity_types=reference_table_entries[
                        'reference_severity_types'],
                    reference_notification_types=reference_table_entries[
                        'reference_notification_types'])
                template = 'create_alert_notification.html'
            elif event_type_id == 2:
                form = monitoring_forms.AuditNotificationsForm(
                    request.POST,
                    reference_notification_types=reference_table_entries[
                        'reference_notification_types'])
                template = 'create_audit_notification.html'
            elif event_type_id == 3:
                form = monitoring_forms.LogNotificationsForm(
                    request.POST,
                    reference_notification_types=reference_table_entries[
                        'reference_notification_types'],
                    reference_event_subtypes=reference_table_entries[
                        'reference_event_subtypes'])
                template = 'create_report_notification.html'
            return_dict['form'] = form
            if not form.is_valid():
                return django.shortcuts.render_to_response(
                    template,
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
            cd = form.cleaned_data

            psp, err = config.get_python_scripts_path()
            if err:
                raise Exception(err)
            if 'subsystem_type_id' in cd:
                subsystem_type_id = int(cd['subsystem_type_id'])
            else:
                subsystem_type_id = -1
            if 'event_subtype_id' in cd:
                event_subtype_id = int(cd['event_subtype_id'])
            else:
                event_subtype_id = -1
            if 'severity_type_id' in cd:
                severity_type_id = int(cd['severity_type_id'])
            else:
                severity_type_id = -1
            if int(cd['notification_type_id']) == 1:
                enc_id, err = mail.create_event_notification_configuration(
                    cd['recipient_list'])
                if err:
                    raise Exception(err)
            audit_str, err = event_notifications.create_event_notification(
                schedule,
                event_type_id,
                event_subtype_id,
                subsystem_type_id,
                int(cd['notification_type_id']),
                severity_type_id,
                enc_id,
                reference_table_entries=reference_table_entries)
            if err:
                if int(cd['notification_type_id']) == 1:
                    mail.delete_event_notification_configuration(enc_id)
                raise Exception(err)

            if int(cd['notification_type_id']) == 1:
                audit_str += " Emails will be sent to %s" % cd['recipient_list']

            if event_type_id == 1:
                audit.audit("create_alert_notification", audit_str, request)
            elif event_type_id == 2:
                audit.audit("create_audit_notification", audit_str, request)
            elif event_type_id == 3:
                audit.audit("create_report_notification", audit_str, request)

            return django.http.HttpResponseRedirect(
                '/view_scheduled_notifications?ack=created')
    except Exception, e:
        return_dict["page_title"] = 'Crete scheduled notification'
        return_dict['tab'] = 'scheduled_notifications_tab'
        return_dict["error"] = 'Error creating scheduled notification'
        return_dict['base_template'] = "logging_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 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))
def create_scheduled_notification(request):
    return_dict = {}
    try:
        req_params, err = django_utils.get_request_parameter_values(request, [
            'event_type_id', 'scheduler'])
        if err:
            raise Exception(err)

        reference_table_entries, err = event_notifications.get_reference_table_entries(
            ['reference_event_types', 'reference_event_subtypes', 'reference_notification_types', 'reference_severity_types', 'reference_subsystem_types'])
        if err:
            raise Exception(err)
        if 'event_type_id' not in req_params or int(req_params['event_type_id']) not in reference_table_entries['reference_event_types'].keys():
            raise Exception('Invalid request. Please use the menus.')
        return_dict['event_type_id'] = req_params['event_type_id']
        event_type_id = int(req_params['event_type_id'])
        if request.method == "GET":
            if event_type_id == 1:
                form = system_forms.AlertNotificationsForm(reference_subsystem_types=reference_table_entries['reference_subsystem_types'], reference_severity_types=reference_table_entries[
                                                               'reference_severity_types'], reference_notification_types=reference_table_entries['reference_notification_types'])
                template = 'create_alert_notification.html'
            elif event_type_id == 2:
                form = system_forms.AuditNotificationsForm(
                    reference_notification_types=reference_table_entries['reference_notification_types'])
                template = 'create_audit_notification.html'
            elif event_type_id == 3:
                form = system_forms.LogNotificationsForm(
                    reference_notification_types=reference_table_entries['reference_notification_types'], reference_event_subtypes=reference_table_entries['reference_event_subtypes'])
                template = 'create_report_notification.html'
            return_dict['form'] = form
            return django.shortcuts.render_to_response(template, return_dict, context_instance=django.template.context.RequestContext(request))

        elif request.method == "POST":
            scheduler = req_params['scheduler']
            schedule = scheduler.split()
            if event_type_id == 1:
                form = system_forms.AlertNotificationsForm(request.POST, reference_subsystem_types=reference_table_entries['reference_subsystem_types'], reference_severity_types=reference_table_entries[
                                                               'reference_severity_types'], reference_notification_types=reference_table_entries['reference_notification_types'])
                template = 'create_alert_notification.html'
            elif event_type_id == 2:
                form = system_forms.AuditNotificationsForm(
                    request.POST, reference_notification_types=reference_table_entries['reference_notification_types'])
                template = 'create_audit_notification.html'
            elif event_type_id == 3:
                form = system_forms.LogNotificationsForm(request.POST, reference_notification_types=reference_table_entries[
                                                             'reference_notification_types'], reference_event_subtypes=reference_table_entries['reference_event_subtypes'])
                template = 'create_report_notification.html'
            return_dict['form'] = form
            if not form.is_valid():
                return django.shortcuts.render_to_response(template, return_dict, context_instance=django.template.context.RequestContext(request))
            cd = form.cleaned_data

            psp, err = config.get_python_scripts_path()
            if err:
                raise Exception(err)
            if 'subsystem_type_id' in cd:
                subsystem_type_id = int(cd['subsystem_type_id'])
            else:
                subsystem_type_id = -1
            if 'event_subtype_id' in cd:
                event_subtype_id = int(cd['event_subtype_id'])
            else:
                event_subtype_id = -1
            if 'severity_type_id' in cd:
                severity_type_id = int(cd['severity_type_id'])
            else:
                severity_type_id = -1
            if int(cd['notification_type_id']) == 1:
                enc_id, err = mail.create_event_notification_configuration(
                    cd['recipient_list'])
                if err:
                    raise Exception(err)
            audit_str, err = event_notifications.create_event_notification(schedule, event_type_id, event_subtype_id, subsystem_type_id, int(
                cd['notification_type_id']), severity_type_id, enc_id, reference_table_entries=reference_table_entries)
            if err:
                if int(cd['notification_type_id']) == 1:
                    mail.delete_event_notification_configuration(enc_id)
                raise Exception(err)

            if int(cd['notification_type_id']) == 1:
                audit_str += " Emails will be sent to %s" % cd['recipient_list']

            if event_type_id == 1:
                audit.audit("create_alert_notification", audit_str, request)
            elif event_type_id == 2:
                audit.audit("create_audit_notification", audit_str, request)
            elif event_type_id == 3:
                audit.audit("create_report_notification", audit_str, request)

            return django.http.HttpResponseRedirect('/system/view_scheduled_notifications?ack=created')
    except Exception, e:
        return_dict["page_title"] = 'Crete scheduled notification'
        return_dict['tab'] = 'scheduled_notifications_tab'
        return_dict["error"] = 'Error creating scheduled notification'
        return_dict['base_template'] = "system_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 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))
def remove_bond():
    try:
        os.system('clear')
        interfaces, err = networking.get_interfaces()
        if err:
            raise Exception(
                'Error retrieving interface information : %s' % err)
        if not interfaces:
            raise Exception('No interfaces detected')

        print
        print
        print 'IntegralSTOR NIC Bonding'
        print '---------------------------------'
        print
        print
        print 'Active bond(s): \n'

        bm, err = networking.get_bonding_masters()
        if err:
            raise Exception(err)
        bid, err = networking.get_bonding_info_all()
        if err:
            raise Exception(err)

        avail_if = []
        for if_name, iface in interfaces.items():
            if if_name in bm:
                print '\t- %s' % if_name
                avail_if.append(if_name)
        print "\n"
        if not avail_if:
            raise Exception('There is nothing to remove!')

        bond_name = None
        is_name = False
        while is_name is False:
            bond_name = raw_input('To remove a bond, provide its name: ')
            if bond_name not in avail_if:
                print "\t- Can't remove %s, no such bond exists. Please provide another one.\n" % bond_name
            else:
                is_name = True

        ret, err = networking.delete_bond(bond_name)
        if not ret:
            if err:
                raise Exception('Error removing bond: %s' % err)
            else:
                raise Exception("Couldn't remove bond")
        if ret:
            print "\n\tBond removed!\n"

        print
        print 'Regenerating manifest and status.'
        python_scripts_path, err = config.get_python_scripts_path()
        if err:
            raise Exception(err)
        python_scripts_path, err = config.get_python_scripts_path()
        if err:
            raise Exception(err)
        status_path, err = config.get_system_status_path()
        if err:
            raise Exception(err)

        ret, err = command.get_command_output(
            "python %s/generate_manifest.py %s" % (python_scripts_path, status_path))
        if err:
            raise Exception(err)
        ret, err = command.get_command_output(
            "python %s/generate_status.py %s" % (python_scripts_path, status_path))
        if err:
            raise Exception(err)
        print 'Regenerating manifest and status... Done'
        print
    except Exception, e:
        print "Error: %s" % e
        print
        return -1
def update_hostname(request):
    return_dict = {}
    try:

        hostname = socket.gethostname()
        if request.method == "GET":
            hostname, err = networking.get_hostname()
            if err:
                raise Exception(err)
            domain_name, err = networking.get_domain_name()
            if err:
                raise Exception(err)

            initial = {}
            initial['hostname'] = hostname
            initial['domain_name'] = domain_name

            form = networking_forms.EditHostnameForm(initial=initial)
            return_dict['form'] = form
            return django.shortcuts.render_to_response(
                "update_hostname.html",
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            form = networking_forms.EditHostnameForm(request.POST)
            return_dict['form'] = form
            if not form.is_valid():
                return django.shortcuts.render_to_response(
                    "update_hostname.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
            cd = form.cleaned_data
            result_str = ""
            domain_name = None
            if 'domain_name' in cd:
                domain_name = cd['domain_name']
            result, err = networking.update_hostname(cd['hostname'],
                                                     domain_name)
            if not result:
                if err:
                    raise Exception(err)
                else:
                    raise Exception('Error setting hostname')
            result, err = networking.update_domain_name(domain_name)
            if not result:
                if err:
                    raise Exception(err)
                else:
                    raise Exception('Error setting domain name')
            python_scripts_path, err = config.get_python_scripts_path()
            if err:
                raise Exception(err)
            python_scripts_path, err = config.get_python_scripts_path()
            if err:
                raise Exception(err)
            ss_path, err = config.get_system_status_path()
            if err:
                raise Exception(err)

            ret, err = command.get_command_output(
                "python %s/generate_manifest.py %s" %
                (python_scripts_path, ss_path))
            if err:
                raise Exception(err)

            ret, err = command.get_command_output(
                "python %s/generate_status.py %s" %
                (python_scripts_path, ss_path))

            audit_str = "Hostname set to %s." % cd['hostname']
            if 'domain_name' in cd:
                audit_str += 'Domain name set to %s' % cd['domain_name']
            ret, err = audit.audit("edit_hostname", audit_str, request)
            if err:
                raise Exception(err)

            return django.http.HttpResponseRedirect(
                '/view_hostname?result=saved')
    except Exception, e:
        return_dict['base_template'] = "networking_base.html"
        return_dict["page_title"] = 'Modify system hostname'
        return_dict['tab'] = 'view_hostname_tab'
        return_dict["error"] = 'Error modifying system hostname'
        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 create_bond(request):
    return_dict = {}
    try:

        interfaces, err = networking.get_interfaces()
        if err:
            raise Exception(err)
        if not interfaces:
            raise Exception(
                "Error loading network interface information : No interfaces found"
            )

        bm, err = networking.get_bonding_masters()
        if err:
            raise Exception(err)
        bid, err = networking.get_bonding_info_all()
        if err:
            raise Exception(err)

        return_dict['interfaces'] = interfaces
        iface_list = []
        existing_bonds = []
        for if_name, iface in interfaces.items():
            if if_name.startswith('lo') or if_name in bid['by_slave']:
                continue
            if if_name in bm:
                existing_bonds.append(if_name)
                continue
            iface_list.append(if_name)

        return_dict['is_iface_avail'] = False
        if iface_list:
            return_dict['is_iface_avail'] = True

        if request.method == "GET":
            form = networking_forms.CreateBondForm(
                interfaces=iface_list, existing_bonds=existing_bonds)
            return_dict['form'] = form
            return django.shortcuts.render_to_response(
                "create_bond.html",
                return_dict,
                context_instance=django.template.context.RequestContext(
                    request))
        else:
            form = networking_forms.CreateBondForm(
                request.POST,
                interfaces=iface_list,
                existing_bonds=existing_bonds)
            return_dict['form'] = form
            if not form.is_valid():
                return django.shortcuts.render_to_response(
                    "create_bond.html",
                    return_dict,
                    context_instance=django.template.context.RequestContext(
                        request))
            cd = form.cleaned_data
            print cd
            result, err = networking.create_bond(cd['name'], cd['slaves'],
                                                 int(cd['mode']))
            if not result:
                if err:
                    raise Exception(err)
                else:
                    raise Exception('Bond creation failed!')
            python_scripts_path, err = config.get_python_scripts_path()
            if err:
                raise Exception(err)
            python_scripts_path, err = config.get_python_scripts_path()
            if err:
                raise Exception(err)
            status_path, err = config.get_system_status_path()
            if err:
                raise Exception(err)

            ret, err = command.get_command_output(
                "python %s/generate_manifest.py %s" %
                (python_scripts_path, status_path))
            if err:
                raise Exception(err)

            ret, err = command.get_command_output(
                "python %s/generate_status.py %s" %
                (python_scripts_path, status_path))
            if err:
                raise Exception(err)

            audit_str = "Created a network bond named %s with slaves %s" % (
                cd['name'], ','.join(cd['slaves']))
            audit.audit("create_bond", audit_str, request)
            return django.http.HttpResponseRedirect(
                '/view_interfaces?ack=created_bond')
    except Exception, e:
        return_dict['base_template'] = "networking_base.html"
        return_dict["page_title"] = 'Create a network interface bond'
        return_dict['tab'] = 'view_interfaces_tab'
        return_dict["error"] = 'Error creating a network interface bond'
        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))