-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.go
More file actions
502 lines (442 loc) · 13.7 KB
/
Copy pathengine.go
File metadata and controls
502 lines (442 loc) · 13.7 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
package testrunner
import (
"context"
"fmt"
"math"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"gopkg.in/yaml.v3"
)
var varPattern = regexp.MustCompile(`\{\{\s*(\w+)\s*\}\}`)
// Engine executes a Scenario using the given Registry.
type Engine struct {
registry *Registry
log func(format string, args ...interface{})
// PhaseHook fires at phase boundaries when set. Shape:
// PhaseHook("before", name, "", "") at phase start;
// PhaseHook("after", name, state, errMsg) at phase end.
// Used by the run-control schema (status.json) to keep the
// mutable state up-to-date during the run. Errors from the
// hook are non-fatal — engine logs and proceeds — so a
// flaky shared-drive write never kills the run itself.
PhaseHook func(when, phase, state, errMsg string)
// CancelCheck, when set, is polled before each phase. If it
// returns true, the engine stops dispatching new phases and
// returns a Cancelled-shaped result. Always-phases still run
// for cleanup. Used by the control/cancel signal pattern.
CancelCheck func() bool
}
// NewEngine creates an engine with the given registry and logger.
func NewEngine(registry *Registry, log func(format string, args ...interface{})) *Engine {
if log == nil {
log = func(string, ...interface{}) {}
}
return &Engine{registry: registry, log: log}
}
// callPhaseHook invokes PhaseHook if set, swallowing errors so the
// run never dies because a status write hiccupped.
func (e *Engine) callPhaseHook(when, phase, state, errMsg string) {
if e.PhaseHook == nil {
return
}
defer func() {
if r := recover(); r != nil {
e.log("phase-hook panic: %v", r)
}
}()
e.PhaseHook(when, phase, state, errMsg)
}
// Run executes the scenario end-to-end and returns the result.
func (e *Engine) Run(ctx context.Context, s *Scenario, actx *ActionContext) *ScenarioResult {
start := time.Now()
result := &ScenarioResult{
Name: s.Name,
Status: StatusPass,
}
// Apply scenario timeout.
if s.Timeout.Duration > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, s.Timeout.Duration)
defer cancel()
}
// Seed vars from env (merge: env provides defaults, existing vars win).
if actx.Vars == nil {
actx.Vars = make(map[string]string)
}
for k, v := range s.Env {
if _, exists := actx.Vars[k]; !exists {
actx.Vars[k] = v
}
}
// Allocate a unique per-run temp directory (T6).
if actx.TempRoot == "" {
actx.TempRoot = fmt.Sprintf("/tmp/sw-run-%s-%d", s.Name, start.UnixMilli())
}
actx.Vars["__temp_dir"] = actx.TempRoot
// Separate always-phases for deferred cleanup.
var normalPhases, alwaysPhases []Phase
for _, p := range s.Phases {
if p.Always {
alwaysPhases = append(alwaysPhases, p)
} else {
normalPhases = append(normalPhases, p)
}
}
// Execute normal phases sequentially, expanding repeat.
failed := false
for _, phase := range normalPhases {
count := phase.Repeat
if count <= 0 {
count = 1
}
// Collect save_as values across iterations for aggregation.
var iterValues map[string][]float64
if count > 1 && phase.Aggregate != "none" {
iterValues = make(map[string][]float64)
}
for iter := 1; iter <= count; iter++ {
if e.CancelCheck != nil && e.CancelCheck() {
failed = true
result.Status = StatusFail
result.Cancelled = true
result.Error = "cancelled before phase " + phase.Name
break
}
iterPhase := phase
if phase.Repeat > 1 {
iterPhase.Name = fmt.Sprintf("%s[%d/%d]", phase.Name, iter, count)
}
e.callPhaseHook("before", iterPhase.Name, "", "")
pr := e.runPhase(ctx, actx, iterPhase)
result.Phases = append(result.Phases, pr)
e.callPhaseHook("after", iterPhase.Name, string(pr.Status), pr.Error)
// Collect numeric save_as values for aggregation.
if iterValues != nil {
for _, act := range phase.Actions {
if act.SaveAs != "" {
if v, ok := actx.Vars[act.SaveAs]; ok {
if f, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil {
iterValues[act.SaveAs] = append(iterValues[act.SaveAs], f)
}
}
}
}
}
if pr.Status == StatusFail {
failed = true
result.Status = StatusFail
result.Error = fmt.Sprintf("phase %q failed: %s", iterPhase.Name, pr.Error)
break
}
}
// Aggregate collected values across iterations.
if iterValues != nil && !failed {
trimPct := phase.TrimPct
// 0 means no trimming (explicit or default). Only auto-default
// when repeat >= 5 and trim_pct was not set.
if trimPct == 0 && count >= 5 {
trimPct = 20
}
agg := phase.Aggregate
if agg == "" {
agg = "median" // default aggregation method
}
for varName, values := range iterValues {
if len(values) < 2 {
continue
}
trimmed := trimOutliers(values, trimPct)
stats := ComputeStats(trimmed)
// Store aggregate results as vars.
switch agg {
case "median":
actx.Vars[varName] = strconv.FormatFloat(stats.P50, 'f', 2, 64)
case "mean":
actx.Vars[varName] = strconv.FormatFloat(stats.Mean, 'f', 2, 64)
}
actx.Vars[varName+"_median"] = strconv.FormatFloat(stats.P50, 'f', 2, 64)
actx.Vars[varName+"_mean"] = strconv.FormatFloat(stats.Mean, 'f', 2, 64)
actx.Vars[varName+"_stddev"] = strconv.FormatFloat(stats.StdDev, 'f', 2, 64)
actx.Vars[varName+"_min"] = strconv.FormatFloat(stats.Min, 'f', 2, 64)
actx.Vars[varName+"_max"] = strconv.FormatFloat(stats.Max, 'f', 2, 64)
actx.Vars[varName+"_n"] = strconv.Itoa(stats.Count)
// Store all raw values as comma-separated string.
parts := make([]string, len(values))
for i, v := range values {
parts[i] = strconv.FormatFloat(v, 'f', 2, 64)
}
actx.Vars[varName+"_all"] = strings.Join(parts, ",")
e.log(" [aggregate] %s: n=%d median=%.2f mean=%.2f stddev=%.2f (trimmed %d%% from %d samples)",
varName, stats.Count, stats.P50, stats.Mean, stats.StdDev, trimPct, len(values))
}
}
if failed {
break
}
}
// Always-phases run regardless of failure, with a fresh 60s context
// so they can complete even if the main context was canceled.
cleanupCtx := context.Background()
cleanupCtx, cleanupCancel := context.WithTimeout(cleanupCtx, 60*time.Second)
defer cleanupCancel()
for _, phase := range alwaysPhases {
e.callPhaseHook("before", phase.Name, "", "")
pr := e.runPhase(cleanupCtx, actx, phase)
result.Phases = append(result.Phases, pr)
e.callPhaseHook("after", phase.Name, string(pr.Status), pr.Error)
}
result.Duration = time.Since(start)
if !failed {
result.Status = StatusPass
}
// Preserve all final vars in the result for downstream reporting.
if len(actx.Vars) > 0 {
result.Vars = make(map[string]string, len(actx.Vars))
for k, v := range actx.Vars {
result.Vars[k] = v
}
}
return result
}
// runPhase executes a single phase (sequential or parallel).
func (e *Engine) runPhase(ctx context.Context, actx *ActionContext, phase Phase) PhaseResult {
start := time.Now()
pr := PhaseResult{
Name: phase.Name,
Status: StatusPass,
}
e.log("[phase] %s", phase.Name)
if phase.Parallel {
pr = e.runPhaseParallel(ctx, actx, phase)
} else {
pr = e.runPhaseSequential(ctx, actx, phase)
}
pr.Duration = time.Since(start)
return pr
}
func (e *Engine) runPhaseSequential(ctx context.Context, actx *ActionContext, phase Phase) PhaseResult {
pr := PhaseResult{
Name: phase.Name,
Status: StatusPass,
}
for i, act := range phase.Actions {
ar := e.runAction(ctx, actx, act)
pr.Actions = append(pr.Actions, ar)
if ar.Status == StatusFail && !act.IgnoreError {
pr.Status = StatusFail
pr.Error = fmt.Sprintf("action %d (%s) failed: %s", i, act.Action, ar.Error)
return pr
}
}
return pr
}
func (e *Engine) runPhaseParallel(ctx context.Context, actx *ActionContext, phase Phase) PhaseResult {
pr := PhaseResult{
Name: phase.Name,
Status: StatusPass,
}
results := make([]ActionResult, len(phase.Actions))
var wg sync.WaitGroup
for i, act := range phase.Actions {
wg.Add(1)
go func(idx int, a Action) {
defer wg.Done()
results[idx] = e.runAction(ctx, actx, a)
}(i, act)
}
wg.Wait()
var errors []string
for i, ar := range results {
pr.Actions = append(pr.Actions, ar)
if ar.Status == StatusFail && !phase.Actions[i].IgnoreError {
pr.Status = StatusFail
errors = append(errors, fmt.Sprintf("action %d (%s): %s", i, phase.Actions[i].Action, ar.Error))
}
}
if len(errors) == 1 {
pr.Error = errors[0]
} else if len(errors) > 1 {
pr.Error = fmt.Sprintf("%d actions failed: [1] %s", len(errors), strings.Join(errors, "; "))
}
return pr
}
// runAction resolves variables and executes a single action.
func (e *Engine) runAction(ctx context.Context, actx *ActionContext, act Action) ActionResult {
start := time.Now()
// Resolve variables in the action.
resolved := resolveAction(act, actx.Vars)
// Serialize resolved action to YAML for report display.
yamlDef := marshalActionYAML(resolved)
handler, err := e.registry.Get(resolved.Action)
if err != nil {
return ActionResult{
Action: resolved.Action,
Status: StatusFail,
Duration: time.Since(start),
Error: err.Error(),
}
}
// Handle delay param.
if d, ok := resolved.Params["delay"]; ok {
dur, err := time.ParseDuration(d)
if err == nil {
e.log(" [delay] %s", d)
select {
case <-time.After(dur):
case <-ctx.Done():
return ActionResult{
Action: resolved.Action,
Status: StatusFail,
Duration: time.Since(start),
Error: ctx.Err().Error(),
}
}
}
}
// Enforce action-level timeout if specified.
var actionTimeout time.Duration
if resolved.Timeout != "" {
if dur, err := time.ParseDuration(resolved.Timeout); err == nil && dur > 0 {
actionTimeout = dur
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, dur)
defer cancel()
}
}
// Log action start with context (node/target if available).
actionLabel := resolved.Action
if resolved.Node != "" {
actionLabel += " @" + resolved.Node
} else if resolved.Target != "" {
actionLabel += " >" + resolved.Target
}
e.log(" [action] %s", actionLabel)
output, err := handler.Execute(ctx, actx, resolved)
elapsed := time.Since(start)
// Enrich timeout errors with action-specific context.
if err != nil && ctx.Err() != nil && actionTimeout > 0 {
err = fmt.Errorf("action %q timed out after %s: %w", resolved.Action, actionTimeout, err)
}
ar := ActionResult{
Action: resolved.Action,
Duration: elapsed,
YAML: yamlDef,
}
if err != nil {
ar.Status = StatusFail
ar.Error = err.Error()
if act.IgnoreError {
ar.Status = StatusPass
e.log(" [done] %s (ignored error, %s): %v", actionLabel, fmtDuration(elapsed), err)
} else {
e.log(" [FAIL] %s (%s): %v", actionLabel, fmtDuration(elapsed), err)
}
} else {
ar.Status = StatusPass
// Only log completion for slow actions (>1s) to avoid noise on quick ones.
if elapsed >= time.Second {
e.log(" [done] %s (%s)", actionLabel, fmtDuration(elapsed))
}
}
// Store output as var if save_as is set.
if resolved.SaveAs != "" && output != nil {
if v, ok := output["value"]; ok {
actx.Vars[resolved.SaveAs] = v
e.log(" [var] %s = %s", resolved.SaveAs, truncate(v, 60))
}
}
// Store all output keys with double-underscore prefix for cleanup vars.
if output != nil {
for k, v := range output {
if strings.HasPrefix(k, "__") {
actx.Vars[k] = v
}
}
}
if output != nil {
if v, ok := output["value"]; ok {
ar.Output = truncate(v, 65536)
}
}
return ar
}
// resolveAction substitutes {{ var }} references in the action's fields.
func resolveAction(act Action, vars map[string]string) Action {
resolved := Action{
Action: act.Action,
Target: act.Target,
Replica: act.Replica,
Node: act.Node,
SaveAs: act.SaveAs,
IgnoreError: act.IgnoreError,
Retry: act.Retry,
Timeout: act.Timeout,
Params: make(map[string]string),
}
// Copy and resolve params.
for k, v := range act.Params {
resolved.Params[k] = resolveVars(v, vars)
}
return resolved
}
// resolveVars replaces {{ name }} with the value from vars.
func resolveVars(s string, vars map[string]string) string {
return varPattern.ReplaceAllStringFunc(s, func(match string) string {
sub := varPattern.FindStringSubmatch(match)
if len(sub) < 2 {
return match
}
name := sub[1]
if v, ok := vars[name]; ok {
return v
}
return match // leave unresolved
})
}
func truncate(s string, max int) string {
if len(s) <= max {
return s
}
return s[:max] + fmt.Sprintf("...[truncated, %d/%d bytes]", max, len(s))
}
// fmtDuration formats a duration as a human-readable string.
func fmtDuration(d time.Duration) string {
if d < time.Second {
return fmt.Sprintf("%dms", d.Milliseconds())
}
if d < time.Minute {
return fmt.Sprintf("%.1fs", d.Seconds())
}
return fmt.Sprintf("%dm%ds", int(d.Minutes()), int(d.Seconds())%60)
}
// marshalActionYAML serializes a resolved action to YAML for report
// display. Secret-named params are redacted before marshaling so the
// run bundle's result.json never carries live credentials.
func marshalActionYAML(act Action) string {
data, err := yaml.Marshal(RedactAction(act))
if err != nil {
return ""
}
return string(data)
}
// trimOutliers removes the top and bottom pct% of values.
// E.g. pct=20 on 10 values removes the 2 lowest and 2 highest, returning 6.
// Returns a copy; does not modify the input.
func trimOutliers(values []float64, pct int) []float64 {
if len(values) <= 2 || pct <= 0 {
return values
}
sorted := make([]float64, len(values))
copy(sorted, values)
sort.Float64s(sorted)
trim := int(math.Round(float64(len(sorted)) * float64(pct) / 100.0))
if trim*2 >= len(sorted) {
// Can't trim more than half from each end; keep at least 1.
trim = (len(sorted) - 1) / 2
}
return sorted[trim : len(sorted)-trim]
}