Ps Irule Dashboard

Problem this snippet solves:

This Powershell application will use iControl and the Google Chart API to build a dashboard to monitor the usage of your iRules.

PowerShell is a very extensible scripting language and the fact that it integrates so nicely with iControl means you can do all sorts of fun things with it. In this tech tip, I'll illustrate how to use just a couple of iControl method calls (3 to be exact) to create an iRule monitoring dashboard for you desktop (with a little help from the Google Chart API).

Code :

#----------------------------------------------------------------------------
# The contents of this file are subject to the "END USER LICENSE AGREEMENT FOR
# F5 Software Development Kit for iControl"; you may not use this file except
# in compliance with the License. The License is included in the iControl
# Software Development Kit.
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is iControl Code and related documentation
# distributed by F5.
#
# The Initial Developer of the Original Code is F5 Networks,
# Inc. Seattle, WA, USA. Portions created by F5 are Copyright (C) 1996-2010 
# F5 Networks, Inc. All Rights Reserved.  iControl (TM) is a registered 
# trademark of F5 Networks, Inc.
#
# Alternatively, the contents of this file may be used under the terms
# of the GNU General Public License (the "GPL"), in which case the
# provisions of GPL are applicable instead of those above.  If you wish
# to allow use of your version of this file only under the terms of the
# GPL and not to allow others to use your version of this file under the
# License, indicate your decision by deleting the provisions above and
# replace them with the notice and other provisions required by the GPL.
# If you do not delete the provisions above, a recipient may use your
# version of this file under either the License or the GPL.
#----------------------------------------------------------------------------
param (
  $BIGIP = $null,
  $User = $null,
  $Pass = $null,
  $VirtualServer = $null,
  $iRule = $null,
  $Metric = "CPUUSAGE",
  $Debug = $false,
  $Interval = 10
);

$script:DEBUG = $Debug;
$script:TITLE = "iRule Monitor";
$script:VIRTUALSERVER = $VirtualServer;
$script:IRULE = $iRule;

$script:THEATER = $false;
$script:CHARTSIZE = "200x75";
$script:INTERVAL = $Interval;
$script:CHARTPREFIX = 0;
$script:CPUSPEED = 1600;

# CYCLES|RUNTIME|CPUUSAGE|ALL
$script:METRIC = $Metric;

$script:BROWSER = $null;

#-------------------------------------------------------------------------
function Write-Usage()
#-------------------------------------------------------------------------
{
  Write-Host "Usage: iRuleMonitor.ps1 host uid pwd";
  exit;
}

#-------------------------------------------------------------------------
function Write-DebugMessage()
#-------------------------------------------------------------------------
{
  param($msg = $null);
  if ( $script:DEBUG -and ($null -ne $msg) )
  {
    Write-Host "DBG> $msg";
  }
}

#-------------------------------------------------------------------------
function Get-VirtualServerList()
#-------------------------------------------------------------------------
{
  $vslist = @();
  if ( $script:VIRTUALSERVER -eq $null )
  {
    $vslist = (Get-F5.iControl).LocalLBVirtualServer.get_list();
  }
  else
  {
    $vslist = (, $script:VIRTUALSERVER);
  }
  return $vslist;
}

#-------------------------------------------------------------------------
function Filter-RuleStatistics()
#-------------------------------------------------------------------------
{
  param($VirtualServerRuleA, $RuleStatistics);

  $RuleStatsForVip = @();
  
  foreach($VirtualServerRule in $VirtualServerRuleA)
  {
    foreach($RuleStatisticEntry in $RuleStatistics.statistics)
    {
      if ( $VirtualServerRule.rule_name -eq $RuleStatisticEntry.rule_name )
      {
        $RuleStatsForVip += @(, $RuleStatisticEntry);
      }
    }
  }
  if ( $RuleStatsForVip.Length -eq 0 ) { $RuleStatsForVip = $null; }

  return $RuleStatsForVip;
}

#-------------------------------------------------------------------------
function Convert-To64Bit()
#-------------------------------------------------------------------------
{
  param($high, $low);
  return ($high*[Math]::Pow(2,32))+$low;
}

#-------------------------------------------------------------------------
function Extract-Statistic()
#-------------------------------------------------------------------------
{
  param($StatisticA, $type);
  $value = -1;
  
  foreach($Statistic in $StatisticA)
  { 
    if ( $Statistic.type -eq $type )
    {
      $value = Convert-To64Bit $Statistic.value.high $Statistic.value.low;
      break;
    }
  }
  return $value;
}

#-------------------------------------------------------------------------
function Get-ChartPrefix()
#-------------------------------------------------------------------------
{
  $prefix = $script:CHARTPREFIX % 10;
  $script:CHARTPREFIX++;
  return "${prefix}.";
}

#-------------------------------------------------------------------------
function Get-Chart()
#-------------------------------------------------------------------------
{
  param($min, $val, $max, $type, $fmt);
  
  $chart = "";
  Write-DebugMessage "Querying chart for '$min', '$val', '$max', '$type'...";
  
  if ( ($null -ne $val) -and ($null -ne $fmt) )
  {
    $val = $val.ToString($fmt);
  }
  
  $suffix = "";
  switch($type)
  {
    "CYCLES" { $suffix = ""; }
    "RUNTIME" { $suffix = " ms."; }
    "CPUUSAGE" { $suffix = "%"; }
  }
  
  $prefix = Get-ChartPrefix;
  $charturl = "http://${prefix}chart.apis.google.com/chart?cht=gom";
  
  $charturl += "&chs=$($script:CHARTSIZE)";
  $charturl += "&chco=00FF00,FF0000";
  $charturl += "&chds=$min,$max";
  $charturl += "&chd=t:$val";
  $charturl += "&chxt=x,y";
  $charturl += "&chxl=0:|$val$suffix|1:|0||$max";
  $charturl += "&chf=c,lg,45,FFE7C6,0,76A4FB,0.75";
  
  Write-DebugMessage "returning chart: $charturl...";

  $chart += "";
  switch($type)
  {
    "CYCLES" {
      $chart += "
CPU Cycles/Request
"; } "RUNTIME" { $chart += "
Runtime (ms)/Request
"; } "CPUUSAGE" { $chart += "
Percent CPU Usage/Request
"; } "ERRORS" { $chart += "
Total Errors
"; } } $chart += ""; return $chart; } #------------------------------------------------------------------------- # function Get-Data #------------------------------------------------------------------------- function Get-Data() { $now = [DateTime]::Now; $page_data = "$($script:TITLE)

iRule Monitor

$now

"; $vslist = [string[]]$(Get-VirtualServerList); $VirtualServerRuleAofA = (Get-F5.iControl).LocalLBVirtualServer.get_rule( $vslist ); $RuleStatistics = (Get-F5.iControl).LocalLBRule.get_all_statistics(); # loop through all the virtual servers for($i=0; $i -lt $VirtualServerRuleAofA.Length; $i++) { $vs = $vslist[$i]; # rules for current vs $VirtualServerRuleA = $VirtualServerRuleAofA[$i]; # rule stats for current vs $RuleStatisticEntryA = Filter-RuleStatistics $VirtualServerRuleA $RuleStatistics; if ( $RuleStatisticEntryA -ne $null ) { # Build out a column list... $columns = @{}; foreach($RuleStatisticEntry in $RuleStatisticEntryA) { if ( ($columns.count -eq 0) -or ($null -eq $columns[$RuleStatisticEntry.event_name]) ) { $columns.Add($RuleStatisticEntry.event_name, 0); } } $scolumns = $columns.GetEnumerator() | Sort-Object Name; # Build out result graphs Write-DebugMessage "VIRTUAL SERVER $vs"; $page_data += "" $page_data += ""; $page_data += "" foreach($key in $scolumns) { $page_data += ""; } $page_data += ""; # loop through all rules for current virtual server foreach($VirtualServerRule in $VirtualServerRuleA) { if ( ($null -eq $script:IRULE) -or ($VirtualServerRule.rule_name -eq $script:IRULE) ) { $page_data += ""; $page_data += ""; foreach($key in $scolumns) { $aborts = $null; $avg_cycles = $null; $failures = $null; $max_cycles = $null; $min_cycles = $null; $total_executions = $null; foreach($RuleStatisticEntry in $RuleStatisticEntryA) { if ( ($RuleStatisticEntry.rule_name -eq $VirtualServerRule.rule_name) -and ($RuleStatisticEntry.event_name -eq $key.Name) ) { Write-DebugMessage "Searching for '$($RuleStatisticEntry.rule_name), $($RuleStatisticEntry.event_name)..."; # Found a match for the row and column $min_cycles = Extract-Statistic $RuleStatisticEntry.statistics "STATISTIC_RULE_MINIMUM_CYCLES"; $avg_cycles = Extract-Statistic $RuleStatisticEntry.statistics "STATISTIC_RULE_AVERAGE_CYCLES"; $max_cycles = Extract-Statistic $RuleStatisticEntry.statistics "STATISTIC_RULE_MAXIMUM_CYCLES"; $aborts = Extract-Statistic $RuleStatisticEntry.statistics "STATISTIC_RULE_ABORTS"; $failures = Extract-Statistic $RuleStatisticEntry.statistics "STATISTIC_RULE_FAILURES"; $total_executions = Extract-Statistic $RuleStatisticEntry.statistics "STATISTIC_RULE_TOTAL_EXECUTIONS"; break; } } $min = 0; $data_value = $null; $max = 5000; $speedMhz = [Convert]::ToDouble($script:CPUSPEED); $speed = [Convert]::ToUInt64(1000000 * $speedMhz); $cycles_min = $min_cycles; $cycles_avg = $avg_cycles; $cycles_max = $max_cycles; $runtime_min = [Convert]::ToDouble($min_cycles) * (1000.0/$speed); $runtime_avg = [Convert]::ToDouble($avg_cycles) * (1000.0/$speed); $runtime_max = [Convert]::ToDouble($max_cycles) * (1000.0/$speed); $cpu_min = 0; #$min = 100.0 * ([Convert]::ToDouble($min_cycles) / [Convert]::ToDouble($speed)); $cpu_avg = 100.0 * ([Convert]::ToDouble($avg_cycles) / [Convert]::ToDouble($speed)); #$max = 100.0 * ([Convert]::ToDouble($max_cycles) / [Convert]::ToDouble($speed)); $cpu_max = 100; if ( 0 -eq $data_value ) { $data_value = $null; } if ( $null -ne $data_value ) { $data_value = $data_value.ToString("0.0000"); } $cycles_chart = Get-Chart $cycles_min $cycles_avg $cycles_max "CYCLES"; $runtime_chart = Get-Chart $runtime_min $runtime_avg $runtime_max "RUNTIME" "0.00000"; $cpu_chart = Get-Chart $cpu_min $cpu_avg $cpu_max "CPUUSAGE" "0.00000"; $success_chart = Get-Chart 0 ($aborts + $failures) $total_executions "ERRORS"; Write-DebugMessage $charturl; $page_data += ""; } $page_data += ""; } } $page_data += "
Virtual Server '$vs'
iRule$($key.Name)
$($VirtualServerRule.rule_name)"; switch($script:METRIC) { "CYCLES" { $page_data += "$cycles_chart"; $page_data += $success_chart; } "RUNTIME" { $page_data += "$runtime_chart"; $page_data += $success_chart; } "CPUUSAGE" { $page_data += "$cpu_chart"; $page_data += $success_chart; } "ALL" { $page_data += $cycles_chart; $page_data += $runtime_chart; $page_data += $cpu_chart; $page_data += $success_chart; } default { $page_data += "$cycles_chart"; } } $page_data += "

" } } $page_data += "

"; return $page_data; } #------------------------------------------------------------------------- function Refresh-Browser() #------------------------------------------------------------------------- { param($file_data); if ( $null -eq $script:BROWSER ) { Write-DebugMessage "Creating new Browser" $script:BROWSER = New-Object -com InternetExplorer.Application; $script:BROWSER.Navigate2("About:blank"); $script:BROWSER.Visible = $true; $script:BROWSER.TheaterMode = $script:THEATER; } $docBody = $script:BROWSER.Document.DocumentElement.lastChild; $docBody.InnerHTML = $file_data; } #------------------------------------------------------------------------- function Kill-Browser() #------------------------------------------------------------------------- { if ( $null -ne $script:BROWSER ) { $script:BROWSER.TheaterMode = $false; $script:BROWSER.Quit(); $script:BROWSER = $null; } } #------------------------------------------------------------------------- function Run-Dashboard() #------------------------------------------------------------------------- { while($true) { Write-Host "Requesting data..." $file_data = Get-Data; Refresh-Browser $file_data; Start-Sleep $script:INTERVAL; } } #------------------------------------------------------------------------- # Do-Initialize #------------------------------------------------------------------------- function Do-Initialize() { if ( (Get-PSSnapin | Where-Object { $_.Name -eq "iControlSnapIn"}) -eq $null ) { Add-PSSnapIn iControlSnapIn } $success = Initialize-F5.iControl -HostName $BIGIP -Username $User -Password $Pass; return $success; } #------------------------------------------------------------------------- # Exception handling #------------------------------------------------------------------------- Trap [Exception] { Write-Host $("TRAPPED: " + $_.Exception.GetType().FullName); Write-Host $("TRAPPED: " + $_.Exception.Message); Kill-Browser Exit; } #------------------------------------------------------------------------- # Main Application Logic #------------------------------------------------------------------------- if ( ($BIGIP -eq $null) -or ($User -eq $null) -or ($Pass -eq $null) ) { Write-Usage; } if ( Do-Initialize ) { Run-Dashboard } else { Write-Error "ERROR: iControl subsystem not initialized" Kill-Browser }
Published Mar 09, 2015
Version 1.0

Was this article helpful?

1 Comment

  • Hey. Hoping you can point me in the right direction. The chart opens up, shows all the vs and irules but there is no data. Only x where the data should be. Thanks.