https://cdn.zabbix.com/zabbix/binaries/stable/7.4/7.4.15/zabbix_agent-7.4.15-windows-amd64-openssl.msi <# install-zabbix-raid.ps1 - Exabytes Windows RAID monitoring installer for Zabbix PowerShell version of raid.sh. Run in an elevated PowerShell (Run as administrator): powershell -ExecutionPolicy Bypass -File .\install-zabbix-raid.ps1 powershell -ExecutionPolicy Bypass -File .\install-zabbix-raid.ps1 -ToolDir 'D:\Tools\storcli' - Detects Zabbix Agent or Zabbix Agent 2 (service, config, include folder) - Installs the helper \scripts\zabbix-raid-monitor.ps1 - Adds the raid.* UserParameters (same keys as Linux, so the same template works) - Finds StorCLI / PercCLI / MegaCLI / ssacli / arcconf; handles Storage Spaces - Sets Timeout=30, restarts the agent and tests every key Safe to run again. #> [CmdletBinding()] param( [string]$ToolDir = '' # optional folder with storcli64.exe / perccli64.exe / MegaCli64.exe ) $ErrorActionPreference = 'Continue' # native tools may write warnings to stderr function Say([string]$m) { Write-Host $m } function Info([string]$m) { Write-Host "[INFO] $m" } function Fail([string]$m) { Write-Host "[ERROR] $m" -ForegroundColor Red; exit 1 } $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Fail 'Run this installer in an elevated PowerShell (Run as administrator).' } # ============================================================ 1. find the agent if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { $svcs = @(Get-CimInstance Win32_Service -Filter "Name LIKE 'Zabbix Agent%'") } else { $svcs = @(Get-WmiObject Win32_Service -Filter "Name LIKE 'Zabbix Agent%'") } if ($svcs.Count -eq 0) { Fail 'No Zabbix Agent service found (looked for "Zabbix Agent*").' } # prefer a running agent, then agent 2 $svc = $svcs | Sort-Object @{ Expression = { if ($_.State -eq 'Running') { 0 } else { 1 } } }, @{ Expression = { if ($_.Name -match '2') { 0 } else { 1 } } } | Select-Object -First 1 $pn = [string]$svc.PathName if ($pn -match '^\s*"([^"]+)"') { $exe = $Matches[1] } else { $exe = ($pn.Trim() -split '\s+')[0] } $isAgent2 = ((Split-Path $exe -Leaf) -match 'agent2') if ($pn -match '(?:^|\s)(?:-c|--config)\s+"([^"]+)"') { $conf = $Matches[1] } elseif ($pn -match '(?:^|\s)(?:-c|--config)[\s=]+([^\s"]+)') { $conf = $Matches[1] } else { $conf = Join-Path (Split-Path $exe) $(if ($isAgent2) { 'zabbix_agent2.conf' } else { 'zabbix_agentd.conf' }) } if (-not (Test-Path -LiteralPath $exe)) { Fail "Agent executable not found: $exe" } if (-not (Test-Path -LiteralPath $conf)) { Fail "Agent config not found: $conf" } $agentDir = Split-Path $conf # include folder: last Include= that is not the agent 2 plugins folder; relative = next to the config $inc = Get-Content -LiteralPath $conf | Where-Object { $_ -match '^\s*Include\s*=' } | ForEach-Object { ($_ -replace '^\s*Include\s*=\s*', '').Trim().Trim('"') } | Where-Object { $_ -notmatch 'plugins\.d' } | Select-Object -Last 1 $incDir = $null if ($inc) { if (-not [IO.Path]::IsPathRooted($inc)) { $inc = Join-Path $agentDir ($inc -replace '^\.[\\/]', '') } if ($inc -match '\*') { $incDir = Split-Path $inc } elseif (Test-Path -LiteralPath $inc -PathType Container) { $incDir = $inc.TrimEnd('\') } } if (-not $incDir) { $incDir = Join-Path $agentDir $(if ($isAgent2) { 'zabbix_agent2.d' } else { 'zabbix_agentd.d' }) Add-Content -LiteralPath $conf -Value "`r`nInclude=$incDir\*.conf" -Encoding ASCII Info "Added Include=$incDir\*.conf" } New-Item -ItemType Directory -Path $incDir -Force | Out-Null Info "Detected Zabbix type : $(if ($isAgent2) { 'agent2' } else { 'agentd' }) (service '$($svc.Name)')" Info "Agent config : $conf" Info "UserParameter dir : $incDir" # ============================================================ 2. helper + cache folder $scriptDir = Join-Path $agentDir 'scripts' New-Item -ItemType Directory -Path $scriptDir -Force | Out-Null $helper = Join-Path $scriptDir 'zabbix-raid-monitor.ps1' $HelperCode = @' <# zabbix-raid-monitor.ps1 - Windows RAID monitoring helper for Zabbix (Exabytes) PowerShell port of zabbix-raid-monitor.sh: same modes, same status codes, same LLD macros, so "Template Linux RAID Universal" works unchanged on Windows hosts. Backends: StorCLI / PercCLI (JSON), MegaCLI, HP ssacli, Adaptec arcconf (hardware RAID) Storage Spaces (Windows software RAID, the Windows equivalent of mdadm) Both at once are reported together, e.g. STORAGESPACES+STORCLI. Usage: zabbix-raid-monitor.ps1 [id] type | status | details | array_count | disk_total | disk_failed | disk_rebuild | rebuild_progress disk_discovery disk_serial | disk_model | disk_type | disk_size | disk_health | disk_power_on_hours | disk_temp disk_media_errors | disk_other_errors | disk_predictive | disk_rebuild_progress Status: 0 OK, 1 degraded, 2 rebuilding, 3 failed, 4 unknown/unreadable, 5 no RAID #> param([string]$Mode = 'status', [string]$Arg = '') $ErrorActionPreference = 'SilentlyContinue' $ProgressPreference = 'SilentlyContinue' $Inv = [Globalization.CultureInfo]::InvariantCulture $CacheDir = if ($env:ZBX_RAID_CACHE) { $env:ZBX_RAID_CACHE } else { Join-Path $env:ProgramData 'zabbix-raid-monitoring' } $CacheTtl = 60 # seconds, tool output $HwTtl = 300 # seconds, detected controller type if (-not (Test-Path -LiteralPath $CacheDir)) { New-Item -ItemType Directory -Path $CacheDir -Force | Out-Null } # RAID tools write storcli.log / MegaSAS.log to the current folder: keep them here Set-Location -LiteralPath $CacheDir $ToolDirs = @( 'C:\Scripts\MegaRaid', 'C:\Scripts\StorCLI', 'C:\Scripts\PercCLI', "$env:ProgramFiles\MegaRAID\storcli", "$env:ProgramFiles\Broadcom\storcli", "$env:ProgramFiles\LSI\storcli", 'C:\storcli', 'C:\Tools\storcli', 'C:\Tools', "$env:ProgramFiles\Dell\PERCCLI", "${env:ProgramFiles(x86)}\Dell\PERCCLI", 'C:\perccli', "$env:ProgramFiles\MegaRAID\MegaCli", "${env:ProgramFiles(x86)}\MegaRAID Storage Manager", "$env:ProgramFiles\MegaRAID Storage Manager", 'C:\MegaCli', "$env:ProgramFiles\Smart Storage Administrator\ssacli\bin", "$env:ProgramFiles\HP\hpssacli\bin", "$env:ProgramFiles\Adaptec\maxView Storage Manager\cli", "$env:ProgramFiles\Adaptec\RemoteArcconf" ) $tdFile = Join-Path $CacheDir 'tooldirs.txt' # written by the installer when tools live elsewhere if (Test-Path -LiteralPath $tdFile) { $ToolDirs = @(Get-Content -LiteralPath $tdFile | Where-Object { $_.Trim() }) + $ToolDirs } if ($env:ZBX_RAID_TOOLDIR) { $ToolDirs = @($env:ZBX_RAID_TOOLDIR) + $ToolDirs } # ------------------------------------------------------------------ helpers function Out-Val($v) { if ($v -is [double] -or $v -is [single] -or $v -is [decimal]) { [string]::Format($Inv, '{0}', $v) } else { "$v" } } function Test-Fresh([string]$File, [int]$Ttl) { if (-not (Test-Path -LiteralPath $File)) { return $false } $i = Get-Item -LiteralPath $File return ($i.Length -gt 0 -and ((Get-Date) - $i.LastWriteTime).TotalSeconds -lt $Ttl) } # One tool run at a time (MegaCLI/StorCLI misbehave when several copies query the controller) function Enter-RaidLock { $m = New-Object System.Threading.Mutex($false, 'Global\ZabbixRaidMonitor') try { [void]$m.WaitOne(25000) } catch [System.Threading.AbandonedMutexException] { } return $m } function Exit-RaidLock($m) { try { $m.ReleaseMutex() } catch { }; $m.Dispose() } function Invoke-Cached([string]$Name, [string]$Exe, [string[]]$ArgList) { $f = Join-Path $CacheDir $Name if (Test-Fresh $f $CacheTtl) { return [IO.File]::ReadAllText($f) } $m = Enter-RaidLock try { if (Test-Fresh $f $CacheTtl) { return [IO.File]::ReadAllText($f) } $out = (& $Exe @ArgList 2>$null | Out-String) if ($out -and $out.Trim()) { [IO.File]::WriteAllText($f, $out); return $out } if (Test-Path -LiteralPath $f) { return [IO.File]::ReadAllText($f) } # last good copy return '' } finally { Exit-RaidLock $m } } # Cache any PowerShell result as JSON (Storage Spaces cmdlets are slow) function Get-CachedObject([string]$Name, [scriptblock]$Build, [int]$Ttl = $CacheTtl) { $f = Join-Path $CacheDir $Name if (Test-Fresh $f $Ttl) { try { return ([IO.File]::ReadAllText($f) | ConvertFrom-Json) } catch { } } $o = & $Build try { [IO.File]::WriteAllText($f, (ConvertTo-Json -InputObject $o -Depth 5 -Compress)) } catch { } return $o } function Find-Tool([string[]]$Names) { foreach ($n in $Names) { foreach ($d in $ToolDirs) { if ($d) { $p = Join-Path $d $n; if (Test-Path -LiteralPath $p) { return $p } } } $c = Get-Command $n -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if ($c) { return $c.Path } } return $null } function Find-StorCli { Find-Tool @('storcli64.exe', 'storcli.exe') } function Find-PercCli { Find-Tool @('perccli64.exe', 'perccli.exe') } function Find-MegaCli { Find-Tool @('MegaCli64.exe', 'MegaCli.exe') } function Find-SsaCli { Find-Tool @('ssacli.exe', 'hpssacli.exe') } function Find-ArcConf { Find-Tool @('arcconf.exe') } function Get-Int($v) { $s = [regex]::Match([string]$v, '\d+').Value; if ($s) { [int64]$s } else { 0 } } function New-Metrics([string]$Type) { @{ type = $Type; status = 0; details = ''; array_count = 0; disk_total = 0; disk_failed = 0; disk_rebuild = 0; rebuild_progress = 0 } } # ------------------------------------------------------------------ detection function Get-CtlCount([string]$Exe) { $t = (& $Exe 'show' 2>$null | Out-String) if ($t -match 'Number of Controllers\s*=\s*(\d+)') { return [int]$Matches[1] } return 0 } function Get-HwTypeUncached { $c = Find-StorCli; if ($c -and (Get-CtlCount $c) -gt 0) { return 'STORCLI' } $c = Find-PercCli; if ($c -and (Get-CtlCount $c) -gt 0) { return 'PERCCLI' } $c = Find-MegaCli if ($c) { $t = (& $c '-LDInfo' '-Lall' '-aALL' '-NoLog' 2>$null | Out-String) if ($t -match '(?m)^\s*Adapter\s+\d+|^\s*Virtual (Drive|Disk):') { return 'MEGACLI' } } if (Find-SsaCli) { return 'SSACLI' } if (Find-ArcConf) { return 'ARCCONF' } # no tool can read the controller, but Windows itself sees a RAID volume if ((Get-Command Get-PhysicalDisk -ErrorAction SilentlyContinue) -and @(Get-PhysicalDisk -ErrorAction SilentlyContinue | Where-Object { [string]$_.BusType -eq 'RAID' }).Count) { return 'WINRAID' } # a RAID card without its tool? (Get-CimInstance needs PS 3+, older systems have Get-WmiObject) $ctl = $null try { if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) { $ctl = @(Get-CimInstance Win32_SCSIController -ErrorAction Stop) } elseif (Get-Command Get-WmiObject -ErrorAction SilentlyContinue) { $ctl = @(Get-WmiObject Win32_SCSIController -ErrorAction Stop) } } catch { $ctl = $null } if (@($ctl | Where-Object { $_.Name -match 'MegaRAID|PERC|LSI.*RAID|Broadcom.*RAID|Avago.*RAID' }).Count) { return 'MEGARAID_NOCLI' } return 'NONE' } function Get-HwType { $f = Join-Path $CacheDir 'hwtype.txt' if (Test-Fresh $f $HwTtl) { return ([IO.File]::ReadAllText($f)).Trim() } $m = Enter-RaidLock try { if (Test-Fresh $f $HwTtl) { return ([IO.File]::ReadAllText($f)).Trim() } $t = Get-HwTypeUncached # never cache "no usable tool" while a RAID tool is installed (likely a one-off failure) if (($t -eq 'NONE' -or $t -eq 'MEGARAID_NOCLI') -and ((Find-StorCli) -or (Find-PercCli) -or (Find-MegaCli))) { return $t } [IO.File]::WriteAllText($f, $t) return $t } finally { Exit-RaidLock $m } } # ------------------------------------------------------------------ Storage Spaces # Does this server use Storage Spaces? Checked every 5 minutes only: loading the Storage # module costs a second or more, and the disk layout does not change between polls. function Test-StorageSpaces { $n = Get-CachedObject 'ss-count.json' { if (Get-Command Get-VirtualDisk -ErrorAction SilentlyContinue) { @(Get-VirtualDisk -ErrorAction SilentlyContinue).Count } else { 0 } } $HwTtl return ([int]$n -gt 0) } function Get-SSMetrics { Get-CachedObject 'ss-metrics.json' { $m = New-Metrics 'STORAGESPACES' $vds = @(Get-VirtualDisk -ErrorAction SilentlyContinue) $pds = @(Get-StoragePool -IsPrimordial $false -ErrorAction SilentlyContinue | Get-PhysicalDisk -ErrorAction SilentlyContinue) $m.array_count = $vds.Count $m.disk_total = $pds.Count $st = 0; $parts = @() foreach ($v in $vds) { $os = (@($v.OperationalStatus) -join ','); $hs = [string]$v.HealthStatus if ($hs -eq 'Unhealthy' -or $os -match 'Detached|Lost Communication|No Redundancy|Stale Metadata') { $st = 3 } elseif ($os -match 'In ?Service') { if ($st -eq 0) { $st = 2 }; $m.disk_rebuild++ } elseif ($hs -eq 'Warning' -or $os -match 'Degraded|Incomplete|Not Available') { if ($st -ne 3) { $st = 1 } } $parts += ("'{0}' {1} {2}/{3} {4} TB" -f $v.FriendlyName, $v.ResiliencySettingName, $os, $hs, [math]::Round($v.Size / 1TB, 2)) } $failed = @($pds | Where-Object { [string]$_.HealthStatus -eq 'Unhealthy' -or ((@($_.OperationalStatus) -join ',') -match 'Lost Communication|Failed|Removing|Split') }).Count $m.disk_failed = $failed if ($failed -gt 0) { $st = 3 } $jobs = @(Get-StorageJob -ErrorAction SilentlyContinue | Where-Object { [string]$_.JobState -eq 'Running' }) if ($jobs.Count -gt 0) { if ($m.disk_rebuild -eq 0) { $m.disk_rebuild = 1 } if ($st -eq 0) { $st = 2 } $m.rebuild_progress = ($jobs | Measure-Object -Property PercentComplete -Minimum).Minimum } $m.status = $st $m.details = "StorageSpaces: " + ($(if ($parts) { $parts -join '; ' } else { 'no virtual disks' })) + "; physical=$($pds.Count) failed=$failed" $m } } function Get-SSDisks { Get-CachedObject 'ss-disks.json' { @(Get-StoragePool -IsPrimordial $false -ErrorAction SilentlyContinue | Get-PhysicalDisk -ErrorAction SilentlyContinue | ForEach-Object { $rc = $_ | Get-StorageReliabilityCounter -ErrorAction SilentlyContinue $hs = [string]$_.HealthStatus; $os = (@($_.OperationalStatus) -join ',') $health = if ($hs -eq 'Unhealthy' -or $os -match 'Lost Communication|Failed') { 'Failed' } elseif ($os -match 'In Maintenance|Starting|Updating') { 'Rebuilding' } elseif ($hs -eq 'Warning') { 'Online, Warning' } else { 'Online' } [pscustomobject]@{ Id = [string]$_.DeviceId; Serial = ([string]$_.SerialNumber).Trim(); Model = ([string]$_.FriendlyName).Trim() Type = ('{0} {1}' -f $_.BusType, $_.MediaType); Size = ('{0} TB' -f [math]::Round($_.Size / 1TB, 2)) Health = $health; Temp = [int]$rc.Temperature; Poh = [int64]$rc.PowerOnHours Media = [int64]$rc.ReadErrorsUncorrected; Other = [int64]$rc.WriteErrorsUncorrected Predictive = $(if ($hs -eq 'Warning') { 1 } else { 0 }) } }) } } # ------------------------------------------------------------------ StorCLI / PercCLI (JSON) # JSON output ("... J"). Older PercCLI/StorCLI builds do not support it: that is remembered for # 5 minutes, so their J calls are skipped and the text output is used straight away. function Get-StorJson([string]$Name, [string[]]$ArgList) { $flag = Join-Path $CacheDir "$($script:Tag)-nojson.flag" if (Test-Fresh $flag $HwTtl) { return $null } $t = Invoke-Cached $Name $script:Cli $ArgList if (-not $t) { return $null } $s = $t.IndexOf('{') $j = $null if ($s -ge 0) { try { $j = ($t.Substring($s) | ConvertFrom-Json) } catch { $j = $null } } if (-not $j -or -not $j.Controllers) { [IO.File]::WriteAllText($flag, 'no json'); return $null } return $j } function Convert-StorState([string]$s) { switch ($s) { 'Onln' { 'Online, Spun Up' } 'Offln' { 'Offline' } 'Rbld' { 'Rebuilding' } 'UGood' { 'Unconfigured Good' } 'UBad' { 'Unconfigured Bad' } 'GHS' { 'Global Hot Spare' } 'DHS' { 'Dedicated Hot Spare' } 'Cpybck' { 'Copyback' } 'JBOD' { 'JBOD' } 'Msng' { 'Missing' } default { $s } } } function ConvertFrom-StorDrives($j) { if (-not $j) { return } foreach ($c in @($j.Controllers)) { $ctl = $c.'Command Status'.Controller $rd = $c.'Response Data' if (-not $rd) { continue } foreach ($d in @($rd.'Drive Information')) { if (-not $d) { continue } $es = ([string]$d.'EID:Slt').Split(':') $eid = $es[0].Trim(); $slt = $(if ($es.Count -gt 1) { $es[1].Trim() } else { '' }) if ($slt -eq '') { continue } if ($eid) { $id = "c${ctl}e${eid}s${slt}"; $path = "/c$ctl/e$eid/s$slt" } else { $id = "c${ctl}s${slt}"; $path = "/c$ctl/s$slt" } [pscustomobject]@{ Id = $id; Path = $path; Slot = $slt; Did = [string]$d.DID; State = [string]$d.State Size = [string]$d.Size; Intf = [string]$d.Intf; Med = [string]$d.Med; Model = ([string]$d.Model).Trim() } } } } # Text output (older PercCLI/StorCLI builds without JSON). Table rows look like: # 252:0 8 Onln 0 1.818 TB SATA HDD N N 512B ST2000NM001A-2J2101 U - # 0/0 RAID5 Dgrd RW Yes RWBD - ON 27.285 TB VD0 function ConvertFrom-StorDriveText([string]$t, [string]$ctl) { if (-not $ctl) { $ctl = '0' } foreach ($line in ($t -split "`r?`n")) { if ($line -match '^\s*Controller\s*=\s*(\d+)') { $ctl = $Matches[1]; continue } if ($line -notmatch '^\s*(\d*):(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\d+(?:\.\d+)?)\s+(\S+)\s+(\S+)\s+(\S+)(.*)$') { continue } $eid = $Matches[1]; $slt = $Matches[2]; $did = $Matches[3]; $state = $Matches[4] $size = "$($Matches[6]) $($Matches[7])"; $intf = $Matches[8]; $med = $Matches[9] $rest = @(($Matches[10].Trim()) -split '\s+') # SED PI SeSz Model... Sp Type $model = $(if ($rest.Count -gt 5) { ($rest[3..($rest.Count - 3)] -join ' ') } else { '' }) if ($eid) { $id = "c${ctl}e${eid}s${slt}"; $path = "/c$ctl/e$eid/s$slt" } else { $id = "c${ctl}s${slt}"; $path = "/c$ctl/s$slt" } [pscustomobject]@{ Id = $id; Path = $path; Slot = $slt; Did = $did; State = $state; Size = $size; Intf = $intf; Med = $med; Model = $model } } } function Get-StorDrives { $list = @(ConvertFrom-StorDrives (Get-StorJson "$($script:Tag)-pd.json" @('/call/eall/sall', 'show', 'J'))) if ($list.Count -eq 0) { $list = @(ConvertFrom-StorDrives (Get-StorJson "$($script:Tag)-pd2.json" @('/call/sall', 'show', 'J'))) } if ($list.Count -eq 0) { $list = @(ConvertFrom-StorDriveText (Invoke-Cached "$($script:Tag)-pd.txt" $script:Cli @('/call/eall/sall', 'show')) '0') } if ($list.Count -eq 0) { $list = @(ConvertFrom-StorDriveText (Invoke-Cached "$($script:Tag)-pd2.txt" $script:Cli @('/call/sall', 'show')) '0') } return $list } function Get-StorVDs { $out = @() $j = Get-StorJson "$($script:Tag)-vd.json" @('/call/vall', 'show', 'J') if ($j) { foreach ($c in @($j.Controllers)) { foreach ($v in @($c.'Response Data'.'Virtual Drives')) { if ($v) { $out += $v } } } } if ($out.Count -eq 0) { $t = Invoke-Cached "$($script:Tag)-vd.txt" $script:Cli @('/call/vall', 'show') foreach ($line in ($t -split "`r?`n")) { if ($line -match '^\s*(\d+/\d+)\s+(RAID\d+|JBOD|Cac\S*)\s+(\S+)') { $sz = [regex]::Match($line, '(\d+(?:\.\d+)?)\s+(KB|MB|GB|TB|PB)') $out += [pscustomobject]@{ 'DG/VD' = $Matches[1]; TYPE = $Matches[2]; State = $Matches[3]; Size = $(if ($sz.Success) { "$($sz.Groups[1].Value) $($sz.Groups[2].Value)" } else { '' }) } } } } return $out } # all leaf properties of a nested JSON object, flattened by name function Get-Flat($o, [hashtable]$h = @{}, [int]$depth = 0) { if ($null -eq $o -or $depth -gt 5) { return $h } foreach ($p in $o.PSObject.Properties) { $v = $p.Value if ($v -is [System.Management.Automation.PSCustomObject]) { [void](Get-Flat $v $h ($depth + 1)) } elseif ($v -is [array]) { foreach ($x in $v) { if ($x -is [System.Management.Automation.PSCustomObject]) { [void](Get-Flat $x $h ($depth + 1)) } } } elseif (-not $h.ContainsKey($p.Name)) { $h[$p.Name] = $v } } return $h } # Details of ALL disks with one call (a call takes seconds on Windows; per disk it would not # fit in the item timeout). Result: disk id (c0e32s0) -> flat hashtable of its fields. function Get-StorAllDetails { if ($script:AllDetails) { return $script:AllDetails } $all = @{} $idOf = { param($n) if ($n -match '/c(\d+)/e(\d+)/s(\d+)') { "c$($Matches[1])e$($Matches[2])s$($Matches[3])" } elseif ($n -match '/c(\d+)/s(\d+)') { "c$($Matches[1])s$($Matches[2])" } else { $null } } foreach ($q in @(@('/call/eall/sall', 'show', 'all', 'J'), @('/call/sall', 'show', 'all', 'J'))) { $j = Get-StorJson "$($script:Tag)-alldetail-$($q[0].Replace('/','_')).json" $q if (-not $j) { break } foreach ($c in @($j.Controllers)) { $rd = $c.'Response Data'; if (-not $rd) { continue } foreach ($p in $rd.PSObject.Properties) { $id = & $idOf $p.Name; if (-not $id) { continue } if (-not $all.ContainsKey($id)) { $all[$id] = @{} } [void](Get-Flat $p.Value $all[$id]) } } if ($all.Count) { break } } if ($all.Count -eq 0) { # text: sections start with "Drive /c0/e32/s0 State :" etc., then "Key = Value" lines foreach ($q in @(@('/call/eall/sall', 'show', 'all'), @('/call/sall', 'show', 'all'))) { $t = Invoke-Cached "$($script:Tag)-alldetail-$($q[0].Replace('/','_')).txt" $script:Cli $q $cur = $null foreach ($line in ($t -split "`r?`n")) { if ($line -match '^\s*Drive\s+(/c\S+)') { $cur = & $idOf $Matches[1]; if ($cur -and -not $all.ContainsKey($cur)) { $all[$cur] = @{} }; continue } if ($cur -and $line -match '^\s*([^=]+?)\s*=\s*(.*)$' -and -not $all[$cur].ContainsKey($Matches[1])) { $all[$cur][$Matches[1]] = $Matches[2].Trim() } } if ($all.Count) { break } } } $script:AllDetails = $all return $all } function Get-StorDetail($drive) { $all = Get-StorAllDetails if ($all.ContainsKey($drive.Id)) { return $all[$drive.Id] } return @{} } function Get-StorRebuild($drive) { $j = Get-StorJson "$($script:Tag)-$($drive.Id)-rb.json" @($drive.Path, 'show', 'rebuild', 'J') if (-not $j) { return 0 } foreach ($r in @($j.Controllers[0].'Response Data')) { foreach ($p in $r.PSObject.Properties) { if ($p.Name -match 'Progress' -and ([string]$p.Value) -match '^\s*\d') { return (Get-Int $p.Value) } } } return 0 } $BadPd = @('Offln', 'UBad', 'Failed', 'Msng', 'Missing', 'Flt') $RbldPd = @('Rbld', 'Rebuild', 'Recon', 'Cpybck') function Get-StorMetrics { $m = New-Metrics $script:HwKind $vds = @(Get-StorVDs); $pds = @(Get-StorDrives) if ($vds.Count -eq 0 -and $pds.Count -eq 0) { $m.status = 4; $m.details = "$($script:HwKind) detected but controller output is unavailable"; return $m } $m.array_count = $vds.Count $m.disk_total = $pds.Count $m.disk_failed = @($pds | Where-Object { $BadPd -contains $_.State }).Count $rb = @($pds | Where-Object { $RbldPd -contains $_.State }) $m.disk_rebuild = $rb.Count # status describes the ARRAY: FAILED only when a virtual drive is offline/failed, # a failed disk in a working (redundant) array = degraded $vdBad = @($vds | Where-Object { @('OfLn', 'Offln', 'Offline', 'Failed') -contains [string]$_.State }).Count $vdDgrd = @($vds | Where-Object { @('Dgrd', 'Pdgd', 'Degraded') -contains [string]$_.State }).Count if ($vdBad) { $st = 3 } elseif ($m.disk_rebuild -gt 0) { $st = 2 } elseif ($vdDgrd -or $m.disk_failed -gt 0) { $st = 1 } else { $st = 0 } $m.status = $st if ($rb.Count) { $m.rebuild_progress = (@($rb | ForEach-Object { Get-StorRebuild $_ }) | Measure-Object -Minimum).Minimum } $vtxt = @($vds | ForEach-Object { 'VD{0} {1} {2} {3}' -f ([string]$_.'DG/VD').Split('/')[-1], $_.TYPE, $_.State, $_.Size }) -join ', ' $m.details = "$($script:HwKind): $vtxt; arrays=$($m.array_count); physical=$($m.disk_total); failed=$($m.disk_failed); rebuilding=$($m.disk_rebuild)" if ($rb.Count) { $m.details += "; progress=$($m.rebuild_progress)%" } return $m } # ------------------------------------------------------------------ MegaCLI (text) function Get-MegaLd { Invoke-Cached 'megacli-ldinfo.txt' $script:Cli @('-LDInfo', '-Lall', '-aALL', '-NoLog') } function Get-MegaPd { Invoke-Cached 'megacli-pdlist.txt' $script:Cli @('-PDList', '-aALL', '-NoLog') } function Get-MegaRecords { $pd = Get-MegaPd $out = @() foreach ($r in ($pd -split 'Enclosure Device ID:')) { if ($r -match '(?m)^\s*Slot Number:\s*(\d+)') { $slot = $Matches[1] $f = @{} foreach ($line in ($r -split "`r?`n")) { if ($line -match '^\s*([^:]+?)\s*:\s*(.*)$' -and -not $f.ContainsKey($Matches[1])) { $f[$Matches[1]] = $Matches[2].Trim() } } $out += [pscustomobject]@{ Slot = $slot; F = $f } } } return $out } # Serial and model out of MegaCLI "Inquiry Data" (vendors glue them together differently) function Split-Inquiry([string]$inq) { $inq = $inq.Trim(); $t = @($inq -split '\s+') $vend = 'SEAGATE|HGST|HITACHI|WDC|TOSHIBA|IBM|DELL|HP|HPE|LENOVO' $tokRe = '(SSDSC[0-9A-Z-]+|MZ[0-9A-Z-]+|THNS[0-9A-Z-]+|MTFD[0-9A-Z-]+|HFS[0-9A-Z-]+|HUH[0-9A-Z-]+|HUS[0-9A-Z-]+|ST[0-9]{3,5}[A-Z]{2}[0-9A-Z]*(-[0-9A-Z]+)?|WD[0-9]{2,}[A-Z0-9-]+)' if ($inq -cmatch '^HGST\s+(HUH[0-9A-Z-]+)\s+([0-9A-Z-]+)') { return @{ Serial = $Matches[2]; Model = "HGST $($Matches[1])" } } if ($inq -cmatch "^($vend)\s+(\S+)\s+(\S+)") { $sn = $Matches[3]; if ($Matches[1] -eq 'SEAGATE' -and $sn.Length -eq 12) { $sn = $sn.Substring(4) } return @{ Serial = $sn; Model = "$($Matches[1]) $($Matches[2])" } } if ($inq -match '\sSamsung\s+SSD\s') { $model = ($t[1..($t.Count - 2)] -join ' ') -replace '^Samsung ', 'SAMSUNG ' return @{ Serial = $t[0]; Model = $model } } $first = $t[0]; $model = '' $tok = [regex]::Match($inq, $tokRe).Value if ($tok -and $first.Contains($tok)) { $first = $first.Substring(0, $first.IndexOf($tok)) } foreach ($v in 'INTEL', 'SAMSUNG', 'TOSHIBA', 'KIOXIA', 'MICRON', 'SKHYNIX', 'HYNIX') { if ($first.EndsWith($v)) { $first = $first.Substring(0, $first.Length - $v.Length) } } switch -regex -casesensitive ($tok) { '^ST\d' { $model = "SEAGATE $tok" } '^WD\d' { $model = "WDC $tok" } '^HU[SH]' { $model = "HGST $tok" } '^SSDSC' { $model = "INTEL $tok" } '^MZ' { $model = "SAMSUNG $tok" } '^THNS' { $model = "TOSHIBA $tok" } '^MTFD' { $model = "MICRON $tok" } '^HFS' { $model = "SK HYNIX $tok" } } if (-not $model) { if ($t.Count -ge 4) { $model = $t[1..($t.Count - 2)] -join ' ' } elseif ($t.Count -ge 2) { $model = $t[1..($t.Count - 1)] -join ' ' } } return @{ Serial = $first; Model = $model } } function Get-MegaMetrics { $m = New-Metrics 'MEGACLI' $ld = Get-MegaLd; $pd = Get-MegaPd if (-not $ld -and -not $pd) { $m.status = 4; $m.details = 'MegaCLI detected but controller health output is unavailable'; return $m } $recs = @(Get-MegaRecords) $m.array_count = ([regex]::Matches($ld, '(?m)^\s*Virtual Drive:')).Count $m.disk_total = $recs.Count $m.disk_failed = @($recs | Where-Object { $_.F['Firmware state'] -match 'failed|offline|unconfigured\(bad\)|missing' }).Count $pred = 0; $media = 0; $other = 0 foreach ($r in $recs) { $pred += Get-Int $r.F['Predictive Failure Count']; $media += Get-Int $r.F['Media Error Count']; $other += Get-Int $r.F['Other Error Count'] } $m.disk_rebuild = @($recs | Where-Object { $_.F['Firmware state'] -match 'Rebuild' }).Count if ($m.disk_rebuild -gt 0) { $rb = (& $script:Cli '-PDRbld' '-ShowProg' '-PhysDrv' '[ALL:ALL]' '-aALL' '-NoLog' 2>$null | Out-String) $p = [regex]::Match($rb, '(\d+(\.\d+)?)\s*%'); if ($p.Success) { $m.rebuild_progress = [double]::Parse($p.Groups[1].Value, $Inv) } } # status describes the ARRAY (see Get-StorMetrics) if ($ld -match '(?m)^\s*State\s*:\s*(Offline|Failed)') { $st = 3 } elseif ($m.disk_rebuild -gt 0) { $st = 2 } elseif ($ld -match '(?m)^\s*State\s*:\s*(Degraded|Partially Degraded)' -or $m.disk_failed -gt 0 -or $pred -gt 0) { $st = 1 } else { $st = 0 } $m.status = $st $state = [regex]::Match($ld, '(?m)^\s*State\s*:\s*(.+)$').Groups[1].Value.Trim() $size = [regex]::Match($ld, '(?m)^\s*Size\s*:\s*(.+)$').Groups[1].Value.Trim() $m.details = "MegaRAID: arrays=$($m.array_count) state=$state size=$size; physical=$($m.disk_total) failed=$($m.disk_failed) predictive=$pred media_errors=$media other_errors=$other" if ($m.disk_rebuild -gt 0) { $m.details += "; rebuild=$($m.disk_rebuild) progress=$($m.rebuild_progress)%" } return $m } # ------------------------------------------------------------------ ssacli / arcconf (summary only) function Get-SsaMetrics { $m = New-Metrics 'SSACLI' $o = Invoke-Cached 'ssacli.txt' $script:Cli @('ctrl', 'all', 'show', 'config', 'detail') if (-not $o) { $m.status = 4; $m.details = 'SSACLI detected but no output'; return $m } $m.array_count = ([regex]::Matches($o, '(?mi)^\s*array [A-Za-z0-9]+')).Count $m.disk_total = ([regex]::Matches($o, '(?i)physicaldrive ')).Count $m.disk_failed = ([regex]::Matches($o, '(?i)physicaldrive .*\((Failed|Predictive Failure|Offline)')).Count if ($o -match '(?i)Degraded|Recovering') { $m.status = 1 } if ($o -match '(?i)Failed|Predictive Failure|Offline') { $m.status = 3 } if ($o -match '(?i)Rebuilding|Recovering|Transforming') { $m.disk_rebuild = 1; if ($m.status -eq 0) { $m.status = 2 } } $p = [regex]::Match($o, '(?i)(Rebuild|Recover|Transform)[^%]*?(\d+(\.\d+)?)%'); if ($p.Success) { $m.rebuild_progress = [double]::Parse($p.Groups[2].Value, $Inv) } $m.details = 'SSACLI: ' + ((@($o -split "`r?`n" | Where-Object { $_ -match '(?i)Smart Array|Controller Status|logicaldrive |physicaldrive .*\(' } | Select-Object -First 12) | ForEach-Object { $_.Trim() }) -join '; ') return $m } function Get-ArcMetrics { $m = New-Metrics 'ARCCONF' $o = Invoke-Cached 'arcconf.txt' $script:Cli @('GETCONFIG', '1', 'AL') if (-not $o) { $m.status = 4; $m.details = 'ARCCONF detected but no output'; return $m } $m.array_count = ([regex]::Matches($o, 'Logical device number')).Count $m.disk_total = ([regex]::Matches($o, 'Device #\d+')).Count $m.disk_failed = ([regex]::Matches($o, '(?i)State\s*:\s*(Failed|Offline)')).Count if ($o -match '(?i)Status of logical device\s*:\s*(Degraded|Impacted)') { $m.status = 1 } if ($o -match '(?i)Status of logical device\s*:\s*(Failed|Offline)') { $m.status = 3 } if ($o -match '(?i)Rebuild|Rebuilding|Migrating') { $m.disk_rebuild = 1; if ($m.status -eq 0) { $m.status = 2 } } $m.details = 'ARCCONF: ' + ((@($o -split "`r?`n" | Where-Object { $_ -match '(?i)Controller Status|Logical device number|Status of logical device|State\s*:' } | Select-Object -First 12) | ForEach-Object { $_.Trim() }) -join '; ') return $m } # ------------------------------------------------------------------ Windows view of a RAID volume # Used when no CLI can read the controller: Windows only knows the volume's health, # not the individual disks behind the controller. function Get-WinRaidMetrics { $m = New-Metrics 'WINRAID' $vols = @(Get-PhysicalDisk -ErrorAction SilentlyContinue | Where-Object { [string]$_.BusType -eq 'RAID' }) $m.array_count = $vols.Count $st = 0; $parts = @() foreach ($v in $vols) { $hs = [string]$v.HealthStatus; $os = (@($v.OperationalStatus) -join ',') if ($hs -eq 'Unhealthy' -or $os -match 'Lost Communication|Failed|No Media') { $st = 3 } elseif (($hs -ne 'Healthy' -or $os -ne 'OK') -and $st -lt 3) { $st = 1 } $parts += ("{0} Health={1} Status={2} {3} TB" -f $v.FriendlyName, $hs, $os, [math]::Round($v.Size / 1TB, 2)) } $m.status = $st $m.details = 'Windows RAID volume (no controller CLI): ' + ($parts -join '; ') return $m } # ------------------------------------------------------------------ one implementation function Get-HwMetrics([string]$hw) { switch ($hw) { 'STORCLI' { $script:Cli = Find-StorCli; $script:Tag = 'storcli'; $script:HwKind = 'STORCLI'; return (Get-StorMetrics) } 'PERCCLI' { $script:Cli = Find-PercCli; $script:Tag = 'perccli'; $script:HwKind = 'PERCCLI'; return (Get-StorMetrics) } 'MEGACLI' { $script:Cli = Find-MegaCli; return (Get-MegaMetrics) } 'SSACLI' { $script:Cli = Find-SsaCli; return (Get-SsaMetrics) } 'ARCCONF' { $script:Cli = Find-ArcConf; return (Get-ArcMetrics) } 'WINRAID' { return (Get-WinRaidMetrics) } 'MEGARAID_NOCLI' { $m = New-Metrics 'MEGARAID'; $m.status = 4; $m.details = 'Broadcom/LSI MegaRAID controller detected, but StorCLI/PercCLI/MegaCLI is not installed'; return $m } default { $m = New-Metrics 'NONE'; $m.status = 5; $m.details = 'No supported Windows RAID implementation detected'; return $m } } } # Worst first: 3 failed > 1 degraded > 2 rebuilding > 4 unreadable > 0 OK; 5 only if all say 5 function Get-WorstStatus([int[]]$s) { $rank = @{ 3 = 5; 1 = 4; 2 = 3; 4 = 2; 0 = 1 } $best = -1; $r = 5 foreach ($v in $s) { $k = $(if ($rank.ContainsKey($v)) { $rank[$v] } else { 0 }); if ($k -gt $best) { $best = $k; $r = $v } } if ($best -le 0) { $r = 5 } return $r } # ------------------------------------------------------------------ per-disk function Invoke-DiskMode([string]$hw, [bool]$ss) { $num = 'disk_power_on_hours', 'disk_temp', 'disk_media_errors', 'disk_other_errors', 'disk_predictive', 'disk_rebuild_progress' if ($hw -eq 'STORCLI' -or $hw -eq 'PERCCLI') { $script:Cli = $(if ($hw -eq 'STORCLI') { Find-StorCli } else { Find-PercCli }); $script:Tag = $hw.ToLower(); $script:HwKind = $hw $drives = @(Get-StorDrives) if ($Mode -eq 'disk_discovery') { $items = foreach ($d in $drives) { $x = Get-StorDetail $d [ordered]@{ '{#SLOT}' = $d.Id; '{#PHYSLOT}' = $d.Slot; '{#DISKNO}' = [string]([int]$d.Slot + 1); '{#DEVICEID}' = $d.Did '{#SERIAL}' = ([string]$x['SN']).Trim(); '{#MODEL}' = $(if ($x['Model Number']) { ([string]$x['Model Number']).Trim() } else { $d.Model }) '{#HEALTH}' = (Convert-StorState $d.State); '{#TEMP}' = [string](Get-Int $x['Drive Temperature']) } } return (ConvertTo-LldJson $items) } $d = $drives | Where-Object { $_.Id -eq $Arg } | Select-Object -First 1 if (-not $d) { if ($num -contains $Mode) { return 0 } else { return '' } } $x = Get-StorDetail $d switch ($Mode) { 'disk_serial' { return ([string]$x['SN']).Trim() } 'disk_model' { if ($x['Model Number']) { return ([string]$x['Model Number']).Trim() } else { return $d.Model } } 'disk_type' { return ("$($d.Intf) $($d.Med)").Trim() } 'disk_size' { if ($d.Size) { return $d.Size } else { return [string]$x['Raw size'] } } 'disk_health' { return (Convert-StorState $d.State) } 'disk_power_on_hours' { return 0 } # not readable through the controller on Windows 'disk_temp' { return (Get-Int $x['Drive Temperature']) } 'disk_media_errors' { return (Get-Int $x['Media Error Count']) } 'disk_other_errors' { return (Get-Int $x['Other Error Count']) } 'disk_predictive' { return (Get-Int $x['Predictive Failure Count']) } 'disk_rebuild_progress' { if ($RbldPd -contains $d.State) { return (Get-StorRebuild $d) } else { return 0 } } } } elseif ($hw -eq 'MEGACLI') { $script:Cli = Find-MegaCli $recs = @(Get-MegaRecords) if ($Mode -eq 'disk_discovery') { $items = foreach ($r in $recs) { $s = Split-Inquiry $r.F['Inquiry Data'] [ordered]@{ '{#SLOT}' = $r.Slot; '{#DEVICEID}' = [string]$r.F['Device Id']; '{#SERIAL}' = $s.Serial; '{#MODEL}' = $s.Model '{#HEALTH}' = [string]$r.F['Firmware state']; '{#TEMP}' = [string](Get-Int $r.F['Drive Temperature']) } } return (ConvertTo-LldJson $items) } $r = $recs | Where-Object { $_.Slot -eq $Arg } | Select-Object -First 1 if (-not $r) { if ($num -contains $Mode) { return 0 } else { return '' } } $s = Split-Inquiry $r.F['Inquiry Data'] switch ($Mode) { 'disk_serial' { return $s.Serial } 'disk_model' { return $s.Model } 'disk_type' { $med = [string]$r.F['Media Type'] $med = $(if ($med -match '(?i)solid state|^ssd$') { 'SSD' } elseif ($med -match '(?i)hard disk|^hdd$') { 'HDD' } else { $med }) return ("$($r.F['PD Type']) $med").Trim() } 'disk_size' { return (([string]$r.F['Raw Size']) -replace '\s*\[.*', '') } 'disk_health' { return [string]$r.F['Firmware state'] } 'disk_power_on_hours' { return 0 } 'disk_temp' { return (Get-Int (([regex]::Match([string]$r.F['Drive Temperature'], '\d+C')).Value)) } 'disk_media_errors' { return (Get-Int $r.F['Media Error Count']) } 'disk_other_errors' { return (Get-Int $r.F['Other Error Count']) } 'disk_predictive' { return (Get-Int $r.F['Predictive Failure Count']) } 'disk_rebuild_progress' { if ([string]$r.F['Firmware state'] -match '(?i)rebuild') { $rb = (& $script:Cli '-PDRbld' '-ShowProg' '-PhysDrv' '[ALL:ALL]' '-aALL' '-NoLog' 2>$null | Out-String) return (Get-Int ([regex]::Match($rb, '\d+(\.\d+)?\s*%').Value)) } return 0 } } } elseif ($ss) { $disks = @(Get-SSDisks) if ($Mode -eq 'disk_discovery') { $items = foreach ($d in $disks) { [ordered]@{ '{#SLOT}' = $d.Id; '{#DEVICEID}' = $d.Id; '{#SERIAL}' = $d.Serial; '{#MODEL}' = $d.Model; '{#HEALTH}' = $d.Health; '{#TEMP}' = [string]$d.Temp } } return (ConvertTo-LldJson $items) } $d = $disks | Where-Object { [string]$_.Id -eq $Arg } | Select-Object -First 1 if (-not $d) { if ($num -contains $Mode) { return 0 } else { return '' } } switch ($Mode) { 'disk_serial' { return $d.Serial } 'disk_model' { return $d.Model } 'disk_type' { return $d.Type } 'disk_size' { return $d.Size } 'disk_health' { return $d.Health } 'disk_power_on_hours' { return $d.Poh } 'disk_temp' { return $d.Temp } 'disk_media_errors' { return $d.Media } 'disk_other_errors' { return $d.Other } 'disk_predictive' { return $d.Predictive } 'disk_rebuild_progress' { return 0 } } } if ($Mode -eq 'disk_discovery') { return '[]' } if ($num -contains $Mode) { return 0 } return '' } function ConvertTo-LldJson($items) { $parts = @(foreach ($i in @($items)) { if ($i) { ConvertTo-Json -InputObject $i -Compress } }) return '[' + ($parts -join ',') + ']' } # ------------------------------------------------------------------ main $validAgg = 'type', 'status', 'details', 'array_count', 'disk_total', 'disk_failed', 'disk_rebuild', 'rebuild_progress' $validDisk = 'disk_discovery', 'disk_serial', 'disk_model', 'disk_type', 'disk_size', 'disk_health', 'disk_power_on_hours', 'disk_temp', 'disk_media_errors', 'disk_other_errors', 'disk_predictive', 'disk_rebuild_progress' if (($validAgg + $validDisk) -notcontains $Mode) { [Console]::Error.WriteLine("Unsupported mode: $Mode"); exit 1 } $hw = Get-HwType $ss = Test-StorageSpaces if ($validDisk -contains $Mode) { Write-Output (Out-Val (Invoke-DiskMode $hw $ss)); exit 0 } # raid.type needs only the detected implementation(s), not the array state if ($Mode -eq 'type') { $names = @() if ($ss) { $names += 'STORAGESPACES' } if ($hw -ne 'NONE' -or -not $ss) { $names += $(if ($hw -eq 'MEGARAID_NOCLI') { 'MEGARAID' } else { $hw }) } Write-Output ($names -join '+'); exit 0 } $parts = @() if ($ss) { $parts += ,(Get-SSMetrics) } if ($hw -ne 'NONE' -or -not $ss) { $parts += ,(Get-HwMetrics $hw) } $res = $null switch ($Mode) { 'type' { $res = (@($parts | ForEach-Object { $_.type }) -join '+') } 'status' { $res = Get-WorstStatus @($parts | ForEach-Object { [int]$_.status }) } 'details' { $res = (@($parts | ForEach-Object { $_.details }) -join ' | ') } 'rebuild_progress' { $rb = @($parts | Where-Object { [int]$_.disk_rebuild -gt 0 } | ForEach-Object { [double]$_.rebuild_progress }) $res = $(if ($rb.Count) { ($rb | Measure-Object -Minimum).Minimum } else { 0 }) } default { $res = (@($parts | ForEach-Object { [int64]$_.$Mode }) | Measure-Object -Sum).Sum; if ($null -eq $res) { $res = 0 } } } Write-Output (Out-Val $res) exit 0 '@ [IO.File]::WriteAllText($helper, $HelperCode, (New-Object Text.UTF8Encoding($true))) try { Unblock-File -LiteralPath $helper } catch { } Info "Helper : $helper" # cache folder: only SYSTEM and Administrators may write (it can hold a tool-folder list). # The rights are set on the FOLDER only; files inside inherit them. ("/T" on files would strip # them to no rights at all - older versions of this installer did that, so repair it first.) $cache = Join-Path $env:ProgramData 'zabbix-raid-monitoring' New-Item -ItemType Directory -Path $cache -Force | Out-Null & takeown.exe /F $cache /R /A /D Y 2>&1 | Out-Null & icacls.exe $cache /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' '*S-1-5-32-545:(OI)(CI)RX' /Q | Out-Null if (Get-ChildItem -LiteralPath $cache -Force -ErrorAction SilentlyContinue) { & icacls.exe "$cache\*" /reset /T /C /Q 2>&1 | Out-Null } Get-ChildItem -LiteralPath $cache -File -ErrorAction SilentlyContinue | Where-Object { $_.Name -ne 'tooldirs.txt' } | Remove-Item -Force -ErrorAction SilentlyContinue try { [IO.File]::WriteAllText((Join-Path $cache '.write-test'), 'x'); Remove-Item (Join-Path $cache '.write-test') -Force } catch { Fail "Cannot write to $cache even after resetting its permissions: $($_.Exception.Message)" } $tdFile = Join-Path $cache 'tooldirs.txt' if ($ToolDir) { if (-not (Test-Path -LiteralPath $ToolDir -PathType Container)) { Fail "ToolDir not found: $ToolDir" } Set-Content -LiteralPath $tdFile -Value $ToolDir -Encoding ASCII Info "Tool folder : $ToolDir" } # ============================================================ 3. UserParameters + Timeout $ps = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' $cmd = "`"$ps`" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$helper`"" $keys = [ordered]@{ 'raid.type' = 'type'; 'raid.status' = 'status'; 'raid.details' = 'details'; 'raid.array.count' = 'array_count' 'raid.disk.total' = 'disk_total'; 'raid.disk.failed' = 'disk_failed'; 'raid.disk.rebuild' = 'disk_rebuild' 'raid.rebuild.progress' = 'rebuild_progress'; 'raid.disk.discovery' = 'disk_discovery' } $diskKeys = [ordered]@{ 'raid.disk.serial' = 'disk_serial'; 'raid.disk.model' = 'disk_model'; 'raid.disk.type' = 'disk_type'; 'raid.disk.size' = 'disk_size' 'raid.disk.health' = 'disk_health'; 'raid.disk.power_on_hours' = 'disk_power_on_hours'; 'raid.disk.temp' = 'disk_temp' 'raid.disk.media_errors' = 'disk_media_errors'; 'raid.disk.other_errors' = 'disk_other_errors' 'raid.disk.predictive' = 'disk_predictive'; 'raid.disk.rebuild_progress' = 'disk_rebuild_progress' } $lines = @('# Windows RAID monitoring (Exabytes) - generated by install-zabbix-raid.ps1') foreach ($k in $keys.Keys) { $lines += "UserParameter=$k,$cmd $($keys[$k])" } foreach ($k in $diskKeys.Keys) { $lines += "UserParameter=$k[*],$cmd $($diskKeys[$k]) `"`$1`"" } $confFile = Join-Path $incDir 'raid-monitoring.conf' [IO.File]::WriteAllLines($confFile, [string[]]$lines, (New-Object Text.UTF8Encoding($false))) # no BOM: the agent reads it Info "Keys : $confFile" # Timeout=30 (PowerShell start + controller queries can exceed the default 3 s) $c = Get-Content -LiteralPath $conf if ($c | Where-Object { $_ -match '^\s*Timeout\s*=' }) { $c = $c | ForEach-Object { if ($_ -match '^\s*Timeout\s*=') { 'Timeout=30' } else { $_ } } [IO.File]::WriteAllLines($conf, [string[]]$c, (New-Object Text.UTF8Encoding($false))) } else { Add-Content -LiteralPath $conf -Value 'Timeout=30' -Encoding ASCII } # ============================================================ 4. tools not in the usual places? look once $type0 = (& $ps -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper type | Out-String).Trim() if (-not $ToolDir -and ($type0 -eq 'NONE' -or $type0 -eq 'MEGARAID')) { Info "No readable RAID tool in the usual folders ($type0); searching Program Files and C:\ (can take a minute)..." $found = @() foreach ($root in @($env:ProgramFiles, ${env:ProgramFiles(x86)}, 'C:\')) { if (-not $root -or -not (Test-Path -LiteralPath $root)) { continue } $depth = if ($root -eq 'C:\') { 2 } else { 4 } foreach ($n in 'storcli64.exe', 'perccli64.exe', 'MegaCli64.exe', 'ssacli.exe', 'arcconf.exe') { try { $found += Get-ChildItem -LiteralPath $root -Filter $n -Recurse -Depth $depth -File -ErrorAction SilentlyContinue | Select-Object -ExpandProperty DirectoryName } catch { } # -Depth needs PowerShell 5 } } $found = @($found | Select-Object -Unique) if ($found.Count) { try { Set-Content -LiteralPath $tdFile -Value $found -Encoding ASCII -ErrorAction Stop } catch { Fail "Found RAID tools but cannot save $tdFile : $($_.Exception.Message)" } Info ("Found RAID tools in: " + ($found -join '; ')) Remove-Item -LiteralPath (Join-Path $cache 'hwtype.txt') -Force -ErrorAction SilentlyContinue $type1 = (& $ps -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper type | Out-String).Trim() Info "RAID type now : $type1" } } # ============================================================ 5. validate, restart, test Info 'Validating Zabbix configuration...' $v = & $exe -c $conf -t agent.ping 2>&1 | Out-String if ($LASTEXITCODE -ne 0) { Say $v; Fail 'Zabbix agent configuration validation failed.' } Info 'Zabbix configuration validation OK.' function Restart-Agent { # RAID checks still running (or hung) keep the agent from stopping: end them first Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -match 'zabbix-raid-monitor\.ps1' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } try { Restart-Service -Name $svc.Name -Force -ErrorAction Stop } catch { Info "Service did not stop cleanly ($($_.Exception.Message)); ending the agent process." Stop-Process -Name ([IO.Path]::GetFileNameWithoutExtension($exe)) -Force -ErrorAction SilentlyContinue Start-Sleep -Seconds 2 Start-Service -Name $svc.Name -ErrorAction SilentlyContinue } for ($i = 0; $i -lt 20; $i++) { if ((Get-Service -Name $svc.Name).Status -eq 'Running') { return $true } Start-Sleep -Seconds 1 } return $false } if (-not (Restart-Agent)) { Fail "Service '$($svc.Name)' is not running after restart. Check the agent log: $agentDir\*.log" } Say '============================================================' Say ' Zabbix Windows RAID Monitoring Installed' Say ' Storage Spaces + StorCLI / PercCLI / MegaCLI / ssacli / arcconf + 30s cache' Say '============================================================' Say "Agent : $(if ($isAgent2) { 'agent2' } else { 'agentd' })" Say "Config : $conf" Say "Helper : $helper" Say "Keys : $confFile" Say '' # first run reads the controller with an empty cache (the slow part); time it, then test the keys $sw = [Diagnostics.Stopwatch]::StartNew() & $ps -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper status | Out-Null & $ps -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper disk_discovery | Out-Null Info ("Controller read (empty cache): {0:N1} s" -f $sw.Elapsed.TotalSeconds) $sw = [Diagnostics.Stopwatch]::StartNew() & $ps -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper status | Out-Null Info ("One poll from cache : {0:N1} s" -f $sw.Elapsed.TotalSeconds) Say '' foreach ($k in $keys.Keys) { & $exe -c $conf -t $k 2>&1 | Out-String | ForEach-Object { $_.TrimEnd() } } $disc = (& $ps -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper disk_discovery | Out-String).Trim() $first = $null try { $arr = ConvertFrom-Json -InputObject $disc; $first = @($arr)[0].'{#SLOT}' } catch { } if ($first) { Say '' Say "Example per-disk tests (first disk: $first):" foreach ($k in 'raid.disk.health', 'raid.disk.serial', 'raid.disk.model', 'raid.disk.type', 'raid.disk.temp') { & $exe -c $conf -t "$k[$first]" 2>&1 | Out-String | ForEach-Object { $_.TrimEnd() } } } Say '============================================================' Say 'Next: link "Template Linux RAID Universal" to this host (same keys as Linux),' Say 'then run "Execute now" on "RAID: Physical disk discovery".'