Abort on SIGTERM after waiting for the HTTP requests to finish

This commit is contained in:
André Duffeck
2025-11-25 15:45:02 +01:00
parent 9457d264a5
commit 41602dae0e

View File

@@ -11,8 +11,11 @@ import (
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
"os/signal"
"strconv" "strconv"
"strings" "strings"
"sync"
"syscall"
"time" "time"
"github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter"
@@ -115,6 +118,18 @@ func BenchmarkClientCommand(cfg *config.Config) *cli.Command {
}, },
Category: "benchmark", Category: "benchmark",
Action: func(c *cli.Context) error { Action: func(c *cli.Context) error {
// Set up signal handling for Ctrl+C
ctx, cancel := context.WithCancel(c.Context)
defer cancel()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
go func() {
<-sigChan
fmt.Println("\nReceived interrupt signal, shutting down...")
cancel()
}()
opt := clientOptions{ opt := clientOptions{
url: c.Args().First(), url: c.Args().First(),
insecure: c.Bool("insecure"), insecure: c.Bool("insecure"),
@@ -258,7 +273,7 @@ func BenchmarkClientCommand(cfg *config.Config) *cli.Command {
defer opt.ticker.Stop() defer opt.ticker.Stop()
} }
return client(c.Context, opt) return client(ctx, opt)
}, },
} }
@@ -283,8 +298,12 @@ func client(ctx context.Context, o clientOptions) error {
status int status int
} }
stats := make(chan stat) stats := make(chan stat)
var wg sync.WaitGroup
for i := 0; i < o.jobs; i++ { for i := 0; i < o.jobs; i++ {
wg.Add(1)
go func(i int) { go func(i int) {
defer wg.Done()
tr := &http.Transport{ tr := &http.Transport{
TLSClientConfig: &tls.Config{ TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12, MinVersion: tls.VersionTLS12,
@@ -362,6 +381,7 @@ func client(ctx context.Context, o clientOptions) error {
fmt.Printf("req %d took %v and returned status %d\n", numRequests, stat.duration, stat.status) fmt.Printf("req %d took %v and returned status %d\n", numRequests, stat.duration, stat.status)
case <-ctx.Done(): case <-ctx.Done():
fmt.Println("\nShutting down...") fmt.Println("\nShutting down...")
wg.Wait()
return nil return nil
} }
} }
@@ -384,6 +404,7 @@ func client(ctx context.Context, o clientOptions) error {
fmt.Printf("\n%d req at %v/req\n", numRequests, duration/time.Duration(numRequests)) fmt.Printf("\n%d req at %v/req\n", numRequests, duration/time.Duration(numRequests))
} }
fmt.Println("Shutting down...") fmt.Println("Shutting down...")
wg.Wait()
return nil return nil
} }
} }