Skip to content

Commit

Permalink
audittail: React to SIGINT (#17)
Browse files Browse the repository at this point in the history
The kubelet uses SIGINT to trigger shutdown of pods, this makes sure we
can appropriately react to it.

Signed-off-by: Juan Antonio Osorio <[email protected]>
  • Loading branch information
JAORMX authored Apr 14, 2022
1 parent e74aa52 commit d0f999b
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 4 deletions.
4 changes: 4 additions & 0 deletions cmds/audittail/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ const (
// rootCmd represents the base command when called without any subcommands.
var rootCmd = NewRootCmd()

func GetCmd() *cobra.Command {
return rootCmd
}

func NewRootCmd() *cobra.Command {
c := &cobra.Command{
Use: "audittail",
Expand Down
7 changes: 7 additions & 0 deletions cmds/audittail/cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,3 +237,10 @@ func TestFileTrailerUnknownErrorWhenTailing(t *testing.T) {
err := ft.tailFile(context.Background())
require.Error(t, err, "unexpected success")
}

func TestRootCmdSingletonGet(t *testing.T) {
t.Parallel()

c := GetCmd()
require.Equal(t, &rootCmd, &c, "GetCmd() should return the rootCmd singleton")
}
36 changes: 32 additions & 4 deletions cmds/audittail/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,42 @@ limitations under the License.
package main

import (
"context"
"os"
"os/signal"

"github.com/metal-toolbox/auditevent/cmds/audittail/cmd"
)

func main() {
c := cmd.NewRootCmd()
if err := c.Execute(); err != nil {
os.Exit(1)
func runCommand() int {
ctx := context.Background()

// trap Ctrl+C and call cancel on the context
ctx, cancel := context.WithCancel(ctx)

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)

defer func() {
signal.Stop(c)
cancel()
}()

go func() {
select {
case <-c:
cancel()
case <-ctx.Done():
}
}()

if err := cmd.GetCmd().ExecuteContext(ctx); err != nil {
return 1
}

return 0
}

func main() {
os.Exit(runCommand())
}

0 comments on commit d0f999b

Please sign in to comment.