summaryrefslogtreecommitdiff
path: root/internal/statsengine/engine.go
blob: 7d85e9615c319b21f2c732140d7b13580adb2a20 (plain)
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
package statsengine

import (
	"math"
	"sync"
	"time"

	"golang.org/x/sync/errgroup"

	"ior/internal/event"
	"ior/internal/types"
)

const (
	// trendWindowSlots is the number of slots used for trend detection in ring
	// time series. Two consecutive windows of this size are compared to detect
	// rising, falling, or stable throughput/latency trends.
	trendWindowSlots = 20

	// DefaultTopN is the default maximum number of top entries tracked per
	// category (files, processes). It is exported so callers can use it as the
	// standard capacity when constructing a new Engine via NewEngine.
	DefaultTopN = 64
)

// Accumulator is the event-ingestion side of the stats engine.
// It accepts incoming event pairs (Ingest) and supports resetting all
// accumulated state back to zero (Reset). Snapshot building is a separate
// responsibility expressed by runtime.SnapshotSource; separating the two
// satisfies SRP — callers that only push events hold an Accumulator, while
// callers that only read statistics hold a SnapshotSource.
type Accumulator interface {
	// Ingest records one event pair into the in-memory aggregates.
	Ingest(pair *event.Pair)
	// Reset clears all accumulated stats and restarts series baselines.
	Reset()
}

// compile-time assertion: *Engine must satisfy Accumulator.
var _ Accumulator = (*Engine)(nil)

// Engine aggregates streaming syscall data into immutable snapshots.
type Engine struct {
	mu sync.Mutex

	now       func() time.Time
	startedAt time.Time
	topN      int

	totalSyscalls   uint64
	totalErrors     uint64
	totalBytes      uint64
	totalReadBytes  uint64
	totalWriteBytes uint64
	totalLatency    uint64
	totalGap        uint64

	syscalls         *syscallAccumulator
	families         *familyAccumulator
	files            *fileRanker
	processes        *processAccumulator
	latencyHist      *histogram
	gapHist          *histogram
	latencySeries    *ringTimeSeries
	gapSeries        *ringTimeSeries
	throughputSeries *ringTimeSeries
}

type snapshotInputs struct {
	now       time.Time
	startedAt time.Time

	totalSyscalls   uint64
	totalErrors     uint64
	totalBytes      uint64
	totalReadBytes  uint64
	totalWriteBytes uint64
	totalLatency    uint64
	totalGap        uint64

	latencySeries    []float64
	gapSeries        []float64
	throughputSeries []float64

	syscalls  []syscallSnapshotInput
	families  []familySnapshotInput
	files     []fileSnapshotInput
	processes []processSnapshotInput

	latencyHist histogramSnapshotInput
	gapHist     histogramSnapshotInput
}

// NewEngine creates a new stats engine.
func NewEngine(topN int) *Engine {
	return newEngineWithClock(topN, time.Now)
}

func newEngineWithClock(topN int, now func() time.Time) *Engine {
	if now == nil {
		now = time.Now
	}

	return &Engine{
		now:              now,
		startedAt:        now(),
		topN:             topN,
		syscalls:         newSyscallAccumulator(),
		families:         newFamilyAccumulator(),
		files:            newFileRankerWithConfig(topN),
		processes:        newProcessAccumulatorWithConfig(topN),
		latencyHist:      newHistogram(),
		gapHist:          newHistogram(),
		latencySeries:    newRingTimeSeries(),
		gapSeries:        newRingTimeSeries(),
		throughputSeries: newRingTimeSeries(),
	}
}

// Reset clears all accumulated stats and restarts series baselines.
func (e *Engine) Reset() {
	if e == nil {
		return
	}

	e.mu.Lock()
	defer e.mu.Unlock()

	e.startedAt = e.now()
	e.totalSyscalls = 0
	e.totalErrors = 0
	e.totalBytes = 0
	e.totalReadBytes = 0
	e.totalWriteBytes = 0
	e.totalLatency = 0
	e.totalGap = 0
	e.syscalls = newSyscallAccumulator()
	e.families = newFamilyAccumulator()
	e.files = newFileRankerWithConfig(e.topN)
	e.processes = newProcessAccumulatorWithConfig(e.topN)
	e.latencyHist = newHistogram()
	e.gapHist = newHistogram()
	e.latencySeries = newRingTimeSeries()
	e.gapSeries = newRingTimeSeries()
	e.throughputSeries = newRingTimeSeries()
}

// Ingest updates all aggregates for one event pair.
func (e *Engine) Ingest(pair *event.Pair) {
	if e == nil || pair == nil {
		return
	}

	e.mu.Lock()
	defer e.mu.Unlock()

	now := e.now()
	e.totalSyscalls++
	e.totalBytes += pair.Bytes
	e.totalLatency += pair.Duration
	e.totalGap += pair.DurationToPrev

	e.updateErrorAndByteClasses(pair)
	e.syscalls.Add(pair)
	e.families.Add(pair)
	e.files.Add(pair)
	e.processes.Add(pair)
	e.latencyHist.Increment(pair.Duration)
	e.gapHist.Increment(pair.DurationToPrev)
	e.latencySeries.Add(float64(pair.Duration), now)
	e.gapSeries.Add(float64(pair.DurationToPrev), now)
	e.throughputSeries.Add(float64(pair.Bytes), now)
}

func (e *Engine) updateErrorAndByteClasses(pair *event.Pair) {
	retEv, ok := pair.ExitEv.(*types.RetEvent)
	if !ok {
		return
	}
	if retEv.Ret < 0 {
		e.totalErrors++
	}

	switch retEv.RetType {
	case types.READ_CLASSIFIED:
		e.totalReadBytes += pair.Bytes
	case types.WRITE_CLASSIFIED:
		e.totalWriteBytes += pair.Bytes
	case types.TRANSFER_CLASSIFIED:
		e.totalReadBytes += pair.Bytes
		e.totalWriteBytes += pair.Bytes
	}
}

// subSnapshots holds the concurrently built per-category snapshot slices.
type subSnapshots struct {
	syscalls    []SyscallSnapshot
	families    []FamilySnapshot
	files       []FileSnapshot
	processes   []ProcessSnapshot
	latencyHist HistogramSnapshot
	gapHist     HistogramSnapshot
}

// captureSnapshotInputs copies all engine state under the lock so that the
// subsequent (lock-free) computation does not block ingestion.
func (e *Engine) captureSnapshotInputs() snapshotInputs {
	e.mu.Lock()
	defer e.mu.Unlock()

	return snapshotInputs{
		now:              e.now(),
		startedAt:        e.startedAt,
		totalSyscalls:    e.totalSyscalls,
		totalErrors:      e.totalErrors,
		totalBytes:       e.totalBytes,
		totalReadBytes:   e.totalReadBytes,
		totalWriteBytes:  e.totalWriteBytes,
		totalLatency:     e.totalLatency,
		totalGap:         e.totalGap,
		latencySeries:    e.latencySeries.Values(),
		gapSeries:        e.gapSeries.Values(),
		throughputSeries: e.throughputSeries.Values(),
		syscalls:         e.syscalls.snapshotInputs(),
		families:         e.families.snapshotInputs(),
		files:            e.files.snapshotInputs(),
		processes:        e.processes.snapshotInputs(),
		latencyHist:      e.latencyHist.snapshotInputs(),
		gapHist:          e.gapHist.snapshotInputs(),
	}
}

// buildSubSnapshots runs all per-category snapshot builders concurrently
// using errgroup so that any error from a sub-builder is captured and returned
// to the caller instead of being silently dropped.
func buildSubSnapshots(in snapshotInputs, elapsed time.Duration) (subSnapshots, error) {
	var (
		ss subSnapshots
		eg errgroup.Group
	)

	eg.Go(func() error {
		var err error
		ss.syscalls, err = buildSyscallSnapshots(in.syscalls, elapsed)
		return err
	})
	eg.Go(func() error {
		var err error
		ss.families, err = buildFamilySnapshots(in.families, elapsed)
		return err
	})
	eg.Go(func() error {
		var err error
		ss.files, err = buildFileSnapshots(in.files)
		return err
	})
	eg.Go(func() error {
		var err error
		ss.processes, err = buildProcessSnapshots(in.processes, elapsed)
		return err
	})
	eg.Go(func() error {
		var err error
		ss.latencyHist, err = buildHistogramSnapshot(in.latencyHist)
		return err
	})
	eg.Go(func() error {
		var err error
		ss.gapHist, err = buildHistogramSnapshot(in.gapHist)
		return err
	})

	if err := eg.Wait(); err != nil {
		return subSnapshots{}, err
	}

	return ss, nil
}

// populateSnapshotFields fills in the scalar fields of the snapshot from the
// captured inputs and pre-computed elapsed/rateDiv values.
func populateSnapshotFields(snap *Snapshot, in snapshotInputs, elapsed time.Duration) {
	rateDiv := elapsed.Seconds()

	snap.GeneratedAt = in.now
	snap.Elapsed = elapsed
	snap.TotalSyscalls = in.totalSyscalls
	snap.TotalErrors = in.totalErrors
	snap.TotalBytes = in.totalBytes
	snap.SyscallRatePerSec = safeRate(in.totalSyscalls, rateDiv)
	snap.ErrorRatePerSec = safeRate(in.totalErrors, rateDiv)
	snap.ReadBytesPerSec = safeRate(in.totalReadBytes, rateDiv)
	snap.WriteBytesPerSec = safeRate(in.totalWriteBytes, rateDiv)
	snap.LatencyMeanNs = safeMean(in.totalLatency, in.totalSyscalls)
	snap.GapMeanNs = safeMean(in.totalGap, in.totalSyscalls)
	snap.LatencyTrend = detectTrend(in.latencySeries)
	snap.GapTrend = detectTrend(in.gapSeries)
	snap.ThroughputTrend = detectTrend(in.throughputSeries)
}

// Snapshot returns an immutable point-in-time view of all stats.
// It captures engine state under the lock, then builds sub-snapshots
// concurrently via errgroup, and finally assembles the result without holding
// the lock. An error is returned if any sub-builder fails.
func (e *Engine) Snapshot() (*Snapshot, error) {
	if e == nil {
		return nil, nil
	}

	in := e.captureSnapshotInputs()
	elapsed := nonNegativeDuration(in.now.Sub(in.startedAt))

	ss, err := buildSubSnapshots(in, elapsed)
	if err != nil {
		return nil, err
	}

	snap := NewSnapshotWithFamilies(
		in.latencySeries, in.gapSeries, in.throughputSeries,
		ss.syscalls, ss.families, ss.files, ss.processes,
		ss.latencyHist, ss.gapHist,
	)
	populateSnapshotFields(&snap, in, elapsed)

	return &snap, nil
}

func safeMean(total uint64, count uint64) float64 {
	if count == 0 {
		return 0
	}
	return float64(total) / float64(count)
}

func nonNegativeDuration(d time.Duration) time.Duration {
	if d < 0 {
		return 0
	}
	return d
}

func detectTrend(series []float64) Trend {
	if len(series) < trendWindowSlots*2 {
		return Trend{Direction: TrendStable}
	}

	prev := average(series[len(series)-trendWindowSlots*2 : len(series)-trendWindowSlots])
	recent := average(series[len(series)-trendWindowSlots:])
	delta := recent - prev

	if prev == 0 {
		if recent == 0 {
			return Trend{Direction: TrendStable}
		}
		return Trend{Direction: TrendRising, DeltaPercent: 100}
	}

	deltaPercent := delta / math.Abs(prev) * 100
	if math.Abs(deltaPercent) < 5 {
		return Trend{Direction: TrendStable, DeltaPercent: deltaPercent}
	}
	if deltaPercent > 0 {
		return Trend{Direction: TrendRising, DeltaPercent: deltaPercent}
	}
	return Trend{Direction: TrendFalling, DeltaPercent: deltaPercent}
}

func average(values []float64) float64 {
	if len(values) == 0 {
		return 0
	}
	sum := 0.0
	for _, v := range values {
		sum += v
	}
	return sum / float64(len(values))
}