#===============================================================#
#                                                               #
# ID                                                            #
#                                                               #
# perf_cpu_util.py                                              #
#                                                               #
# Copyright (c) 2011 NetApp, Inc. All rights reserved.          #
# Specifications subject to change without notice.              #
#                                                               #
# This Sample code is supported from DataFabric Manager 3.7.1   #
# onwards.                                                      #
# However few of the functionalities of the sample code may     #
# work on older versions of DataFabric Manager.                 #
#===============================================================#

import time
import sys
sys.path.append("../../../../../../../lib/python/NetApp")
from NaServer import *


def print_help() :
    print ("\nCommand:\n")
    print ("perf_cpu_util.py <dfm> <user> <password> <storage-system>\n")
    print ("<dfm>            -- DFM Server name\n")
    print ("<user>           -- User name\n")
    print ("<password>       -- Password\n")
    print ("<storage-system> -- Storage system\n")
    print ("-" * 80 + "\n")

    print ("This sample code prints CPU utilization statistics of a storage \n")
    print ("system. The sample code collects CPU utilization data for 2 weeks\n")
    print ("and prints the data in a format, which enables comparision of CPU\n")
    print ("utilization in day, hour format for both the weeks\n")
    print ("Output data of this sample code can be used to generate chart.\n")
    print ("To generate the graph, redirect output of this sample code to\n")
    print ("an Excel sheet.\n")
    sys.exit (1)


def per_week_data(server_ctx, start_time, end_time) :
    perf_in = NaElement("perf-get-counter-data")
    perf_in.child_add_string("start-time", start_time)
    perf_in.child_add_string("end-time", end_time)
    perf_in.child_add_string("sample-rate", 3600)
    perf_in.child_add_string("time-consolidation-method", "average")

    instance_info = NaElement("instance-counter-info")
    instance_info.child_add_string("object-name-or-id", storage_system)

    counter_info = NaElement("counter-info")
    perf_obj_ctr = NaElement("perf-object-counter")
    perf_obj_ctr.child_add_string("object-type", "system")
    perf_obj_ctr.child_add_string("counter-name", "avg_processor_busy")

    counter_info.child_add(perf_obj_ctr)
    instance_info.child_add(counter_info)
    perf_in.child_add(instance_info)

    perf_out = server_ctx.invoke_elem(perf_in)
    
    if(perf_out.results_status() == "failed") :
        print(perf_out.results_reason() + "\n")
        sys.exit(2)
    
    return perf_out


def get_time_arr(perf_out) :
    instance = perf_out.child_get("perf-instances")
    instances = instance.children_get()
    time_arr = [] 

    if(instances != None):
        for rec in instances :
            counters = rec.child_get("counters")
            perf_cnt_data = counters.children_get()
        
            for rec1 in perf_cnt_data :
                counter_str = rec1.child_get_string("counter-data")
                counter_arr = counter_str.split (',')
            
                for time_val in counter_arr :
                    time_val_arr = [float(s) for s in time_val.split(':')]
                    time_arr.append(time_val_arr[0])
    return time_arr


def get_data_arr(perf_out):
    i = 0
    instance = perf_out.child_get("perf-instances")
    instances = instance.children_get()
    data_arr = []
 
    if(instances != None):
        for rec in instances :
            counters = rec.child_get("counters")
            perf_cnt_data = counters.children_get()
        
            for rec1 in perf_cnt_data :
                counter_str = rec1.child_get_string("counter-data")
                counter_arr = counter_str.split (',')
             
                for time_val in counter_arr :
                    time_val_arr = [float(s) for s in time_val.split(':')]
                    data_arr.append(time_val_arr[1])

    return data_arr


def print_output(time_arr1, time_arr2, data_arr1, data_arr2) :
    print ("Week1\t\t\t\t\t          Week2\t\n")
    print ("Time\t\t\t\tCPU Busy\tTime\t\t\t\tCPU Busy\n")
    i = 0
    j = 0
    
    while(i < len(time_arr1) and j < len(time_arr2)):
        
        if ((time_arr2[j] - time_arr1[i]) > 608400) :
            print ("%s\t%.3f" %(time.asctime(time.localtime(time_arr1[i])),data_arr1[i]))
            i = i + 1
        
        elif ((time_arr2[j] - time_arr1[i]) < 601200) :
            print ("%s\t%.3f" %(time.asctime(time.localtime(time_arr2[j])),data_arr2[j]))
            j = j + 1
            
        else :
            print ("%s\t%.3f\t\t%s\t%.3f" %(time.asctime(time.localtime(time_arr1[i])),data_arr1[i],time.asctime(time.localtime(time_arr2[j])),data_arr2[j]))
            i = i + 1
            j = j + 1
        
    while(i < len(time_arr1)) :
        print ("%s\t%.3f" %(time.asctime(time.localtime(time_arr1[i])),data_arr1[i]))
        i = i + 1
    
        while(j < len(time_arr2)):
            print ("%s\t%.3f" %(time.asctime(time.localtime(time_arr2[j])),data_arr2[j]))
        j = j + 1
    

def main() :
    # Initialize server context
    server_ctx = NaServer (dfm, 1, 0)
    server_ctx.set_transport_type("HTTP")
    server_ctx.set_style("LOGIN")
    server_ctx.set_admin_user(user, pw)
    server_ctx.set_server_type("DFM")
    server_ctx.set_port(8088)

    # Start time and end time for week1 data collection
    #Start time = current time - (60sec * 60min * 24hrs * 14days)
    starttime1 = time.time() - 1209600
    #end time = current time - (60sec * 60min * 24hrs * 7days)
    endtime1 = time.time() - 604800

    # Start time and end time for week2 data collection
    #Start time = current time - (60sec * 60min * 24hrs * 7days)
    starttime2 = time.time() - 604800
    # end time = current time
    endtime2 = time.time()

    # Collect data for Week1
    perf_out1 = per_week_data(server_ctx, starttime1, endtime1)

    # Collect data for Week2
    perf_out2 = per_week_data(server_ctx, starttime2, endtime2)
    time_arr1 = get_time_arr(perf_out1)
    time_arr2 = get_time_arr(perf_out2)
    data_arr1 = get_data_arr(perf_out1)
    data_arr2 = get_data_arr(perf_out2)
    print_output(time_arr1, time_arr2, data_arr1, data_arr2)
    sys.exit(1)

# check for valid number of parameters
args = len(sys.argv) - 1
if (args < 4)  :
    print_help()

# Command line arguments
dfm = sys.argv[1]
user = sys.argv[2]
pw  = sys.argv[3]
storage_system = sys.argv[4]

#Invoke routine
main()

#=========================== POD ============================#

'''=head1 NAME

  perf_cpu_util.py - Prints CPU utilization statistics. This sample code
  compares CPU utilization statistics of 2 weeks.


=head1 SYNOPSIS

  perf_cpu_util.py <dfm> <user> <password> <storage-system>

=head1 ARGUMENTS

  <dfm>
  DFM Server name.

  <user>
  User name.

  <password>
  Password.

  <storage-system>
  Storage system.

=head1 SEE ALSO

  NaElement.py, NaServer.py

=head1 COPYRIGHT

 Copyright (c) 2009 NetApp, Inc. All rights reserved.
 Specifications subject to change without notice.

=cut'''

