├── CheckGroups └── checkgroup_services.json ├── Checks ├── Get-PingResponseTime.ps1 ├── Get-ProcessStatus.ps1 ├── Get-VolumePercentUsed.ps1 ├── Test-HTTPContent.ps1 ├── Test-PerformanceCounter.ps1 ├── Test-TCPConnection.ps1 ├── check_cpu_usage.ps1 ├── check_service.ps1 └── check_used_memory.ps1 ├── Functions ├── Internal.ps1 ├── Start-SensuChecks.ps1 └── Write-PSLog.ps1 ├── LICENSE ├── PoshSensu.Tests.ps1 ├── PoshSensu.psd1 ├── PoshSensu.psm1 ├── README.md ├── poshsensu_config.json.example └── poshsensu_config.json.example2 /CheckGroups/checkgroup_services.json: -------------------------------------------------------------------------------- 1 | { 2 | "group_name": "check_services", 3 | "max_execution_time": 15, 4 | "ttl": 125, 5 | "interval": 60, 6 | "checks": [ 7 | { 8 | "name": "service_dhcp", 9 | "type": "metric", 10 | "command": "check_service.ps1", 11 | "arguments": "-Name Dhcp" 12 | }, 13 | { 14 | "name": "service_ip_helper", 15 | "type": "metric", 16 | "command": "check_service.ps1", 17 | "arguments": "-Name iphlpsvc" 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /Checks/Get-PingResponseTime.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Used to test ping response time to a server 4 | .DESCRIPTION 5 | Provide a ComputerName (Host or IP Address), and a WarningThreshold and ErrorThreshold in ms to test a machine. 6 | .EXAMPLE 7 | Get-PingResponseTime -ComputerName 8.8.8.8 -WarningThreshold 50 -ErrorThreshold 70 8 | 9 | Perform a ping test to the google DNS server. 10 | #> 11 | function Get-PingResponseTime 12 | { 13 | 14 | Param 15 | ( 16 | # Name or IP address of the remote host to perform a ping test 17 | [Parameter(Mandatory=$true)] 18 | [ValidateNotNull()] 19 | [ValidateNotNullOrEmpty()] 20 | [string] 21 | $ComputerName, 22 | 23 | # Warning Threshold For Ping Response Time (ms) 24 | [Parameter(Mandatory=$true)] 25 | [int] 26 | $WarningThreshold, 27 | 28 | # Error Threshold For Ping Response Time (ms) 29 | [Parameter(Mandatory=$true)] 30 | [int] 31 | $ErrorThreshold 32 | ) 33 | 34 | $metricObject = @{} 35 | 36 | $preTest = Test-Connection -ComputerName $ComputerName -Quiet -Count 2 -ErrorVariable pingfail -ErrorAction SilentlyContinue 37 | 38 | # Verify we can ping the machine first 39 | if ($preTest) 40 | { 41 | $results = Test-Connection -ComputerName $ComputerName -ErrorAction SilentlyContinue 42 | 43 | $totalPingTime = 0 44 | $pingCount = 0 45 | 46 | # Get an Average Ping Time 47 | ForEach ($r in $results) 48 | { 49 | $totalPingTime = $TotalPingTime + $r.ResponseTime 50 | $metricObject."ping_$($pingCount)" = "$($r.ResponseTime)ms" 51 | $pingCount++ 52 | } 53 | 54 | $avgPingTime = $totalPingTime / $results.Count 55 | 56 | $metricObject.avg_ping_time = "$($avgPingTime)ms" 57 | 58 | if ($avgPingTime -ge $ErrorThreshold) 59 | { 60 | $sensu_status = 2 61 | $output = "Ping response time over Error Threshold of $($ErrorThreshold)ms - Currently $($avgPingTime)ms" 62 | } 63 | elseif ($avgPingTime -gt $WarningThreshold) 64 | { 65 | $sensu_status = 1 66 | $output = "Ping response time over Over Warning Threshold of $($WarningThreshold)ms - Currently $($avgPingTime)ms" 67 | } 68 | else 69 | { 70 | $sensu_status = 0 71 | $output = "Ping response time OK - $($avgPingTime)ms" 72 | } 73 | } 74 | else 75 | { 76 | $sensu_status = 2 77 | $output = "No ping response from $($ComputerName)! Cannot ping server" 78 | } 79 | 80 | $metricObject.output = $output 81 | $metricObject.status = $sensu_status 82 | $metricObject.computer_pinged = $ComputerName 83 | 84 | 85 | return $metricObject 86 | } 87 | -------------------------------------------------------------------------------- /Checks/Get-ProcessStatus.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Used to return the status of processes - if they are running or not and how many there are. 4 | .DESCRIPTION 5 | Provide a process name and if you want it to be running or not. You can also provide an expected process count. 6 | .EXAMPLE 7 | Get-ProcessStatus -ProcessName w3wp -ProcessRunning $true -ProcessCount 5 8 | 9 | Checks if the w3wp process is running and there are 5 instances of it 10 | .EXAMPLE 11 | Get-ProcessStatus -ProcessName atom -ProcessRunning $false 12 | 13 | Checks to see if the atom process is not running. If it is running the check will fail. 14 | #> 15 | function Get-ProcessStatus 16 | { 17 | 18 | Param 19 | ( 20 | # The name of the process to check for 21 | [Parameter(Mandatory=$true)] 22 | [ValidateNotNull()] 23 | [ValidateNotNullOrEmpty()] 24 | [string] 25 | $ProcessName, 26 | 27 | # True to check if the process is running. False to check the process is not running 28 | [Parameter(Mandatory=$false)] 29 | [ValidateNotNull()] 30 | [ValidateNotNullOrEmpty()] 31 | [boolean] 32 | $ProcessRunning = $true, 33 | 34 | # To count the amount of processes that are running 35 | [Parameter(Mandatory=$false)] 36 | [ValidateNotNull()] 37 | [ValidateNotNullOrEmpty()] 38 | [ValidateRange(1,99999)] 39 | [int] 40 | $ProcessCount 41 | ) 42 | 43 | $metricObject = @{} 44 | 45 | $process = Get-Process -ProcessName $ProcessName -ErrorAction SilentlyContinue 46 | 47 | # If user wants there to be a process running 48 | if ($ProcessRunning) 49 | { 50 | if ($process) 51 | { 52 | $metricObject.status = 0 53 | $metricObject.output = "Process Check OK: $($ProcessName) is running." 54 | $returnProcDetails = $true 55 | } 56 | else 57 | { 58 | $metricObject.status = 2 59 | $metricObject.output = "Process Check FAIL: $($ProcessName) is not running." 60 | $returnProcDetails = $false 61 | } 62 | } 63 | # If the user doesn't want there to be a process running 64 | else 65 | { 66 | if($process) 67 | { 68 | $metricObject.status = 2 69 | $returnProcDetails = $true 70 | $metricObject.output = "Process Check FAIL: $($ProcessName) is running and it shouldn't be." 71 | } 72 | else 73 | { 74 | $metricObject.status = 0 75 | $returnProcDetails = $false 76 | $metricObject.output = "Process Check OK: $($ProcessName) is not running and it shouldn't be." 77 | } 78 | } 79 | 80 | # If user is interested in process count 81 | if($ProcessCount) 82 | { 83 | # If the process count matches 84 | if ($process.Length -eq $ProcessCount) 85 | { 86 | $metricObject.status = 0 87 | $metricObject.output = "Process Check OK: There are $($ProcessCount) process named $($ProcessName) running." 88 | $returnProcDetails = $true 89 | } 90 | # If the process count doesn't match 91 | else 92 | { 93 | $metricObject.status = 2 94 | $returnProcDetails = $true 95 | $metricObject.output = "Process Check FAIL: There are $($process.Length) process named $($ProcessName) running when there should be $($ProcessCount)." 96 | } 97 | } 98 | 99 | 100 | $processCounter = 0 101 | # If returning proc details, loop through each of them and return them 102 | ForEach ($p in $process) 103 | { 104 | $metricObject."pid_$($p.Id)_processname" = $p.ProcessName 105 | $metricObject."pid_$($p.Id)_handles" = $p.Handles 106 | $metricObject."pid_$($p.Id)_path" = $p.Path 107 | $metricObject."pid_$($p.Id)_company" = $p.Company 108 | $metricObject."pid_$($p.Id)_fileversion" = $p.FileVersion 109 | $processCounter ++ 110 | } 111 | 112 | $metricObject.total_proc_count = $processCounter 113 | 114 | return $metricObject 115 | } 116 | -------------------------------------------------------------------------------- /Checks/Get-VolumePercentUsed.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Returns the usage percentage of a volume. 4 | .DESCRIPTION 5 | Provide a disk identifier, either VolumeName, VolumeSerialNumber, DeviceID, Caption or Name and its value and the volume usage percentage will be returned along with other useful volume information. 6 | .EXAMPLE 7 | Get-VolumePercentUsed -Identifier DeviceID -Value 'C:' -WarningThreshold 70 -ErrorThreshold 80 8 | 9 | Returns the volume usage percentage for the disk with the DeviceID 'C:' and returns an output on the Warning and Error thresholds specified. 10 | .EXAMPLE 11 | Get-VolumePercentUsed -Identifier VolumeName -Value DATA 12 | 13 | Returns the volume usage percentage for the disk with the VolumeName 'DATA' and returns output on the default Warning (80) and Error (90) thresholds. 14 | #> 15 | function Get-VolumePercentUsed 16 | { 17 | 18 | Param 19 | ( 20 | # Warning Threshold 21 | [Parameter(Mandatory=$false)] 22 | [int] 23 | $WarningThreshold = 80, 24 | 25 | # Error Threshold 26 | [Parameter(Mandatory=$false)] 27 | [int] 28 | $ErrorThreshold = 90, 29 | 30 | # The property used to idenfitfy a Disk 31 | [Parameter(Mandatory=$true)] 32 | [ValidateNotNull()] 33 | [ValidateNotNullOrEmpty()] 34 | [ValidateSet("VolumeName", "VolumeSerialNumber", "DeviceID", "Caption", "Name")] 35 | $Identifier, 36 | 37 | # The value of the property used to identify a disk 38 | [Parameter(Mandatory=$true)] 39 | [ValidateNotNull()] 40 | [ValidateNotNullOrEmpty()] 41 | $Value 42 | ) 43 | 44 | 45 | $disk = Get-CimInstance -ClassName Win32_LogicalDisk | Where-Object { $_.Description -eq 'Local Fixed Disk' } | Where-Object { $_.($Identifier) -eq $Value } 46 | 47 | $metricObject = @{} 48 | $metricObject.disk_identifier_passed = $Identifier 49 | $metricObject.disk_value_passed = $Value 50 | $metricObject.disk_name = $disk.Name 51 | $metricObject.disk_volumename = $disk.VolumeName 52 | $metricObject.disk_volume_serial = $disk.VolumeSerialNumber 53 | $metricObject.disk_device_id = $disk.DeviceID 54 | $metricObject.disk_caption = $disk.Caption 55 | $metricObject.disk_filesystem = $disk.FileSystem 56 | 57 | 58 | # Find % Free 59 | $freePercentage = ($disk.FreeSpace / $disk.Size) * 100 60 | $freePercentage = [math]::Round($freePercentage) 61 | $usagePercent = 100 - $freePercentage 62 | 63 | $metricObject.disk_percent_free = "$($freePercentage)%" 64 | $metricObject.disk_percent_used = "$($usagePercent)%" 65 | 66 | $totalsize = [math]::Round($disk.Size / 1GB) 67 | $freesize = [math]::Round($disk.FreeSpace / 1GB) 68 | $usedSize = $totalsize - $freesize 69 | 70 | $metricObject.disk_size_gb = "$($totalsize)GB" 71 | $metricObject.disk_free_gb = "$($freesize)GB" 72 | $metricObject.disk_used_gb = "$($usedSize)GB" 73 | 74 | if ($usagePercent -ge $ErrorThreshold) 75 | { 76 | $metricObject.status = 2 77 | $metricObject.output = "Disk Used Percentage Over Error Threshold of $($ErrorThreshold)% - Currently $($usagePercent)% Space Used ($($metricObject.disk_used_gb)/$($metricObject.disk_size_gb))" 78 | } 79 | elseif ($usagePercent -gt $WarningThreshold) 80 | { 81 | $metricObject.status = 1 82 | $metricObject.output = "Disk Used Percentage Over Warning Threshold of $($WarningThreshold)% - Currently $($usagePercent)% Space Used ($($metricObject.disk_used_gb)/$($metricObject.disk_size_gb))" 83 | } 84 | else 85 | { 86 | $metricObject.status = 0 87 | $metricObject.output = "Disk Used Percentage OK - $($usagePercent)% Space Used ($($metricObject.disk_used_gb)/$($metricObject.disk_size_gb))" 88 | } 89 | 90 | return $metricObject 91 | } 92 | -------------------------------------------------------------------------------- /Checks/Test-HTTPContent.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Used to test for HTTP content on a web page 4 | .DESCRIPTION 5 | Provide a Uri (URL) and content to match on a page. 6 | .EXAMPLE 7 | Test-HTTPContent -Uri 'https://10.1.1.140' -IgnoreSSLErrors -ContentToMatch 'asdasd' 8 | 9 | Test to see if 'asdasd' is located on a page. Also ignores any SSL errors. 10 | #> 11 | function Test-HTTPContent 12 | { 13 | 14 | Param 15 | ( 16 | # Name or IP address of the remote host to perform a ping test 17 | [Parameter(Mandatory=$true)] 18 | [ValidateNotNull()] 19 | [ValidateNotNullOrEmpty()] 20 | [string] 21 | $Uri, 22 | 23 | # RegEx for content to match 24 | [Parameter(Mandatory=$true)] 25 | [string] 26 | $ContentToMatch, 27 | 28 | # Ignore any SSL errors - default is false 29 | [Parameter(Mandatory=$false)] 30 | [switch] 31 | $IgnoreSSLErrors=$false 32 | ) 33 | 34 | if ($IgnoreSSLErrors) 35 | { 36 | Add-Type @" 37 | using System.Net; 38 | using System.Security.Cryptography.X509Certificates; 39 | public class TrustAllCertsPolicy : ICertificatePolicy { 40 | public bool CheckValidationResult( 41 | ServicePoint srvPoint, X509Certificate certificate, 42 | WebRequest request, int certificateProblem) { 43 | return true; 44 | } 45 | } 46 | "@ 47 | 48 | [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy 49 | } 50 | 51 | $metricObject = @{} 52 | 53 | try 54 | { 55 | $content = Invoke-WebRequest -UseBasicParsing -Uri $Uri -ErrorAction Stop 56 | $metricObject.statuscode = $content.StatusCode 57 | $metricObject.statusdescription = $content.StatusDescription 58 | $metricObject.rawcontentlength = $content.RawContentLength 59 | 60 | # If content matches and it is supposed to 61 | if ($content.Content -match $ContentToMatch) 62 | { 63 | $sensu_status = 0 64 | $output = "Match FOUND on page $($Uri)" 65 | } 66 | else 67 | { 68 | $sensu_status = 2 69 | $output = "Match NOT FOUND on page $($Uri)" 70 | $metricObject.rawcontent = $content.RawContent 71 | } 72 | } 73 | catch 74 | { 75 | $sensu_status = 2 76 | $output = "Error trying to access page $($Uri)" 77 | } 78 | 79 | $metricObject.output = $output 80 | $metricObject.status = $sensu_status 81 | $metricObject.uri_tested = $Uri 82 | 83 | 84 | return $metricObject 85 | } 86 | -------------------------------------------------------------------------------- /Checks/Test-PerformanceCounter.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Used to test a performance counter. 4 | .DESCRIPTION 5 | Provide a performance counter and a WarningThreshold and ErrorThreshold to test the value. Test is performed 4 times and averaged. 6 | .EXAMPLE 7 | Test-PerformanceCounter -Counter "\Memory\Available MBytes" -WarningThreshold 9800 -ErrorThreshold 10000 8 | 9 | Tests the memory a performance counter. 10 | #> 11 | function Test-PerformanceCounter 12 | { 13 | [CmdletBinding()] 14 | Param 15 | ( 16 | # Performance Counter to Test 17 | [Parameter(Mandatory=$true)] 18 | $Counter, 19 | 20 | # Warning Threshold For The Counter 21 | [Parameter(Mandatory=$true)] 22 | [int] 23 | $WarningThreshold, 24 | 25 | # Error Threshold For The Counter 26 | [Parameter(Mandatory=$true)] 27 | [int] 28 | $ErrorThreshold 29 | ) 30 | 31 | $metricObject = @{} 32 | 33 | $counterResult = Get-Counter -Counter $Counter -SampleInterval 1 -MaxSamples 4 34 | 35 | $totalValue = 0 36 | $testCount = 0 37 | 38 | ForEach ($cv in $counterResult.CounterSamples.CookedValue) 39 | { 40 | $totalValue += $cv 41 | $metricObject."cookedvalue_$($testCount)" = $cv 42 | $testCount++ 43 | } 44 | 45 | $avgValue = $totalValue / $counterResult.CounterSamples.CookedValue.Length 46 | 47 | if ($avgValue -ge $ErrorThreshold) 48 | { 49 | $sensu_status = 2 50 | $output = "Counter ""$($Counter)"" over Error Threshold of $($ErrorThreshold) - Currently $($avgValue)" 51 | } 52 | elseif ($avgValue -gt $WarningThreshold) 53 | { 54 | $sensu_status = 1 55 | $output = "Counter ""$($Counter)"" over Warning Threshold of $($WarningThreshold) - Currently $($avgValue)" 56 | } 57 | else 58 | { 59 | $sensu_status = 0 60 | $output = "Counter ""$($Counter)"" OK - Currently $($avgValue)" 61 | } 62 | 63 | $metricObject.counter_name = $Counter 64 | $metricObject.output = $output 65 | $metricObject.status = $sensu_status 66 | 67 | return $metricObject 68 | } -------------------------------------------------------------------------------- /Checks/Test-TCPConnection.ps1: -------------------------------------------------------------------------------- 1 | function Test-TCPConnection 2 | { 3 | Param( 4 | [Parameter(Mandatory=$true)] 5 | [ValidateNotNull()] 6 | [ValidateNotNullOrEmpty()] 7 | [string] 8 | $ComputerName, 9 | 10 | [Parameter(Mandatory=$true)] 11 | [ValidateNotNull()] 12 | [ValidateNotNullOrEmpty()] 13 | [ValidateRange(1,65535)] 14 | [int] 15 | $Port 16 | ) 17 | 18 | $test = New-Object System.Net.Sockets.TcpClient 19 | 20 | $metricObject = @{} 21 | 22 | Try 23 | { 24 | $test.Connect($ComputerName, $Port); 25 | $sensu_status = 0 26 | $output = "TCP connection successful to $($ComputerName):$($Port)" 27 | } 28 | Catch 29 | { 30 | $sensu_status = 2 31 | $output = "TCP connection failure to $($ComputerName):$($Port)" 32 | } 33 | Finally 34 | { 35 | $test.Dispose(); 36 | $metricObject.status = $sensu_status 37 | $metricObject.output = $output 38 | } 39 | 40 | return $metricObject 41 | } -------------------------------------------------------------------------------- /Checks/check_cpu_usage.ps1: -------------------------------------------------------------------------------- 1 | Param 2 | ( 3 | # Warning Threshold 4 | [Parameter(Mandatory=$false)] 5 | [int] 6 | $WarningThreshold = 80, 7 | 8 | # Error Threshold 9 | [Parameter(Mandatory=$false)] 10 | [int] 11 | $ErrorThreshold = 90 12 | ) 13 | 14 | $cpu = Get-CimInstance -ClassName CIM_Processor 15 | $cpuUsageTotal = 0 16 | $numberOfCPUs = 0 17 | $metricObject = @{} 18 | 19 | ForEach ($c in $cpu) 20 | { 21 | # Add up the load percentage for each CPU 22 | $cpuUsageTotal += $c.LoadPercentage 23 | 24 | # Add the number of CPU's - didn't work with the $cpu.Lenght Property 25 | $numberOfCPUs++ 26 | 27 | # Add info on this CPU 28 | 29 | $metricObject."$($c.DeviceID.ToLower())_name" = $c.Name 30 | $metricObject."$($c.DeviceID.ToLower())_cores" = $c.NumberOfCores 31 | $metricObject."$($c.DeviceID.ToLower())_logicalprocessors" = $c.NumberOfLogicalProcessors 32 | $metricObject."$($c.DeviceID.ToLower())_loadpercentage" = $c.LoadPercentage 33 | $metricObject."$($c.DeviceID.ToLower())_availability" = $c.Availability 34 | } 35 | 36 | # Get average across all CPU's 37 | $avgLoad = $cpuUsageTotal / $numberOfCPUs 38 | 39 | if ($avgLoad -ge $ErrorThreshold) 40 | { 41 | $sensu_status = 2 42 | $output = "CPU Average Load Percentage Over Error Threshold of $($ErrorThreshold)% - Currently $($avgLoad)%" 43 | } 44 | elseif ($avgLoad -gt $WarningThreshold) 45 | { 46 | $sensu_status = 1 47 | $output = "CPU Average Load Percentage Over Warning Threshold of $($WarningThreshold)% - Currently $($avgLoad)%" 48 | } 49 | else 50 | { 51 | $sensu_status = 0 52 | $output = "CPU Average Load Percentage OK - $($avgLoad)%" 53 | } 54 | 55 | $metricObject.output = $output 56 | $metricObject.status = $sensu_status 57 | $metricObject.cim_class_url = "https://msdn.microsoft.com/en-us/library/aa387978(v=vs.85).aspx" 58 | 59 | return $metricObject 60 | -------------------------------------------------------------------------------- /Checks/check_service.ps1: -------------------------------------------------------------------------------- 1 | Param 2 | ( 3 | # Name of Service to Check 4 | [Parameter(Mandatory=$true)] 5 | [string]$Name 6 | ) 7 | 8 | $srv = Get-Service -Name $Name 9 | 10 | if ($srv.Status -ne 'Running') 11 | { 12 | $sensu_status = 2 13 | $output = "Serivce Check FAIL: The $($Name) service is not running." 14 | } 15 | else 16 | { 17 | $sensu_status = 0 18 | $output = "Serivce Check OK: The $($Name) service is running." 19 | } 20 | 21 | $metricObject = @{ 22 | service_display_name = $srv.DisplayName 23 | dependant_services = $srv.DependentServices | Select-Object -ExpandProperty Name 24 | required_services = $srv.RequiredServices | Select-Object -ExpandProperty Name 25 | service_status = $srv.Status.ToString() 26 | output = $output 27 | status = $sensu_status 28 | } 29 | 30 | return $metricObject 31 | -------------------------------------------------------------------------------- /Checks/check_used_memory.ps1: -------------------------------------------------------------------------------- 1 | Param 2 | ( 3 | # Warning Threshold 4 | [Parameter(Mandatory=$false)] 5 | [int] 6 | $WarningThreshold = 80, 7 | 8 | # Error Threshold 9 | [Parameter(Mandatory=$false)] 10 | [int] 11 | $ErrorThreshold = 90 12 | ) 13 | 14 | $mem = Get-CimInstance -ClassName Win32_OperatingSystem | Select FreePhysicalMemory,TotalVisibleMemorySize 15 | $metricObject = @{} 16 | 17 | # Get A Percent Value 18 | $percentFree = ($mem.FreePhysicalMemory / $mem.TotalVisibleMemorySize) * 100 19 | 20 | # Minus the percentage value from 100 (to get used percentage) 21 | $percentUsed = 100 - $percentFree 22 | 23 | # Round the Percentage for Text Output 24 | $percentUsed = [math]::Round($percentUsed) 25 | 26 | $totalMemory = [math]::Round($mem.TotalVisibleMemorySize / 1KB) 27 | $freeMemory = [math]::Round($mem.FreePhysicalMemory / 1KB) 28 | $usedMemory = $totalMemory - $freeMemory 29 | 30 | # Return total and free memory as MB 31 | $metricObject.total_memory_mb = "$($totalMemory)MB" 32 | $metricObject.free_memory_mb = "$($freeMemory)MB" 33 | $metricObject.used_memory_mb = "$($usedMemory)MB" 34 | 35 | if ($percentUsed -ge $ErrorThreshold) 36 | { 37 | $sensu_status = 2 38 | $output = "Memory Usage Percentage Over Error Threshold of $($ErrorThreshold)% - Currently $($percentUsed)% Memory Used ($($metricObject.used_memory_mb)/$($metricObject.total_memory_mb))" 39 | } 40 | elseif ($percentUsed -gt $WarningThreshold) 41 | { 42 | $sensu_status = 1 43 | $output = "Memory Usage Percentage Over Warning Threshold of $($WarningThreshold)% - Currently $($percentUsed)% Memory Used ($($metricObject.used_memory_mb)/$($metricObject.total_memory_mb))" 44 | } 45 | else 46 | { 47 | $sensu_status = 0 48 | $output = "Memory Usage Percentage OK - $($percentUsed)% Memory Used ($($metricObject.used_memory_mb)/$($metricObject.total_memory_mb))" 49 | } 50 | 51 | # Return results 52 | $metricObject.output = $output 53 | $metricObject.status = $sensu_status 54 | 55 | return $metricObject -------------------------------------------------------------------------------- /Functions/Internal.ps1: -------------------------------------------------------------------------------- 1 | Function Import-JsonConfig 2 | { 3 | <# 4 | .Synopsis 5 | Loads the JSON Config File for PoshSensu. 6 | 7 | .Description 8 | Loads the JSON Config File for PoshSensu. 9 | 10 | .Parameter ConfigPath 11 | Full path to the configuration JSON file. 12 | 13 | .Example 14 | Import-JsonConfig -ConfigPath C:\PoshSensu\poshsensu_config.json 15 | 16 | .Notes 17 | NAME: Import-JsonConfig 18 | AUTHOR: Matthew Hodgkins 19 | WEBSITE: http://www.hodgkins.net.au 20 | 21 | #> 22 | [CmdletBinding()] 23 | Param 24 | ( 25 | # Configuration File Path 26 | [Parameter(Mandatory = $true)] 27 | $ConfigPath 28 | ) 29 | 30 | $Config = Get-Content -Path $ConfigPath | Out-String | ConvertFrom-Json 31 | 32 | # If checks directory is '.\Checks', this needs to be searched in the module path. 33 | if ($Config.checks_directory -eq '.\Checks') 34 | { 35 | $Config.checks_directory = Join-Path -Path $here -ChildPath 'Checks' 36 | } 37 | 38 | $checksFullPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Config.checks_directory) 39 | 40 | if (-not(Test-Path -Path $checksFullPath)) 41 | { 42 | throw "Configuration File Error: check_path in the configuration file does not exist ($checksFullPath)." 43 | } 44 | 45 | # If check groups is empty, make an empty array as we will have some checks to add from the additional config files 46 | if ([string]::IsNullOrEmpty($Config.check_groups)) 47 | { 48 | $Config.check_groups = @() 49 | } 50 | 51 | # Folder containing check group additional configuration files 52 | 53 | # Check if value is not null or empty 54 | if (-not([string]::IsNullOrEmpty($Config.check_groups_path))) 55 | { 56 | if (Test-Path -Path $Config.check_groups_path) 57 | { 58 | # Get only the json files 59 | $additionalChecks = Get-ChildItem -Path $Config.check_groups_path -Include "*.json" -Recurse 60 | 61 | # Loop through each and add to check groups 62 | ForEach ($ac in $additionalChecks) 63 | { 64 | Write-Verbose "Adding CheckGroup configuration file $($Config.check_groups_path)" 65 | $cg = Get-Content -Path $ac.FullName | Out-String | ConvertFrom-Json 66 | $Config.check_groups += $cg 67 | } 68 | } 69 | else 70 | { 71 | throw "Configuration File Error: check_groups_path in the configuration file does not exist ($($Config.check_groups_path))" 72 | } 73 | } 74 | 75 | # Sort the checks by max exeuction time so they can be started first 76 | $Config.check_groups = $Config.check_groups | Sort-Object -Property max_execution_time 77 | 78 | # Add the date when the configuration file was last written 79 | Add-Member -InputObject $Config –NotePropertyName last_config_update –NotePropertyValue (Get-Item -Path $ConfigPath).LastWriteTime 80 | 81 | Return $Config 82 | } 83 | 84 | function Start-BackgroundCollectionJob 85 | { 86 | [CmdletBinding()] 87 | Param 88 | ( 89 | # Job Name 90 | [Parameter(Mandatory=$true)] 91 | $Name, 92 | 93 | # Specifies the arguments (parameter values) for the script. 94 | $ArgumentList, 95 | 96 | # Specifies the commands to run in the background job. Enclose the commands in braces ( { } ) to create a script block. 97 | $ScriptBlock, 98 | 99 | # Specifies commands that run before the job starts. Enclose the commands in braces ( { } ) to create a script block. 100 | $InitializationScript 101 | ) 102 | 103 | $Config = Import-JsonConfig -ConfigPath $configPath 104 | 105 | $loggingDefaults = @{ 106 | 'Path' = Join-Path -ChildPath $Config.logging_filename -Path $Config.logging_directory 107 | 'MaxFileSizeMB' = $Config.logging_max_file_size_mb 108 | 'ModuleName' = $MyInvocation.MyCommand.Name 109 | 'ShowLevel' = $Config.logging_level 110 | } 111 | 112 | # Remove any jobs with the same name as the one that is going to be created 113 | Remove-Job -Name $Name -Force -ErrorAction SilentlyContinue 114 | 115 | $job = Start-Job -Name $Name -ArgumentList $ArgumentList -ScriptBlock $ScriptBlock -InitializationScript $InitializationScript 116 | 117 | Write-PSLog @loggingDefaults -Method DEBUG -Message "Started Background job '$($Name)'" 118 | 119 | return $job 120 | 121 | } 122 | 123 | <# 124 | .Synopsis 125 | Tests the state of a background collection job. 126 | 127 | .Description 128 | Tests the state of a background collection job and returns the job results as JSON if there is data. If there is no data or there is an error, returns false. 129 | 130 | .Parameter Job 131 | A PSRemotingJob object 132 | 133 | .Example 134 | Test-BackgroundCollectionJob -Job $job 135 | 136 | Tests a job in the variable $job 137 | 138 | .Notes 139 | NAME: Test-BackgroundCollectionJob 140 | AUTHOR: Matthew Hodgkins 141 | WEBSITE: http://www.hodgkins.net.au 142 | 143 | #> 144 | function Test-BackgroundCollectionJob 145 | { 146 | [CmdletBinding()] 147 | Param 148 | ( 149 | # Job Name 150 | [Parameter(Mandatory=$true)] 151 | [System.Management.Automation.Job] 152 | $Job 153 | ) 154 | 155 | $Config = Import-JsonConfig -ConfigPath $configPath 156 | 157 | $loggingDefaults = @{ 158 | 'Path' = Join-Path -ChildPath $Config.logging_filename -Path $Config.logging_directory 159 | 'MaxFileSizeMB' = $Config.logging_max_file_size_mb 160 | 'ModuleName' = $MyInvocation.MyCommand.Name 161 | 'ShowLevel' = $Config.logging_level 162 | } 163 | 164 | $testedJob = $Job | Get-Job 165 | 166 | if (($testedJob.State -eq 'Running') -and ($testedJob.HasMoreData -eq $true)) 167 | { 168 | $jobResults = $testedJob | Receive-Job 169 | Write-PSLog @loggingDefaults -Method DEBUG -Message "Backgound Running and Has Data ::: Check group: $($testedJob.Name)" 170 | 171 | # Check if the results are not null (even though HasMoreData is true, sometimes there may not be data) 172 | if ([string]::IsNullOrEmpty($jobResults)) 173 | { 174 | return $false 175 | } 176 | else 177 | { 178 | # Convert to and from JSON as the data is a serialized object 179 | return $jobResults | ConvertTo-Json | ConvertFrom-Json 180 | } 181 | } 182 | elseif ($testedJob.State -eq 'Failed') 183 | { 184 | Write-PSLog @loggingDefaults -Method WARN -Message "Failed Backgound Job ::: Check group: $($testedJob.Name) Reason: $($testedJob.ChildJobs[0].JobStateInfo.Reason)" 185 | return $false 186 | } 187 | # Job had to be stopped 188 | elseif ($testedJob.State -eq 'Stopped') 189 | { 190 | Write-PSLog @loggingDefaults -Method WARN -Message "Stopped Backgound Job ::: Check group: $($testedJob.Name) Reason: There is something that is breaking the infinate loop that should have occured." 191 | return $false 192 | } 193 | else 194 | { 195 | Write-PSLog @loggingDefaults -Method WARN -Message "Unexpected Result From Backgound Job ::: Check group: $($testedJob.Name) Job State: $($testedJob.State) Extra Help: Please verify your check scripts manually" 196 | return $false 197 | } 198 | } 199 | 200 | <# 201 | .Synopsis 202 | Merges an array of HashTables or PSObjects into a single object. 203 | .DESCRIPTION 204 | Merges an array of HashTables or PSObjects into a single object, with the ability to filter properties. 205 | .EXAMPLE 206 | Merge-HashtablesAndObjects -InputObjects $lah,$ChecksToValidate -ExcludeProperties checks 207 | 208 | Merges the $lah HashTable and $ChecksToValidate PSObject into a single PSObject. 209 | #> 210 | function Merge-HashtablesAndObjects 211 | { 212 | [CmdletBinding()] 213 | Param 214 | ( 215 | # An array of hashtables or PSobjects to merge. 216 | [Parameter( 217 | Position=0, 218 | Mandatory=$true, 219 | ValueFromPipeline=$true, 220 | ValueFromPipelineByPropertyName=$true) 221 | ] 222 | [ValidateNotNull()] 223 | [ValidateNotNullOrEmpty()] 224 | $InputObjects, 225 | 226 | # Array of properties to exclude 227 | [Parameter( 228 | Position=1, 229 | Mandatory=$false, 230 | ValueFromPipeline=$true, 231 | ValueFromPipelineByPropertyName=$true) 232 | ] 233 | [ValidateNotNull()] 234 | [ValidateNotNullOrEmpty()] 235 | [String[]] 236 | $ExcludeProperties, 237 | 238 | # Overrides memebers when adding objects 239 | [Parameter(Mandatory=$false)] 240 | [ValidateNotNull()] 241 | [ValidateNotNullOrEmpty()] 242 | [Switch] 243 | $Force 244 | ) 245 | 246 | Begin 247 | { 248 | $returnObject = New-Object PSObject -Property @{} 249 | } 250 | Process 251 | { 252 | ForEach($o in $InputObjects) 253 | { 254 | if ($o -is [System.Collections.Hashtable]) 255 | { 256 | $o.GetEnumerator() | Where-Object { $_.Key -notin $ExcludeProperties } | ForEach-Object { 257 | Add-Member -InputObject $returnObject -MemberType NoteProperty -Name $_.Key -Value $_.Value -Force:$Force 258 | } 259 | 260 | } 261 | if ($o -is [System.Management.Automation.PSCustomObject]) 262 | { 263 | $properties = (Get-Member -InputObject $o -MemberType Properties).Name | Where-Object { $_ -notin $ExcludeProperties } 264 | 265 | ForEach ($p in $properties) 266 | { 267 | Add-Member -InputObject $returnObject -MemberType NoteProperty -Name $p -Value $o.$p -Force:$Force 268 | } 269 | 270 | } 271 | } 272 | } 273 | End 274 | { 275 | return $returnObject 276 | } 277 | } 278 | 279 | <# 280 | .Synopsis 281 | Sends data to ComputerName via TCP 282 | .DESCRIPTION 283 | Sends data to ComputerName via TCP 284 | .EXAMPLE 285 | "houston.servers.webfrontend.nic.intel.bytesreceived-sec 24 1434309804" | Send-DataTCP -ComputerName 10.10.10.162 -Port 2003 286 | 287 | Sends a Graphite Formated metric via TCP to 10.10.10.162 on port 2003 288 | #> 289 | function Send-DataTCP 290 | { 291 | [CmdletBinding()] 292 | Param 293 | ( 294 | [CmdletBinding()] 295 | # The data to send via TCP 296 | [Parameter(Mandatory=$true, 297 | ValueFromPipeline=$true, 298 | ValueFromPipelineByPropertyName=$true, 299 | ValueFromRemainingArguments=$false, 300 | Position=0)] 301 | $Data, 302 | 303 | # The Host or IP Address to send the metrics to 304 | [Parameter(Mandatory=$true)] 305 | $ComputerName, 306 | 307 | # The port to send TCP data to 308 | [Parameter(Mandatory=$true)] 309 | $Port 310 | ) 311 | 312 | # If there is no data, do nothing. No good putting it in the Begin or process blocks 313 | if (!$Data) 314 | { 315 | return 316 | } 317 | else 318 | { 319 | $Config = Import-JsonConfig -ConfigPath $configPath 320 | 321 | $loggingDefaults = @{ 322 | 'Path' = Join-Path -ChildPath $Config.logging_filename -Path $Config.logging_directory 323 | 'MaxFileSizeMB' = $Config.logging_max_file_size_mb 324 | 'ModuleName' = $MyInvocation.MyCommand.Name 325 | 'ShowLevel' = $Config.logging_level 326 | } 327 | 328 | try 329 | { 330 | $socket = New-Object System.Net.Sockets.TCPClient 331 | $socket.Connect($ComputerName, $Port) 332 | $stream = $socket.GetStream() 333 | $writer = New-Object System.IO.StreamWriter($stream) 334 | $writer.WriteLine($Data) 335 | $writer.Flush() 336 | Write-Verbose "Sent via TCP to $($ComputerName) on port $($Port)." 337 | } 338 | catch 339 | { 340 | Write-PSLog @loggingDefaults -Method ERROR -Message "$_" 341 | } 342 | finally 343 | { 344 | # Clean up - Checks if variable is set without throwing error. 345 | if (Test-Path variable:SCRIPT:writer) 346 | { 347 | $writer.Dispose() 348 | } 349 | if (Test-Path variable:SCRIPT:stream) 350 | { 351 | $stream.Dispose() 352 | } 353 | if (Test-Path variable:SCRIPT:socket) 354 | { 355 | $socket.Dispose() 356 | } 357 | 358 | [System.GC]::Collect() 359 | } 360 | } 361 | } 362 | 363 | <# 364 | .Synopsis 365 | Returns a list of valid checks from the PoshSensu configuation file. 366 | .DESCRIPTION 367 | Returns a list of valid checks from the PoshSensu configuation file by testing if the checks exist on the disk. 368 | .EXAMPLE 369 | Import-SensuChecks -Config $Config 370 | #> 371 | function Import-SensuChecks 372 | { 373 | [CmdletBinding()] 374 | Param 375 | ( 376 | # The PSObject Containing PoshSensu Configuration 377 | [Parameter(Mandatory=$true)] 378 | [PSCustomObject] 379 | $Config 380 | ) 381 | 382 | $Config = Import-JsonConfig -ConfigPath $configPath 383 | 384 | $loggingDefaults = @{ 385 | 'Path' = Join-Path -ChildPath $Config.logging_filename -Path $Config.logging_directory 386 | 'MaxFileSizeMB' = $Config.logging_max_file_size_mb 387 | 'ModuleName' = $MyInvocation.MyCommand.Name 388 | 'ShowLevel' = $Config.logging_level 389 | } 390 | 391 | $returnObject = @() 392 | 393 | # $Config.check_groups is ordered by max_execution_time 394 | ForEach ($checkgroup in $Config.check_groups) 395 | { 396 | 397 | Write-PSLog @loggingDefaults -Method DEBUG -Message "Verifiying Checks ::: Group Name: $($checkgroup.group_name)" 398 | 399 | # Validates each check first 400 | ForEach ($check in $checkgroup.checks) 401 | { 402 | $checkPath = (Join-Path -Path $Config.checks_directory -ChildPath $check.command) 403 | # Using this instead of Resolve-Path so any warnings can provide the full path to the expected check location 404 | $checkScriptPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($checkPath) 405 | Write-PSLog @loggingDefaults -Method DEBUG -Message "Looking For Check In ::: '$checkScriptPath'" 406 | 407 | # Check if the check actually exists 408 | if (Test-Path -Path $checkScriptPath) 409 | { 410 | 411 | $checkObject = New-Object PSObject -Property @{ 412 | Group = $checkgroup.group_name 413 | TTL = $checkgroup.ttl 414 | Interval = $checkgroup.interval 415 | Name = $check.Name 416 | Path = $checkScriptPath 417 | Arguments = $check.arguments 418 | } 419 | 420 | $returnObject += $checkObject 421 | 422 | Write-PSLog @loggingDefaults -Method DEBUG -Message "Check Added ::: Name: $($check.Name) Path: $($checkScriptPath)" 423 | } 424 | else 425 | { 426 | Write-PSLog @loggingDefaults -Method WARN -Message "Check Not Found ::: Name: '$($check.Name)' Path: '$($checkScriptPath)'." 427 | } 428 | } 429 | } 430 | 431 | return $returnObject 432 | } 433 | 434 | <# 435 | .Synopsis 436 | Formats Sensu Checks into seperate code blocks to be run as background jobs. 437 | .DESCRIPTION 438 | Pass in valid Sensu Checks from the Import-SensuChecks command into this command to format them into code blocks to be run as background jobs. 439 | .EXAMPLE 440 | $backgroundJobs = Import-SensuChecks -Config $Config | Format-SensuChecks 441 | #> 442 | function Format-SensuChecks 443 | { 444 | [CmdletBinding()] 445 | Param 446 | ( 447 | # Valid Checks from Import-SensuChecks 448 | [Parameter( 449 | Position=0, 450 | Mandatory=$true, 451 | ValueFromPipeline=$false) 452 | ] 453 | [ValidateNotNull()] 454 | [ValidateNotNullOrEmpty()] 455 | $SensuChecks 456 | ) 457 | 458 | $returnArray = @{} 459 | 460 | $Config = Import-JsonConfig -ConfigPath $configPath 461 | 462 | $loggingDefaults = @{ 463 | 'Path' = Join-Path -ChildPath $Config.logging_filename -Path $Config.logging_directory 464 | 'MaxFileSizeMB' = $Config.logging_max_file_size_mb 465 | 'ModuleName' = $MyInvocation.MyCommand.Name 466 | 'ShowLevel' = $Config.logging_level 467 | } 468 | 469 | # Build an array of unique check groups 470 | $arrayOfGroups = @() 471 | 472 | ForEach ($cg in ($SensuChecks | Select-Object Group -Unique)) 473 | { 474 | Write-Verbose "Found '$($cg.Group)' check group." 475 | 476 | # Add the unique groups to the array 477 | $arrayOfGroups += $cg.Group 478 | 479 | # Create an array under each checkgroup property 480 | $returnArray.($cg.Group) = @() 481 | } 482 | 483 | # Build the wrapper code for the start of each background job 484 | ForEach ($checkgroup in $arrayOfGroups) 485 | { 486 | # Only grab one of the tests from the group so we can access the Interval and TTL 487 | $SensuChecks | Where-Object { $_.Group -eq $checkgroup } | Get-Unique | ForEach-Object { 488 | 489 | Write-Verbose "Adding header code for '$($_.Group)' check group." 490 | 491 | # Create the pre-job steps 492 | $jobCommand = 493 | " 494 | # Create endless loop 495 | while (`$true) { 496 | 497 | # Create stopwatch to track how long all the jobs are taking 498 | `$stopwatch = [System.Diagnostics.Stopwatch]::StartNew() 499 | 500 | `$returnObject = @{} 501 | 502 | # Build Logging Object 503 | `$loggingDefaults = @{} 504 | `$loggingDefaults.Path = '$($loggingDefaults.Path)' 505 | `$loggingDefaults.MaxFileSizeMB = $($loggingDefaults.MaxFileSizeMB) 506 | `$loggingDefaults.ModuleName = 'Background Job [$($_.Group)]' 507 | `$loggingDefaults.ShowLevel = '$($loggingDefaults.ShowLevel)' 508 | 509 | # Scale the interval back by 4.5% to ensure that the checks in the background job complete in time 510 | `$scaledInterval = $($_.Interval) - ($($_.Interval) * 0.045) 511 | 512 | `Write-PSLog @loggingDefaults -Method DEBUG -Message ""Intervals ::: Check Group: $($_.Interval)s Check Group Scaled: `$(`$scaledInterval)s"" 513 | " 514 | 515 | # Add this command into the script block 516 | $returnArray.($_.Group) += $jobCommand 517 | 518 | } 519 | } 520 | 521 | ForEach ($check in $SensuChecks) 522 | { 523 | # Build the wrapper for each check. Escape variables will be resolved in the background job. 524 | $jobCommand = 525 | " 526 | try 527 | { 528 | # Check if this is a function being passed or a not by checking for the ~ character at the start of the arugment 529 | if (""$($check.Arguments[0])"" -eq ""~"") 530 | { 531 | # Dot source the function 532 | . ""$($check.Path)"" 533 | 534 | # Strip the ~ and any space infront of the argument 535 | `$cleanedArg = ""$($check.Arguments)"" -replace ""^~\s+"","""" 536 | 537 | # Execute the function and its paramaters 538 | `$returnObject.$($check.Name) = Invoke-Expression -Command `$cleanedArg 539 | 540 | } 541 | else 542 | { 543 | # Dot sources the check .ps1 and passes arguments 544 | `$returnObject.$($check.Name) = . ""$($check.Path)"" $($check.Arguments) 545 | } 546 | } 547 | catch 548 | { 549 | Write-PSLog @loggingDefaults -Method WARN -Message ""`$_"" 550 | } 551 | finally 552 | { 553 | Write-PSLog @loggingDefaults -Method DEBUG -Message ""Check Complete ::: Name: $($check.Name) Execution Time: `$(`$stopwatch.Elapsed.Milliseconds)ms"" 554 | } 555 | " 556 | Write-Verbose "Adding check code to '$($check.Group)' check group for check '$($check.Name)'" 557 | 558 | # Add this command into the script block 559 | $returnArray.($check.Group) += $jobCommand 560 | } 561 | 562 | # Build the wrapper code for the end of each background job 563 | ForEach ($checkgroup in $arrayOfGroups) 564 | { 565 | # Only grab one of the tests from the group so we can access the Interval 566 | $SensuChecks | Where-Object { $_.Group -eq $checkgroup } | Get-Unique | ForEach-Object { 567 | 568 | Write-Verbose "Adding footer code for '$($_.Group)' check group." 569 | 570 | $jobCommand = 571 | " 572 | # Return all the data from the jobs 573 | Write-Output `$returnObject 574 | 575 | Write-PSLog @loggingDefaults -Method DEBUG -Message ""Check Group Complete ::: Total Execution Time: `$(`$stopwatch.Elapsed.Milliseconds)ms"" 576 | 577 | `$stopwatch.Stop() 578 | 579 | # Figure out how long to sleep for 580 | `$timeToSleep = `$scaledInterval - `$stopwatch.Elapsed.Seconds 581 | 582 | if (`$stopwatch.Elapsed.Seconds -lt `$scaledInterval) 583 | { 584 | # Wait until the interval has been reached for the check. 585 | Start-Sleep -Seconds `$timeToSleep 586 | Write-PSLog @loggingDefaults -Method DEBUG -Message ""Sleeping Check Group ::: Sleep Time: `$(`$timeToSleep)s"" 587 | } 588 | else 589 | { 590 | Write-Warning ""Job Took Longer Than Interval! Starting It Again Immediately"" 591 | } 592 | 593 | [System.GC]::Collect() 594 | }# End while loop 595 | " 596 | 597 | # Add this command into the script block 598 | $returnArray.($_.Group) += $jobCommand 599 | } 600 | } 601 | 602 | # Convert the value of each check group into a script block 603 | ForEach ($group in $returnArray.GetEnumerator().Name) 604 | { 605 | $returnArray.$group = [scriptblock]::Create($returnArray.$group) 606 | } 607 | 608 | return $returnArray 609 | 610 | } -------------------------------------------------------------------------------- /Functions/Start-SensuChecks.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .Synopsis 3 | Short description 4 | .DESCRIPTION 5 | Long description 6 | .EXAMPLE 7 | Example of how to use this cmdlet 8 | .EXAMPLE 9 | Another example of how to use this cmdlet 10 | #> 11 | function Start-SensuChecks 12 | { 13 | [CmdletBinding()] 14 | Param 15 | ( 16 | # Enable Test Mode. Check results just outputted to screen instead of sent to Sensu Client. 17 | [Parameter(Mandatory=$false)] 18 | [switch] 19 | $TestMode = $false, 20 | 21 | # Path to the PoshSensu configuration file 22 | [Parameter(Mandatory=$false)] 23 | [ValidateScript({ 24 | if(Test-Path -Path $_ -ErrorAction SilentlyContinue) 25 | { 26 | return $true 27 | } 28 | else 29 | { 30 | throw "$($_) is not a valid path." 31 | } 32 | })] 33 | [string] 34 | $ConfigPath = $false 35 | ) 36 | 37 | # Setting global variable for the configuration file path 38 | $global:configPath = $ConfigPath 39 | 40 | # Load the config the first time 41 | $Config = Import-JsonConfig -ConfigPath $configPath 42 | 43 | $firstScriptRun = $true 44 | 45 | # Start infinate loop to read job info 46 | while($true) 47 | { 48 | # Get latest time the config file was written 49 | $configFileLastChanged = (Get-Item -Path $ConfigPath).LastWriteTime 50 | 51 | ##### 52 | # The below if statement is for reloading everything if the configuration file is changed. 53 | ##### 54 | 55 | # If this is the first time the function has been run OR If the config file written date is greater than the date of the config file when it was last imported 56 | if (($firstScriptRun) -or ($configFileLastChanged -gt $Config.last_config_update)) 57 | { 58 | $firstScriptRun = $false 59 | 60 | # Relaod the config 61 | $Config = Import-JsonConfig -ConfigPath $configPath 62 | 63 | # Remove all backgroud jobs incase they changed in the config 64 | Get-Job | Remove-Job -Force -ErrorAction SilentlyContinue 65 | 66 | $loggingDefaults = @{ 67 | 'Path' = Join-Path -ChildPath $Config.logging_filename -Path $Config.logging_directory 68 | 'MaxFileSizeMB' = $Config.logging_max_file_size_mb 69 | 'ModuleName' = $MyInvocation.MyCommand.Name 70 | 'ShowLevel' = $Config.logging_level 71 | } 72 | 73 | Write-PSLog @loggingDefaults -Method DEBUG -Message "Config File Reload ::: Config Path: $($configPath) Reason: First script run or config file changed" 74 | 75 | # Create array hold background jobs 76 | $backgroundJobs = @() 77 | 78 | # Get list of valid checks 79 | $validChecks = Import-SensuChecks -Config $Config 80 | 81 | # Build the background jobs 82 | $bgJobsScriptBlocks = Format-SensuChecks -SensuChecks $validChecks 83 | 84 | $modulePath = "$(Split-Path -Path $PSScriptRoot)\PoshSensu.psd1" 85 | $initScriptForJob = "Import-Module '$($modulePath)'" 86 | $initScriptForJob = [scriptblock]::Create($initScriptForJob) 87 | 88 | ForEach ($bgJobScript in $bgJobsScriptBlocks.GetEnumerator()) 89 | { 90 | Write-PSLog @loggingDefaults -Method INFO -Message "Creating Background Job ::: Check Group: $($bgJobScript.Key)" 91 | 92 | # Start background job. InitializationScript loads the PoshSensu module 93 | $backgroundJobs += Start-BackgroundCollectionJob -Name "$($bgJobScript.Key)" -ScriptBlock $bgJobScript.Value -InitializationScript $initScriptForJob 94 | } 95 | } 96 | 97 | # Handle job timeouts / statuses 98 | $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() 99 | 100 | # Create variable to track if this is the first run 101 | $firstBGJobRun = $true 102 | 103 | # Process each background job that was started 104 | ForEach ($job in $backgroundJobs) 105 | { 106 | # Test the job and save the results 107 | $jobResult = Test-BackgroundCollectionJob -Job $job 108 | 109 | # If the script gets the timing incorrect - there may be more than one result set returned. Loop through each of them. 110 | 111 | ForEach ($j in $jobResult) 112 | { 113 | # If the job tests ok, process the results 114 | if ($j -ne $false) 115 | { 116 | # First run has occured 117 | $firstBGJobRun = $false 118 | 119 | # Get a list of all the checks for this check group 120 | $ChecksToValidate = $Config.check_groups | Where-Object { $_.group_name -eq $job.Name } 121 | 122 | # Go through each check, trying to match it up with a result 123 | ForEach ($check in $ChecksToValidate.checks) 124 | { 125 | # If there is a property on job result matching the check name 126 | if (Get-Member -InputObject $j -Name $check.name -MemberType Properties) 127 | { 128 | Write-PSLog @loggingDefaults -Method DEBUG -Message "Check Result Returned. Merging Data From Config File ::: Check Name: $($check.name)" 129 | 130 | # Merge all the data about the job and return it 131 | $finalCheckResult = Merge-HashtablesAndObjects -InputObjects $j.($check.name),$ChecksToValidate,$check -ExcludeProperties 'checks' | ConvertTo-Json 132 | Write-PSLog @loggingDefaults -Method DEBUG -Message "Check Result ::: Check Name: $($check.name) Result: $finalCheckResult" 133 | 134 | if ($TestMode) 135 | { 136 | Write-Output $finalCheckResult 137 | } 138 | else 139 | { 140 | $finalCheckResult | Send-DataTCP -ComputerName $Config.sensu_socket_ip -Port $Config.sensu_socket_port 141 | } 142 | 143 | } 144 | else 145 | { 146 | Write-PSLog @loggingDefaults -Method WARN -Message "Check Has No Result ::: Check Name: $($check.name) Additonal Help: Verify the check by running it manually out side of PoshSensu" 147 | Write-PSLog @loggingDefaults -Method WARN -Message "Check Has No Result ::: Result Returned: $($j | ConvertTo-Json)" 148 | } 149 | } 150 | } 151 | } 152 | } 153 | 154 | $stopwatch.Stop() 155 | 156 | # If this is the first run and no data has come back yet, sleep for a second and try again 157 | if ($firstBGJobRun) 158 | { 159 | Start-Sleep -Seconds 2 160 | Write-PSLog @loggingDefaults -Method INFO -Message "No Data From Background Jobs ::: Details: No data has been returned from background jobs yet. Looping again quickly to see if any data has been returend yet." 161 | } 162 | # If this is not the first run, sleep until the next interval 163 | else 164 | { 165 | # Sleep for the lowest interval minus how long this run took 166 | $lowestInterval = ($Config.check_groups.interval | Sort-Object)[0] 167 | $sleepTime = ($lowestInterval - $stopwatch.Elapsed.TotalSeconds) 168 | Write-PSLog @loggingDefaults -Method INFO -Message "All Background Jobs Complete ::: Total Background Job(s): $($backgroundJobs.Length) Total Time Taken: $($stopwatch.Elapsed.Milliseconds)ms Sleeping For: $($sleepTime)s" 169 | Start-Sleep -Seconds ($lowestInterval - $stopwatch.Elapsed.TotalSeconds) 170 | } 171 | } 172 | 173 | } -------------------------------------------------------------------------------- /Functions/Write-PSLog.ps1: -------------------------------------------------------------------------------- 1 | function Write-PSLog 2 | { 3 | [CmdletBinding()] 4 | Param 5 | ( 6 | # The log message to write 7 | [Parameter(Mandatory=$true)] 8 | $Message, 9 | 10 | # The method to display the log message 11 | [Parameter(Mandatory=$false)] 12 | [ValidateSet("DEBUG", "INFO", "WARN", "ERROR")] 13 | [string] 14 | $Method, 15 | 16 | # The Path to write the log message 17 | [Parameter(Mandatory=$false)] 18 | [string] 19 | $Path = $null, 20 | 21 | # The maximum file size in MB of the log before it rolls over 22 | [Parameter(Mandatory=$false)] 23 | [string] 24 | $MaxFileSizeMB, 25 | 26 | # The Module or Function That Is Logging 27 | [Parameter(Mandatory=$true)] 28 | $ModuleName, 29 | 30 | # The level of logging to show. This is useful when you only want to log and show error logs for instance 31 | [Parameter(Mandatory=$false)] 32 | [ValidateSet("DEBUG", "INFO", "WARN", "ERROR")] 33 | $ShowLevel = 'DEBUG' 34 | ) 35 | 36 | Begin 37 | { 38 | # Create Log Directory 39 | if ($Path -ne $null) 40 | { 41 | # Get the paths directory 42 | $pathDir = Split-Path -Path $Path -Parent 43 | 44 | if (-not(Test-Path -Path $pathDir)) 45 | { 46 | New-Item -Path $pathDir -ItemType Directory -Force | Out-Null 47 | } 48 | } 49 | 50 | $Message = "$(Get-Date -Format s) [$([System.Diagnostics.Process]::GetCurrentProcess().Id)] - $($ModuleName) - $($Method) - $($Message)" 51 | } 52 | Process 53 | { 54 | # Set values for if the type of log will be actually shown 55 | if ($ShowLevel -ne $null) 56 | { 57 | switch ($ShowLevel) 58 | { 59 | 'DEBUG' { 60 | $showDebug = $true 61 | $showInfo = $true 62 | $showWarn = $true 63 | $showError = $true 64 | } 65 | 'INFO' { 66 | $showDebug = $false 67 | $showInfo = $true 68 | $showWarn = $true 69 | $showError = $true 70 | } 71 | 'WARN' { 72 | $showDebug = $false 73 | $showInfo = $false 74 | $showWarn = $true 75 | $showError = $true 76 | } 77 | 'ERROR' { 78 | $showDebug = $false 79 | $showInfo = $false 80 | $showWarn = $false 81 | $showError = $true 82 | } 83 | } 84 | } 85 | 86 | function Write-LogFile 87 | { 88 | [CmdletBinding()] 89 | Param 90 | ( 91 | # The Path of the file to write 92 | [Parameter(Mandatory=$true)] 93 | $Path, 94 | 95 | # Maximum size of the log files 96 | [int] 97 | $MaxFileSizeMB, 98 | 99 | # The log message to write 100 | [Parameter(Mandatory=$true)] 101 | $Message 102 | ) 103 | 104 | 105 | 106 | # Move the old log file over 107 | if (Test-Path -Path $Path) 108 | { 109 | $logFile = Get-Item -Path $Path 110 | 111 | # Convert log size to MB 112 | $logFileSizeInMB = ($logFile.Length / 1mb) 113 | 114 | if ($logFileSizeInMB -ge $MaxFileSizeMB) 115 | { 116 | Move-Item -Path $Path -Destination "$($Path).old" -Force 117 | } 118 | } 119 | 120 | # If the write_ps_log_queue variable doesnt exist 121 | if (-not(Test-Path variable:global:write_ps_log_queue)) 122 | { 123 | $global:write_ps_log_queue = New-Object System.Collections.Queue 124 | Write-Verbose "creating var write_ps_log_queue" 125 | } 126 | 127 | try 128 | { 129 | while ($global:write_ps_log_queue.Count -gt 0) 130 | { 131 | # Peak at the message and try and write it 132 | Add-Content -Path $Path -Value ($global:write_ps_log_queue.Peek()) -ErrorAction Stop 133 | 134 | # If no failure, remove from queue 135 | $global:write_ps_log_queue.Dequeue() | Out-Null 136 | 137 | Write-Verbose "Message de-queued and written to log file. $($global:write_ps_log_queue.Count) items remain in the queue." 138 | } 139 | 140 | Add-Content -Path $Path -Value $Message -ErrorAction Stop 141 | } 142 | catch 143 | { 144 | 145 | # Add the message to the queue 146 | $global:write_ps_log_queue.Enqueue($Message) 147 | Write-Verbose "Log file busy, putting message in a queue." 148 | } 149 | } 150 | 151 | $splathForWriteLogFile = @{ 152 | 'Path' = $Path 153 | 'MaxFileSizeMB' = $MaxFileSizeMB 154 | 'Message' = $Message 155 | } 156 | 157 | switch ($Method) 158 | { 159 | 'DEBUG' { 160 | if ($showDebug) 161 | { 162 | Write-Verbose $Message 163 | 164 | if ($Path -ne $null) 165 | { 166 | Write-LogFile @splathForWriteLogFile 167 | } 168 | } 169 | 170 | } 171 | 'INFO' { 172 | if ($showInfo) 173 | { 174 | Write-Output $Message 175 | 176 | if ($Path -ne $null) 177 | { 178 | Write-LogFile @splathForWriteLogFile 179 | } 180 | } 181 | } 182 | 'WARN' { 183 | if ($showWarn) 184 | { 185 | Write-Warning $Message 186 | 187 | if ($Path -ne $null) 188 | { 189 | Write-LogFile @splathForWriteLogFile 190 | } 191 | } 192 | } 193 | 'ERROR' { 194 | if ($showError) 195 | { 196 | Write-Error $Message 197 | 198 | if ($Path -ne $null) 199 | { 200 | Write-LogFile @splathForWriteLogFile 201 | } 202 | } 203 | } 204 | } 205 | 206 | } 207 | End 208 | { 209 | } 210 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | -------------------------------------------------------------------------------- /PoshSensu.Tests.ps1: -------------------------------------------------------------------------------- 1 | Import-Module .\PoshSensu.psd1 -Force 2 | 3 | $json_prevalidatedSensuChecks = @" 4 | [ 5 | { 6 | "Arguments": "-Name BITS", 7 | "TTL": 20, 8 | "Interval": 10, 9 | "Group": "quickchecks", 10 | "Path": "E:\\ProjectsGit\\PoshSensu\\Checks\\check_service.ps1", 11 | "Name": "service_bits" 12 | }, 13 | { 14 | "Arguments": "-Name Spooler", 15 | "TTL": 20, 16 | "Interval": 10, 17 | "Group": "quickchecks", 18 | "Path": "E:\\ProjectsGit\\PoshSensu\\Checks\\check_service.ps1", 19 | "Name": "service_spooler" 20 | }, 21 | { 22 | "Arguments": "-Name W32Time", 23 | "TTL": 40, 24 | "Interval": 20, 25 | "Group": "slowchecks", 26 | "Path": "E:\\ProjectsGit\\PoshSensu\\Checks\\check_service.ps1", 27 | "Name": "service_w32time" 28 | } 29 | ] 30 | "@ 31 | 32 | New-Variable -Scope Global -Name prevalidatedSensuChecks -Force -Value (ConvertFrom-Json -InputObject $json_prevalidatedSensuChecks) 33 | 34 | InModuleScope PoshSensu { 35 | 36 | Describe "Format-SensuChecks" { 37 | 38 | $formatedChecks = Format-SensuChecks -SensuChecks $prevalidatedSensuChecks 39 | 40 | It "result should be a System.Collections.Hashtable" { 41 | $formatedChecks -is [System.Collections.Hashtable] | Should Be $true 42 | } 43 | It "result.slowchecks property is a System.Management.Automation.ScriptBlock" { 44 | $formatedChecks.slowchecks -is [System.Management.Automation.ScriptBlock] | Should Be $true 45 | } 46 | It "result.quickchecks property is a System.Management.Automation.ScriptBlock" { 47 | $formatedChecks.quickchecks -is [System.Management.Automation.ScriptBlock] | Should Be $true 48 | } 49 | It "result.quickchecks property contains a variable that hasn't been expanded called `$returnObject.service_bits" { 50 | $formatedChecks.quickchecks -match '\$returnObject\.service_bits' | Should be $true 51 | } 52 | It "result.quickchecks property contains a check for bits" { 53 | $formatedChecks.quickchecks -match '\"E:\\ProjectsGit\\PoshSensu\\Checks\\check_service.ps1\" -Name Bits' | Should be $true 54 | } 55 | It "result.quickchecks property contains a check for spooler" { 56 | $formatedChecks.quickchecks -match '\"E:\\ProjectsGit\\PoshSensu\\Checks\\check_service.ps1\" -Name Spooler' | Should be $true 57 | } 58 | It "result.slowchecks property contains a check for w32time" { 59 | $formatedChecks.slowchecks -match '\"E:\\ProjectsGit\\PoshSensu\\Checks\\check_service.ps1\" -Name W32Time' | Should be $true 60 | } 61 | It "result.quickchecks property does not contains a check for w32time" { 62 | $formatedChecks.quickchecks -match '\"E:\\ProjectsGit\\PoshSensu\\Checks\\check_service.ps1\" -Name W32Time' | Should be $false 63 | } 64 | It "result has 2 check groups" { 65 | $formatedChecks.GetEnumerator().Name.Length | Should be 2 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /PoshSensu.psd1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MattHodge/PoshSensu/bc2c33a0df2e76438e95d7a2ab8b29fa64af0d6d/PoshSensu.psd1 -------------------------------------------------------------------------------- /PoshSensu.psm1: -------------------------------------------------------------------------------- 1 | Set-StrictMode -Version Latest 2 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 3 | 4 | $ps1s = Get-ChildItem -Path ("$here\Functions\") -Filter *.ps1 5 | 6 | ForEach ($ps1 in $ps1s) 7 | { 8 | Write-Verbose "Loading $($ps1.FullName)" 9 | . $ps1.FullName 10 | } 11 | 12 | $functionsToExport = @( 13 | 'Start-SensuChecks' 14 | 'Write-PSLog' 15 | ) 16 | 17 | Export-ModuleMember -Function $functionsToExport -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PoshSensu 2 | PoshSensu is a PowerShell module to handle running PowerShell scripts as Sensu checks. The results are submitted to a Sensu client via the [client socket input](https://sensuapp.org/docs/latest/clients#client-socket-input) feature that the Sensu client provides. 3 | 4 | ## Why Did I Make This Module? 5 | The Sensu client already handles executing PowerShell checks, so you may be wondering why I wrote a module for this. This is why: 6 | ![CPU Spikes when opening PowerShell](https://i.imgur.com/0WhOjUf.gif) 7 | 8 | When a PowerShell process first loads, there is a fairly large CPU impact - usually spiking to around 20-30% for a second or two. When you are running 20-30 PowerShell checks every minute on your servers, this adds up to a lot of wasted CPU cycles. 9 | 10 | This module aims to resolve this problem. 11 | 12 | ## Features 13 | * Sends check results to Sensu Cleint via TCP to the the [client socket input](https://sensuapp.org/docs/latest/clients#client-socket-input) feature 14 | * Easily to use JSON configuration file 15 | * Allows setting different check groups that may have different max execution times, ttl's or execution intervals 16 | * Automatic configuration file reloads allowing adding additional checks without having to restart any services 17 | * Detailed logging (can be turned off) 18 | * Runs checks using PowerShell Background Jobs 19 | * Checks can be loaded from multiple JSON files, making configuration management and templating of checks easy. 20 | * Rotates its own log file 21 | * Runs as a service 22 | 23 | ## Installation 24 | 1. Download the repository and place into a PowerShell Modules directory called PoshSensu. The module directories can be found by running `$env:PSModulePath` in PowerShell. For example, `C:\Program Files\WindowsPowerShell\Modules\PoshSensu` 25 | 1. Make sure the files are un-blocked by right clicking on them and going to properties 26 | 1. Make a new folder to store the configuration file, for example, `C:\PoshSensu` 27 | 1. Copy the `poshsensu_config.json.example` to `C:\PoshSensu\poshsensu_config.json` 28 | 1. Modify the `poshsensu_config.json` configuration file. Instructions in the [Modifying the Configuration File](#confighelp) section. 29 | 1. Open PowerShell and ensure you set your Execution Policy to allow scripts be run. For example `Set-ExecutionPolicy RemoteSigned`. 30 | 31 | ## Verification 32 | You can verify PoshSensu is working correctly by running it in `TestMode`. This will show all output to the screen but not actually send check results to the Sensu server. 33 | 34 | Open a PowerShell window and do the following: 35 | ```powershell 36 | # Import the module 37 | Import-Module -Name PoshSensu 38 | 39 | # Start PoshSensu in TestMode 40 | Start-SensuChecks -ConfigPath 'C:\PoshSensu\poshsensu_config.json' -TestMode 41 | ``` 42 | You should see some JSON output of the script starting and the checks returning, which should look similar to this: 43 | 44 | ![PoshSensu Test Mode](http://i.imgur.com/ksPt7wv.png) 45 | 46 | You can also run the script without the `TestMode` switch in the PowerShell console and checks should be sent to the local Sensu Client. 47 | 48 | After you are happy everything is working correctly, you can install PoshSensu as a service. 49 | 50 | ## Installing as a Service 51 | The easiest way to achieve this is using NSSM - the Non-Sucking Service Manager. 52 | 53 | 1. Download nssm from [nssm.cc](http://nssm.cc/) 54 | 1. Extract the zip file to your machine, for example to `C:\nssm-2.24` 55 | 56 | Now you can use NSSM and PowerShell to install the service: 57 | 58 | ```powershell 59 | # Change to the nssm path 60 | cd C:\nssm-2.24\win64 61 | 62 | # Install Service 63 | Start-Process -FilePath .\nssm.exe -ArgumentList 'install PoshSensu "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-command "& { Import-Module -Name PoshSensu ; Start-SensuChecks -ConfigPath "C:\PoshSensu\poshsensu_config.json" }"" ' -NoNewWindow -Wait 64 | 65 | # Set the service description 66 | Start-Process -FilePath .\nssm.exe -ArgumentList 'set PoshSensu Description "PoshSensu - The PowerShell check runner for Sensu."' -NoNewWindow -Wait 67 | 68 | # Start the service 69 | Start-Service -Name PoshSensu 70 | 71 | # Make sure the service is running 72 | Get-Service -Name PoshSensu 73 | ``` 74 | 75 | It is a good idea to check the PoshSensu log file for any errors. 76 | 77 | You can remove the service by running the following: 78 | ```powershell 79 | Stop-Service -Name PoshSensu -Force 80 | cd C:\nssm-2.24\win64 81 | Start-Process -FilePath .\nssm.exe -ArgumentList 'remove PoshSensu confirm' 82 | ``` 83 | 84 | ### Modifying the Configuration File 85 | 86 | The following section details each setting in the configuration file. 87 | 88 | **NOTE:** When using JSON configuration files, backslashes need to be escaped, for example `\` would be `\\`. 89 | 90 | #### Main Configuration 91 | Key | Default Value | Description 92 | --- | --- | --- 93 | sensu_socket_ip | `localhost` | IP address or host name of the Sensu client where check results will be sent via TCP 94 | sensu_socket_port | `3030` | TCP Port of the Sensu client socket input 95 | logging_enabled | `true` | Enable or disable logging to a file 96 | logging_level | `debug` | Level of logging to perform. Valid options are `debug`, `info`, `warn`, `error` 97 | logging_directory | `C:\\PoshSensu` | Directory to store the log file. The directory will be created if it doesn't exist 98 | logging_filename | `poshsensu.log` | Name for the log file 99 | logging_max_file_size_mb | `10` | The size of the log file before it is rotated 100 | checks_directory | `C:\\Program Files\\WindowsPowerShell\\Modules\\PoshSensu\\Checks` | The directory that contains the PowerShell checks. 101 | check_groups | `N/A` | Array of check groups 102 | check_group_path | `null` | Optional path to directory containing JSON files of additional check groups that will be merged into the configuration file. 103 | 104 | #### Check Group Configuration 105 | A Check Group is a grouping of checks. Each check group is run in its own PowerShell instance using Background Jobs. 106 | 107 | The reason there is multiple check groups it to allow you to bundle checks together that have the same check interval. 108 | 109 | You can additionally add any other JSON key/value for the check group and it will get sent to the Sensu client. All key/values in the check group configuration section (including the defaults) are sent to the Sensu server. 110 | 111 | There are 2 methods for adding check groups to the configuration file: 112 | 1. Add them in the main configuration file as a JSON array (shown in `poshsensu_config.json.example`) 113 | 2. Configure the `check_group_path` option in the configuration file to point to a directory containing multiple JSON files, each containing its own check group (show in `poshsensu_config.json.example2`). 114 | 115 | The below values can be configured for a check group: 116 | 117 | Key | Example Value | Description 118 | --- | --- | --- 119 | group_name | `quickchecks` | Name of the check group. Useful to find the group in the log file 120 | max_execution_time | `30` | Used to determine the check group run order. Does not currently have any other function. 121 | ttl | `120` | Sent to Sensu so it knows how often the check should be received. If no message is received in this time period, Sensu will throw a warning. 122 | interval | `60` | How often each check in this group needs to be run 123 | checks | `N/A` | Array of checks 124 | 125 | Here is an example of a check group configuration that is in its own JSON file (located in `.\CheckGroups\checkgroup_services.json`): 126 | 127 | ```json 128 | { 129 | "group_name": "check_services", 130 | "max_execution_time": 15, 131 | "ttl": 125, 132 | "interval": 60, 133 | "checks": [ 134 | { 135 | "name": "service_dhcp", 136 | "type": "metric", 137 | "command": "check_service.ps1", 138 | "arguments": "-Name Dhcp" 139 | }, 140 | { 141 | "name": "service_ip_helper", 142 | "type": "metric", 143 | "command": "check_service.ps1", 144 | "arguments": "-Name iphlpsvc" 145 | } 146 | ] 147 | } 148 | ``` 149 | 150 | #### Check Configuration 151 | A check is the PowerShell script that will be run, with the results being sent to the Sensu client. 152 | 153 | PoshSensu allows two methods to execute a check, depending on how the check script is written in PowerShell. 154 | 155 | ##### Check written as Advanced PowerShell Function 156 | This is the most common method of writing advanced PowerShell functions. You wrap PowerShell code in a `function Get-Beer { #logic }` block. To use these functions in PowerShell you would usually dot source and then execute the function with paramaters. For example: 157 | 158 | ```powershell 159 | # Dot Source the function 160 | . .\Get-Beer.ps1 161 | # Execute the function with optional paramaters 162 | Get-Beer -Location 'The Fridge' 163 | ``` 164 | 165 | To use a PowerShell function with a check, the check configration option `arguments` uses a special syntax - it has a `~` in front of the function name and paramaters. Here is a configuration example of what a check running a function would look like: 166 | ```json 167 | { 168 | "name": "disk_c", 169 | "type": "metric", 170 | "command": "Get-VolumePercentUsed.ps1", 171 | "arguments": "~ Get-VolumePercentUsed -Identifier DeviceID -Value 'E:'" 172 | } 173 | ``` 174 | Take note of the `~` in front of the function call. This tells PoshSensu it is a function and to dot source it first. 175 | 176 | ##### Check written with parameters but not as an Advanced PowerShell Function 177 | This is a less commonly used method to write PowerShell functions that require input. They usually have a paramater block, but are not wrapped in the `function` tags. These are executed diferently in PowerShell, for example: 178 | 179 | ```powershell 180 | # Run the function and pass paramaters on the same line 181 | .\check_service.ps1 -Name 'Netlogon' 182 | ``` 183 | To execute a check like this with PoshSensu, the check configuration would look like this: 184 | 185 | ```json 186 | { 187 | "name": "service_spooler", 188 | "type": "metric", 189 | "command": "check_service.ps1", 190 | "arguments": "-Name Spooler" 191 | } 192 | ``` 193 | 194 | 195 | Key | Example Value | Description 196 | --- | --- | --- 197 | name | `service_bits` | Name of the check that will be sent to Sensu 198 | type | `metric` | The check type, either `standard` or `metric`. Setting type to metric will cause OK (exit 0) check results to create events. I recommend keeping this on `metric` 199 | command | `check_service.ps1` | The file name of the check to execute in PowerShell. These checks are located in the `checks_directory` configuration value configured previously. 200 | arguments | `-Name BITS` | Any arguments that are required to run the PowerShell check. Useful when using parameters in your checks. If the check is an advanced PowerShell function, use a `~` in front of the function call. If your arguments contain a variable, for example `$true`, make sure you escape it with a back tick (``$true`) 201 | 202 | ## How To Write a PowerShell Check 203 | 204 | Writing checks for use with the Sensu PowerShell module is reasonably simple. The only requirement is that they return a PSObject or Hash with the mandatory fields `output` and `status` 205 | 206 | Mandatory Field | Example Value | Description 207 | --- | --- | --- 208 | output | `Serivce Check OK: The lanmanworkstation service is running.` | This is where the result or an explanation of the check status is returned 209 | status | `1` | A number which relates to Sensu status code. `0` for `OK`, `1` for `WARNING`, `2` for `CRITICAL` and `3` or greater to indicate `UNKNOWN` 210 | 211 | It is also a good idea to parameterize your checks so they are more useful across multiple servers. 212 | 213 | You can use Advanced Functions that have paramaters or just simple PowerShell scripts that return a result without requiring any parameters. 214 | 215 | The check can also return key/value which will get sent to the Sensu client. This is handy for providing some more details on the check, for example in the `check_service.ps1` check, I am also retrieving `DisplayName`, `DependentServices`, `RequiredServices` and `Status` properties from the service object in PowerShell and returning them. These details show up when the check has a problem: 216 | 217 | ![Sensu Check Details](http://i.imgur.com/Tvd7nIM.png) 218 | 219 | Take a look at some [example checks](https://github.com/MattHodge/PoshSensu/tree/master/Checks) to give yourself an idea how checks work. 220 | -------------------------------------------------------------------------------- /poshsensu_config.json.example: -------------------------------------------------------------------------------- 1 | { 2 | "sensu_socket_ip": "localhost", 3 | "sensu_socket_port": "3030", 4 | "logging_enabled": true, 5 | "logging_level": "debug", 6 | "logging_directory": "C:\\PoshSensu\\Logs", 7 | "logging_filename": "poshsensu.log", 8 | "logging_max_file_size_mb": "10", 9 | "checks_directory": "C:\\Program Files\\WindowsPowerShell\\Modules\\PoshSensu\\Checks", 10 | "check_groups": [ 11 | { 12 | "group_name": "quickchecks", 13 | "max_execution_time": 30, 14 | "ttl": 180, 15 | "interval": 60, 16 | "checks": [ 17 | { 18 | "name": "service_bits", 19 | "type": "metric", 20 | "command": "check_service.ps1", 21 | "arguments": "-Name BITS" 22 | }, 23 | { 24 | "name": "service_spooler", 25 | "type": "metric", 26 | "command": "check_service.ps1", 27 | "arguments": "-Name Spooler" 28 | }, 29 | { 30 | "name": "disk_c", 31 | "type": "metric", 32 | "command": "Get-VolumePercentUsed.ps1", 33 | "arguments": "~ Get-VolumePercentUsed -Identifier DeviceID -Value 'C:'" 34 | }, 35 | { 36 | "name": "proc_lsass", 37 | "type": "metric", 38 | "command": "Get-ProcessStatus.ps1", 39 | "arguments": "~ Get-ProcessStatus -ProcessName lsass -ProcessRunning `$true" 40 | } 41 | ] 42 | }, 43 | { 44 | "group_name": "slowchecks", 45 | "max_execution_time": 120, 46 | "ttl": 360, 47 | "interval": 120, 48 | "checks": [ 49 | { 50 | "name": "ping_google", 51 | "type": "metric", 52 | "command": "Get-PingResponseTime.ps1", 53 | "arguments": "~ Get-PingResponseTime -ComputerName www.google.com -WarningThreshold 50 -ErrorThreshold 70" 54 | }, 55 | { 56 | "name": "tcp_google_443", 57 | "type": "metric", 58 | "command": "Test-TCPConnection.ps1", 59 | "arguments": "~ Test-TCPConnection -ComputerName www.google.com -Port 443" 60 | } 61 | ] 62 | } 63 | ] 64 | } 65 | -------------------------------------------------------------------------------- /poshsensu_config.json.example2: -------------------------------------------------------------------------------- 1 | { 2 | "sensu_socket_ip": "localhost", 3 | "sensu_socket_port": "3030", 4 | "logging_enabled": true, 5 | "logging_level": "debug", 6 | "logging_directory": "C:\\PoshSensu\\Logs", 7 | "logging_filename": "poshsensu.log", 8 | "logging_max_file_size_mb": "10", 9 | "checks_directory": "C:\\Program Files\\WindowsPowerShell\\Modules\\PoshSensu\\", 10 | "check_groups_path": "C:\\PoshSensu\\CheckGroups", 11 | "check_groups": null 12 | } 13 | --------------------------------------------------------------------------------