From 017c1de1977990db2dad9108859875fb12bf3788 Mon Sep 17 00:00:00 2001 From: abs3nt Date: Sun, 27 Oct 2024 12:32:52 -0700 Subject: [PATCH] daemon refactor --- src/components/daemon/daemon.go | 103 +++++++++++++++++--------------- 1 file changed, 55 insertions(+), 48 deletions(-) diff --git a/src/components/daemon/daemon.go b/src/components/daemon/daemon.go index 6335979..18d1220 100644 --- a/src/components/daemon/daemon.go +++ b/src/components/daemon/daemon.go @@ -1,6 +1,7 @@ package daemon import ( + "fmt" "log" "net" "net/rpc" @@ -15,53 +16,59 @@ import ( func Run(c *commands.Commander, conf *config.Config, s fx.Shutdowner) { for { - func() { - defer func() { - if r := recover(); r != nil { - log.Printf("Recovered in Run: %v", r) - } - }() - - socketPath := conf.SocketPath - if _, err := os.Stat(socketPath); err == nil { - os.Remove(socketPath) - } - - CommandHandler := Handler{ - Commander: c, - } - - server := rpc.NewServer() - server.Register(&CommandHandler) - - listener, err := net.Listen("unix", socketPath) - if err != nil { - log.Println("Listen error:", err) - time.Sleep(time.Second) - return - } - defer listener.Close() - os.Chmod(socketPath, 0o666) - - log.Println("Daemon is listening on", socketPath) - - for { - conn, err := listener.Accept() - if err != nil { - log.Println("Accept error:", err) - continue - } - codec := NewLoggingServerCodec(conn) - go func() { - defer func() { - if r := recover(); r != nil { - log.Printf("Recovered in ServeCodec goroutine: %v", r) - } - }() - server.ServeCodec(codec) - }() - } - }() - time.Sleep(time.Second) + err := startServer(c, conf) + if err != nil { + log.Printf("Server error: %v", err) + time.Sleep(time.Second) + continue + } + break } } + +func startServer(c *commands.Commander, conf *config.Config) error { + socketPath := conf.SocketPath + + if _, err := os.Stat(socketPath); err == nil { + if err := os.Remove(socketPath); err != nil { + return fmt.Errorf("failed to remove existing socket: %w", err) + } + } + + commandHandler := &Handler{Commander: c} + server := rpc.NewServer() + if err := server.Register(commandHandler); err != nil { + return fmt.Errorf("failed to register RPC handler: %w", err) + } + + listener, err := net.Listen("unix", socketPath) + if err != nil { + return fmt.Errorf("listen error: %w", err) + } + defer listener.Close() + + if err := os.Chmod(socketPath, 0o666); err != nil { + return fmt.Errorf("failed to set socket permissions: %w", err) + } + + log.Println("Daemon is listening on", socketPath) + + for { + conn, err := listener.Accept() + if err != nil { + log.Println("Accept error:", err) + continue + } + codec := NewLoggingServerCodec(conn) + go handleConnection(server, codec) + } +} + +func handleConnection(server *rpc.Server, codec rpc.ServerCodec) { + defer func() { + if r := recover(); r != nil { + log.Printf("Recovered in handleConnection: %v", r) + } + }() + server.ServeCodec(codec) +}