Skip to content

Agent Mesh

fix(cmd): add graceful signal handling and node teardown on shutdown

Antonio Ojeace618a8e1328
diff --git a/cmd/sam-control-plane/main.go b/cmd/sam-control-plane/main.go
index d731b6b4..605c46e9 100644
--- a/cmd/sam-control-plane/main.go
+++ b/cmd/sam-control-plane/main.go
@@ -17,7 +17,9 @@ package main
import (
"context"
"os"
+ "os/signal"
"strings"
+ "syscall"
"time"
"github.com/google/sam/api"
@@ -179,7 +181,7 @@ func main() {
adminCmd.AddCommand(banCmd, unbanCmd)
rootCmd.AddCommand(adminCmd)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
if err := rootCmd.ExecuteContext(ctx); err != nil {
diff --git a/cmd/sam-node/main.go b/cmd/sam-node/main.go
index d016d7f8..f88e78f3 100644
--- a/cmd/sam-node/main.go
+++ b/cmd/sam-node/main.go
@@ -385,6 +385,9 @@ func main() {
}
defer func() {
_ = sidecarSrv.Close()
+ if err := meshNode.Teardown(); err != nil {
+ logger.Warnf("Error during mesh node teardown: %v", err)
+ }
}()
fmt.Printf("SAM Node Online.\nPeerID: %s\nListening on: %v\n", meshNode.Host.ID(), meshNode.Host.Addrs())
diff --git a/cmd/sam-router/main.go b/cmd/sam-router/main.go
index 1b1d4d60..1f0bff5c 100644
--- a/cmd/sam-router/main.go
+++ b/cmd/sam-router/main.go
@@ -17,6 +17,8 @@ package main
import (
"context"
"os"
+ "os/signal"
+ "syscall"
"time"
"github.com/google/sam/internal/router"
@@ -109,7 +111,7 @@ func main() {
rootCmd.Flags().DurationVar(&dhtProviderAddrTTL, "dht-provider-addr-ttl", 0, "Time-To-Live for DHT provider addresses (0s uses library default)")
rootCmd.Flags().DurationVar(&dhtMaxRecordAge, "dht-max-record-age", 0, "Maximum age for DHT records (0s uses library default)")
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
if err := rootCmd.ExecuteContext(ctx); err != nil {