|
| 1 | +//go:build !windows |
| 2 | + |
| 3 | +package app |
| 4 | + |
| 5 | +import ( |
| 6 | + "encoding/json" |
| 7 | + "log/slog" |
| 8 | + "math" |
| 9 | + "os" |
| 10 | + "os/signal" |
| 11 | + "syscall" |
| 12 | + |
| 13 | + "github.com/alexandre-daubois/ember/internal/fetcher" |
| 14 | + "github.com/alexandre-daubois/ember/internal/model" |
| 15 | +) |
| 16 | + |
| 17 | +// dumpSignal returns a channel that receives a value each time SIGUSR1 is sent to the process. |
| 18 | +func dumpSignal() <-chan os.Signal { |
| 19 | + ch := make(chan os.Signal, 1) |
| 20 | + signal.Notify(ch, syscall.SIGUSR1) |
| 21 | + return ch |
| 22 | +} |
| 23 | + |
| 24 | +func dumpState(state *model.State, log *slog.Logger) { |
| 25 | + if state.Current == nil { |
| 26 | + log.Info("dump requested but no data available yet") |
| 27 | + return |
| 28 | + } |
| 29 | + |
| 30 | + out := buildJSONOutput(state.Current, state) |
| 31 | + sanitizeForJSON(&out) |
| 32 | + b, err := json.Marshal(out) |
| 33 | + if err != nil { |
| 34 | + log.Error("dump failed", "err", err) |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + log.Info("state dump (SIGUSR1)", "snapshot", string(b)) |
| 39 | +} |
| 40 | + |
| 41 | +// sanitizeForJSON removes +Inf and NaN values that encoding/json cannot serialize. |
| 42 | +func sanitizeForJSON(out *jsonOutput) { |
| 43 | + out.Metrics.DurationBuckets = sanitizeBuckets(out.Metrics.DurationBuckets) |
| 44 | + for _, h := range out.Metrics.Hosts { |
| 45 | + h.DurationBuckets = sanitizeBuckets(h.DurationBuckets) |
| 46 | + h.TTFBBuckets = sanitizeBuckets(h.TTFBBuckets) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +func sanitizeBuckets(buckets []fetcher.HistogramBucket) []fetcher.HistogramBucket { |
| 51 | + clean := make([]fetcher.HistogramBucket, 0, len(buckets)) |
| 52 | + for _, b := range buckets { |
| 53 | + if math.IsInf(b.UpperBound, 0) || math.IsNaN(b.UpperBound) { |
| 54 | + continue |
| 55 | + } |
| 56 | + clean = append(clean, b) |
| 57 | + } |
| 58 | + return clean |
| 59 | +} |
0 commit comments