Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

move scli's UntilInterrupted() here #38

Merged
merged 2 commits into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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...")
}
}