From 7bf9cee1494686c6f02465c07fb3d8063997dd71 Mon Sep 17 00:00:00 2001 From: Aldo Lacuku Date: Wed, 30 Aug 2023 17:18:09 +0200 Subject: [PATCH] fix(cmd): correctly propagate signal handler to sub-commands The context used to handle the signals is not propagated to the sub-commands. This makes `falcoctl` unresponsive to signals sent to it. This commit fixes this behavior by correctly passing the context that handles the signals. Signed-off-by: Aldo Lacuku --- cmd/root.go | 11 ----------- main.go | 15 ++++++++++++++- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index fb2acb00..5beec79c 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -16,9 +16,6 @@ package cmd import ( "context" - "fmt" - "os/signal" - "syscall" "github.com/spf13/cobra" @@ -68,14 +65,6 @@ func New(ctx context.Context, opt *options.Common) *cobra.Command { // Execute configures the signal handlers and runs the command. func Execute(cmd *cobra.Command, printer *output.Printer) error { - ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL) - - // If the ctx is marked as done then we reset the signals. - go func() { - <-ctx.Done() - fmt.Printf("\nreceived signal, terminating...\n") - stop() - }() // we do not log the error here since we expect that each subcommand // handles the errors by itself. err := cmd.Execute() diff --git a/main.go b/main.go index fff9ba38..b2b6844f 100644 --- a/main.go +++ b/main.go @@ -18,6 +18,8 @@ package main import ( "context" "os" + "os/signal" + "syscall" "github.com/falcosecurity/falcoctl/cmd" "github.com/falcosecurity/falcoctl/pkg/options" @@ -27,7 +29,18 @@ func main() { // Set up the root cmd. opt := options.NewOptions() opt.Initialize(options.WithWriter(os.Stdout)) - rootCmd := cmd.New(context.Background(), opt) + + // Register signal handler + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL) + // If the ctx is marked as done then we reset the signals. + go func() { + <-ctx.Done() + opt.Printer.Info.Println("Received signal, terminating...") + stop() + }() + + // Create root command + rootCmd := cmd.New(ctx, opt) // Execute the command. if err := cmd.Execute(rootCmd, opt.Printer); err != nil {