#!/usr/bin/env python

# Copyright (C) 2014
# EMC Corporation.  All rights reserved.

# Runs a full dd read against each bootdisk if both disks show as 'COMPLETE'
# in gmirror status output and have the expected partitions in the mirror.
# Will stop if it hits an error during the dd read testing. Only one drive
# can be marked bad at a time.

import sys
import syslog

import isi.app.lib.procs as procs
import isi.hw.hal as hal
import isi.hw.version as hwver
import isi.sys.bootdisk as bootdisk

# Skip list for nodes with geom and boot HDDs. We don't want to run the test on
# these nodes
SKIP = [hwver.CHASSIS_EMC8BAY]

def main():
    if bootdisk.current_system_is_geom():
        run_test = True
        # Check to see if we can run the bootdisk read tests
        try:
            bootdisk.verify_mirrors()
        except bootdisk.BootdiskMirrorException:
            run_test = False

        if hal.getChassisType(0) in SKIP:
            sys.exit(0)

        # Run the read tests, break out at the first failure
        syslog.openlog('isi_bootdisk_read_test', 0, syslog.LOG_USER)
        if run_test:
            bootdisk_names = hal.getEligibleBootdiskDeviceNames()
            for disk in bootdisk_names:
                cmd = 'dd if=/dev/%s of=/dev/null bs=64k' % disk
                (err, out) = procs.get_cmd_output(cmd)
                if err:
                    err_msg = ('Halting bootdisk read test due to error on %s.'
                            % disk)
                    sys.stdout.write(err_msg + '\n')
                    syslog.syslog(syslog.LOG_ERR, err_msg)
                    break
                else:
                    finish_msg = 'Bootdisk read test complete on %s.' % disk
                    sys.stdout.write(finish_msg + '\n')
                    syslog.syslog(syslog.LOG_INFO, finish_msg)
        else:
            # Print a statement saying we have bad bootdisk mirror
            mirror_msg = 'Bootdisk read test not run, check gmirror status.'
            sys.stdout.write(mirror_msg + '\n')
            syslog.syslog(syslog.LOG_ERR, mirror_msg)

if __name__ == "__main__":
    main()
