Skip to content

Commit

Permalink
Merge pull request #26 from brenol/fix-panic-when-stopping-infinite-a…
Browse files Browse the repository at this point in the history
…ttack

fix panic when doing Ctrl-C in the middle of a attack
  • Loading branch information
nakabonne authored Oct 2, 2020
2 parents 0091795 + 95a3d3f commit d334ef0
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 9 deletions.
10 changes: 5 additions & 5 deletions attacker/attacker.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ type Result struct {
// Attack keeps the request running for the specified period of time.
// Results are sent to the given channel as soon as they arrive.
// When the attack is over, it gives back final statistics.
func Attack(ctx context.Context, target string, resCh chan *Result, metricsCh chan *Metrics, opts Options) *Metrics {
func Attack(ctx context.Context, target string, resCh chan *Result, metricsCh chan *Metrics, opts Options) {
if target == "" {
return nil
return
}
if opts.Method == "" {
opts.Method = DefaultMethod
Expand Down Expand Up @@ -88,14 +88,14 @@ func Attack(ctx context.Context, target string, resCh chan *Result, metricsCh ch
select {
case <-ctx.Done():
opts.Attacker.Stop()
// metricsCh is already closed (as context is done) so we shouldn't send any metric
return
default:
resCh <- &Result{Latency: res.Latency}
metrics.Add(res)
metricsCh <- newMetrics(&metrics)
}
}
metrics.Close()

// TODO: No need to give back metrics anymore.
return newMetrics(&metrics)
metricsCh <- newMetrics(&metrics)
}
3 changes: 1 addition & 2 deletions attacker/attacker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ func TestAttack(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
resCh := make(chan *Result, 100)
metricsCh := make(chan *Metrics, 100)
got := Attack(ctx, tt.target, resCh, metricsCh, tt.opts)
assert.Equal(t, tt.want, got)
Attack(ctx, tt.target, resCh, metricsCh, tt.opts)
assert.Equal(t, tt.wantResCount, len(resCh))
})
}
Expand Down
3 changes: 1 addition & 2 deletions gui/keybinds.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ func attack(ctx context.Context, d *drawer, target string, opts attacker.Options
go d.redrawChart(ctx, requestNum)
go d.redrawGauge(ctx, requestNum)
go func(ctx context.Context, d *drawer, t string, o attacker.Options) {
metrics := attacker.Attack(ctx, t, d.chartCh, d.metricsCh, o)
d.metricsCh <- metrics
attacker.Attack(ctx, t, d.chartCh, d.metricsCh, o) // this blocks until attack finishes
d.chartCh <- &attacker.Result{End: true}
d.messageCh <- "Attack completed"
}(ctx, d, target, opts)
Expand Down

0 comments on commit d334ef0

Please sign in to comment.