Debian Codegraph @

server/pse/pse_windows.go

raw
1 // Copyright 2015-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 //go:build windows
15
16 package pse
17
18 import (
19 "fmt"
20 "os"
21 "path/filepath"
22 "strings"
23 "sync"
24 "syscall"
25 "time"
26 "unsafe"
27
28 "golang.org/x/sys/windows"
29 )
30
31 var (
32 pdh = windows.NewLazySystemDLL("pdh.dll")
33 winPdhOpenQuery = pdh.NewProc("PdhOpenQuery")
34 winPdhAddCounter = pdh.NewProc("PdhAddCounterW")
35 winPdhCollectQueryData = pdh.NewProc("PdhCollectQueryData")
36 winPdhGetFormattedCounterValue = pdh.NewProc("PdhGetFormattedCounterValue")
37 winPdhGetFormattedCounterArray = pdh.NewProc("PdhGetFormattedCounterArrayW")
38 )
39
40 func init() {
41 if err := pdh.Load(); err != nil {
42 panic(err)
43 }
44 for _, p := range []*windows.LazyProc{
45 winPdhOpenQuery, winPdhAddCounter, winPdhCollectQueryData,
46 winPdhGetFormattedCounterValue, winPdhGetFormattedCounterArray,
47 } {
48 if err := p.Find(); err != nil {
49 panic(err)
50 }
51 }
52 }
53
54 // global performance counter query handle and counters
55 var (
56 pcHandle PDH_HQUERY
57 pidCounter, cpuCounter, rssCounter, vssCounter PDH_HCOUNTER
58 prevCPU float64
59 prevRss int64
60 prevVss int64
61 lastSampleTime time.Time
62 processPid int
63 pcQueryLock sync.Mutex
64 initialSample = true
65 )
66
67 // maxQuerySize is the number of values to return from a query.
68 // It represents the maximum # of servers that can be queried
69 // simultaneously running on a machine.
70 const maxQuerySize = 512
71
72 // Keep static memory around to reuse; this works best for passing
73 // into the pdh API.
74 var counterResults [maxQuerySize]PDH_FMT_COUNTERVALUE_ITEM_DOUBLE
75
76 // PDH Types
77 type (
78 PDH_HQUERY syscall.Handle
79 PDH_HCOUNTER syscall.Handle
80 )
81
82 // PDH constants used here
83 const (
84 PDH_FMT_DOUBLE = 0x00000200
85 PDH_INVALID_DATA = 0xC0000BC6
86 PDH_MORE_DATA = 0x800007D2
87 )
88
89 // PDH_FMT_COUNTERVALUE_DOUBLE - double value
90 type PDH_FMT_COUNTERVALUE_DOUBLE struct {
91 CStatus uint32
92 DoubleValue float64
93 }
94
95 // PDH_FMT_COUNTERVALUE_ITEM_DOUBLE is an array
96 // element of a double value
97 type PDH_FMT_COUNTERVALUE_ITEM_DOUBLE struct {
98 SzName *uint16 // pointer to a string
99 FmtValue PDH_FMT_COUNTERVALUE_DOUBLE
100 }
101
102 func pdhAddCounter(hQuery PDH_HQUERY, szFullCounterPath string, dwUserData uintptr, phCounter *PDH_HCOUNTER) error {
103 ptxt, _ := syscall.UTF16PtrFromString(szFullCounterPath)
104 r0, _, _ := winPdhAddCounter.Call(
105 uintptr(hQuery),
106 uintptr(unsafe.Pointer(ptxt)),
107 dwUserData,
108 uintptr(unsafe.Pointer(phCounter)))
109
110 if r0 != 0 {
111 return fmt.Errorf("pdhAddCounter failed. %d", r0)
112 }
113 return nil
114 }
115
116 func pdhOpenQuery(datasrc *uint16, userdata uint32, query *PDH_HQUERY) error {
117 r0, _, _ := syscall.Syscall(winPdhOpenQuery.Addr(), 3, 0, uintptr(userdata), uintptr(unsafe.Pointer(query)))
118 if r0 != 0 {
119 return fmt.Errorf("pdhOpenQuery failed - %d", r0)
120 }
121 return nil
122 }
123
124 func pdhCollectQueryData(hQuery PDH_HQUERY) error {
125 r0, _, _ := winPdhCollectQueryData.Call(uintptr(hQuery))
126 if r0 != 0 {
127 return fmt.Errorf("pdhCollectQueryData failed - %d", r0)
128 }
129 return nil
130 }
131
132 // pdhGetFormattedCounterArrayDouble returns the value of return code
133 // rather than error, to easily check return codes
134 func pdhGetFormattedCounterArrayDouble(hCounter PDH_HCOUNTER, lpdwBufferSize *uint32, lpdwBufferCount *uint32, itemBuffer *PDH_FMT_COUNTERVALUE_ITEM_DOUBLE) uint32 {
135 ret, _, _ := winPdhGetFormattedCounterArray.Call(
136 uintptr(hCounter),
137 uintptr(PDH_FMT_DOUBLE),
138 uintptr(unsafe.Pointer(lpdwBufferSize)),
139 uintptr(unsafe.Pointer(lpdwBufferCount)),
140 uintptr(unsafe.Pointer(itemBuffer)))
141
142 return uint32(ret)
143 }
144
145 func getCounterArrayData(counter PDH_HCOUNTER) ([]float64, error) {
146 var bufSize uint32
147 var bufCount uint32
148
149 // Retrieving array data requires two calls, the first which
150 // requires an addressable empty buffer, and sets size fields.
151 // The second call returns the data.
152 initialBuf := make([]PDH_FMT_COUNTERVALUE_ITEM_DOUBLE, 1)
153 ret := pdhGetFormattedCounterArrayDouble(counter, &bufSize, &bufCount, &initialBuf[0])
154 if ret == PDH_MORE_DATA {
155 // we'll likely never get here, but be safe.
156 if bufCount > maxQuerySize {
157 bufCount = maxQuerySize
158 }
159 ret = pdhGetFormattedCounterArrayDouble(counter, &bufSize, &bufCount, &counterResults[0])
160 if ret == 0 {
161 rv := make([]float64, bufCount)
162 for i := 0; i < int(bufCount); i++ {
163 rv[i] = counterResults[i].FmtValue.DoubleValue
164 }
165 return rv, nil
166 }
167 }
168 if ret != 0 {
169 return nil, fmt.Errorf("getCounterArrayData failed - %d", ret)
170 }
171
172 return nil, nil
173 }
174
175 // getProcessImageName returns the name of the process image, as expected by
176 // the performance counter API.
177 func getProcessImageName() (name string) {
178 name = filepath.Base(os.Args[0])
179 name = strings.TrimSuffix(name, ".exe")
180 return
181 }
182
183 // initialize our counters
184 func initCounters() (err error) {
185
186 processPid = os.Getpid()
187 // require an addressible nil pointer
188 var source uint16
189 if err := pdhOpenQuery(&source, 0, &pcHandle); err != nil {
190 return err
191 }
192
193 // setup the performance counters, search for all server instances
194 name := fmt.Sprintf("%s*", getProcessImageName())
195 pidQuery := fmt.Sprintf("\\Process(%s)\\ID Process", name)
196 cpuQuery := fmt.Sprintf("\\Process(%s)\\%% Processor Time", name)
197 rssQuery := fmt.Sprintf("\\Process(%s)\\Working Set - Private", name)
198 vssQuery := fmt.Sprintf("\\Process(%s)\\Virtual Bytes", name)
199
200 if err = pdhAddCounter(pcHandle, pidQuery, 0, &pidCounter); err != nil {
201 return err
202 }
203 if err = pdhAddCounter(pcHandle, cpuQuery, 0, &cpuCounter); err != nil {
204 return err
205 }
206 if err = pdhAddCounter(pcHandle, rssQuery, 0, &rssCounter); err != nil {
207 return err
208 }
209 if err = pdhAddCounter(pcHandle, vssQuery, 0, &vssCounter); err != nil {
210 return err
211 }
212
213 // prime the counters by collecting once, and sleep to get somewhat
214 // useful information the first request. Counters for the CPU require
215 // at least two collect calls.
216 if err = pdhCollectQueryData(pcHandle); err != nil {
217 return err
218 }
219 time.Sleep(50)
220
221 return nil
222 }
223
224 // ProcUsage returns process CPU and memory statistics
225 func ProcUsage(pcpu *float64, rss, vss *int64) error {
226 var err error
227
228 // For simplicity, protect the entire call.
229 // Most simultaneous requests will immediately return
230 // with cached values.
231 pcQueryLock.Lock()
232 defer pcQueryLock.Unlock()
233
234 // First time through, initialize counters.
235 if initialSample {
236 if err = initCounters(); err != nil {
237 return err
238 }
239 initialSample = false
240 } else if time.Since(lastSampleTime) < (2 * time.Second) {
241 // only refresh every two seconds as to minimize impact
242 // on the server.
243 *pcpu = prevCPU
244 *rss = prevRss
245 *vss = prevVss
246 return nil
247 }
248
249 // always save the sample time, even on errors.
250 defer func() {
251 lastSampleTime = time.Now()
252 }()
253
254 // refresh the performance counter data
255 if err = pdhCollectQueryData(pcHandle); err != nil {
256 return err
257 }
258
259 // retrieve the data
260 var pidAry, cpuAry, rssAry, vssAry []float64
261 if pidAry, err = getCounterArrayData(pidCounter); err != nil {
262 return err
263 }
264 if cpuAry, err = getCounterArrayData(cpuCounter); err != nil {
265 return err
266 }
267 if rssAry, err = getCounterArrayData(rssCounter); err != nil {
268 return err
269 }
270 if vssAry, err = getCounterArrayData(vssCounter); err != nil {
271 return err
272 }
273 // find the index of the entry for this process
274 idx := int(-1)
275 for i := range pidAry {
276 if int(pidAry[i]) == processPid {
277 idx = i
278 break
279 }
280 }
281 // no pid found...
282 if idx < 0 {
283 return fmt.Errorf("could not find pid in performance counter results")
284 }
285 // assign values from the performance counters
286 *pcpu = cpuAry[idx]
287 *rss = int64(rssAry[idx])
288 *vss = int64(vssAry[idx])
289
290 // save off cache values
291 prevCPU = *pcpu
292 prevRss = *rss
293 prevVss = *vss
294
295 return nil
296 }