Commit 501364e7
501364e77073Merged
Amir Shams <[email protected]> ยท 2 years ago ยท 1 file ยท ~1 modified
Description
feat: cancel ctx when SIGTERM or SIGINT arrives
- add boolean flag HELMWAVE_HANDLE_SIGNAL
[experimental]
Details
- Commit
- 501364e77073
- Parent
- cf17636fd39b
cmd/helmwave/main.gomodifiedView file
@@ -1,8 +1,11 @@
11
package main22
33
import (4+
"context"45
"fmt"56
"os"7+
"os/signal"8+
"syscall"69
710
"github.com/helmwave/helmwave/pkg/action"811
"github.com/helmwave/helmwave/pkg/cache"@@ -71,6 +74,10 @@
7174
"2. $ helmwave up\n"7275
7376
c.Before = func(ctx *cli.Context) error {77+
if ctx.Bool("cancel-on-kill") {78+
// cancel the ctx if it gets these signals79+
ctx.Context = cancelCtxOnSignal(ctx.Context, syscall.SIGTERM, syscall.SIGINT)80+
}7481
err := logSetup.Default.Run(ctx)7582
if err != nil {7683
return err@@ -84,6 +91,7 @@
8491
return nil8592
}8693
c.Flags = append(logSetup.Default.Flags(), cache.DefaultConfig.Flags()...)94+
c.Flags = append(c.Flags, cancelFlag())8795
8896
c.Commands = commands8997
c.CommandNotFound = command404@@ -120,3 +128,54 @@
120128
},121129
}122130
}131+
132+
func cancelFlag() *cli.BoolFlag {133+
return &cli.BoolFlag{134+
Name: "cancel-on-kill",135+
Usage: "cancel helm on SigINT,SigTERM",136+
137+
Value: false,138+
EnvVars: []string{"HELMWAVE_HANDLE_SIGNAL"},139+
Hidden: true, // experimental140+
}141+
}142+
143+
type signalCtx struct {144+
context.Context145+
}146+
147+
func (ctx signalCtx) Err() error {148+
// Unwrap for readablity, if ctx cancelled by reciving a signal149+
if sigErr, ok := context.Cause(ctx.Context).(signalErr); ok {150+
return sigErr151+
}152+
return ctx.Context.Err()153+
}154+
155+
type signalErr struct {156+
sig os.Signal157+
}158+
159+
func (e signalErr) Error() string {160+
return "context canceled: got signal " + e.sig.String()161+
}162+
163+
// cancelCtxOnSignal closes Done channel when one of the listed signals arrives164+
func cancelCtxOnSignal(parent context.Context, signals ...os.Signal) (ctx context.Context) {165+
ctx, cancel := context.WithCancelCause(parent)166+
ctx = signalCtx{ctx} // wrap for err handling167+
168+
ch := make(chan os.Signal, 1)169+
signal.Notify(ch, signals...)170+
if ctx.Err() == nil {171+
go func() {172+
select {173+
case sig := <-ch:174+
// log.Warn("got signal " + sig.String())175+
cancel(signalErr{sig})176+
case <-ctx.Done():177+
}178+
}()179+
}180+
return ctx181+
}