#!/usr/bin/env python
# ex: set shiftwidth=4 tabstop=4 expandtab:
#
# Copyright (C) 2016
# EMC Corporation.  All rights reserved.

# Collects Performance Harness data either via a single run or a cron job
# This tool is designed for performance debugging and testing

import argparse
import errno
import fcntl
import os
import platform
import socket
import subprocess
import sys
import time

import isi.config.array as array
import isi.config.mcp as mcp
import isi.app.lib.cluster as cluster
import isi.misc

try:
    import isi.ph.perf as perf
    import isi.ph.util as util
    import isi.ph.perfcollector as perfcollector

except ImportError:
    try:
        # old-style, from ph directory
        import perf as perf
        import util as util
        import perfcollector as perfcollector
    except ImportError:
        print "Either run on a node or from within the ph library directory."
        sys.exit(1)

PC_DIR = "/ifs/pcdata/"
PHLOCK = "/ifs/.ifsvar/isi_ph_dump.lock"
LOCKFILE = PC_DIR + ".ph_dump_lock"
RCPD_WAIT = 10

CRONDATA = "# WARNING: This file was created with the isi_ph_dump service \n" \
           "# and should not be removed manually. To disable please run\n" \
           "# isi_ph_dump -d on the node \n\n" \
           "# Run isi_ph_dump every sixth hour (0,6,12,18) \n\n" \
           "0 0/6 * * * python /usr/bin/isi_ph_dump -r >> " + PC_DIR + "ph_dump.log \n"

CRONFILE = "/var/cron/tabs/root"


def singleton(cls):

    instances = {}

    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]

    return getinstance


@singleton
class CronTab:
    def create(self):
        if not exists(CRONFILE):
            try:
                os.makedirs(os.path.dirname(CRONFILE))
            except OSError, error:
                if error.errno != errno.EEXIST:
                    raise
            with open(CRONFILE, "w") as cronfile:
                cronfile.write(CRONDATA)
            cronfile.close()
            os.chmod(CRONFILE, 0600)

    def remove(self):
        if exists(LOCKFILE):
            if LockFile().node() == platform.node() and exists(CRONFILE):
                try:
                    os.remove(CRONFILE)
                except OSError, error:
                    if error.errno != errno.ENOENT:
                        raise
            else:
                raise OSError
        else:
            pass


@singleton
class LockFile:

    def create(self):
        if not exists(LOCKFILE):
            try:
                os.makedirs(os.path.dirname(LOCKFILE))
            except OSError, error:
                if error.errno != errno.EEXIST:
                    raise
            with open(LOCKFILE, "a") as lockfile:
                lockfile.write(platform.node())

    def node(self):
        if exists(LOCKFILE):
            with open(LOCKFILE, "r") as lockfile:
                return lockfile.read()
        else:
            return "UNKNOWN"

    def remove(self):
        try:
            os.remove(LOCKFILE)
        except OSError, error:
            if error.errno != errno.ENOENT:
                raise


@singleton
class RPCService:

    def disable(self):
        try:
            mcp.mcpconfig().disable('isi_ph_rpcd')
            util.DropRTPrio()
        except:
            return False

        time.sleep(RCPD_WAIT)
        return True

    def enable(self):
        try:
            mcp.mcpconfig().enable('isi_ph_rpcd')
            util.TakeRTPrio()
        except:
            return False

        time.sleep(RCPD_WAIT)
        return True


@singleton
class Service:

    def disable(self):
        try:
            CronTab().remove()
        except OSError:
            print "Warning: isi_ph_dump must be disabled"  \
                   " from the node it was started on: %s" % LockFile().node()
            sys.exit(1)
        LockFile().remove()

    def enable(self):
        if not exists(CRONFILE) and not exists(LOCKFILE):
            LockFile().create()
            CronTab().create()
        else:
            print "isi_ph_dump service is already" \
                   " enabled on node %s" % LockFile().node()

    def run(self, duration, light):

        if isi.misc.sysctlbyname('efs.gmp.is_degraded') != 0:
            print """
            Unable to collect using isi_ph_dump when the cluster is in a degraded state. \n
            Please use isi_ph_pc specifying the IP's of only online nodes. \n\n

            For more information please view the Performance Harness help: \n
            isi_ph_pc --help
            """
            sys.exit(1)

        ph_lock = open(PHLOCK, 'w+')
        try:
            fcntl.flock(ph_lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError:
            print "Unable to take the isi_ph_dump lock (%s)" % PHLOCK
            sys.exit(1)

        directory = PC_DIR + cluster.Cluster().name() \
                    + '-D' + time.strftime('%F-T%H%M')

        if not os.path.exists(directory):
            try:
                os.makedirs(directory)
            except OSError, error:
                print "Failed to make PC data directory: %s" % str(error)
                sys.exit(1)

        nodeOps = array.NodeOps()
        nodeOps.defaultToStorage()

        nodes = [node.internal_a() for node in array.getNodes(nodeOps)]

        if len(nodes) > 10:
            print """
            Unable to collect from a large number of nodes in a single run. \n
            This collection has been reduced to 10 nodes. We recommend collecting \n
            subsets of the cluster based upon where performance issues are being seen via isi_ph_pc. \n\n

            For more information please view the Performance Harness help: \n
            isi_ph_pc --help
            """
            nodes = nodes[1:10]

        pcs = {}
        RPCService().enable()


        if light:
            mode="light"
        else:
            mode="full"

        for node in nodes:
            try:
                pcs[node] = perfcollector.TestManagerCaller(node, None, mode=mode)
            except socket.error, error:
                print "Unable to start collector on node: %s" % str(node)
                sys.exit(1)

            pcs[node].Start()

        for node in nodes:
            error = pcs[node].WaitStarted()
            if error:
                print "Error on node %s while waiting for performance" \
                      "collectors to start:\n\t%s" % (node, error)
                sys.exit(1)

        error, data = perf.GetPCData(pcs, [], "manual", duration)
        if error:
            print "Error while collecting performance data: %d" % error
            sys.exit(1)

        perf.StorePCDataDir(directory, data)
        RPCService().disable()

        fcntl.flock(ph_lock, fcntl.LOCK_UN)

        print "Finished PC data collection, results in: %s" % directory

    def status(self):
        if exists(LOCKFILE):
            return "isi_ph_dump service is currently:\033[1m Enabled \033[0m"
        else:
            return "isi_ph_dump service is currently:\033[1m Disabled \033[0m"


def exists(filepath):
    return True if os.path.isfile(filepath) else False


def main():

    argparser = argparse.ArgumentParser(
        prog='isi_ph_dump',
        formatter_class=argparse.RawTextHelpFormatter,
        usage='isi_ph_dump [-h] [-r] [-l] [-d] [-e] [-t TIME]\n\n' + Service().status(),
        description='''
isi_ph_dump is a simple interface to collect Performance Harness Data (often called PCData).
A single run will collect one 60 second sample of PCData while enabling the service will
create hourly dumps of PCData until the service is disabled.

This tool is only to be used for debugging and performance analysis, long term use
is neither recommended nor supported.

To collect performance data for an Escalation:
isi_ph_dump -r

Unable to collect using isi_ph_dump when the cluster is in a degraded state.
Please use isi_ph_pc specifying the IP's of only online nodes.
        ''',
        epilog='''
For more information please view the Performance Harness help: \n
isi_ph_pc --help
        '''
    )

    arg_group = argparser.add_mutually_exclusive_group()

    arg_group.add_argument('-d', '--disable',
        action='store_true',
        dest='disable',
        help="Disable the isi_ph_dump service")

    arg_group.add_argument('-e', '--enable',
        action='store_true',
        dest='enable',
        help="Enable the isi_ph_dump service")

    argparser.add_argument('-l', '--light',
        action='store_true',
        dest='light',
        help="Collect a a lightweight set suitable for longer runs")

    argparser.add_argument('-r', '--run',
        action='store_true',
        dest='run',
        help="Run a single collection of PCData")

    argparser.add_argument('-t', '--time',
        default=60,
        metavar='<seconds>',
        type=int,
        help="The amount of time the collection should last")

    args = argparser.parse_args()

    if len(sys.argv) <= 1:
        argparser.print_usage()
        sys.exit(1)

    if args.enable:
        Service().enable()
        sys.exit(0)

    if args.disable:
        Service().disable()
        sys.exit(0)

    if args.run or args.time:
        Service().run(args.time, args.light)


if __name__ == '__main__':
    main()
