From a3715e2ab0c02e54c83da8a52b296c6877541c85 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Mon, 2 Mar 2020 05:35:07 +0000 Subject: [PATCH 01/14] Update rubocop requirement from ~> 0.51.0 to ~> 0.80.1 Updates the requirements on [rubocop](https://github.com/rubocop-hq/rubocop) to permit the latest version. - [Release notes](https://github.com/rubocop-hq/rubocop/releases) - [Changelog](https://github.com/rubocop-hq/rubocop/blob/master/CHANGELOG.md) - [Commits](https://github.com/rubocop-hq/rubocop/compare/v0.51.0...v0.80.1) Signed-off-by: dependabot-preview[bot] --- sensu-plugins-windows.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sensu-plugins-windows.gemspec b/sensu-plugins-windows.gemspec index 3a09888..626ac3c 100644 --- a/sensu-plugins-windows.gemspec +++ b/sensu-plugins-windows.gemspec @@ -37,6 +37,6 @@ Gem::Specification.new do |s| s.add_development_dependency 'rake', '~> 12.3' s.add_development_dependency 'redcarpet', '~> 3.2' s.add_development_dependency 'rspec', '~> 3.1' - s.add_development_dependency 'rubocop', '~> 0.51.0' + s.add_development_dependency 'rubocop', '~> 0.80.1' s.add_development_dependency 'yard', '~> 0.9.11' end From 6263e5e755a7bf4ad0bd9f34212d0d0e43016b85 Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Fri, 13 Mar 2020 10:11:35 -0500 Subject: [PATCH 02/14] rubocop fixes --- Rakefile | 2 +- bin/check-windows-disk.rb | 2 +- bin/check-windows-process.rb | 9 +++++---- sensu-plugins-windows.gemspec | 7 ++++--- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/Rakefile b/Rakefile index a68b194..60c3572 100644 --- a/Rakefile +++ b/Rakefile @@ -29,7 +29,7 @@ desc 'Test for binstubs' task :check_binstubs do bin_list = Gem::Specification.load('sensu-plugins-windows.gemspec').executables bin_list.each do |b| - `which #{ b }` + `which #{b}` unless $CHILD_STATUS.success? puts "#{b} was not a binstub" exit diff --git a/bin/check-windows-disk.rb b/bin/check-windows-disk.rb index 9799d27..163fecb 100755 --- a/bin/check-windows-disk.rb +++ b/bin/check-windows-disk.rb @@ -86,7 +86,7 @@ def read_wmic end # If label value is not set, the drive letter will end up in that column. Set mnt to label in that case. mnt = label if mnt.nil? - prct_used = (100 * (1 - (_avail.to_f / capacity.to_f))) + prct_used = (100 * (1 - (_avail / capacity).to_f)) if prct_used >= config[:crit] @crit_fs << "#{mnt} #{prct_used.round(2)}" elsif prct_used >= config[:warn] diff --git a/bin/check-windows-process.rb b/bin/check-windows-process.rb index 1bb9d59..dcb0d86 100755 --- a/bin/check-windows-process.rb +++ b/bin/check-windows-process.rb @@ -43,7 +43,7 @@ opts.on('-p', '--processname PROCESS', 'Unique process string to search for.') do |p| options[:procname] = p if p == '' - STDERR.puts 'Empty string for -p : Expected a string to match against.' + warn 'Empty string for -p : Expected a string to match against.' exit 3 end end @@ -53,7 +53,7 @@ begin options[:warn] = Integer(w) rescue ArgumentError - STDERR.puts 'Optional -w needs to be a value in seconds' + warn 'Optional -w needs to be a value in seconds' exit 3 end end @@ -62,7 +62,7 @@ parser.parse! if options[:procname] == '' - STDERR.puts 'Expected a process to match against.' + warn 'Expected a process to match against.' raise OptionParser::MissingArgument end @@ -72,8 +72,9 @@ status = 2 wmi.ExecQuery('select * from win32_process').each do |process| next unless process.Name.downcase.include? options[:procname].downcase + if !options[:warn].nil? - delta_days = DateTime.now - DateTime.parse(process.CreationDate) # rubocop:disable Style/DateTime + delta_days = Date.now - Date.parse(process.CreationDate) delta_secs = (delta_days * 24 * 60 * 60).to_i if delta_secs > options[:warn] puts "OK: #{process.Name} running more than #{options[:warn]} seconds." diff --git a/sensu-plugins-windows.gemspec b/sensu-plugins-windows.gemspec index 3a09888..159aa87 100644 --- a/sensu-plugins-windows.gemspec +++ b/sensu-plugins-windows.gemspec @@ -1,6 +1,6 @@ # frozen_string_literal: true -lib = File.expand_path('../lib', __FILE__) +lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'date' @@ -32,11 +32,12 @@ Gem::Specification.new do |s| s.add_runtime_dependency 'sensu-plugin', '~> 4.0' s.add_development_dependency 'bundler', '~> 2.0' + s.add_development_dependency 'codeclimate-test-reporter', '~> 1.0' s.add_development_dependency 'github-markup', '~> 3.0' s.add_development_dependency 'pry', '~> 0.10' - s.add_development_dependency 'rake', '~> 12.3' + s.add_development_dependency 'rake', '~> 13.0' s.add_development_dependency 'redcarpet', '~> 3.2' s.add_development_dependency 'rspec', '~> 3.1' - s.add_development_dependency 'rubocop', '~> 0.51.0' + s.add_development_dependency 'rubocop', '~> 0.80.1' s.add_development_dependency 'yard', '~> 0.9.11' end From f61a2c325ab27607f3cad25ad8ea13ad64e86714 Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Fri, 13 Mar 2020 16:37:47 -0500 Subject: [PATCH 03/14] rubocop additional fixes --- bin/check-windows-disk.rb | 6 +++--- test/check-windows-disk.rb | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/bin/check-windows-disk.rb b/bin/check-windows-disk.rb index 163fecb..0264523 100755 --- a/bin/check-windows-disk.rb +++ b/bin/check-windows-disk.rb @@ -71,9 +71,9 @@ def read_wmic `wmic volume where DriveType=3 list brief /format:"%WINDIR%\\System32\\wbem\\en-US\\csv"`.split("\n").drop(1).each do |line| begin # #YELLOW - _hostname, capacity, type, _fs, _avail, label, mnt = line.split(',') # rubocop:disable Lint/UnderscorePrefixedVariableName + _hostname, capacity, type, _fs, avail, label, mnt = line.split(',') next if /\S/ !~ line - next if _avail.nil? + next if avail.nil? next if line.include?('System Reserved') next if line.include?('\Volume') next if config[:mount_points] && !config[:mount_points].include?(mnt) @@ -86,7 +86,7 @@ def read_wmic end # If label value is not set, the drive letter will end up in that column. Set mnt to label in that case. mnt = label if mnt.nil? - prct_used = (100 * (1 - (_avail / capacity).to_f)) + prct_used = (100 * (1 - (avail / capacity).to_f)) if prct_used >= config[:crit] @crit_fs << "#{mnt} #{prct_used.round(2)}" elsif prct_used >= config[:warn] diff --git a/test/check-windows-disk.rb b/test/check-windows-disk.rb index 3067ead..047269f 100644 --- a/test/check-windows-disk.rb +++ b/test/check-windows-disk.rb @@ -29,7 +29,8 @@ def check_mount_point(check) expect do begin check.run - rescue SystemExit # rubocop:disable HandleExceptions + rescue StandardError + exit end end end From 74351a8978d395a3cc43c8d15b979b9f9437fafe Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Fri, 13 Mar 2020 16:56:24 -0500 Subject: [PATCH 04/14] use #{} for floatpoint --- bin/metric-windows-network.rb | 2 +- bin/metric-windows-uptime.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/metric-windows-network.rb b/bin/metric-windows-network.rb index b12a471..7b3341f 100755 --- a/bin/metric-windows-network.rb +++ b/bin/metric-windows-network.rb @@ -56,7 +56,7 @@ def run next unless ifz && metric ifz_name = ifz[18, ifz.length - 19].tr('.', ' ') - value = format('%.2f', v.to_f) + value = format("#{amount.round(2)}", v.to_f) name = [config[:scheme], ifz_name, metric].join('.').tr(' ', '_').tr('{}', '').tr('[]', '') output name, value, timestamp diff --git a/bin/metric-windows-uptime.rb b/bin/metric-windows-uptime.rb index 3223996..fbccd03 100755 --- a/bin/metric-windows-uptime.rb +++ b/bin/metric-windows-uptime.rb @@ -42,7 +42,7 @@ def acquire_uptime IO.popen('typeperf -sc 1 "\\System\\System Up Time" ') { |io| io.each { |line| temp_arr.push(line) } } uptime_str = temp_arr[2].split(',')[1] uptime = uptime_str.strip[1, uptime_str.length - 3] - [format('%.2f', uptime), timestamp] + [format("#{amount.round(2)}", uptime), timestamp] end def run From 2f20d8f5f08bd3c0a0f62d65f10e20b5c5ac907c Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Fri, 13 Mar 2020 16:56:55 -0500 Subject: [PATCH 05/14] formatting to satisfy cop --- sensu-plugins-windows.gemspec | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/sensu-plugins-windows.gemspec b/sensu-plugins-windows.gemspec index 159aa87..5f5f7e7 100644 --- a/sensu-plugins-windows.gemspec +++ b/sensu-plugins-windows.gemspec @@ -15,11 +15,13 @@ Gem::Specification.new do |s| s.files = Dir.glob('{bin,lib}/**/*') + %w[LICENSE README.md CHANGELOG.md] s.homepage = 'https://github.com/sensu-plugins/sensu-plugins-windows' s.license = 'MIT' - s.metadata = { 'maintainer' => 'sensu-plugin', + s.metadata = { + 'maintainer' => 'sensu-plugin', 'development_status' => 'active', 'production_status' => 'unstable - testing recommended', 'release_draft' => 'false', - 'release_prerelease' => 'false' } + 'release_prerelease' => 'false' + } s.name = 'sensu-plugins-windows' s.platform = Gem::Platform::RUBY s.post_install_message = 'You can use the embedded Ruby by setting EMBEDDED_RUBY=true in /etc/default/sensu' From 5188882b19360b4354fa4cf44fd9a416b42d9364 Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Sat, 14 Mar 2020 12:52:35 -0500 Subject: [PATCH 06/14] proper rubocop corrections --- bin/metric-windows-network.rb | 2 +- bin/metric-windows-uptime.rb | 2 +- sensu-plugins-windows.gemspec | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/bin/metric-windows-network.rb b/bin/metric-windows-network.rb index 7b3341f..d98eb67 100755 --- a/bin/metric-windows-network.rb +++ b/bin/metric-windows-network.rb @@ -56,7 +56,7 @@ def run next unless ifz && metric ifz_name = ifz[18, ifz.length - 19].tr('.', ' ') - value = format("#{amount.round(2)}", v.to_f) + value = format(v.round(2).to_s, v.to_f) name = [config[:scheme], ifz_name, metric].join('.').tr(' ', '_').tr('{}', '').tr('[]', '') output name, value, timestamp diff --git a/bin/metric-windows-uptime.rb b/bin/metric-windows-uptime.rb index fbccd03..c5bd113 100755 --- a/bin/metric-windows-uptime.rb +++ b/bin/metric-windows-uptime.rb @@ -42,7 +42,7 @@ def acquire_uptime IO.popen('typeperf -sc 1 "\\System\\System Up Time" ') { |io| io.each { |line| temp_arr.push(line) } } uptime_str = temp_arr[2].split(',')[1] uptime = uptime_str.strip[1, uptime_str.length - 3] - [format("#{amount.round(2)}", uptime), timestamp] + [format(v.round(2).to_s, uptime), timestamp] end def run diff --git a/sensu-plugins-windows.gemspec b/sensu-plugins-windows.gemspec index 159aa87..f11575b 100644 --- a/sensu-plugins-windows.gemspec +++ b/sensu-plugins-windows.gemspec @@ -15,10 +15,10 @@ Gem::Specification.new do |s| s.files = Dir.glob('{bin,lib}/**/*') + %w[LICENSE README.md CHANGELOG.md] s.homepage = 'https://github.com/sensu-plugins/sensu-plugins-windows' s.license = 'MIT' - s.metadata = { 'maintainer' => 'sensu-plugin', + s.metadata = { 'maintainer' => 'sensu-plugin', 'development_status' => 'active', - 'production_status' => 'unstable - testing recommended', - 'release_draft' => 'false', + 'production_status' => 'unstable - testing recommended', + 'release_draft' => 'false', 'release_prerelease' => 'false' } s.name = 'sensu-plugins-windows' s.platform = Gem::Platform::RUBY From 95bfcb5298a527e50ae300461757e4381d933afb Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Wed, 18 Mar 2020 22:45:02 -0500 Subject: [PATCH 07/14] code review --- bin/check-windows-process.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/check-windows-process.rb b/bin/check-windows-process.rb index dcb0d86..ad55650 100755 --- a/bin/check-windows-process.rb +++ b/bin/check-windows-process.rb @@ -43,7 +43,7 @@ opts.on('-p', '--processname PROCESS', 'Unique process string to search for.') do |p| options[:procname] = p if p == '' - warn 'Empty string for -p : Expected a string to match against.' + unknown 'Empty string for -p : Expected a string to match against.' exit 3 end end @@ -53,7 +53,7 @@ begin options[:warn] = Integer(w) rescue ArgumentError - warn 'Optional -w needs to be a value in seconds' + unknown 'Optional -w needs to be a value in seconds' exit 3 end end From 3e94b21f1081bf8377164ff65d042584b1acf2c7 Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Wed, 18 Mar 2020 23:12:07 -0500 Subject: [PATCH 08/14] handle missingargument with rescue and unknown exit --- bin/check-windows-process.rb | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/bin/check-windows-process.rb b/bin/check-windows-process.rb index ad55650..70fdf67 100755 --- a/bin/check-windows-process.rb +++ b/bin/check-windows-process.rb @@ -53,7 +53,7 @@ begin options[:warn] = Integer(w) rescue ArgumentError - unknown 'Optional -w needs to be a value in seconds' + warn 'Optional -w needs to be a value in seconds' exit 3 end end @@ -62,8 +62,11 @@ parser.parse! if options[:procname] == '' - warn 'Expected a process to match against.' - raise OptionParser::MissingArgument + begin + raise OptionParser::MissingArgument + rescue OptionParser::MissingArgument + unknown 'Expected a process to match against.' + end end wmi = WIN32OLE.connect('winmgmts://') From a8e2d5e25211b445a402ad1413f8fda1a0d05bfd Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Wed, 18 Mar 2020 23:12:49 -0500 Subject: [PATCH 09/14] remove exit 3 --- bin/check-windows-process.rb | 2 -- 1 file changed, 2 deletions(-) diff --git a/bin/check-windows-process.rb b/bin/check-windows-process.rb index 70fdf67..e7285d2 100755 --- a/bin/check-windows-process.rb +++ b/bin/check-windows-process.rb @@ -44,7 +44,6 @@ options[:procname] = p if p == '' unknown 'Empty string for -p : Expected a string to match against.' - exit 3 end end @@ -54,7 +53,6 @@ options[:warn] = Integer(w) rescue ArgumentError warn 'Optional -w needs to be a value in seconds' - exit 3 end end end From d30ca7acf83e53d7bbd33589d85e8dc856009b72 Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Fri, 13 Nov 2020 15:03:15 -0600 Subject: [PATCH 10/14] linting --- bin/metric-windows-network.rb | 2 +- bin/metric-windows-uptime.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/metric-windows-network.rb b/bin/metric-windows-network.rb index 7b3341f..d98eb67 100755 --- a/bin/metric-windows-network.rb +++ b/bin/metric-windows-network.rb @@ -56,7 +56,7 @@ def run next unless ifz && metric ifz_name = ifz[18, ifz.length - 19].tr('.', ' ') - value = format("#{amount.round(2)}", v.to_f) + value = format(v.round(2).to_s, v.to_f) name = [config[:scheme], ifz_name, metric].join('.').tr(' ', '_').tr('{}', '').tr('[]', '') output name, value, timestamp diff --git a/bin/metric-windows-uptime.rb b/bin/metric-windows-uptime.rb index fbccd03..c5bd113 100755 --- a/bin/metric-windows-uptime.rb +++ b/bin/metric-windows-uptime.rb @@ -42,7 +42,7 @@ def acquire_uptime IO.popen('typeperf -sc 1 "\\System\\System Up Time" ') { |io| io.each { |line| temp_arr.push(line) } } uptime_str = temp_arr[2].split(',')[1] uptime = uptime_str.strip[1, uptime_str.length - 3] - [format("#{amount.round(2)}", uptime), timestamp] + [format(v.round(2).to_s, uptime), timestamp] end def run From 78107b50ac249298304b90813bfc47898e18cb11 Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Fri, 8 Jan 2021 14:12:12 -0600 Subject: [PATCH 11/14] Replace exit with ExitWithCode Helps the exitcode of the ps1 reach Sensu --- bin/check-windows-cpu-load.ps1 | 18 +++++++++++--- bin/check-windows-directory.ps1 | 16 +++++++++++-- bin/check-windows-disk.ps1 | 25 ++++++++++++++++---- bin/check-windows-event-log.ps1 | 17 ++++++++++--- bin/check-windows-http.ps1 | 16 +++++++++++-- bin/check-windows-log.ps1 | 14 +++++++++-- bin/check-windows-pagefile.ps1 | 17 ++++++++++--- bin/check-windows-process.ps1 | 15 ++++++++++-- bin/check-windows-processor-queue-length.ps1 | 18 +++++++++++--- bin/check-windows-ram.ps1 | 17 ++++++++++--- bin/check-windows-service.ps1 | 17 ++++++++++--- 11 files changed, 159 insertions(+), 31 deletions(-) diff --git a/bin/check-windows-cpu-load.ps1 b/bin/check-windows-cpu-load.ps1 index 54b1608..6fb63b6 100644 --- a/bin/check-windows-cpu-load.ps1 +++ b/bin/check-windows-cpu-load.ps1 @@ -34,6 +34,18 @@ Param( [int]$CRITICAL ) +# Function to help the exitcode be seen by Sensu +function ExitWithCode +{ + param + ( + $exitcode + ) + + $host.SetShouldExit($exitcode) + exit +} + . (Join-Path $PSScriptRoot perfhelper.ps1) $ThisProcess = Get-Process -Id $pid @@ -49,14 +61,14 @@ $Value = [System.Math]::Round((Get-Counter "\$localizedCategoryName(_total)\$loc If ($Value -ge $CRITICAL) { Write-Host CheckWindowsCpuLoad CRITICAL: CPU at $Value%. - Exit 2 } + ExitWithCode 2 } If ($Value -ge $WARNING) { Write-Host CheckWindowsCpuLoad WARNING: CPU at $Value%. - Exit 1 + ExitWithCode 1 } Else { Write-Host CheckWindowsCpuLoad OK: CPU at $Value%. - Exit 0 + ExitWithCode 0 } diff --git a/bin/check-windows-directory.ps1 b/bin/check-windows-directory.ps1 index 9ccb52a..441eea3 100644 --- a/bin/check-windows-directory.ps1 +++ b/bin/check-windows-directory.ps1 @@ -21,13 +21,25 @@ Param( [string]$Dir ) +# Function to help the exitcode be seen by Sensu +function ExitWithCode +{ + param + ( + $exitcode + ) + + $host.SetShouldExit($exitcode) + exit +} + $ThisDir = Test-Path -Path $Dir #Shows diretory if it exist if ($ThisDir) { "CheckDirectory OK: Directory exist" - EXIT 0 + ExitWithCode 0 }else { "CheckDirectory CRITICAL: Directory doesn't exist" - EXIT 2 + ExitWithCode 2 } diff --git a/bin/check-windows-disk.ps1 b/bin/check-windows-disk.ps1 index 660f3f4..764715c 100644 --- a/bin/check-windows-disk.ps1 +++ b/bin/check-windows-disk.ps1 @@ -14,7 +14,7 @@ # Powershell 3.0 or above # # USAGE: -# Powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -NoLogo -File C:\\etc\\sensu\\plugins\\check-windows-disk.ps1 90 95 ab +# Powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -NoLogo -File check-windows-disk.ps1 -Warning 90 -Critical 95 # # NOTES: # @@ -38,13 +38,28 @@ Param( [string]$IGNORE ) +# Function to help the exitcode be seen by Sensu +function ExitWithCode +{ + param + ( + $exitcode + ) + + $host.SetShouldExit($exitcode) + exit +} + +# Set the process priority $ThisProcess = Get-Process -Id $pid $ThisProcess.PriorityClass = "BelowNormal" +# Set $IGNORE and $INCLUDE values if not provided. If ($IGNORE -eq "") { $IGNORE = "ab" } +# Select all fixed local disks (3) which are $INCLUDE and not $IGNORE $AllDisks = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType = 3" | Where-Object { $_.DeviceID -notmatch "[$IGNORE]:"} $crit = 0 @@ -70,15 +85,15 @@ foreach ($ObjDisk in $AllDisks) { if ($crit -ne 0) { if ($warn -ne 0 ){ - Write-Host "CheckDisk CRITICAL: $crit disks in critical state `n$critDisks;`n$warn disks in warning state:`n$warnDisks" + Write-Host "CheckDisk CRITICAL: $crit disks in critical state `n$critDisks;`nCheckDisk WARNING: $warn disks in warning state:`n$warnDisks" } else { Write-Host "CheckDisk CRITICAL: $crit disks in critical state `n$critDisks" } - exit 2 + ExitWithCode 2 } elseif ($warn -ne 0) { Write-Host "CheckDisk WARNING: $warn disks in warning state `n$warnDisks" - exit 1 + ExitWithCode 1 } Write-Host "CheckDisk OK: All disk usage under $WARNING%." -Exit 0 \ No newline at end of file +ExitWithCode 0 diff --git a/bin/check-windows-event-log.ps1 b/bin/check-windows-event-log.ps1 index 18df4f1..8d81053 100644 --- a/bin/check-windows-event-log.ps1 +++ b/bin/check-windows-event-log.ps1 @@ -26,6 +26,17 @@ Param( [string]$Pattern ) +# Function to help the exitcode be seen by Sensu +function ExitWithCode +{ + param + ( + $exitcode + ) + + $host.SetShouldExit($exitcode) + exit +} #Search for pattern inside of File $ThisEvent = Get-WinEvent $LogName -ErrorAction SilentlyContinue | Where {$_.Message -like "*$($Pattern)*"} @@ -40,12 +51,12 @@ $CountWarns=($ThisEvent | Where{$_.LevelDisplayName -eq 'Warning'}).count #Prints count of how many ciritials and warnings If($CountCrits -eq 0 -And $CountWarns -eq 0){ "CheckLog OK: $CountCrits criticals $CountWarns warnings" - EXIT 0 + ExitWithCode 0 }ElseIF ($CountCrits -gt 0) { "CheckLog CRITICAL: $CountCrits criticals $CountWarns warnings" - EXIT 2 + ExitWithCode 2 } Else { "CheckLog WARNING: $CountCrits criticals $CountWarns warnings" - EXIT 1 + ExitWithCode 1 } diff --git a/bin/check-windows-http.ps1 b/bin/check-windows-http.ps1 index e49fa38..200b6e6 100644 --- a/bin/check-windows-http.ps1 +++ b/bin/check-windows-http.ps1 @@ -29,6 +29,18 @@ Param( [string]$CheckAddress ) +# Function to help the exitcode be seen by Sensu +function ExitWithCode +{ + param + ( + $exitcode + ) + + $host.SetShouldExit($exitcode) + exit +} + $ThisProcess = Get-Process -Id $pid $ThisProcess.PriorityClass = "BelowNormal" @@ -48,9 +60,9 @@ if (!$Available) { if ($Available) { if ($Available.statuscode -eq 200) { Write-Host OK: $CheckAddress is available! - Exit 0 + ExitWithCode 0 } else { Write-Host CRITICAL: URL $CheckAddress is not accessible! - Exit 2 + ExitWithCode 2 } } diff --git a/bin/check-windows-log.ps1 b/bin/check-windows-log.ps1 index 56a43d5..322f25e 100644 --- a/bin/check-windows-log.ps1 +++ b/bin/check-windows-log.ps1 @@ -25,16 +25,26 @@ Param( [Parameter(Mandatory=$True)] [string]$Pattern ) +# Function to help the exitcode be seen by Sensu +function ExitWithCode +{ + param + ( + $exitcode + ) + $host.SetShouldExit($exitcode) + exit +} #Search for pattern inside of File $ThisLog = Select-String -Path $LogPath -Pattern $Pattern -AllMatch #Show matched lines if they exist If($ThisLog -eq $null ){ "CheckLog OK: The pattern doesn't exist in log" - EXIT 0 + ExitWithCode 0 }else{ $ThisLog "CheckLog CRITICAL" - EXIT 2 + ExitWithCode 2 } diff --git a/bin/check-windows-pagefile.ps1 b/bin/check-windows-pagefile.ps1 index ecf651f..90f90dc 100644 --- a/bin/check-windows-pagefile.ps1 +++ b/bin/check-windows-pagefile.ps1 @@ -34,6 +34,17 @@ Param( [int]$CRITICAL ) +# Function to help the exitcode be seen by Sensu +function ExitWithCode +{ + param + ( + $exitcode + ) + + $host.SetShouldExit($exitcode) + exit +} $ThisProcess = Get-Process -Id $pid $ThisProcess.PriorityClass = "BelowNormal" @@ -44,12 +55,12 @@ $ThisProcess.PriorityClass = "BelowNormal" If ($Value -gt $CRITICAL) { Write-Host CheckWindowsPagefile CRITICAL: Pagefile usage at $Value%. - Exit 2 } + ExitWithCode 2 } If ($Value -gt $WARNING) { Write-Host CheckWindowsPagefile WARNING: Pagefile usage at $Value%. - Exit 1 } + ExitWithCode 1 } Else { Write-Host CheckWindowsPagefile OK: Pagefile usage at $Value%. - Exit 0 } + ExitWithCode 0 } diff --git a/bin/check-windows-process.ps1 b/bin/check-windows-process.ps1 index 0373b47..3124f1f 100644 --- a/bin/check-windows-process.ps1 +++ b/bin/check-windows-process.ps1 @@ -30,6 +30,17 @@ Param( [string]$ProcessName ) +# Function to help the exitcode be seen by Sensu +function ExitWithCode +{ + param + ( + $exitcode + ) + + $host.SetShouldExit($exitcode) + exit +} $ThisProcess = Get-Process -Id $pid $ThisProcess.PriorityClass = "BelowNormal" @@ -37,8 +48,8 @@ $Exists = Get-Process $ProcessName -ErrorAction SilentlyContinue If (!$Exists) { Write-Host CRITICAL: $ProcessName not found! - Exit 2 } + ExitWithCode 2 } If ($Exists) { Write-Host OK: $ProcessName running. - Exit 0 } + ExitWithCode 0 } diff --git a/bin/check-windows-processor-queue-length.ps1 b/bin/check-windows-processor-queue-length.ps1 index 23fc233..d36e09a 100644 --- a/bin/check-windows-processor-queue-length.ps1 +++ b/bin/check-windows-processor-queue-length.ps1 @@ -34,6 +34,18 @@ Param( [int]$CRITICAL ) +# Function to help the exitcode be seen by Sensu +function ExitWithCode +{ + param + ( + $exitcode + ) + + $host.SetShouldExit($exitcode) + exit +} + $ThisProcess = Get-Process -Id $pid $ThisProcess.PriorityClass = "BelowNormal" @@ -41,12 +53,12 @@ $Value = (Get-CimInstance -className Win32_PerfFormattedData_PerfOS_System).Proc If ($Value -gt $CRITICAL) { Write-Host CheckWindowsProcessorQueueLength CRITICAL: Processor Queue at $Value. - Exit 2 } + ExitWithCode 2 } If ($Value -gt $WARNING) { Write-Host CheckWindowsProcessorQueueLength WARNING: Processor Queue at $Value. - Exit 1 } + ExitWithCode 1 } Else { Write-Host CheckWindowsProcessorQueueLength OK: Processor Queue at $Value. - Exit 0 } + ExitWithCode 0 } diff --git a/bin/check-windows-ram.ps1 b/bin/check-windows-ram.ps1 index 319d4f3..e6c24cb 100644 --- a/bin/check-windows-ram.ps1 +++ b/bin/check-windows-ram.ps1 @@ -34,6 +34,17 @@ Param( [int]$CRITICAL ) +# Function to help the exitcode be seen by Sensu +function ExitWithCode +{ + param + ( + $exitcode + ) + + $host.SetShouldExit($exitcode) + exit +} $ThisProcess = Get-Process -Id $pid $ThisProcess.PriorityClass = "BelowNormal" @@ -43,12 +54,12 @@ $Value = [System.Math]::Round(((($Memory.TotalVisibleMemorySize-$Memory.FreePhys If ($Value -ge $CRITICAL) { Write-Host CheckWindowsRAMLoad CRITICAL: RAM at $Value%. - Exit 2 } + ExitWithCode 2 } If ($Value -ge $WARNING) { Write-Host CheckWindowsRAMLoad WARNING: RAM at $Value%. - Exit 1 } + ExitWithCode 1 } Else { Write-Host CheckWindowsRAMLoad OK: RAM at $Value%. - Exit 0 } + ExitWithCode 0 } diff --git a/bin/check-windows-service.ps1 b/bin/check-windows-service.ps1 index 3619058..b8d2f08 100644 --- a/bin/check-windows-service.ps1 +++ b/bin/check-windows-service.ps1 @@ -31,6 +31,17 @@ Param( [string]$ServiceName ) +# Function to help the exitcode be seen by Sensu +function ExitWithCode +{ + param + ( + $exitcode + ) + + $host.SetShouldExit($exitcode) + exit +} $ThisProcess = Get-Process -Id $pid $ThisProcess.PriorityClass = "BelowNormal" @@ -39,13 +50,13 @@ $Exists = Get-Service $ServiceName -ErrorAction SilentlyContinue If ($Exists) { If (($Exists).Status -eq "Running") { Write-Host OK: $ServiceName Running. - Exit 0 } + ExitWithCode 0 } If (($Exists).Status -eq "Stopped") { Write-Host CRITICAL: $ServiceName Stopped. - Exit 2 } + ExitWithCode 2 } } If (!$Exists) { Write-Host CRITICAL: $ServiceName not found! - Exit 2 } + ExitWithCode 2 } From b3b5a8e606c3fd9f075c5b68dd8d704516ebcd71 Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Fri, 8 Jan 2021 15:07:07 -0600 Subject: [PATCH 12/14] rubocop autocorrects, require ruby > 2.4 --- .rubocop.yml | 2 +- sensu-plugins-windows.gemspec | 14 +++++++------- test/check-windows-disk.rb | 2 +- test/check-windows-service_spec.rb | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 2629f7d..48efefc 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -2,7 +2,7 @@ inherit_from: .rubocop_todo.yml # Support all non EOL rubies AllCops: - TargetRubyVersion: 2.3 + TargetRubyVersion: 2.4 MethodLength: Max: 200 diff --git a/sensu-plugins-windows.gemspec b/sensu-plugins-windows.gemspec index 5f5f7e7..50f8dfe 100644 --- a/sensu-plugins-windows.gemspec +++ b/sensu-plugins-windows.gemspec @@ -16,17 +16,17 @@ Gem::Specification.new do |s| s.homepage = 'https://github.com/sensu-plugins/sensu-plugins-windows' s.license = 'MIT' s.metadata = { - 'maintainer' => 'sensu-plugin', - 'development_status' => 'active', - 'production_status' => 'unstable - testing recommended', - 'release_draft' => 'false', - 'release_prerelease' => 'false' - } + 'maintainer' => 'sensu-plugin', + 'development_status' => 'active', + 'production_status' => 'unstable - testing recommended', + 'release_draft' => 'false', + 'release_prerelease' => 'false' + } s.name = 'sensu-plugins-windows' s.platform = Gem::Platform::RUBY s.post_install_message = 'You can use the embedded Ruby by setting EMBEDDED_RUBY=true in /etc/default/sensu' s.require_paths = ['lib'] - s.required_ruby_version = '>= 2.3.0' + s.required_ruby_version = '>= 2.4.0' s.summary = 'Sensu plugins for Windows' s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.version = SensuPluginsWindows::Version::VER_STRING diff --git a/test/check-windows-disk.rb b/test/check-windows-disk.rb index 047269f..b12caed 100644 --- a/test/check-windows-disk.rb +++ b/test/check-windows-disk.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require_relative '../bin/check-windows-disk.rb' +require_relative '../bin/check-windows-disk' describe CheckDisk do before(:all) do diff --git a/test/check-windows-service_spec.rb b/test/check-windows-service_spec.rb index e2637ce..7d31d32 100644 --- a/test/check-windows-service_spec.rb +++ b/test/check-windows-service_spec.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require_relative '../bin/check-windows-service.rb' +require_relative '../bin/check-windows-service' describe CheckWinService do before(:all) do From a3137f60ea678983dc2b8f5c2d44ed0581120965 Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Fri, 8 Jan 2021 15:07:21 -0600 Subject: [PATCH 13/14] update changelog, readme --- .mdlrc | 2 + CHANGELOG.md | 5 ++- README.md | 103 ++++++++++++++++++++++----------------------------- 3 files changed, 50 insertions(+), 60 deletions(-) create mode 100644 .mdlrc diff --git a/.mdlrc b/.mdlrc new file mode 100644 index 0000000..b17ad40 --- /dev/null +++ b/.mdlrc @@ -0,0 +1,2 @@ +# https://github.com/markdownlint/markdownlint/blob/master/docs/RULES.md +rules "~MD013", "~MD022", "~MD024", "~ND032" diff --git a/CHANGELOG.md b/CHANGELOG.md index b8415fe..c257e32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,14 @@ # Change Log + This project adheres to [Semantic Versioning](http://semver.org/). -This CHANGELOG follows the format listed at [Our CHANGELOG Guidelines ](https://github.com/sensu-plugins/community/blob/master/HOW_WE_CHANGELOG.md). +This CHANGELOG follows the format listed at [Our CHANGELOG Guidelines](https://github.com/sensu-plugins/community/blob/master/HOW_WE_CHANGELOG.md). Which is based on [Keep A Changelog](http://keepachangelog.com/) ## [Unreleased] + ### Changes +- update powershell checks to provide the proper exitcode (@derekgroh) - update tests to favor Pester instead of Ruby (@derekgroh) ### Breaking Changes - update metrics-windows-network.ps1 -Interface argument handling to work with Interfaces names that contain underscores diff --git a/README.md b/README.md index e37e60d..dcc5cd5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Sensu-Plugins-Windows +# Sensu-Plugins-Windows [![Build Status](https://travis-ci.org/sensu-plugins/sensu-plugins-windows.svg?branch=master)](https://travis-ci.org/sensu-plugins/sensu-plugins-windows) [![Gem Version](https://badge.fury.io/rb/sensu-plugins-windows.svg)](http://badge.fury.io/rb/sensu-plugins-windows) @@ -13,44 +13,43 @@ These files provide basic Checks and Metrics for a Windows system. ### Ruby - * bin/check-windows-cpu-load.rb - * bin/check-windows-disk.rb - * bin/check-windows-process.rb - * bin/check-windows-processor-queue-length.rb - * bin/check-windows-ram.rb - * bin/check-windows-service.rb - * bin/metric-windows-cpu-load.rb - * bin/metric-windows-disk-usage.rb - * bin/metric-windows-network.rb - * bin/metric-windows-processor-queue-length.rb - * bin/metric-windows-ram-usage.rb - * bin/metric-windows-uptime.rb - * bin/powershell_helper.rb +* bin/check-windows-cpu-load.rb +* bin/check-windows-disk.rb +* bin/check-windows-process.rb +* bin/check-windows-processor-queue-length.rb +* bin/check-windows-ram.rb +* bin/check-windows-service.rb +* bin/metric-windows-cpu-load.rb +* bin/metric-windows-disk-usage.rb +* bin/metric-windows-network.rb +* bin/metric-windows-processor-queue-length.rb +* bin/metric-windows-ram-usage.rb +* bin/metric-windows-uptime.rb +* bin/powershell_helper.rb ### Powershell - * bin/check-windows-cpu-load.ps1 - * bin/check-windows-disk.ps1 - * bin/check-windows-disk-writeable.ps1 - * bin/check-windows-pagefile.ps1 - * bin/check-windows-process.ps1 - * bin/check-windows-processor-queue-length.ps1 - * bin/check-windows-ram.ps1 - * bin/check-windows-service.ps1 - * bin/metric-windows-cpu-load.ps1 - * bin/metric-windows-disk-usage.ps1 - * bin/metric-windows-network.ps1 - * bin/metric-windows-processor-queue-length.ps1 - * bin/metric-windows-ram-usage.ps1 - * bin/metric-windows-uptime.ps1 - * bin/check-windows-directory.ps1 - * bin/check-windows-event-log.ps1 - * bin/check-windows-log.ps1 - +* bin/check-windows-cpu-load.ps1 +* bin/check-windows-disk.ps1 +* bin/check-windows-disk-writeable.ps1 +* bin/check-windows-pagefile.ps1 +* bin/check-windows-process.ps1 +* bin/check-windows-processor-queue-length.ps1 +* bin/check-windows-ram.ps1 +* bin/check-windows-service.ps1 +* bin/metric-windows-cpu-load.ps1 +* bin/metric-windows-disk-usage.ps1 +* bin/metric-windows-network.ps1 +* bin/metric-windows-processor-queue-length.ps1 +* bin/metric-windows-ram-usage.ps1 +* bin/metric-windows-uptime.ps1 +* bin/check-windows-directory.ps1 +* bin/check-windows-event-log.ps1 +* bin/check-windows-log.ps1 ## Usage -##### Example 1: +### Example 1 Execute Powershell functions using the helper (No copy needed), see example below: @@ -61,53 +60,39 @@ Execute Powershell functions using the helper (No copy needed), see example belo "command": "c:\\opt\\sensu\\embedded\\bin\\ruby C:\\opt\\sensu\\embedded\\bin\\powershell_helper.rb check-windows-ram.ps1 90 95", "interval": 30, "type": "check", - "handler": "win_metrics", - "subscribers": ["win_metrics"] + "handler": "win_memory", + "subscribers": ["win_memory"], + "runtime_assets": ["sensu-plugins-windows", "sensu-ruby-runtime"] } } } ``` -##### Example 2: - -- Copy either the Ruby or Powershell files on a Sensu Client, typically under C:\etc\sensu\plugins. +### Example 2 -- You should also include the full escaped path to the ruby interpreter in the check's command configuration, see example below: +Execute Powershell functions directly, see example below: ```json { "checks": { "cpu_percent": { - "command": "c:\\opt\\sensu\\embedded\\bin\\ruby C:\\opt\\sensu\\etc\\plugins\\metric-windows-cpu-load.rb", + "command": "Powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -NoLogo -File check-windows-ram.ps1 90 95", "interval": 30, "type": "metric", "handler": "win_metrics", - "subscribers": ["win_metrics"] + "subscribers": ["win_metrics"], + "runtime_assets": ["sensu-plugins-windows"] } } } ``` -You should also include the full escaped path to the ruby interpreter in the check's command configuration, see example below: - -```json -{ - "checks": { - "cpu_percent": { - "command": "c:\\opt\\sensu\\embedded\\bin\\ruby C:\\opt\\sensu\\etc\\plugins\\metric-windows-cpu-load.rb", - "interval": 30, - "type": "metric", - "handler": "win_metrics", - "subscribers": ["win_metrics"] - } - } -} -``` - ## Dependencies - * Powershell checks require Powershell version 3.0 or higher. + +* Powershell checks require Powershell version 3.0 or higher. ## Troubleshooting + * Failures to pull counter data with messages like below, might be due to corrupt performance counters. See [Here](https://support.microsoft.com/en-us/help/2554336/how-to-manually-rebuild-performance-counters-for-windows-server-2008-6) for more information. Short answer on fix is `lodctr /R` in an Admin elevated command prompt `Check failed to run: undefined method length' for nil:NilClass, "c:/opt/sensu/plugins/check-windows-ram.rb:45:inacquire_ram_usage'", "c:/opt/sensu/plugins/check-windows-ram.rb:54:in run'", "c:/opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/sensu-plugin-1.` @@ -148,4 +133,4 @@ Invoke-Pester ## Installation -[Installation and Setup](http://sensu-plugins.io/docs/installation_instructions.html) +[Install Sensu plugins](https://docs.sensu.io/sensu-go/latest/plugins/install-plugins/) From d991e8ae09abb019fe43ea46e1578b04f48745ea Mon Sep 17 00:00:00 2001 From: Derek Groh Date: Thu, 14 Jan 2021 09:57:51 -0600 Subject: [PATCH 14/14] remove dependency on perfhelper.ps1 --- bin/check-windows-cpu-load.ps1 | 13 +++---------- bin/metric-windows-cpu-load.ps1 | 4 +--- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/bin/check-windows-cpu-load.ps1 b/bin/check-windows-cpu-load.ps1 index 6fb63b6..79ea71d 100644 --- a/bin/check-windows-cpu-load.ps1 +++ b/bin/check-windows-cpu-load.ps1 @@ -46,22 +46,15 @@ function ExitWithCode exit } -. (Join-Path $PSScriptRoot perfhelper.ps1) - $ThisProcess = Get-Process -Id $pid $ThisProcess.PriorityClass = "BelowNormal" -$perfCategoryID = Get-PerformanceCounterByID -Name 'Processor Information' -$perfCounterID = Get-PerformanceCounterByID -Name '% Processor Time' - -$localizedCategoryName = Get-PerformanceCounterLocalName -ID $perfCategoryID -$localizedCounterName = Get-PerformanceCounterLocalName -ID $perfCounterID - -$Value = [System.Math]::Round((Get-Counter "\$localizedCategoryName(_total)\$localizedCounterName" -SampleInterval 1 -MaxSamples 1).CounterSamples.CookedValue) +$Value = [System.Math]::Round((Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue) If ($Value -ge $CRITICAL) { Write-Host CheckWindowsCpuLoad CRITICAL: CPU at $Value%. - ExitWithCode 2 } + ExitWithCode 2 +} If ($Value -ge $WARNING) { Write-Host CheckWindowsCpuLoad WARNING: CPU at $Value%. diff --git a/bin/metric-windows-cpu-load.ps1 b/bin/metric-windows-cpu-load.ps1 index 6b4fa82..15c8ac1 100644 --- a/bin/metric-windows-cpu-load.ps1 +++ b/bin/metric-windows-cpu-load.ps1 @@ -30,8 +30,6 @@ param( $ThisProcess = Get-Process -Id $pid $ThisProcess.PriorityClass = "BelowNormal" -. (Join-Path $PSScriptRoot perfhelper.ps1) - if ($UseFullyQualifiedHostname -eq $false) { $Path = ($env:computername).ToLower() }else { @@ -52,7 +50,7 @@ foreach ($counter in $counters) { $perfCounterID = Get-PerformanceCounterByID -Name $counter $localizedCounterName = Get-PerformanceCounterLocalName -ID $perfCounterID -$value = [System.Math]::Round((Get-Counter "\$localizedCategoryName(_total)\$localizedCounterName" -SampleInterval 1 -MaxSamples 1).CounterSamples.CookedValue) +$value = [System.Math]::Round((Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue) $Time = DateTimeToUnixTimestamp -DateTime (Get-Date)