]> go.fuhry.dev Git - runtime.git/commitdiff
machines_agent: daemonize with utils/daemon
authorDan Fuhry <dan@fuhry.com>
Fri, 13 Sep 2024 00:42:16 +0000 (20:42 -0400)
committerDan Fuhry <dan@fuhry.com>
Fri, 13 Sep 2024 00:42:16 +0000 (20:42 -0400)
machines/machines_agent/main.go

index 909313710846cf06b2e7ae9b13d9bf60fb4a7d66..04052ccdbe52470ae5c6606619547595951f1ab6 100644 (file)
@@ -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 {