Get-NodePerfData – Powershell Script to query NetApp Oncommand Performance Manager (OPM)

<#
script : Get-NodePerfData.ps1
Example:
Get-NodePerfData.ps1

This script queries OPM(version 2.1/7.0) Server and extract following performance counters for each node in clusters
    Date, Time, avgProcessorBusy, cpuBusy, cifsOps, nfsOps, avgLatency

All data is saved in to "thismonth" directory. e.g. 1608 (YYMM)

#>
Function Get-TzDateTime{
   Return (Get-TzDate) + " " + (Get-TzTime)
}
Function Get-TzDate{
   Return Get-Date -uformat "%Y-%m-%d"
}
Function Get-TzTime{
   Return Get-Date -uformat "%H:%M:%S"
}
Function Log-Msg{
   <#
   .SYNOPSIS
   This function appends a message to log file based on the message type.
   .DESCRIPTION
   Appends a message to a log a file.
   .PARAMETER
   Accepts an integer representing the log file extension type
   .PARAMETER
   Accepts a string value containing the message to append to the log file.
   .EXAMPLE
   Log-Msg -logType 0 -message "Command completed succuessfully"
   .EXAMPLE
   Log-Msg -logType 2, -message "Application is not installed"
   #>
   [CmdletBinding()]
   Param(
      [Parameter(Position=0,
         Mandatory=$True,
         ValueFromPipeLine=$True,
         ValueFromPipeLineByPropertyName=$True)]
      [Int]$logType,
      [Parameter(Position=1,
         Mandatory=$True,
         ValueFromPipeLine=$True,
         ValueFromPipeLineByPropertyName=$True)]
      [String]$message
   )
   Switch($logType){
      0 {$extension = "log"; break}
      1 {$extension = "err"; break}
      2 {$extension = "err"; break}
      3 {$extension = "csv"; break}
      default {$extension = "log"}
   }
   If($logType -eq 1){
      $message = ("Error " + $error[0] + " " + $message)
   }
   $prefix = Get-TzDateTime
   ($prefix + "," + $message) | Out-File -filePath `
   ($scriptLogPath + "." + $extension) -encoding ASCII -append
}
function MySQLOPM {
    Param(
      [Parameter(
      Mandatory = $true,
      ParameterSetName = '',
      ValueFromPipeline = $true)]
      [string]$Switch,
      [string]$Query
      )

    if($switch -match 'performance') {
        $MySQLDatabase = 'netapp_performance'
    }
    elseif($switch -match 'model'){
        $MySQLDatabase = 'netapp_model_view'    
    }
    $MySQLAdminUserName = 'report'
    $MySQLAdminPassword = 'password123'
    $MySQLHost = 'opm-server'
    $ConnectionString = "server=" + $MySQLHost + ";port=3306;Integrated Security=False;uid=" + $MySQLAdminUserName + ";pwd=" + $MySQLAdminPassword + ";database="+$MySQLDatabase

    Try {
      [void][System.Reflection.Assembly]::LoadFrom("E:\ssh\L080898\MySql.Data.dll")
      $Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
      $Connection.ConnectionString = $ConnectionString
      $Connection.Open()

      $Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
      $DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
      $DataSet = New-Object System.Data.DataSet
      $RecordCount = $dataAdapter.Fill($dataSet, "data")
      $DataSet.Tables[0]
      }

    Catch {
      Write-Host "ERROR : Unable to run query : $query `n$Error[0]"
     }

    Finally {
      $Connection.Close()
    }
}
#'------------------------------------------------------------------------------
#'Initialization Section. Define Global Variables.
#'------------------------------------------------------------------------------
##'Set Date and Time Variables
[String]$lastmonth      = (Get-Date).AddMonths(-1).ToString('yyMM')
[String]$thismonth      = (Get-Date).ToString('yyMM')
[String]$yesterday      = (Get-Date).AddDays(-1).ToString('yyMMdd')
[String]$today          = (Get-Date).ToString('yyMMdd')
[String]$fileTime       = (Get-Date).ToString('HHmm')
[String]$workDay        = (Get-Date).AddDays(-1).DayOfWeek
[String]$DOM            = (Get-Date).ToString('dd')
[String]$filedate       = (Get-Date).ToString('yyyyMMdd')
##'Set Path Variables
[String]$scriptPath     = Split-Path($MyInvocation.MyCommand.Path)
[String]$scriptSpec     = $MyInvocation.MyCommand.Definition
[String]$scriptBaseName = (Get-Item $scriptSpec).BaseName
[String]$scriptName     = (Get-Item $scriptSpec).Name
[String]$scriptLogPath  = $scriptPath + "\Logs\" + (Get-TzDate) + "-" + $scriptBaseName
[System.Object]$fso     = New-Object -ComObject "Scripting.FileSystemObject"
[String]$outputPath     = $scriptPath + "\Reports\" + $thismonth
[string]$logPath        = $scriptPath+ "\Logs"

# MySQL Query to get objectid, name of all nodes
$nodes = MySQLOPM -Switch model -Query "select objid,name from node"

# Create hash of nodename and objid
$hash =@{}

foreach ($line in $nodes) {
    $hash.add($line.name, $line.objid)
}
# Create Log Directory
if ( -not (Test-Path $logPath) ) { 
       Try{
          New-Item -Type directory -Path $logPath -ErrorAction Stop | Out-Null
          Log-Msg 0 "Created Folder ""logPath"""
       }
       Catch{
          Log-Msg 0 "Failed creating folder ""$logPath"" . Error " + $_.Exception.Message
          Exit -1;
       }
    }

# Check hash is not empty, then query OPM server to extract counters
if ($hash.count -gt 0) {

    # If Report directory does not exist then create
    if ( -not (Test-Path $outputPath) ) { 
       Try{
          New-Item -Type directory -Path $outputPath -ErrorAction Stop | Out-Null
          Log-Msg 0 "Created Folder ""$outputPath"""
       }
       Catch{
          Log-Msg 0 "Failed creating folder ""$outputPath"" . Error " + $_.Exception.Message
          Exit -1;
       }
    }
    # foreach node
    foreach ($h in $hash.GetEnumerator()) {
    
        $nodeperffilename  = "$($h.name)`_$filedate.csv"
        $nodePerfFile = Join-Path $outputPath $nodeperffilename

        # MySQL Query to query each object and save data to lastmonth directory
        MySQLOPM -Switch performance -Query "select objid,Date_Format(FROM_UNIXTIME(time/1000), '%Y:%m:%d') AS Date ,Date_Format(FROM_UNIXTIME(time/1000), '%H:%i') AS Time, round(avgProcessorBusy,1) AS cpuBusy,round(cifsOps,1) AS cifsOps,round(nfsOps,1) AS nfsOps,round((avgLatency/1000),1) As avgLatency from sample_node where objid=$($h.value)" | Export-Csv -Path $nodePerfFile -NoTypeInformation
        Log-Msg 0 "Exported Performance Logs for $($h.name)"
    }
} 

Leave a Reply

Your email address will not be published. Required fields are marked *