-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.go
More file actions
597 lines (504 loc) · 15.3 KB
/
Copy pathexecutor.go
File metadata and controls
597 lines (504 loc) · 15.3 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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
package chaoskit
import (
"context"
"errors"
"fmt"
"log/slog"
"math/rand"
"os"
"time"
)
// ExecutionResult contains the result of a scenario execution
type ExecutionResult struct {
ScenarioName string
Success bool
Error error
Duration time.Duration
StepsExecuted int
Timestamp time.Time
}
// FailurePolicy defines how the executor handles failures
type FailurePolicy int
const (
// FailFast stops execution on first failure
FailFast FailurePolicy = iota
// ContinueOnFailure continues execution even after failures
ContinueOnFailure
)
// Executor runs scenarios
type Executor struct {
metrics *MetricsCollector
reporter *Reporter
logger *slog.Logger
failurePolicy FailurePolicy
}
// ExecutorOption configures an Executor
type ExecutorOption func(*Executor)
// WithLogger sets a custom logger (deprecated, use WithSlogLogger)
func WithLogger(logger Logger) ExecutorOption {
return func(e *Executor) {
// Convert old Logger to slog.Logger for backward compatibility
e.logger = slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
}
}
// WithSlogLogger sets a structured logger
func WithSlogLogger(logger *slog.Logger) ExecutorOption {
return func(e *Executor) {
e.logger = logger
}
}
// WithJSONLogging sets JSON output format
func WithJSONLogging() ExecutorOption {
return func(e *Executor) {
e.logger = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
}
}
// WithFailurePolicy sets the failure handling policy
func WithFailurePolicy(policy FailurePolicy) ExecutorOption {
return func(e *Executor) {
e.failurePolicy = policy
}
}
// WithMetrics sets a custom metrics collector
func WithMetrics(metrics *MetricsCollector) ExecutorOption {
return func(e *Executor) {
e.metrics = metrics
}
}
// WithReporter sets a custom reporter
func WithReporter(reporter *Reporter) ExecutorOption {
return func(e *Executor) {
e.reporter = reporter
}
}
// NewExecutor creates a new executor with options
func NewExecutor(opts ...ExecutorOption) *Executor {
e := &Executor{
metrics: NewMetricsCollector(),
reporter: NewReporter(),
logger: slog.Default(),
failurePolicy: FailFast,
}
for _, opt := range opts {
opt(e)
}
return e
}
// wrappedStep is a helper type that wraps a function to implement the Step interface
type wrappedStep struct {
name string
execute func(ctx context.Context, target Target) error
}
func (w *wrappedStep) Name() string {
return w.name
}
func (w *wrappedStep) Execute(ctx context.Context, target Target) error {
return w.execute(ctx, target)
}
// internal event recorder that forwards to validators
type validatorEventRecorder struct{ validators []Validator }
func (r *validatorEventRecorder) RecordPanic(ctx context.Context) {
for _, v := range r.validators {
if pr, ok := v.(PanicRecorder); ok {
pr.RecordPanic(ctx)
}
}
}
func (r *validatorEventRecorder) RecordRecursionDepth(depth int) {
for _, v := range r.validators {
if rr, ok := v.(RecursionRecorder); ok {
rr.RecordRecursion(depth)
}
}
}
func (r *validatorEventRecorder) RecordError(ctx context.Context) {
for _, v := range r.validators {
if er, ok := v.(ErrorRecorder); ok {
er.RecordError(ctx)
}
}
}
// getAllInjectors collects all injectors from scenario (both direct and from scopes)
func (e *Executor) getAllInjectors(scenario *Scenario) []Injector {
allInjectors := make([]Injector, 0, len(scenario.injectors))
// Add direct injectors
allInjectors = append(allInjectors, scenario.injectors...)
// Add injectors from scopes
for _, scope := range scenario.scopes {
if e.logger != nil {
e.logger.Debug("scope contains injectors",
slog.String("scope", scope.name),
slog.Int("injector_count", len(scope.injectors)))
}
allInjectors = append(allInjectors, scope.injectors...)
}
return allInjectors
}
// Run executes a scenario
func (e *Executor) Run(ctx context.Context, scenario *Scenario) error {
if scenario.target == nil {
return fmt.Errorf("scenario %s has no target", scenario.name)
}
// Create a deterministic random generator if seed is set
var rng *rand.Rand
if scenario.seed != nil {
rng = rand.New(rand.NewSource(*scenario.seed))
if e.logger != nil {
e.logger.Info("using deterministic seed",
slog.String("scenario", scenario.name),
slog.Int64("seed", *scenario.seed))
}
} else {
rng = rand.New(rand.NewSource(rand.Int63()))
}
ctx = AttachRand(ctx, rng)
// Setup target
if err := scenario.target.Setup(ctx); err != nil {
return fmt.Errorf("setup failed: %w", err)
}
defer func() {
if err := scenario.target.Teardown(ctx); err != nil {
if e.logger != nil {
e.logger.Warn("teardown error",
slog.String("scenario", scenario.name),
slog.String("error", err.Error()))
}
}
}()
// Collect all injectors (from direct injectors and scopes)
allInjectors := e.getAllInjectors(scenario)
// Setup network injectors first (if they need proxy setup)
networkInjectors := make([]Injector, 0)
for _, inj := range allInjectors {
if lifecycle, ok := inj.(NetworkInjectorLifecycle); ok {
if err := lifecycle.SetupNetwork(ctx); err != nil {
return fmt.Errorf("network setup failed for %s: %w", inj.Name(), err)
}
networkInjectors = append(networkInjectors, inj)
if e.logger != nil {
e.logger.Info("network injector setup completed",
slog.String("scenario", scenario.name),
slog.String("injector", inj.Name()))
}
}
}
defer func() {
for _, inj := range networkInjectors {
if lifecycle, ok := inj.(NetworkInjectorLifecycle); ok {
if err := lifecycle.TeardownNetwork(ctx); err != nil {
if e.logger != nil {
e.logger.Warn("network teardown error",
slog.String("scenario", scenario.name),
slog.String("injector", inj.Name()),
slog.String("error", err.Error()))
}
}
}
}
}()
// Start injectors
activeInjectors := make([]Injector, 0, len(allInjectors))
for _, inj := range allInjectors {
if err := inj.Inject(ctx); err != nil {
if e.logger != nil {
e.logger.Error("injector failed to start",
slog.String("scenario", scenario.name),
slog.String("injector", inj.Name()),
slog.String("error", err.Error()))
}
// Stop already started injectors
e.stopInjectors(ctx, activeInjectors)
return fmt.Errorf("injector %s failed: %w", inj.Name(), err)
}
activeInjectors = append(activeInjectors, inj)
}
defer e.stopInjectors(ctx, activeInjectors)
// Execute scenario
if scenario.duration > 0 {
return e.runForDuration(ctx, scenario)
}
// Check if repeat is set
if scenario.repeat <= 0 {
return fmt.Errorf("scenario %s: repeat must be > 0 (got %d), use RunFor() for duration-based execution",
scenario.name, scenario.repeat)
}
return e.runRepeated(ctx, scenario)
}
func (e *Executor) stopInjectors(ctx context.Context, injectors []Injector) {
for _, inj := range injectors {
if err := inj.Stop(ctx); err != nil {
if e.logger != nil {
e.logger.Warn("injector failed to stop",
slog.String("injector", inj.Name()),
slog.String("error", err.Error()))
}
}
}
}
func (e *Executor) runRepeated(ctx context.Context, scenario *Scenario) error {
var firstError error
for i := 0; i < scenario.repeat; i++ {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
// Reset validators before each iteration
e.resetValidators(scenario.validators)
result := e.executeOnce(ctx, scenario)
e.metrics.RecordExecution(result)
e.reporter.AddResult(result)
if result.Error != nil {
if firstError == nil {
firstError = fmt.Errorf("execution %d failed: %w", i+1, result.Error)
}
if e.failurePolicy == FailFast {
return firstError
}
// Continue on failure - just log it
if e.logger != nil {
e.logger.Warn("execution failed (continuing)",
slog.String("scenario", scenario.name),
slog.Int("iteration", i+1),
slog.String("error", result.Error.Error()))
}
}
}
return firstError
}
func (e *Executor) runForDuration(ctx context.Context, scenario *Scenario) error {
ctx, cancel := context.WithTimeout(ctx, scenario.duration)
defer cancel()
iteration := 0
var firstError error
for {
select {
case <-ctx.Done():
// Timeout is expected, not an error
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return firstError
}
return ctx.Err()
default:
}
// Reset validators before each iteration
e.resetValidators(scenario.validators)
result := e.executeOnce(ctx, scenario)
e.metrics.RecordExecution(result)
e.reporter.AddResult(result)
if result.Error != nil {
if firstError == nil {
firstError = fmt.Errorf("execution %d failed: %w", iteration+1, result.Error)
}
if e.failurePolicy == FailFast {
return firstError
}
// Continue on failure - just log it
if e.logger != nil {
e.logger.Warn("execution failed (continuing)",
slog.String("scenario", scenario.name),
slog.Int("iteration", iteration+1),
slog.String("error", result.Error.Error()))
}
}
iteration++
}
}
func (e *Executor) resetValidators(validators []Validator) {
for _, val := range validators {
if resettable, ok := val.(Resettable); ok {
resettable.Reset()
}
}
}
func (e *Executor) executeOnce(ctx context.Context, scenario *Scenario) ExecutionResult {
start := time.Now()
result := ExecutionResult{
ScenarioName: scenario.name,
Success: true,
Timestamp: start,
}
// Ensure rand generator is attached (in case executeOnce is called directly)
if ctx.Value(randKey{}) == nil {
var rng *rand.Rand
if scenario.seed != nil {
rng = rand.New(rand.NewSource(*scenario.seed))
} else {
rng = rand.New(rand.NewSource(rand.Int63()))
}
ctx = AttachRand(ctx, rng)
}
// Attach event recorder to context for steps to use
recorder := &validatorEventRecorder{validators: scenario.validators}
ctx = AttachRecorder(ctx, recorder)
// Attach logger to context for injectors and validators to use
if e.logger != nil {
ctx = AttachLogger(ctx, e.logger)
}
// Collect all injectors (from direct injectors and scopes)
allInjectors := e.getAllInjectors(scenario)
// Attach chaos context for user code to use
chaosCtx := e.buildChaosContext(ctx, allInjectors)
ctx = AttachChaos(ctx, chaosCtx)
// Execute steps with panic recovery
for i, step := range scenario.steps {
stepErr := func() (err error) {
defer func() {
if r := recover(); r != nil {
// record panic and convert to error
recorder.RecordPanic(ctx)
err = fmt.Errorf("panic in step %s: %v", step.Name(), r)
}
}()
// Apply injectors before step
for _, inj := range allInjectors {
if stepInj, ok := inj.(StepInjector); ok {
if err := stepInj.BeforeStep(ctx); err != nil {
return fmt.Errorf("injector %s before step failed: %w", inj.Name(), err)
}
}
}
// Apply step wrappers from validators
// Wrappers are applied in reverse order so the first wrapper becomes the outermost
wrappedStepFunc := func(ctx context.Context, target Target) error {
return step.Execute(ctx, target)
}
for j := len(scenario.validators) - 1; j >= 0; j-- {
if wrapper, ok := scenario.validators[j].(StepWrapper); ok {
wrappedStepFunc = wrapper.WrapStep(&wrappedStep{
name: step.Name(),
execute: wrappedStepFunc,
})
}
}
// Execute wrapped step
stepErr := wrappedStepFunc(ctx, scenario.target)
// Apply injectors after step
for _, inj := range allInjectors {
if stepInj, ok := inj.(StepInjector); ok {
if err := stepInj.AfterStep(ctx, stepErr); err != nil {
return fmt.Errorf("injector %s after step failed: %w", inj.Name(), err)
}
}
}
return stepErr
}()
if stepErr != nil {
result.Success = false
result.Error = fmt.Errorf("step %s failed: %w", step.Name(), stepErr)
result.StepsExecuted = i
result.Duration = time.Since(start)
return result
}
}
result.StepsExecuted = len(scenario.steps)
// Run validators
for _, val := range scenario.validators {
if err := val.Validate(ctx, scenario.target); err != nil {
result.Success = false
result.Error = fmt.Errorf("validator %s failed: %w", val.Name(), err)
result.Duration = time.Since(start)
return result
}
}
result.Duration = time.Since(start)
return result
}
func (e *Executor) buildChaosContext(ctx context.Context, injectors []Injector) *ChaosContext {
chaos := NewChaosContext()
// Find delay injector
for _, inj := range injectors {
if delayProvider, ok := inj.(ChaosDelayProvider); ok {
// Copy provider to local variable to avoid closure issues
dp := delayProvider
chaos.SetDelayFunc(func() bool {
delay, ok := dp.GetChaosDelay(ctx)
if ok && delay > 0 {
GetLogger(ctx).Debug("delay injected in user code",
slog.Duration("delay", delay))
time.Sleep(delay)
return true
}
return false
})
}
if panicProvider, ok := inj.(ChaosErrorProvider); ok {
// Copy provider to local variable to avoid closure issues
pp := panicProvider
chaos.SetErrorFunc(func() error {
if err := pp.ShouldReturnError(); err != nil {
GetLogger(ctx).Debug("error returned in user code",
slog.String("error", err.Error()))
return err
}
return nil
})
}
if panicProvider, ok := inj.(ChaosPanicProvider); ok {
// Copy provider to local variable to avoid closure issues
pp := panicProvider
chaos.SetPanicFunc(func() bool {
if pp.ShouldChaosPanic() {
GetLogger(ctx).Debug("panic triggered in user code",
slog.Float64("probability", pp.GetPanicProbability()))
return true
}
return false
})
}
// Find network injector
if networkProvider, ok := inj.(ChaosNetworkProvider); ok {
// Copy provider to local variable to avoid closure issues
np := networkProvider
chaos.SetNetworkFunc(func(host string, port int) bool {
if !np.ShouldApplyNetworkChaos(host, port) {
return false
}
// Apply latency if configured
if latency, hasLatency := np.GetNetworkLatency(host, port); hasLatency && latency > 0 {
GetLogger(ctx).Debug("network latency injected",
slog.String("host", host),
slog.Int("port", port),
slog.Duration("latency", latency))
time.Sleep(latency)
return true
}
// Check for connection drop
if np.ShouldDropConnection(host, port) {
GetLogger(ctx).Debug("network connection drop simulated",
slog.String("host", host),
slog.Int("port", port))
// TODO: implement connection drop
return true
}
return false
})
}
// Find context cancellation injector
if cancellationProvider, ok := inj.(ChaosContextCancellationProvider); ok {
// Copy provider to local variable to avoid closure issues
cp := cancellationProvider
chaos.SetCancellationFunc(func(parent context.Context) (context.Context, context.CancelFunc) {
return cp.GetChaosContext(parent)
})
}
// Register universal providers
if universalProvider, ok := inj.(ChaosProvider); ok {
chaos.RegisterProvider(universalProvider)
}
// Collect metrics if available
if metricsProvider, ok := inj.(MetricsProvider); ok {
metrics := metricsProvider.GetMetrics()
e.metrics.RecordInjectorMetrics(inj.Name(), metrics)
}
}
return chaos
}
// Metrics returns the metrics collector
func (e *Executor) Metrics() *MetricsCollector {
return e.metrics
}
// Reporter returns the reporter
func (e *Executor) Reporter() *Reporter {
return e.reporter
}