Skip to content

Commit

Permalink
move scli's UntilInterrupted() here (#38)
Browse files Browse the repository at this point in the history
* move scli's UntilInterrupted() here

* change order so hopefully codeql doesn't try to run the wait-demo
  • Loading branch information
ldemailly authored Aug 15, 2024
1 parent fcd3323 commit 53eb244
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
7 changes: 5 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@

lint: .golangci.yml
golangci-lint run

wait-demo:
# Doesn't work with tinygo (yet) because undefined symbol: _os/signal.signal_enable...
go run -tags no_net,no_json ./sampleTool/ -wait arg1 arg2

.golangci.yml: Makefile
curl -fsS -o .golangci.yml https://raw.githubusercontent.com/fortio/workflows/main/golangci.yml

.PHONY: lint
.PHONY: lint wait-demo
19 changes: 19 additions & 0 deletions cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ import (
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"

"fortio.org/log"
"fortio.org/version"
Expand Down Expand Up @@ -253,3 +255,20 @@ func PluralExt(i int, noun string, ext string) string {
}
return noun + ext
}

// UntilInterrupted runs forever or until interrupted (ctrl-c or shutdown signal (kill -INT or -TERM)).
// Kubernetes for instance sends a SIGTERM before killing a pod.
// You can place your clean shutdown code after this call in the main().
// This assumes there is another go routine doing something (like a server).
func UntilInterrupted() {
// if UntilInterrupted is called, it implies there should be another goroutine at least.
// so we put back that logging (vs what log.SetDefaultsForClientTools() does).
log.Config.GoroutineID = true
// listen for interrupt signal
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
// Block until a signal is received.
log.LogVf("Waiting for interrupt signal...")
<-c
log.Warnf("Interrupt received.")
}
7 changes: 7 additions & 0 deletions sampleTool/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (

func main() {
myFlag := flag.String("myflag", "default", "my flag")
doWait := flag.Bool("wait", false, "wait for ^C before exiting")

cli.MinArgs = 2
cli.MaxArgs = 4
cli.Main() // Will have either called cli.ExitFunction or everything is valid
Expand All @@ -21,4 +23,9 @@ func main() {
log.Str("myflag", *myFlag),
log.Attr("num_args", len(flag.Args())),
log.Attr("args", flag.Args()))
if *doWait {
log.Infof("Waiting for ^C (or kill) to exit")
cli.UntilInterrupted()
log.Infof("Now done...")
}
}

0 comments on commit 53eb244

Please sign in to comment.