text: ##########################################################################
  # If not stated otherwise in this file or this component's Licenses.txt
  # file the following copyright and licenses apply:
  #
  # Copyright 2019 RDK Management
  #
  # Licensed under the Apache License, Version 2.0 (the "License");
  # you may not use this file except in compliance with the License.
  # You may obtain a copy of the License at
  #
  # http://www.apache.org/licenses/LICENSE-2.0
  #
  # Unless required by applicable law or agreed to in writing, software
  # distributed under the License is distributed on an "AS IS" BASIS,
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  # See the License for the specific language governing permissions and
  # limitations under the License.
  ##########################################################################
  '''
  <?xml version="1.0" encoding="UTF-8"?>
  <xml>
    <id/>
    <version>29</version>
    <name>TS_SANITY_CheckCPUUtilization</name>
    <primitive_test_id/>
    <primitive_test_name>ExecuteCmd</primitive_test_name>
    <primitive_test_version>1</primitive_test_version>
    <status>FREE</status>
    <synopsis>Execute top command in rdkb device and ensure no process should consistently occupy high CPU percentage.</synopsis>
    <groups_id/>
    <execution_time>15</execution_time>
    <long_duration>false</long_duration>
    <advanced_script>false</advanced_script>
    <remarks/>
    <skip>false</skip>
    <box_types>
      <box_type>Broadband</box_type>
      <box_type>Emulator</box_type>
      <box_type>RPI</box_type>
    </box_types>
    <rdk_versions>
      <rdk_version>RDKB</rdk_version>
    </rdk_versions>
    <test_cases>
      <test_case_id>TC_SYSUTIL_18</test_case_id>
      <test_objective>Execute top command in RDKB device and ensure no process is consistently occupying high CPU percentage.</test_objective>
      <test_type>Positive</test_type>
      <test_setup>Broadband,Emulator,RPI.</test_setup>
      <pre_requisite>TDK Agent should be in running state or invoke it through StartTdk.sh script</pre_requisite>
      <api_or_interface_used>ExecuteCmd()</api_or_interface_used>
      <input_parameters>For getCpuUtilPath-  sh %s/tdk_utility.sh parseConfigFile CPU_UTIL_FILEPATH " %TDK_PATH
  
  For GetCpuProcess% - top -n 1 | awk 'NR &gt;4 {print  $7,$8}' &gt; %s</input_parameters>
      <automation_approch>1.Function which needs to be tested will be configured in Test Manager GUI.
  2.Python Script will be generated by Test Manager with provided arguments in configure page.
  3.TM will load the sysutil library via Test agent
  4.From python script, invoke ExecuteCmd() stub function.
  5.With ExecuteCmd() get the cpu util path as output.
  6.With next ExecuteCmd() check output of top command and write to file at CPU_UTIL_FILEPATH.
  7.Check whether each process's cpu utilization crosses threshold or not.
  8.Responses from the sysutil stub function will be logged in Agent Console log.
  9.script will validate the actual result with the expected result and send the result status to Test Manager.
  10.Test Manager will publish the result in GUI as PASS/FAILURE based on the response from stub.</automation_approch>
      <except_output>CheckPoint 1:
   The output  should be logged in the Agent console/Component log
  
  CheckPoint 2:
  Stub function result should be success and should see corresponding log in the agent console log
  
  CheckPoint 3:
  TestManager GUI will publish the result as SUCCESS if the CPU usage of all processes are under threshold value.</except_output>
      <priority>High</priority>
      <test_stub_interface>sysutil</test_stub_interface>
      <test_script>TS_SANITY_CheckCPUUtilization</test_script>
      <skipped>No</skipped>
      <release_version>M64</release_version>
      <remarks>LAN</remarks>
    </test_cases>
    <script_tags/>
  </xml>
  
  '''
  # use tdklib library,which provides a wrapper for tdk testcase script
  import tdklib;
  from tdkbVariables import *;
  
  #Test component to be tested
  obj = tdklib.TDKScriptingLibrary("sysutil","1");
  
  #IP and Port of box, No need to change,
  #This will be replaced with correspoing Box Ip and port while executing script
  ip = <ipaddress>
  port = <port>
  obj.configureTestCase(ip,port,'TS_SANITY_CheckCPUUtilization');
  
  #Get the result of connection with test component and STB
  loadmodulestatus =obj.getLoadModuleResult();
  
  if "SUCCESS" in loadmodulestatus.upper():
      #Set the result status of execution
      obj.setLoadModuleStatus("SUCCESS");
      #Prmitive test case which associated to this Script
      tdkTestObj = obj.createTestStep('ExecuteCmd');
      cmd_path = "sh %s/tdk_utility.sh parseConfigFile CPU_UTIL_FILEPATH " %TDK_PATH;
      expectedresult="SUCCESS";
      tdkTestObj.addParameter("command", cmd_path);
      tdkTestObj.executeTestCase(expectedresult);
      actualresult = tdkTestObj.getResult();
      cpupathdetails = tdkTestObj.getResultDetails().strip();
      cpupathdetails = cpupathdetails.replace("\\n", "");
      if expectedresult in actualresult:
          tdkTestObj.setResultStatus("SUCCESS");
          print "TEST STEP 1: Get the cpu utilization file path ";
          print "EXPECTED RESULT 1: Should get the cpu utilization file path";
          print "ACTUAL RESULT 1: Obtained  cpu utilization file path as %s" %cpupathdetails ;
          #Get the result of execution
          print "[TEST EXECUTION RESULT] : SUCCESS";
          cmd = "top -n 1 | awk 'NR >4 {print  $7,$8}' > %s" %cpupathdetails;
      	expectedresult="SUCCESS";
      	tdkTestObj.addParameter("command", cmd);
  	tdkTestObj.executeTestCase(expectedresult);
          actualresult = tdkTestObj.getResult();
          cpupercentagedetails = tdkTestObj.getResultDetails().strip();
          if expectedresult in actualresult:
              tdkTestObj.setResultStatus("SUCCESS");
              print "TEST STEP 2: Get the list of processes with their respective cpu percentage ";
              print "EXPECTED RESULT 2: Should get the list of processes with their respective cpu percentage";
              print "ACTUAL RESULT 2: Obtained all the processes and the cpu details of the processes ";
              #Get the result of execution
              print "[TEST EXECUTION RESULT] : SUCCESS";
              #command to convert the lines in file to a single list
  	    filepath = tdkTestObj.transferLogs( cpupathdetails, "false" );
              filelist = open(filepath,'r');
  	    List = filelist.read().replace('%',' ').split()
      	    cpuList = List[0::2];
  	    print "cpu percentage list = %s" %cpuList;
      	    processList = List[1::2];
      	    Threshold = 30;
  	    checkFlag = 1;
      	    for i in xrange(len(cpuList)):
                  if int(cpuList[i]) > Threshold :
  	            #Set the result status of execution
                      tdkTestObj.setResultStatus("FAILURE");
              	    print "TEST STEP 3: Check if cpu percentage is less then threshold"
              	    print "EXPECTED RESULT 3: cpu percentage should be less then threshold";
              	    print "ACTUAL RESULT 3: cpu percentage of the %s process is not less then threshold " %processList[i];
              	    #Get the result of execution
              	    print "[TEST EXECUTION RESULT] : FAILURE";
  		    checkFlag = 0;
  
  	    if checkFlag == 1 :
                  tdkTestObj.setResultStatus("SUCCESS");
                  print "TEST STEP 3: Check if cpu percentage is less then threshold"
                  print "EXPECTED RESULT 3: cpu percentage should be less then threshold";
                  print "ACTUAL RESULT 3: cpu percentage of all the processes is less then threshold ";
                  #Get the result of execution
                  print "[TEST EXECUTION RESULT] : SUCCESS";
  
      	else:
  	    tdkTestObj.setResultStatus("FAILURE");
  	    print "TEST STEP 2: Get the list of processes with their respective cpu percentage ";
  	    print "EXPECTED RESULT 2: Should get the list of processes with their respective cpu percentage";
  	    print "ACTUAL RESULT 2:  Failed to obtained all the processes and the cpu details of the processes";
  	    #Get the result of execution
  	    print "[TEST EXECUTION RESULT] : FAILURE";
      else:
          tdkTestObj.setResultStatus("SUCCESS");
          print "TEST STEP 1: Get the cpu utilization file path";
          print "EXPECTED RESULT 1: Should get the  cpu utilization file path";
          print "ACTUAL RESULT 1: failed to obtained the cpu utilization file path";
          #Get the result of execution
          print "[TEST EXECUTION RESULT] : SUCCESS";
      tdkTestObj.addParameter("command", "rm %s" %cpupathdetails );
      tdkTestObj.executeTestCase(expectedresult);
      actualresult = tdkTestObj.getResult();
      details = tdkTestObj.getResultDetails().strip();
      if expectedresult in actualresult:
      	tdkTestObj.setResultStatus("SUCCESS");
  	print "TEST STEP 4: remove the file used for writing the command output ";
          print "EXPECTED RESULT 4: Should remove the file used for writing the command output";
          print "ACTUAL RESULT 4: removed the file sucessfully ";
          #Get the result of execution
          print "[TEST EXECUTION RESULT] : SUCCESS";
      else :
          print "TEST STEP 4: remove the file used for writing the command output ";
          print "EXPECTED RESULT 4: Should remove the file used for writing the command output";
          print "ACTUAL RESULT 4: failed to remove the file ";
  	#Get the result of execution
          print "[TEST EXECUTION RESULT] : FAILURE";
      obj.unloadModule("sysutil");
  else:
      print "Failed to load sysutil module";
      obj.setLoadModuleStatus("FAILURE");
      print "Module loading failed";
  