From 0415cc62998a93b53535086609a7e451f417eca5 Mon Sep 17 00:00:00 2001 From: Dan Fuhry Date: Thu, 12 Sep 2024 20:42:16 -0400 Subject: [PATCH] machines_agent: daemonize with utils/daemon --- machines/machines_agent/main.go | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/machines/machines_agent/main.go b/machines/machines_agent/main.go index 9093137..04052cc 100644 --- a/machines/machines_agent/main.go +++ b/machines/machines_agent/main.go @@ -15,6 +15,7 @@ import ( "go.fuhry.dev/runtime/machines" "go.fuhry.dev/runtime/metrics/metricbus/mbclient" + "go.fuhry.dev/runtime/utils/daemon" "go.fuhry.dev/runtime/utils/log" ) @@ -151,9 +152,34 @@ func main() { return } - ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + err = daemon.Detach() + if err != nil { + logger.Errorf("failed to daemonize: %v", err) + } + + shutdownChan := make(chan struct{}, 1) + defer (func() { shutdownChan <- struct{}{} })() + + if err = daemon.WritePidFile(); err != nil { + logger.Errorf("failed to write pid file: %v", err) + } else { + defer daemon.CleanupPidFile() + } + + ctx, cancel := context.WithCancel(context.Background()) defer cancel() + signalChan := make(chan os.Signal, 1) + signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM) + go (func() { + for sig := range signalChan { + logger.Criticalf("Received signal: %d, %s", sig, sig.String()) + cancel() + <-shutdownChan + os.Exit(0) + } + })() + metrics := mbclient.NewService(ctx) eventsProcessed := metrics.DefineCounter("machines_agent_events", @@ -189,7 +215,9 @@ func main() { cancel() } - logger.Info("successfully created event monitor, listening for events") + logger.Noticef("starting main event loop") + defer logger.Critical("stopping xx0r-machines-agent") + mainLoop: for { select { -- 2.50.1