WiP/DumpvRopsMetric.WiP.ps1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 |
#Powershell collector script for vRops Suite-api <# .SYNOPSIS Collecting metric / state data from vROPS Suite-api and output's to CSV, run the script without parameters for instructions. Script requires Powershell v3 and above. Run the command below to store user and pass in secure credential XML for each environment $cred = Get-Credential $cred | Export-Clixml -Path "d:\vRops\config\HOME.xml" #> param ( [String]$vRopsAddress, [String]$CollectionType, [String]$creds, [Array]$ResourceByName, [Array]$Metrics, [String]$rollUpType, [String]$intervalType, [DateTime]$StartDate = (Get-date).adddays(-1), [DateTime]$EndDate = (Get-date), [String]$Format ) #Get Stored Credentials $ScriptPath = (Get-Item -Path ".\" -Verbose).FullName if($creds -gt ""){ $cred = Import-Clixml -Path "$ScriptPath\config\$creds.xml" $vRopsUser = $cred.GetNetworkCredential().Username $vRopsPassword = $cred.GetNetworkCredential().Password } else { echo "vRops creds missing, stop hammer time!" Exit } #vars $RunDateTime = (Get-date) $RunDateTime = $RunDateTime.tostring("yyyyMMddHHmmss") $Share = '\\localhost\completed\' $Output = $ScriptPath + '\collections\' + $RunDateTime + '\' New-Item $Output -type directory $LogFileLoc = $ScriptPath + '\Log\Logfile.log' $StartDateFile = $StartDate.tostring("yyyyMMdd-HHmmss") $EndDateFile = $EndDate.tostring("yyyyMMdd-HHmmss") #JobControl used to limit how hard the machine's CPU and memory is used. $maxJobCount = 8 $sleepTimer = 3 #Logging Function Function Log([String]$message, [String]$LogType, [String]$LogFile){ $date = Get-Date -UFormat '%m-%d-%Y %H:%M:%S' $message = $date + "`t" + $LogType + "`t" + $message $message >> $LogFile } #Used to execute a job per element to speed up processing. $scriptBlock = { param ( $Resource, $resourceIdLookupTable, $resourceKindKeyLookupTable, $elementsLookupTable, $rollUpType, $intervalType, $StartDate, $EndDate, $Output ) #Vars $StartDateFile = $StartDate.tostring("yyyyMMdd-HHmmss") $EndDateFile = $EndDate.tostring("yyyyMMdd-HHmmss") $MetricOutput = $Output + 'Collected_Metrics_' + $Resource.'resourceId' + '_' + $intervalType + '_' +[String]$StartDateFile + '_' + [String]$EndDateFile + '.csv' $report = @() #Slow part of the code... need to make it faster #---------------------------------------------- foreach ($node in $Resource.'stat-list'.stat) { #Collection Date, not run time $MetricName = $node.statKey.Key $intervalType = $node.intervalUnit.intervalType $rollUpType = $node.rollUpType $Values = @($node.data -split ' ') $Timestamps = @($node.timestamps -split ' ') for ($i=0; $i -lt $Values.Count -and $i -lt $Timestamps.Count; $i++) { $report += New-Object PSObject -Property @{ METRIC = $MetricName resourceId = $Resource.'resourceId' Timestamp = ([TimeZone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddMilliSeconds([int64]$Timestamps[$i]))).tostring("dd/MM/yyyy HH:mm:ss") intervalType = $intervalType rollUpType = $rollUpType value = $Values[$i] } } } #---------------------------------------------- #Add $resourceId, $resourceKindKey & Friendly Name $report | Sort-Object -Property resourceId | ForEach-Object { $_ | Add-Member -MemberType NoteProperty -Name resourceName -Value $resourceIdLookupTable."$($_.resourceId)" -PassThru } | Export-csv $MetricOutput -NoTypeInformation } switch($CollectionType) { Collection { Log -Message "Collecting $intervalType between $StartDateFile and $EndDateFile, running $maxJobCount job's at a time" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc Log -Message "Data collection for object: $ResourceByName" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc if ($Metrics -gt ""){ Log -Message "Collecting the Metrics: $Metrics" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc } else { #$Metrics = "cpu|usagemhz_average" #Log -Message "No metrics were specified, defaulting to cpu|usagemhz_average" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc #echo "No metrics were specified, defaulting to cpu|usagemhz_average" } #Take all certs. add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy [int64]$StartDateEpoc = Get-Date -Date $StartDate.ToUniversalTime() -UFormat %s $StartDateEpoc = $StartDateEpoc*1000 [int64]$EndDateEpoc = Get-Date -Date $EndDate.ToUniversalTime() -UFormat %s $EndDateEpoc = $EndDateEpoc*1000 #Lookup Name and map to resourceId Table $AlarmTable = @() $ObjectLookupTable = @() Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'Looking stuff up' Log -Message "Looking stuff up" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc ForEach ($ResourceName in $ResourceByName){ #Map name to resourceId for lookup $resourceLookup = GetObject $ResourceName $vRopsAddress $vRopsUser $vRopsPassword If ($resourceLookup[0].resourceId -gt ''){ #Generate String for resourceId URL lookup. $ResourceByNameSearcString += 'resourceId='+$resourceLookup[0].resourceId+'&' $ResourceParentvCenter = $resourceLookup[0].vCenter $ResourceParentCluster = $resourceLookup[0].Cluster $ResourceParentHost = $resourceLookup[0].Host $ResourcePowerState = $resourceLookup[0].State $ResourceMemory = $resourceLookup[0].Memory $ResourceCPU = $resourceLookup[0].CPU $ResourceCPUcores = $resourceLookup[0].CPUcores $ResourceINFO = $resourceLookup[0].INFO ForEach ($alarm in $resourceLookup[1]){ $AlarmTable += New-Object PSObject -Property @{ name = $ResourceName controlState = $alarm.controlState suspendUntilTime = $alarm.suspendUntilTime cancelTime = $alarm.cancelTime updateTime = $alarm.updateTime alertLevel = $alarm.alertLevel alertId = $alarm.alertId alertDefinitionName = $alarm.alertDefinitionName startTime = $alarm.startTime status = $alarm.status } } } else { Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo "I Still cant find $ResourceName, are you looking in the correct environment? does the machine still exist?" Log -Message "I Still cant find $ResourceName, does the machine exist?" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc } $ObjectLookupTable += New-Object PSObject -Property @{ resourceId = $resourceLookup[0].resourceId resourceName = $ResourceName resourceKindKey = $resourceLookup[0].resourceKindKey ParentvCenter = $ResourceParentvCenter ParentCluster = $ResourceParentCluster ParentHost = $ResourceParentHost PowerState = $ResourcePowerState Memory = $ResourceMemory CPU = $ResourceCPU CPUcores = $ResourceCPUcores INFO = $ResourceINFO } } Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'Finished mapping UUID to ResourceID' Log -Message "Finished mapping UUID to ResourceID" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc If ($ResourceByNameSearcString -gt ''){ if ($Metrics -gt ''){ ForEach ($Metric in $Metrics){ $MetricLookupString += '&statKey=' + $Metric } $url = 'https://'+$vRopsAddress+'/suite-api/api/resources/stats?'+ $ResourceByNameSearcString + 'rollUpType='+ $rollUpType + '&intervalType=' + $intervalType + $MetricLookupString + '&begin=' + $StartDateEpoc + '&end=' + $EndDateEpoc } else { $url = 'https://'+$vRopsAddress+'/suite-api/api/resources/stats?'+ $ResourceByNameSearcString + 'rollUpType='+ $rollUpType + '&intervalType=' + $intervalType + '&begin=' + $StartDateEpoc + '&end=' + $EndDateEpoc } $webcall = new-object system.net.WebClient $webcall.Credentials = new-object System.Net.NetworkCredential($vRopsUser, $vRopsPassword) } else { Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'No Machines to look up, terminating script' Log -Message "No Machines to look up, terminating script" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc Exit } Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'Call URL to Download the XML' Log -Message "Call URL to Download the XML" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc #Download data in XML from vRops [xml]$Data = $webcall.DownloadString($url) Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'XML data now stored in Variable' Log -Message "XML data now stored in Variable" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc if($Format -eq 'XML'){ #Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'Data Downloaded to XML file' Log -Message "Data Downloaded to XML file" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc $OutputXMLFile = $ScriptPath + '\completed\Collected_Metrics_' + $intervalType + '_' +[String]$StartDateFile + '_' + [String]$EndDateFile + '_' + $RunDateTime + '.xml' $ShareXMLlFile = $share + 'Collected_Metrics_' + $intervalType + '_' +[String]$StartDateFile + '_' + [String]$EndDateFile + '_' + $RunDateTime + '.xml' $webcall.DownloadFile($url, $OutputXMLFile) Log -Message "Task complete, pickup your file from the completed folder" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc Echo "Task complete, pickup your file from the completed folder" Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'All done, Terminating Script' Log -Message "All done, Terminating Script" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc #Return $OutputXMLFile Remove-Variable * -ErrorAction SilentlyContinue remove-item $Output -Force Exit } Log -Message "Running $url" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc #echo $url #Add Name to resourceID Mapping $ObjectLookupTable | Sort-Object -Property resourceId | ForEach-Object -Begin { $resourceIdLookupTable = @{} } -Process { $resourceIdLookupTable.Add($_.resourceId,$_.resourceName) } $jobQueue = New-Object System.Collections.ArrayList $resources = $Data.'stats-of-resources' $UUIDS = $Resource.'resourceId' Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'Processing the XML into a CSVs' Log -Message "Processing the XML into a CSVs" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc # Create our job queue. # Main loop of the script. # Loop through each VM and start a new job if we have less than $maxJobCount outstanding jobs. # If the $maxJobCount has been reached, sleep 3 seconds and check again. Foreach ($Resource in $Resources.'stats-of-resource'){ # Wait until job queue has a slot available. while ($jobQueue.count -ge $maxJobCount) { echo "jobQueue count is $($jobQueue.count): Waiting for jobs to finish before adding more." foreach ($jobObject in $jobQueue.toArray()) { if ($jobObject.job.state -eq 'Completed') { echo "jobQueue count is $($jobQueue.count): Removing job" $jobQueue.remove($jobObject) } } sleep $sleepTimer } echo "jobQueue count is $($jobQueue.count): Adding new job: $($Resource.'resourceId')" $job = Start-Job -name $Resource.'resourceId' -ScriptBlock $scriptBlock -ArgumentList $Resource, $resourceIdLookupTable, $resourceKindKeyLookupTable, $elementsLookupTable, $rollUpType, $intervalType, $StartDate, $EndDate, $Output $jobObject = "" | select Element, job $jobObject.Element = $Element $jobObject.job = $job $jobQueue.add($jobObject) | Out-Null } Get-Job | Wait-Job | Out-Null Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'Finished Generating the CSVs' Log -Message "Finished Generating the CSVs" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'Start merge of the CSVs into a variable' Log -Message "Start merge of the CSVs into a variable" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc #get all CSV files from this job $Filearr = Get-ChildItem $Output | Where-Object {$_.Name -like '*.csv'} | Foreach-Object { $Output + $_.Name} #Merge all CSV data from this job $OutputMerge = @(); foreach($CSV in $filearr) { if(Test-Path $CSV) { $FileName = [System.IO.Path]::GetFileName($CSV) $temp = Import-CSV -Path $CSV | select * $OutputMerge += $temp } else { Write-Warning "$CSV : No such file found" } } #Delete individual CSVs remove-item $Filearr -Force #Output merge to Excel if($Format -eq 'CSV'){ Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'CSV Merge complete, deleting individual CSVs and saving to single CSV' Log -Message "CSV Merge complete, deleting individual CSVs and saving to single CSV" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc $OutputCSVFile = $ScriptPath + '\completed\Collected_Metrics_' + $intervalType + '_' +[String]$StartDateFile + '_' + [String]$EndDateFile + '_' + $RunDateTime + '.csv' $ShareCSVlFile = $share + 'Collected_Metrics_' + $intervalType + '_' +[String]$StartDateFile + '_' + [String]$EndDateFile + '_' + $RunDateTime + '.csv' $OutputMerge | Sort-Object { $_.Timestamp -as [datetime] } | export-csv $OutputCSVFile -NoTypeInformation Log -Message "Task complete, pickup your file from the completed folder" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc Echo "Task complete, pickup your file from the completed folder" Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'All done, Terminating Script' Log -Message "All done, Terminating Script" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc remove-item $Output -Force Remove-Variable * -ErrorAction SilentlyContinue Exit } #Output merge to Excel if($Format -eq 'XLS'){ Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'CSV Merge complete, deleting individual CSVs and creating Excel file' Log -Message "CSV Merge complete, deleting individual CSVs and creating Excel file" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc $OutputExcelFile = $ScriptPath + '\completed\Collected_Metrics_' + $intervalType + '_' +[String]$StartDateFile + '_' + [String]$EndDateFile + '_' + $RunDateTime + '.xlsx' $ShareExcelFile = $share + 'Collected_Metrics_' + $intervalType + '_' +[String]$StartDateFile + '_' + [String]$EndDateFile + '_' + $RunDateTime + '.xlsx' $OutputMerge | select Timestamp,value,METRIC,resourceName,HOSTNAME | Sort-Object { $_.Timestamp -as [datetime] } | Export-Excel $OutputExcelFile -WorkSheetname Data -ChartType Line -IncludePivotChart -IncludePivotTable -PivotRows Timestamp -PivotData value -PivotColumns resourceName,METRIC $ObjectLookupTable | select resourceName,resourceKindKey,ParentvCenter,ParentCluster,ParentHost,PowerState,Memory,CPU,CPUcores,INFO | Export-Excel $OutputExcelFile -WorkSheetname Config $AlarmTable | Sort-Object { $_.startTime -as [datetime] } | select Name,startTime,updateTimealertLevel,suspendUntilTime,cancelTime,alertId,alertDefinitionName,status,controlState | Export-Excel $OutputExcelFile -WorkSheetname Alarms Log -Message "Task complete, pickup your file from the completed folder" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc Echo "Task complete, pickup your file from the completed folder" Get-Date -UFormat '%m-%d-%Y %H:%M:%S' echo 'All done, Terminating Script' Log -Message "All done, Terminating Script" -LogType "JOB-$RunDateTime" -LogFile $LogFileLoc remove-item $Output -Force Remove-Variable * -ErrorAction SilentlyContinue Exit } remove-item $Output -Force Remove-Variable * -ErrorAction SilentlyContinue } default{"Usage The script can be run by specifying all parameters otherwise it will use some default values. -vRopsAddress : IP or DNS name of vRops environment to pull data from. -Creds : HOME is the name of the XML file to pull the credentials from IE: HOME.xml -CollectionType : Collection (this will be used to switch between different types of collections in the future). -ResourceByName : is an array of objects (datastores, hosts, VM's etc...) use the name of the object as it appears in vRops / vCenter. -Metrics : is an array of specific metrics to collect from vRops for the object(s), vRops has 100's of metrics of each object and they can be instance specific so the best way to collect a list is to run a daily collection for 1 day without specifing -Metric and filtering the results in Excel. (Example below) .\DumpvRopsMetric.ps1 -vRopsAddress vRops.vMan.ch -CollectionType Collection -ResourceByName 'WINSRV2','WINSRV4' -Creds HOME -rollUpType AVG -intervalType DAYS -startdate '2016/06/21' -enddate '2016/06/21' -Interval and -rollUpTypes must be specified together. intervalType=HOURS (rollUpType=SUM,AVG,MIN,MAX,LATEST,COUNT) intervalType=MINUTES (rollUpType=SUM,AVG,MIN,MAX,LATEST,COUNT) intervalType=SECONDS intervalType=DAYS (rollUpType=SUM,AVG,MIN,MAX,LATEST,COUNT) intervalType=WEEKS (rollUpType=SUM,AVG,MIN,MAX,LATEST,COUNT) intervalType=MONTHS (rollUpType=SUM,AVG,MIN,MAX,LATEST,COUNT) intervalType=YEARS (rollUpType=SUM,AVG,MIN,MAX,LATEST,COUNT) Run with -Metric, -startdate and -enddate .\DumpvRopsMetric.ps1 -vRopsAddress vRops.vMan.ch -CollectionType Collection -ResourceByName 'WINSRV2','WINSRV4' -Metrics 'cpu|usagemhz_average','cpu|costopPct','cpu|readyPct','cpu|iowaitPct','cpu|idletimepercent','cpu|demandPct' -Creds HOME -rollUpType AVG -intervalType MINUTES -startdate '2016/09/18 19:20' -enddate '2016/09/19 19:20' -Format XLS Run without -startdate & -enddate will default to the last 24H .\DumpvRopsMetric.ps1 -vRopsAddress vRops.vMan.ch -CollectionType Collection -ResourceByName 'WINSRV2','WINSRV4' -Metrics 'cpu|usagemhz_average','mem|usage_average','cpu|perCpuCoStopPct' -Creds HOME -rollUpType AVG -intervalType HOURS -Format XLS Run without -Metrics and it will pull all metrics and state data .\DumpvRopsMetric.ps1 -vRopsAddress vRops.vMan.ch -CollectionType Collection -ResourceByName 'WINSRV2','WINSRV4' -Creds HOME -rollUpType AVG -intervalType DAYS -startdate '2016/08/04 08:00' -enddate '2016/08/05 10:00' -Format XLS "} } |