Skip to content

Commit

Permalink
fix(cmd): correctly propagate signal handler to sub-commands
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
alacuku committed Aug 30, 2023
1 parent 95fdff8 commit 7bf9cee
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
11 changes: 0 additions & 11 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@ package cmd

import (
"context"
"fmt"
"os/signal"
"syscall"

"github.com/spf13/cobra"

Expand Down Expand Up @@ -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()
Expand Down
15 changes: 14 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ package main
import (
"context"
"os"
"os/signal"
"syscall"

"github.com/falcosecurity/falcoctl/cmd"
"github.com/falcosecurity/falcoctl/pkg/options"
Expand All @@ -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 {
Expand Down

0 comments on commit 7bf9cee

Please sign in to comment.