Skip to content

Commit

Permalink
Periodically collect runtime info when requested
Browse files Browse the repository at this point in the history
  • Loading branch information
m90 committed Feb 10, 2024
1 parent 68ba6ce commit 01e41f4
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions cmd/backup/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"log/slog"
"os"
"os/signal"
"runtime"
"syscall"

"github.com/robfig/cron/v3"
Expand Down Expand Up @@ -122,7 +123,7 @@ func runScript(c *Config) (err error) {
return runErr
}

func (c *command) runInForeground() error {
func (c *command) runInForeground(profileCronExpression string) error {
cr := cron.New(
cron.WithParser(
cron.NewParser(
Expand Down Expand Up @@ -189,6 +190,24 @@ func (c *command) runInForeground() error {
}
}

if profileCronExpression != "" {
cr.AddFunc(profileCronExpression, func() {

Check failure on line 194 in cmd/backup/main.go

View workflow job for this annotation

GitHub Actions / lint

Error return value of `cr.AddFunc` is not checked (errcheck)
memStats := runtime.MemStats{}
runtime.ReadMemStats(&memStats)
c.logger.Info(
"Collecting runtime information",
"num_goroutines",
runtime.NumGoroutine(),
"memory_heap_alloc",
formatBytes(memStats.HeapAlloc, false),
"memory_heap_inuse",
formatBytes(memStats.HeapInuse, false),
"memory_heap_sys",
formatBytes(memStats.HeapSys, false),
)
})
}

var quit = make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
cr.Start()
Expand All @@ -214,11 +233,12 @@ func (c *command) runAsCommand() error {

func main() {
foreground := flag.Bool("foreground", false, "run the tool in the foreground")
profile := flag.String("profile", "", "collect runtime metrics and log them periodically on the given cron expression")
flag.Parse()

c := newCommand()
if *foreground {
c.must(c.runInForeground())
c.must(c.runInForeground(*profile))
} else {
c.must(c.runAsCommand())
}
Expand Down

0 comments on commit 01e41f4

Please sign in to comment.