aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/elastic/gosigar/sigar_windows.go
blob: 0cdf928d16adf391cb53ae7d369bf6352bd2d753 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// Copyright (c) 2012 VMware, Inc.

package gosigar

import (
    "fmt"
    "os"
    "path/filepath"
    "runtime"
    "strings"
    "sync"
    "syscall"
    "time"

    "github.com/StackExchange/wmi"
    "github.com/elastic/gosigar/sys/windows"
    "github.com/pkg/errors"
)

// Win32_Process represents a process on the Windows operating system. If
// additional fields are added here (that match the Windows struct) they will
// automatically be populated when calling getWin32Process.
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa394372(v=vs.85).aspx
type Win32_Process struct {
    CommandLine string
}

// Win32_OperatingSystem WMI class represents a Windows-based operating system
// installed on a computer.
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa394239(v=vs.85).aspx
type Win32_OperatingSystem struct {
    LastBootUpTime time.Time
}

var (
    // version is Windows version of the host OS.
    version = windows.GetWindowsVersion()

    // processQueryLimitedInfoAccess is set to PROCESS_QUERY_INFORMATION for Windows
    // 2003 and XP where PROCESS_QUERY_LIMITED_INFORMATION is unknown. For all newer
    // OS versions it is set to PROCESS_QUERY_LIMITED_INFORMATION.
    processQueryLimitedInfoAccess = windows.PROCESS_QUERY_LIMITED_INFORMATION

    // bootTime is the time when the OS was last booted. This value may be nil
    // on operating systems that do not support the WMI query used to obtain it.
    bootTime     *time.Time
    bootTimeLock sync.Mutex
)

func init() {
    if !version.IsWindowsVistaOrGreater() {
        // PROCESS_QUERY_LIMITED_INFORMATION cannot be used on 2003 or XP.
        processQueryLimitedInfoAccess = syscall.PROCESS_QUERY_INFORMATION
    }
}

func (self *LoadAverage) Get() error {
    return ErrNotImplemented{runtime.GOOS}
}

func (self *FDUsage) Get() error {
    return ErrNotImplemented{runtime.GOOS}
}

func (self *ProcEnv) Get(pid int) error {
    return ErrNotImplemented{runtime.GOOS}
}

func (self *ProcExe) Get(pid int) error {
    return ErrNotImplemented{runtime.GOOS}
}

func (self *ProcFDUsage) Get(pid int) error {
    return ErrNotImplemented{runtime.GOOS}
}

func (self *Uptime) Get() error {
    // Minimum supported OS is Windows Vista.
    if !version.IsWindowsVistaOrGreater() {
        return ErrNotImplemented{runtime.GOOS}
    }

    bootTimeLock.Lock()
    defer bootTimeLock.Unlock()
    if bootTime == nil {
        os, err := getWin32OperatingSystem()
        if err != nil {
            return errors.Wrap(err, "failed to get boot time using WMI")
        }
        bootTime = &os.LastBootUpTime
    }

    self.Length = time.Since(*bootTime).Seconds()
    return nil
}

func (self *Mem) Get() error {
    memoryStatusEx, err := windows.GlobalMemoryStatusEx()
    if err != nil {
        return errors.Wrap(err, "GlobalMemoryStatusEx failed")
    }

    self.Total = memoryStatusEx.TotalPhys
    self.Free = memoryStatusEx.AvailPhys
    self.Used = self.Total - self.Free
    self.ActualFree = self.Free
    self.ActualUsed = self.Used
    return nil
}

func (self *Swap) Get() error {
    memoryStatusEx, err := windows.GlobalMemoryStatusEx()
    if err != nil {
        return errors.Wrap(err, "GlobalMemoryStatusEx failed")
    }

    self.Total = memoryStatusEx.TotalPageFile
    self.Free = memoryStatusEx.AvailPageFile
    self.Used = self.Total - self.Free
    return nil
}

func (self *Cpu) Get() error {
    idle, kernel, user, err := windows.GetSystemTimes()
    if err != nil {
        return errors.Wrap(err, "GetSystemTimes failed")
    }

    // CPU times are reported in milliseconds by gosigar.
    self.Idle = uint64(idle / time.Millisecond)
    self.Sys = uint64(kernel / time.Millisecond)
    self.User = uint64(user / time.Millisecond)
    return nil
}

func (self *CpuList) Get() error {
    cpus, err := windows.NtQuerySystemProcessorPerformanceInformation()
    if err != nil {
        return errors.Wrap(err, "NtQuerySystemProcessorPerformanceInformation failed")
    }

    self.List = make([]Cpu, 0, len(cpus))
    for _, cpu := range cpus {
        self.List = append(self.List, Cpu{
            Idle: uint64(cpu.IdleTime / time.Millisecond),
            Sys:  uint64(cpu.KernelTime / time.Millisecond),
            User: uint64(cpu.UserTime / time.Millisecond),
        })
    }
    return nil
}

func (self *FileSystemList) Get() error {
    drives, err := windows.GetLogicalDriveStrings()
    if err != nil {
        return errors.Wrap(err, "GetLogicalDriveStrings failed")
    }

    for _, drive := range drives {
        dt, err := windows.GetDriveType(drive)
        if err != nil {
            return errors.Wrapf(err, "GetDriveType failed")
        }

        self.List = append(self.List, FileSystem{
            DirName:  drive,
            DevName:  drive,
            TypeName: dt.String(),
        })
    }
    return nil
}

// Get retrieves a list of all process identifiers (PIDs) in the system.
func (self *ProcList) Get() error {
    pids, err := windows.EnumProcesses()
    if err != nil {
        return errors.Wrap(err, "EnumProcesses failed")
    }

    // Convert uint32 PIDs to int.
    self.List = make([]int, 0, len(pids))
    for _, pid := range pids {
        self.List = append(self.List, int(pid))
    }
    return nil
}

func (self *ProcState) Get(pid int) error {
    var errs []error

    var err error
    self.Name, err = getProcName(pid)
    if err != nil {
        errs = append(errs, errors.Wrap(err, "getProcName failed"))
    }

    self.State, err = getProcStatus(pid)
    if err != nil {
        errs = append(errs, errors.Wrap(err, "getProcStatus failed"))
    }

    self.Ppid, err = getParentPid(pid)
    if err != nil {
        errs = append(errs, errors.Wrap(err, "getParentPid failed"))
    }

    self.Username, err = getProcCredName(pid)
    if err != nil {
        errs = append(errs, errors.Wrap(err, "getProcCredName failed"))
    }

    if len(errs) > 0 {
        errStrs := make([]string, 0, len(errs))
        for _, e := range errs {
            errStrs = append(errStrs, e.Error())
        }
        return errors.New(strings.Join(errStrs, "; "))
    }
    return nil
}

// getProcName returns the process name associated with the PID.
func getProcName(pid int) (string, error) {
    handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
    if err != nil {
        return "", errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
    }
    defer syscall.CloseHandle(handle)

    filename, err := windows.GetProcessImageFileName(handle)
    if err != nil {
        return "", errors.Wrapf(err, "GetProcessImageFileName failed for pid=%v", pid)
    }

    return filepath.Base(filename), nil
}

// getProcStatus returns the status of a process.
func getProcStatus(pid int) (RunState, error) {
    handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
    if err != nil {
        return RunStateUnknown, errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
    }
    defer syscall.CloseHandle(handle)

    var exitCode uint32
    err = syscall.GetExitCodeProcess(handle, &exitCode)
    if err != nil {
        return RunStateUnknown, errors.Wrapf(err, "GetExitCodeProcess failed for pid=%v")
    }

    if exitCode == 259 { //still active
        return RunStateRun, nil
    }
    return RunStateSleep, nil
}

// getParentPid returns the parent process ID of a process.
func getParentPid(pid int) (int, error) {
    handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
    if err != nil {
        return RunStateUnknown, errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
    }
    defer syscall.CloseHandle(handle)

    procInfo, err := windows.NtQueryProcessBasicInformation(handle)
    if err != nil {
        return 0, errors.Wrapf(err, "NtQueryProcessBasicInformation failed for pid=%v", pid)
    }

    return int(procInfo.InheritedFromUniqueProcessID), nil
}

func getProcCredName(pid int) (string, error) {
    handle, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))
    if err != nil {
        return "", errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
    }
    defer syscall.CloseHandle(handle)

    // Find process token via win32.
    var token syscall.Token
    err = syscall.OpenProcessToken(handle, syscall.TOKEN_QUERY, &token)
    if err != nil {
        return "", errors.Wrapf(err, "OpenProcessToken failed for pid=%v", pid)
    }

    // Find the token user.
    tokenUser, err := token.GetTokenUser()
    if err != nil {
        return "", errors.Wrapf(err, "GetTokenInformation failed for pid=%v", pid)
    }

    // Close token to prevent handle leaks.
    err = token.Close()
    if err != nil {
        return "", errors.Wrapf(err, "failed while closing process token handle for pid=%v", pid)
    }

    // Look up domain account by SID.
    account, domain, _, err := tokenUser.User.Sid.LookupAccount("")
    if err != nil {
        sid, sidErr := tokenUser.User.Sid.String()
        if sidErr != nil {
            return "", errors.Wrapf(err, "failed while looking up account name for pid=%v", pid)
        }
        return "", errors.Wrapf(err, "failed while looking up account name for SID=%v of pid=%v", sid, pid)
    }

    return fmt.Sprintf(`%s\%s`, domain, account), nil
}

func (self *ProcMem) Get(pid int) error {
    handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess|windows.PROCESS_VM_READ, false, uint32(pid))
    if err != nil {
        return errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
    }
    defer syscall.CloseHandle(handle)

    counters, err := windows.GetProcessMemoryInfo(handle)
    if err != nil {
        return errors.Wrapf(err, "GetProcessMemoryInfo failed for pid=%v", pid)
    }

    self.Resident = uint64(counters.WorkingSetSize)
    self.Size = uint64(counters.PrivateUsage)
    return nil
}

func (self *ProcTime) Get(pid int) error {
    cpu, err := getProcTimes(pid)
    if err != nil {
        return err
    }

    // Windows epoch times are expressed as time elapsed since midnight on
    // January 1, 1601 at Greenwich, England. This converts the Filetime to
    // unix epoch in milliseconds.
    self.StartTime = uint64(cpu.CreationTime.Nanoseconds() / 1e6)

    // Convert to millis.
    self.User = uint64(windows.FiletimeToDuration(&cpu.UserTime).Nanoseconds() / 1e6)
    self.Sys = uint64(windows.FiletimeToDuration(&cpu.KernelTime).Nanoseconds() / 1e6)
    self.Total = self.User + self.Sys

    return nil
}

func getProcTimes(pid int) (*syscall.Rusage, error) {
    handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid))
    if err != nil {
        return nil, errors.Wrapf(err, "OpenProcess failed for pid=%v", pid)
    }
    defer syscall.CloseHandle(handle)

    var cpu syscall.Rusage
    if err := syscall.GetProcessTimes(handle, &cpu.CreationTime, &cpu.ExitTime, &cpu.KernelTime, &cpu.UserTime); err != nil {
        return nil, errors.Wrapf(err, "GetProcessTimes failed for pid=%v", pid)
    }

    return &cpu, nil
}

func (self *ProcArgs) Get(pid int) error {
    // The minimum supported client for Win32_Process is Windows Vista.
    if !version.IsWindowsVistaOrGreater() {
        return ErrNotImplemented{runtime.GOOS}
    }

    process, err := getWin32Process(int32(pid))
    if err != nil {
        return errors.Wrapf(err, "ProcArgs failed for pid=%v", pid)
    }

    self.List = []string{process.CommandLine}
    return nil
}

func (self *FileSystemUsage) Get(path string) error {
    freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes, err := windows.GetDiskFreeSpaceEx(path)
    if err != nil {
        return errors.Wrap(err, "GetDiskFreeSpaceEx failed")
    }

    self.Total = totalNumberOfBytes
    self.Free = totalNumberOfFreeBytes
    self.Used = self.Total - self.Free
    self.Avail = freeBytesAvailable
    return nil
}

// getWin32Process gets information about the process with the given process ID.
// It uses a WMI query to get the information from the local system.
func getWin32Process(pid int32) (Win32_Process, error) {
    var dst []Win32_Process
    query := fmt.Sprintf("WHERE ProcessId = %d", pid)
    q := wmi.CreateQuery(&dst, query)
    err := wmi.Query(q, &dst)
    if err != nil {
        return Win32_Process{}, fmt.Errorf("could not get Win32_Process %s: %v", query, err)
    }
    if len(dst) < 1 {
        return Win32_Process{}, fmt.Errorf("could not get Win32_Process %s: Process not found", query)
    }
    return dst[0], nil
}

func getWin32OperatingSystem() (Win32_OperatingSystem, error) {
    var dst []Win32_OperatingSystem
    q := wmi.CreateQuery(&dst, "")
    err := wmi.Query(q, &dst)
    if err != nil {
        return Win32_OperatingSystem{}, errors.Wrap(err, "wmi query for Win32_OperatingSystem failed")
    }
    if len(dst) != 1 {
        return Win32_OperatingSystem{}, errors.New("wmi query for Win32_OperatingSystem failed")
    }
    return dst[0], nil
}

func (self *Rusage) Get(who int) error {
    if who != 0 {
        return ErrNotImplemented{runtime.GOOS}
    }

    pid := os.Getpid()
    cpu, err := getProcTimes(pid)
    if err != nil {
        return err
    }

    self.Utime = windows.FiletimeToDuration(&cpu.UserTime)
    self.Stime = windows.FiletimeToDuration(&cpu.KernelTime)

    return nil
}