Ensure listener is closed even if the daemon is killed unexpectedly

This commit is contained in:
2025-05-04 20:03:23 -04:00
parent 9314852f06
commit 5975c71b4f
2 changed files with 19 additions and 0 deletions
+11
View File
@@ -8,7 +8,9 @@ import (
"net" "net"
"net/rpc" "net/rpc"
"os" "os"
"os/signal"
"strconv" "strconv"
"syscall"
"time" "time"
peercred "github.com/rwinkhart/peercred-mini" peercred "github.com/rwinkhart/peercred-mini"
@@ -35,6 +37,15 @@ func Start(passphrase string) {
defer listener.Close() defer listener.Close()
log.Printf("RPC daemon listening on unix://%s", socketPath) log.Printf("RPC daemon listening on unix://%s", socketPath)
// capture sigterms to ensure listener is closed
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
go func() {
<-sigChan
listener.Close()
os.Exit(0)
}()
// accept connections (timeout after 3 minutes of inactivity) // accept connections (timeout after 3 minutes of inactivity)
for { for {
listener.(*net.UnixListener).SetDeadline(time.Now().Add(3 * time.Minute)) listener.(*net.UnixListener).SetDeadline(time.Now().Add(3 * time.Minute))
+8
View File
@@ -8,6 +8,8 @@ import (
"net" "net"
"net/rpc" "net/rpc"
"os" "os"
"os/signal"
"syscall"
"time" "time"
"github.com/Microsoft/go-winio" // For Windows named pipes "github.com/Microsoft/go-winio" // For Windows named pipes
@@ -48,6 +50,9 @@ func Start(passphrase string) {
defer listener.Close() defer listener.Close()
log.Printf("RPC daemon listening on %s", socketPath) log.Printf("RPC daemon listening on %s", socketPath)
// capture sigterms to ensure listener is closed
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
// create 3-minute inactivity timer // create 3-minute inactivity timer
timer := time.NewTimer(3 * time.Minute) timer := time.NewTimer(3 * time.Minute)
killTimer := make(chan struct{}) killTimer := make(chan struct{})
@@ -59,6 +64,9 @@ func Start(passphrase string) {
os.Exit(0) os.Exit(0)
case <-killTimer: case <-killTimer:
return return
case <-sigChan:
listener.Close()
os.Exit(0)
} }
}() }()