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

# Sets on_slow_op sysctl's and collects PCData when we trigger them
# This tool is designed for performance debugging and testing

import argparse
import os
import platform
import subprocess
import sys
import time

SYSLOG_ENTRY = "kern.err                                       | exec isi_ph_filter \n"
SYSLOG_FILE = "/etc/mcp/override/syslog.conf"
SYSCTL_WAIT = 1

def singleton(cls):

    instances = {}

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

    return getinstance


@singleton
class Syslog:

    def disable(self):
        mcp = open(SYSLOG_FILE, "r+")
        mcp_lines = mcp.readlines()
        mcp.seek(0)
        for line in mcp_lines:
            if line != SYSLOG_ENTRY:
                mcp.write(line)
        mcp.truncate()
        mcp.close()

    def enable(self):
        if not Syslog().status():
            with open(SYSLOG_FILE, "a") as mcp:
                mcp.write(SYSLOG_ENTRY)

    def status(self):
        if os.path.isfile(SYSLOG_FILE):
            with open(SYSLOG_FILE, "r") as mcp:
                for line in mcp:
                    if SYSLOG_ENTRY in line:
                        return True
        else:
            pass
        return False


@singleton
class Sysctls:

    def disable(self):
        output, error = subprocess.Popen(
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.create_threshold=0"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.lookup_threshold=0"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.remove_threshold=0"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.getattr_threshold=0"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.setattr_threshold=0"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.action="],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.holdoff=1000000"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        if error:
            return False
        else:
            time.sleep(SYSCTL_WAIT)
            return True

    def enable(self):

        output, error = subprocess.Popen(
            # Creates taking longer than 400 milliseconds
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.create_threshold=400000"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            # Lookups taking longer than 400 milliseconds
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.lookup_threshold=400000"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            # Removes taking longer than 400 milliseconds
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.remove_threshold=400000"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            # Getattr's taking longer than 400 milliseconds
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.getattr_threshold=400000"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            # Setattr's taking longer than 400 milliseconds
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.setattr_threshold=400000"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.action=syslog"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        output, error = subprocess.Popen(
            # 15 minutes before the next event
            ["isi_sysctl_cluster", "isi.stats.protocol.nfs.on_slow_op.holdoff=600000000"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        if error:
            return False
        else:
            time.sleep(SYSCTL_WAIT)
            return True


@singleton
class Service:

    def disable(self):
        Sysctls().disable()
        Syslog().disable()

    def enable(self):
        Syslog().enable()
        Sysctls().enable()

    def status(self):
        if Syslog().status():
            return "isi_ph_trace service is currently:\033[1m Enabled \033[0m"
        else:
            return "isi_ph_trace service is currently:\033[1m Disabled \033[0m"


def main():

    argparser = argparse.ArgumentParser(
        prog='isi_ph_trace',
        formatter_class=argparse.RawTextHelpFormatter,
        usage='isi_ph_trace [-h] [-d] [-e] \n\n' + Service().status(),
        description='''
isi_ph_trace when enabled sets slow operation triggers that when hit dump PCData for low level performance analysis.
This tool is for debugging and performance analysis, long term use is supported.
        ''',
        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_trace service")

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

    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 __name__ == '__main__':
    main()
