Repository navigation
windows stats #36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
windows stats #36
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| //go:build windows | ||
|
|
||
| package processmanager | ||
|
|
||
| import ( | ||
| "context" | ||
| "sync" | ||
| "time" | ||
| "unsafe" | ||
|
|
||
| "github.com/gameap/daemon/internal/app/config" | ||
| "github.com/gameap/daemon/internal/app/domain" | ||
| "github.com/gameap/daemon/pkg/logger" | ||
| "github.com/pkg/errors" | ||
| "golang.org/x/sys/windows" | ||
| ) | ||
|
|
||
| const ( | ||
| processSnapshotInitialSize = 512 * 1024 | ||
| processSnapshotMaxSize = 64 * 1024 * 1024 | ||
| processSnapshotAttempts = 5 | ||
|
|
||
| // processSnapshotMaxAge lets every server of one metrics tick share a snapshot. It is half the | ||
| // shortest collection interval, so two ticks never do. | ||
| processSnapshotMaxAge = config.MetricsMinCollectionInterval / 2 | ||
| ) | ||
|
|
||
| var nativeProcessRecordLayout = processRecordLayout{ | ||
| size: int(unsafe.Sizeof(windows.SYSTEM_PROCESS_INFORMATION{})), | ||
| threads: int(unsafe.Offsetof(windows.SYSTEM_PROCESS_INFORMATION{}.NumberOfThreads)), | ||
| privateWorkingSet: int(unsafe.Offsetof(windows.SYSTEM_PROCESS_INFORMATION{}.WorkingSetPrivateSize)), | ||
| createTime: int(unsafe.Offsetof(windows.SYSTEM_PROCESS_INFORMATION{}.CreateTime)), | ||
| userTime: int(unsafe.Offsetof(windows.SYSTEM_PROCESS_INFORMATION{}.UserTime)), | ||
| kernelTime: int(unsafe.Offsetof(windows.SYSTEM_PROCESS_INFORMATION{}.KernelTime)), | ||
| pid: int(unsafe.Offsetof(windows.SYSTEM_PROCESS_INFORMATION{}.UniqueProcessID)), | ||
| parentPID: int(unsafe.Offsetof(windows.SYSTEM_PROCESS_INFORMATION{}.InheritedFromUniqueProcessID)), | ||
| readBytes: int(unsafe.Offsetof(windows.SYSTEM_PROCESS_INFORMATION{}.ReadTransferCount)), | ||
| writeBytes: int(unsafe.Offsetof(windows.SYSTEM_PROCESS_INFORMATION{}.WriteTransferCount)), | ||
| } | ||
|
|
||
| // processSnapshotter reads the process list of the host. The list covers every process and thread | ||
| // on the host, hundreds of kilobytes, so one read serves every server of a metrics tick and the | ||
| // buffer is kept for the next tick. | ||
| type processSnapshotter struct { | ||
| mu sync.Mutex | ||
| buf []uint64 | ||
| procs []processInfo | ||
| takenAt time.Time | ||
| } | ||
|
|
||
| // snapshot returns the process list and the time it was read. The list is shared between callers | ||
| // and must not be modified. | ||
| func (s *processSnapshotter) snapshot() ([]processInfo, time.Time, error) { | ||
| s.mu.Lock() | ||
| defer s.mu.Unlock() | ||
|
|
||
| if s.procs != nil && time.Since(s.takenAt) < processSnapshotMaxAge { | ||
| return s.procs, s.takenAt, nil | ||
| } | ||
|
|
||
| procs, takenAt, err := s.read() | ||
| if err != nil { | ||
| return nil, time.Time{}, err | ||
| } | ||
|
|
||
| s.procs, s.takenAt = procs, takenAt | ||
|
|
||
| return procs, takenAt, nil | ||
| } | ||
|
|
||
| // read queries the process list. The buffer is a []uint64 because the records carry 64-bit fields, | ||
| // which the kernel writes aligned. | ||
| func (s *processSnapshotter) read() ([]processInfo, time.Time, error) { | ||
| if len(s.buf) == 0 { | ||
| s.buf = make([]uint64, processSnapshotInitialSize/8) | ||
| } | ||
|
|
||
| for range processSnapshotAttempts { | ||
| size := len(s.buf) * 8 | ||
| takenAt := time.Now() | ||
|
|
||
| var written uint32 | ||
|
|
||
| err := windows.NtQuerySystemInformation( | ||
| windows.SystemProcessInformation, unsafe.Pointer(&s.buf[0]), uint32(size), &written, | ||
| ) | ||
| if errors.Is(err, windows.STATUS_INFO_LENGTH_MISMATCH) { | ||
| // Processes start between two calls, so the buffer gets more room than the kernel | ||
| // asked for a moment ago. | ||
| grown := max(2*size, int(written)+int(written)/4) | ||
| if grown > processSnapshotMaxSize { | ||
| return nil, time.Time{}, errors.WithMessagef( | ||
| ErrProcessSnapshotTooLarge, "%d bytes needed, at most %d allowed", written, processSnapshotMaxSize, | ||
| ) | ||
| } | ||
|
|
||
| s.buf = make([]uint64, (grown+7)/8) | ||
|
|
||
| continue | ||
| } | ||
| if err != nil { | ||
| return nil, time.Time{}, errors.Wrap(err, "failed to query the process list") | ||
| } | ||
|
|
||
| buf := unsafe.Slice((*byte)(unsafe.Pointer(&s.buf[0])), min(int(written), size)) | ||
|
|
||
| procs, err := parseProcessSnapshot(buf, nativeProcessRecordLayout) | ||
| if err != nil { | ||
| return nil, time.Time{}, err | ||
| } | ||
|
|
||
| return procs, takenAt, nil | ||
| } | ||
|
|
||
| return nil, time.Time{}, errors.WithMessagef( | ||
| ErrProcessSnapshotTooLarge, "the process list kept growing over %d attempts", processSnapshotAttempts, | ||
| ) | ||
| } | ||
|
|
||
| // serviceProcessMetrics reports what the processes a Windows service started are using: the game | ||
| // server and whatever it runs through, such as cmd.exe for a script. The service process itself is | ||
| // a supervisor, and systemd and container runtimes keep theirs out of a unit's or container's | ||
| // accounting as well. | ||
| // | ||
| // It returns nothing while the service has no process; the caller reports liveness on its own. | ||
| func serviceProcessMetrics( | ||
| ctx context.Context, serviceName string, snapshots *processSnapshotter, usage *processTreeSampler, | ||
| ) []domain.Metric { | ||
| status, err := queryService(serviceName) | ||
| if err != nil || status.ProcessId == 0 { | ||
| usage.forget(serviceName) | ||
|
|
||
| if err != nil && !errors.Is(err, ErrServiceNotFound) { | ||
| logger.WithError(ctx, err).Debug("Failed to query service " + serviceName + " for metrics") | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| procs, takenAt, err := snapshots.snapshot() | ||
| if err != nil { | ||
| logger.WithError(ctx, err).Debug("Failed to read the process list for metrics") | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| // The snapshot can be up to processSnapshotMaxAge older than the query. A service that started | ||
| // in between is not in it yet and is measured on the next tick; in the rare case that its | ||
| // process ID was still held by another process then, that process is reported for one tick. | ||
| tree, found := processDescendants(procs, status.ProcessId) | ||
| if !found { | ||
| usage.forget(serviceName) | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| return processTreeMetrics(takenAt, serviceName, usage.observe(serviceName, tree, takenAt)) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| //go:build windows | ||
|
|
||
| package processmanager | ||
|
|
||
| import ( | ||
| "os" | ||
| "os/exec" | ||
| "testing" | ||
| "time" | ||
| "unsafe" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestNativeProcessRecordLayout(t *testing.T) { | ||
| want := processRecordLayout64 | ||
| if unsafe.Sizeof(uintptr(0)) == 4 { | ||
| want = processRecordLayout386 | ||
| } | ||
|
|
||
| assert.Equal(t, want, nativeProcessRecordLayout) | ||
| } | ||
|
|
||
| func TestProcessSnapshotterRead_ContainsCurrentProcess(t *testing.T) { | ||
| procs, takenAt, err := (&processSnapshotter{}).read() | ||
| require.NoError(t, err) | ||
| assert.WithinDuration(t, time.Now(), takenAt, time.Minute) | ||
|
|
||
| var self *processInfo | ||
|
|
||
| for i := range procs { | ||
| if procs[i].PID == uint32(os.Getpid()) { | ||
| self = &procs[i] | ||
| } | ||
| } | ||
|
|
||
| require.NotNil(t, self, "the snapshot must contain the test process") | ||
| assert.Equal(t, uint32(os.Getppid()), self.ParentPID) | ||
| assert.Positive(t, self.Threads) | ||
| assert.Positive(t, self.PrivateWorkingSet) | ||
| assert.Positive(t, self.CPUTime) | ||
| assert.Less(t, self.CreateTime, filetimeTicks(time.Now())) | ||
| } | ||
|
|
||
| func TestProcessSnapshotterRead_GrowsBuffer(t *testing.T) { | ||
| snapshots := &processSnapshotter{buf: make([]uint64, 1)} | ||
|
|
||
| procs, _, err := snapshots.read() | ||
|
|
||
| require.NoError(t, err) | ||
| assert.NotEmpty(t, procs) | ||
| assert.Greater(t, len(snapshots.buf), 1) | ||
| } | ||
|
|
||
| func TestProcessSnapshotterSnapshot_SharesRecentRead(t *testing.T) { | ||
| snapshots := &processSnapshotter{} | ||
|
|
||
| _, first, err := snapshots.snapshot() | ||
| require.NoError(t, err) | ||
|
|
||
| _, second, err := snapshots.snapshot() | ||
| require.NoError(t, err) | ||
|
|
||
| assert.Equal(t, first, second) | ||
| } | ||
|
|
||
| func TestProcessDescendants_FindsChildAndGrandchild(t *testing.T) { | ||
| cmd := exec.Command("cmd.exe", "/c", "ping", "-n", "3", "127.0.0.1") | ||
| require.NoError(t, cmd.Start()) | ||
|
|
||
| t.Cleanup(func() { | ||
| _ = cmd.Wait() | ||
| }) | ||
|
|
||
| cmdPID := uint32(cmd.Process.Pid) | ||
|
|
||
| assert.Eventually(t, func() bool { | ||
| procs, _, err := (&processSnapshotter{}).read() | ||
| if err != nil { | ||
| return false | ||
| } | ||
|
|
||
| tree, found := processDescendants(procs, uint32(os.Getpid())) | ||
| if !found { | ||
| return false | ||
| } | ||
|
|
||
| var hasCmd, hasPing bool | ||
|
|
||
| for _, p := range tree { | ||
| hasCmd = hasCmd || p.PID == cmdPID | ||
| hasPing = hasPing || p.ParentPID == cmdPID | ||
| } | ||
|
|
||
| return hasCmd && hasPing | ||
| }, 5*time.Second, 100*time.Millisecond, "cmd.exe and the ping it runs must be in the test process's tree") | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Update the public docs in
gameap/gameap.github.ioto match the new Shawl metrics.This change makes three pages in the docs repository wrong:
en/daemon/process_managers.md: Lines 61-64 and the Shawl feature table near lines 406-410 still say that Shawl reports only liveness.ru/daemon/process_managers.md: Lines 60-63 and the Shawl feature table have the same liveness-only text.en/websocket.md: It definesgameap_server_process_pidsas the number of server processes. For Shawl, this metric is the thread count, and the Shawl process itself is not counted.Fix:
en/websocket.md, say thatgameap_server_process_pidscounts threads (tasks) for Shawl and systemd.Also applies to: 230-230
🤖 Prompt for AI Agents
Source: Linked repositories