Files
mtusi2026lab2/degradation.go
T

95 lines
2.8 KiB
Go

package main
import (
"fmt"
"os"
"runtime"
runtimemetrics "runtime/metrics"
"strconv"
"strings"
"sync/atomic"
)
type limits struct {
maxInFlight int
maxBodyBytes int64
}
func loadLimits() limits {
return limits{
maxInFlight: envInt("MAX_IN_FLIGHT", 64, 1),
maxBodyBytes: int64(envInt("MAX_BODY_BYTES", 1<<20, 1024)),
}
}
func envInt(name string, fallback, minimum int) int {
value, err := strconv.Atoi(os.Getenv(name))
if err != nil || value < minimum {
return fallback
}
return value
}
type metrics struct {
requests atomic.Uint64
inFlight atomic.Int64
status413 atomic.Uint64
status429 atomic.Uint64
status503 atomic.Uint64
accepted atomic.Uint64
}
func (metrics *metrics) snapshot() string {
var memory runtime.MemStats
runtime.ReadMemStats(&memory)
processCPU := processCPUSeconds()
residentMemory := residentMemoryBytes()
return fmt.Sprintf("# HELP messenger_requests_total Total HTTP requests.\n"+
"# TYPE messenger_requests_total counter\n"+
"messenger_requests_total %d\n"+
"# HELP messenger_responses_total Responses rejected by overload protection.\n"+
"# TYPE messenger_responses_total counter\n"+
"messenger_responses_total{status=\"413\"} %d\n"+
"messenger_responses_total{status=\"429\"} %d\n"+
"messenger_responses_total{status=\"503\"} %d\n"+
"# HELP messenger_messages_accepted_total Confirmed message writes.\n"+
"# TYPE messenger_messages_accepted_total counter\n"+
"messenger_messages_accepted_total %d\n"+
"# HELP messenger_in_flight Current requests inside the admission gate.\n"+
"# TYPE messenger_in_flight gauge\n"+"messenger_in_flight %d\n"+
"# HELP messenger_memory_alloc_bytes Go heap bytes currently allocated.\n"+
"# TYPE messenger_memory_alloc_bytes gauge\n"+"messenger_memory_alloc_bytes %d\n"+
"# HELP process_cpu_seconds_total CPU time consumed by the Go process.\n"+
"# TYPE process_cpu_seconds_total counter\n"+"process_cpu_seconds_total %.6f\n"+
"# HELP process_resident_memory_bytes Resident memory used by the Go process.\n"+
"# TYPE process_resident_memory_bytes gauge\n"+"process_resident_memory_bytes %d\n",
metrics.requests.Load(), metrics.status413.Load(), metrics.status429.Load(), metrics.status503.Load(),
metrics.accepted.Load(), metrics.inFlight.Load(), memory.Alloc,
processCPU, residentMemory)
}
func processCPUSeconds() float64 {
samples := []runtimemetrics.Sample{{Name: "/cpu/classes/total:cpu-seconds"}}
runtimemetrics.Read(samples)
if samples[0].Value.Kind() != runtimemetrics.KindFloat64 {
return 0
}
return samples[0].Value.Float64()
}
func residentMemoryBytes() int64 {
data, err := os.ReadFile("/proc/self/statm")
if err != nil {
return 0
}
fields := strings.Fields(string(data))
if len(fields) < 2 {
return 0
}
residentPages, err := strconv.ParseInt(fields[1], 10, 64)
if err != nil {
return 0
}
return residentPages * int64(os.Getpagesize())
}