Skip to content

Commit 3c3609b

Browse files
authored
Merge pull request #612 from mcshooter/updateUptimeCMd
Update powershell command for uptime to help efficiency
2 parents 7a33650 + dd0d0d7 commit 3c3609b

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

pkg/healthchecker/health_checker_windows.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,19 @@ import (
3333
// getUptimeFunc returns the time for which the given service has been running.
3434
func getUptimeFunc(service string) func() (time.Duration, error) {
3535
return func() (time.Duration, error) {
36-
// Using the WinEvent Log Objects to find the Service logs' time when the Service last entered running state.
36+
// To attempt to calculate uptime more efficiently, we attempt to grab the process id to grab the start time.
37+
// If the process id does not exist (meaning the service is not running for some reason), we will result to
38+
// using the WinEvent Log Objects to find the Service logs' time when the Service last entered running state.
39+
// In addition to filtering not by the logname=system we also filter on event id=7036 to reduce the number of
40+
// entries the next command Where-Object will have to look through. id 7036 messages indicating a stopped or running service.
3741
// The powershell command formats the TimeCreated of the event log in RFC1123Pattern.
3842
// However, because the time library parser does not recognize the ',' in this RFC1123Pattern format,
3943
// it is manually removed before parsing it using the UptimeTimeLayout.
40-
getTimeCreatedCmd := "(Get-WinEvent -Logname System | Where-Object {$_.Message -Match '.*(" + service +
41-
").*(running).*'} | Select-Object -Property TimeCreated -First 1 | foreach {$_.TimeCreated.ToString('R')} | Out-String).Trim()"
44+
getTimeCreatedCmd := `$ProcessId = (Get-WMIObject -Class Win32_Service -Filter "Name='` + service + `'" | Select-Object -ExpandProperty ProcessId);` +
45+
`if ([string]::IsNullOrEmpty($ProcessId) -or $ProcessId -eq 0) { (Get-WinEvent -FilterHashtable @{logname='system';id=7036} ` +
46+
`| Where-Object {$_.Message -match '.*(` + service + `).*(running).*'} | Select-Object -Property TimeCreated -First 1 | ` +
47+
`foreach {$_.TimeCreated.ToString('R')} | Out-String).Trim() } else { (Get-Process -Id $ProcessId | Select starttime | ` +
48+
`foreach {$_.starttime.ToString('R')} | Out-String).Trim() }`
4249
out, err := powershell(getTimeCreatedCmd)
4350
if err != nil {
4451
return time.Duration(0), err

0 commit comments

Comments
 (0)