-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmcp_runtime.go
More file actions
542 lines (474 loc) · 15.8 KB
/
mcp_runtime.go
File metadata and controls
542 lines (474 loc) · 15.8 KB
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app
import (
"cmp"
"context"
"fmt"
"math"
"runtime"
"runtime/debug"
"slices"
"strings"
"time"
"rivaas.dev/router/route"
)
const (
goroutineWarningThreshold = 1000
goroutineHighThreshold = 5000
heapWarningMB = 512
heapHighMB = 1024
gcPauseWarningMS = 10
)
type runtimeStatsResponse struct {
Service string `json:"service"`
Version string `json:"version"`
Uptime string `json:"uptime"`
UptimeSecs float64 `json:"uptime_secs"`
Goroutines int `json:"goroutines"`
Memory runtimeMemoryStats `json:"memory"`
GoVersion string `json:"go_version"`
NumCPU int `json:"num_cpu"`
GOMAXPROCS int `json:"gomaxprocs"`
Signals []string `json:"signals"`
}
type runtimeMemoryStats struct {
HeapAllocBytes uint64 `json:"heap_alloc_bytes"`
HeapAllocMB float64 `json:"heap_alloc_mb"`
HeapSysBytes uint64 `json:"heap_sys_bytes"`
HeapObjects uint64 `json:"heap_objects"`
StackInuseBytes uint64 `json:"stack_inuse_bytes"`
TotalAllocBytes uint64 `json:"total_alloc_bytes"`
SysBytes uint64 `json:"sys_bytes"`
Mallocs uint64 `json:"mallocs"`
Frees uint64 `json:"frees"`
GCCycles uint32 `json:"gc_cycles"`
LastGC string `json:"last_gc"`
GCPauseTotalNs uint64 `json:"gc_pause_total_ns"`
NextGCBytes uint64 `json:"next_gc_bytes"`
}
type goroutineProfileResponse struct {
TotalGoroutines int `json:"total_goroutines"`
FilteredCount int `json:"filtered_count"`
StateFilter string `json:"state_filter"`
StateSummary map[string]int `json:"state_summary"`
Goroutines []goroutineEntry `json:"goroutines"`
Signals []string `json:"signals"`
}
type goroutineEntry struct {
Header string `json:"header"`
State string `json:"state"`
Stack string `json:"stack"`
}
type gcStatsResponse struct {
GCCycles uint32 `json:"gc_cycles"`
LastGC string `json:"last_gc"`
PauseTotalNs uint64 `json:"pause_total_ns"`
PauseTotalMs float64 `json:"pause_total_ms"`
LastPauseNs uint64 `json:"last_pause_ns"`
LastPauseMs float64 `json:"last_pause_ms"`
AvgPauseMs float64 `json:"avg_pause_ms"`
NextGCBytes uint64 `json:"next_gc_bytes"`
GCCPUFraction float64 `json:"gc_cpu_fraction"`
EnableGC bool `json:"enable_gc"`
HeapAllocBytes uint64 `json:"heap_alloc_bytes"`
HeapObjects uint64 `json:"heap_objects"`
Mallocs uint64 `json:"mallocs"`
Frees uint64 `json:"frees"`
LiveObjects uint64 `json:"live_objects"`
Signals []string `json:"signals"`
}
type buildInfoResponse struct {
Available bool `json:"available"`
GoVersion string `json:"go_version,omitempty"`
Path string `json:"path,omitempty"`
MainModule string `json:"main_module,omitempty"`
MainVersion string `json:"main_version,omitempty"`
Dependencies []buildDep `json:"dependencies,omitempty"`
Settings map[string]string `json:"settings,omitempty"`
Signals []string `json:"signals"`
}
type buildDep struct {
Path string `json:"path"`
Version string `json:"version"`
ReplacedBy string `json:"replaced_by,omitempty"`
ReplacedVersion string `json:"replaced_version,omitempty"`
}
func collectRuntimeStats(serviceName, serviceVersion string, start time.Time) *runtimeStatsResponse {
var m runtime.MemStats
runtime.ReadMemStats(&m)
numGoroutines := runtime.NumGoroutine()
heapMB := float64(m.HeapAlloc) / (1024 * 1024)
uptime := time.Since(start)
var signals []string
if numGoroutines > goroutineHighThreshold {
signals = append(signals, fmt.Sprintf("goroutine count (%d) is very high — likely leak or unbounded concurrency", numGoroutines))
} else if numGoroutines > goroutineWarningThreshold {
signals = append(signals, fmt.Sprintf("goroutine count (%d) exceeds typical threshold — investigate if expected", numGoroutines))
}
if heapMB > heapHighMB {
signals = append(signals, fmt.Sprintf("heap usage (%.1f MB) is very high — check for memory leaks", heapMB))
} else if heapMB > heapWarningMB {
signals = append(signals, fmt.Sprintf("heap usage (%.1f MB) is elevated — monitor for growth trends", heapMB))
}
return &runtimeStatsResponse{
Service: serviceName,
Version: serviceVersion,
Uptime: uptime.String(),
UptimeSecs: uptime.Seconds(),
Goroutines: numGoroutines,
Memory: runtimeMemoryStats{
HeapAllocBytes: m.HeapAlloc,
HeapAllocMB: heapMB,
HeapSysBytes: m.HeapSys,
HeapObjects: m.HeapObjects,
StackInuseBytes: m.StackInuse,
TotalAllocBytes: m.TotalAlloc,
SysBytes: m.Sys,
Mallocs: m.Mallocs,
Frees: m.Frees,
GCCycles: m.NumGC,
LastGC: time.Unix(0, safeInt64(m.LastGC)).Format(time.RFC3339),
GCPauseTotalNs: m.PauseTotalNs,
NextGCBytes: m.NextGC,
},
GoVersion: runtime.Version(),
NumCPU: runtime.NumCPU(),
GOMAXPROCS: runtime.GOMAXPROCS(0),
Signals: signals,
}
}
func collectGoroutineProfile(stateFilter string) *goroutineProfileResponse {
buf := make([]byte, 1<<20) //nolint:makezero // runtime.Stack requires a pre-sized buffer
n := runtime.Stack(buf, true)
stackDump := string(buf[:n])
allGoroutines := parseGoroutineStacks(stackDump)
numGoroutines := runtime.NumGoroutine()
var signals []string
if numGoroutines > goroutineHighThreshold {
signals = append(signals, fmt.Sprintf("goroutine count (%d) is very high — likely leak or unbounded concurrency", numGoroutines))
} else if numGoroutines > goroutineWarningThreshold {
signals = append(signals, fmt.Sprintf("goroutine count (%d) exceeds typical threshold", numGoroutines))
}
stateCounts := make(map[string]int)
for _, g := range allGoroutines {
stateCounts[g.State]++
}
filterNorm := strings.ToLower(strings.TrimSpace(stateFilter))
filtered := allGoroutines
if filterNorm != "" && filterNorm != "all" {
filtered = make([]goroutineEntry, 0, len(allGoroutines))
for _, g := range allGoroutines {
if strings.Contains(strings.ToLower(g.State), filterNorm) {
filtered = append(filtered, g)
}
}
}
return &goroutineProfileResponse{
TotalGoroutines: numGoroutines,
FilteredCount: len(filtered),
StateFilter: stateFilter,
StateSummary: stateCounts,
Goroutines: filtered,
Signals: signals,
}
}
func parseGoroutineStacks(dump string) []goroutineEntry {
sections := strings.Split(dump, "\n\n")
var goroutines []goroutineEntry
for _, section := range sections {
section = strings.TrimSpace(section)
if section == "" {
continue
}
lines := strings.SplitN(section, "\n", 2)
header := lines[0]
var state string
if start := strings.Index(header, "["); start != -1 {
if end := strings.Index(header[start:], "]"); end != -1 {
state = header[start+1 : start+end]
}
}
stack := ""
if len(lines) > 1 {
stack = lines[1]
}
goroutines = append(goroutines, goroutineEntry{
Header: header,
State: state,
Stack: stack,
})
}
return goroutines
}
func collectGCStats() *gcStatsResponse {
var m runtime.MemStats
runtime.ReadMemStats(&m)
var signals []string
lastPauseNs := uint64(0)
if m.NumGC > 0 {
lastPauseNs = m.PauseNs[(m.NumGC+255)%256]
}
lastPauseMS := float64(lastPauseNs) / 1e6
if lastPauseMS > gcPauseWarningMS {
signals = append(signals, fmt.Sprintf("last GC pause (%.2f ms) is high — may cause latency spikes", lastPauseMS))
}
avgPauseMS := float64(0)
if m.NumGC > 0 {
avgPauseMS = float64(m.PauseTotalNs) / float64(m.NumGC) / 1e6
}
return &gcStatsResponse{
GCCycles: m.NumGC,
LastGC: time.Unix(0, safeInt64(m.LastGC)).Format(time.RFC3339),
PauseTotalNs: m.PauseTotalNs,
PauseTotalMs: float64(m.PauseTotalNs) / 1e6,
LastPauseNs: lastPauseNs,
LastPauseMs: lastPauseMS,
AvgPauseMs: avgPauseMS,
NextGCBytes: m.NextGC,
GCCPUFraction: m.GCCPUFraction,
EnableGC: m.EnableGC,
HeapAllocBytes: m.HeapAlloc,
HeapObjects: m.HeapObjects,
Mallocs: m.Mallocs,
Frees: m.Frees,
LiveObjects: m.Mallocs - m.Frees,
Signals: signals,
}
}
func collectBuildInfo() *buildInfoResponse {
bi, ok := debug.ReadBuildInfo()
if !ok {
return &buildInfoResponse{
Available: false,
Signals: []string{"build info not available — binary may not have been built with module support"},
}
}
var deps []buildDep
for _, dep := range bi.Deps {
d := buildDep{
Path: dep.Path,
Version: dep.Version,
}
if dep.Replace != nil {
d.ReplacedBy = dep.Replace.Path
d.ReplacedVersion = dep.Replace.Version
}
deps = append(deps, d)
}
settings := make(map[string]string)
for _, s := range bi.Settings {
settings[s.Key] = s.Value
}
return &buildInfoResponse{
Available: true,
GoVersion: bi.GoVersion,
Path: bi.Path,
MainModule: bi.Main.Path,
MainVersion: bi.Main.Version,
Dependencies: deps,
Settings: settings,
Signals: []string{},
}
}
// --- Memory Profile ---
type memoryProfileResponse struct {
TotalAllocBytes uint64 `json:"total_alloc_bytes"`
TotalAllocObjects int64 `json:"total_alloc_objects"`
InUseBytes int64 `json:"in_use_bytes"`
InUseObjects int64 `json:"in_use_objects"`
TopN int `json:"top_n"`
Records []memoryProfileRecord `json:"records"`
Signals []string `json:"signals"`
}
type memoryProfileRecord struct {
FuncName string `json:"func_name"`
File string `json:"file"`
Line int `json:"line"`
AllocBytes int64 `json:"alloc_bytes"`
AllocObjects int64 `json:"alloc_objects"`
InUseBytes int64 `json:"in_use_bytes"`
InUseObjects int64 `json:"in_use_objects"`
}
func collectMemoryProfile(topN int) *memoryProfileResponse {
if topN <= 0 {
topN = 20
}
// MemProfile(nil, true) returns the count of records needing inuse_zero=true
n, _ := runtime.MemProfile(nil, true)
records := make([]runtime.MemProfileRecord, n+50) //nolint:makezero // runtime.MemProfile requires a pre-sized buffer
n, ok := runtime.MemProfile(records, true)
if !ok {
records = make([]runtime.MemProfileRecord, n*2) //nolint:makezero // retry with larger pre-sized buffer
n, _ = runtime.MemProfile(records, true)
}
records = records[:n]
slices.SortFunc(records, func(a, b runtime.MemProfileRecord) int {
return cmp.Compare(b.InUseBytes(), a.InUseBytes())
})
if topN > len(records) {
topN = len(records)
}
var totalInUse int64
for _, r := range records {
totalInUse += r.InUseBytes()
}
result := make([]memoryProfileRecord, 0, topN)
for _, r := range records[:topN] {
frames := runtime.CallersFrames(r.Stack())
frame, _ := frames.Next()
result = append(result, memoryProfileRecord{
FuncName: frame.Function,
File: frame.File,
Line: frame.Line,
AllocBytes: r.AllocBytes,
AllocObjects: r.AllocObjects,
InUseBytes: r.InUseBytes(),
InUseObjects: r.InUseObjects(),
})
}
var signals []string
if len(result) > 0 && totalInUse > 0 && result[0].InUseBytes > totalInUse/2 {
signals = append(signals, fmt.Sprintf(
"top allocation site (%s) accounts for >50%% of heap — investigate for memory concentration",
result[0].FuncName,
))
}
var totalAllocBytes uint64
var totalAllocObjects int64
for _, r := range records {
totalAllocBytes += uint64(r.AllocBytes) //nolint:gosec // AllocBytes is always non-negative
totalAllocObjects += r.AllocObjects
}
return &memoryProfileResponse{
TotalAllocBytes: totalAllocBytes,
TotalAllocObjects: totalAllocObjects,
InUseBytes: totalInUse,
InUseObjects: 0,
TopN: topN,
Records: result,
Signals: signals,
}
}
// --- Routes ---
type routesResponse struct {
TotalRoutes int `json:"total_routes"`
Routes []routeRecord `json:"routes"`
Signals []string `json:"signals"`
}
type routeRecord struct {
Method string `json:"method"`
Path string `json:"path"`
HandlerName string `json:"handler_name"`
Middleware []string `json:"middleware"`
Constraints map[string]string `json:"constraints"`
IsStatic bool `json:"is_static"`
Version string `json:"version"`
ParamCount int `json:"param_count"`
}
func collectRoutes(routes []route.Info) *routesResponse {
records := make([]routeRecord, len(routes)) //nolint:makezero // directly indexed by i
for i, r := range routes {
records[i] = routeRecord{
Method: r.Method,
Path: r.Path,
HandlerName: r.HandlerName,
Middleware: r.Middleware,
Constraints: r.Constraints,
IsStatic: r.IsStatic,
Version: r.Version,
ParamCount: r.ParamCount,
}
}
var signals []string
if len(records) == 0 {
signals = append(signals, "no routes registered — app may not be fully initialized")
}
return &routesResponse{
TotalRoutes: len(records),
Routes: records,
Signals: signals,
}
}
// --- Health Status ---
type healthStatusResponse struct {
Liveness healthCheckResult `json:"liveness"`
Readiness healthCheckResult `json:"readiness"`
Signals []string `json:"signals"`
}
type healthCheckResult struct {
Status string `json:"status"`
Checks map[string]string `json:"checks"`
Failures map[string]string `json:"failures,omitempty"`
}
func collectHealthStatus(ctx context.Context, h *healthSettings) *healthStatusResponse {
if h == nil || !h.enabled {
return &healthStatusResponse{
Signals: []string{"health endpoints not configured — no checks to run"},
}
}
livenessFailures := runChecks(ctx, h.liveness, h.timeout)
readinessFailures := runChecks(ctx, h.readiness, h.timeout)
liveChecks := make(map[string]string, len(h.liveness))
for name := range h.liveness {
if msg, failed := livenessFailures[name]; failed {
liveChecks[name] = "FAIL: " + msg
} else {
liveChecks[name] = "PASS"
}
}
readyChecks := make(map[string]string, len(h.readiness))
for name := range h.readiness {
if msg, failed := readinessFailures[name]; failed {
readyChecks[name] = "FAIL: " + msg
} else {
readyChecks[name] = "PASS"
}
}
liveStatus := "healthy"
if len(livenessFailures) > 0 {
liveStatus = "unhealthy"
}
readyStatus := "ready"
if len(readinessFailures) > 0 {
readyStatus = "not ready"
}
var signals []string
for name, msg := range livenessFailures {
signals = append(signals, fmt.Sprintf("liveness check %q failed: %s", name, msg))
}
for name, msg := range readinessFailures {
signals = append(signals, fmt.Sprintf("readiness check %q failed: %s", name, msg))
}
return &healthStatusResponse{
Liveness: healthCheckResult{
Status: liveStatus,
Checks: liveChecks,
Failures: livenessFailures,
},
Readiness: healthCheckResult{
Status: readyStatus,
Checks: readyChecks,
Failures: readinessFailures,
},
Signals: signals,
}
}
// safeInt64 converts a uint64 to int64, clamping at math.MaxInt64 to avoid overflow.
func safeInt64(v uint64) int64 {
if v > math.MaxInt64 {
return math.MaxInt64
}
return int64(v) //nolint:gosec // overflow guarded by the check above
}