refactor(socket): decouple command handling and add message sending

- Move command handler to variable for better flexibility
- Add SendMsg function for sending messages through socket
- Fix missing return statements in command execution
- Improve error handling in monitor exception reporting
This commit is contained in:
2026-04-28 19:55:45 +08:00
parent 3a0b591d5e
commit 58a8efc17a
4 changed files with 67 additions and 28 deletions

View File

@@ -50,7 +50,8 @@ func ExecuteCommand(input string) error {
err := monitor.AddServiceMonitor(serviceName) err := monitor.AddServiceMonitor(serviceName)
if err != nil { if err != nil {
return fmt.Errorf("failed to add service monitor: %v", err) return fmt.Errorf("failed to add service monitor: %v", err)
} }
return nil
} }
case "monitor.remove": case "monitor.remove":
serviceName := getContent(input, "serviceName") serviceName := getContent(input, "serviceName")
@@ -60,9 +61,11 @@ func ExecuteCommand(input string) error {
if err != nil { if err != nil {
return fmt.Errorf("failed to remove service monitor: %v", err) return fmt.Errorf("failed to remove service monitor: %v", err)
} }
return nil
} }
case "watchdog.shutdown": case "watchdog.shutdown":
os.Exit(0) os.Exit(0)
return nil
} }
return fmt.Errorf("unknown command") return fmt.Errorf("unknown command")
} }

View File

@@ -1,6 +1,7 @@
package main package main
import ( import (
"Watchdog_Linux-systemd/command"
"Watchdog_Linux-systemd/postLog" "Watchdog_Linux-systemd/postLog"
"Watchdog_Linux-systemd/socket" "Watchdog_Linux-systemd/socket"
"fmt" "fmt"
@@ -44,6 +45,10 @@ func main() {
} }
postLog.Info(fmt.Sprintf("%s %s (Build %d.%s) by %s", softwareInfo.Name, softwareInfo.Version, softwareInfo.BuildVer, softwareInfo.BuildType, softwareInfo.Developer)) postLog.Info(fmt.Sprintf("%s %s (Build %d.%s) by %s", softwareInfo.Name, softwareInfo.Version, softwareInfo.BuildVer, softwareInfo.BuildType, softwareInfo.Developer))
// Set command handler
socket.CommandHandler = command.ExecuteCommand
// End of command handler
go func() { go func() {
err := socket.BootSocket(Type, listenAddr, listenPort) err := socket.BootSocket(Type, listenAddr, listenPort)
if err != nil { if err != nil {

View File

@@ -2,6 +2,7 @@ package monitor
import ( import (
"Watchdog_Linux-systemd/postLog" "Watchdog_Linux-systemd/postLog"
"Watchdog_Linux-systemd/socket"
"fmt" "fmt"
"os/exec" "os/exec"
"strings" "strings"
@@ -123,7 +124,11 @@ func checkServiceLogs(serviceName string) (bool, error) {
func throwException(serviceName, errorContent string) error { func throwException(serviceName, errorContent string) error {
postLog.Error(fmt.Sprintf("[Monitor] Service: %s - Exception: %s", serviceName, errorContent)) postLog.Error(fmt.Sprintf("[Monitor] Service: %s - Exception: %s", serviceName, errorContent))
return fmt.Errorf("service %s exception: %s", serviceName, errorContent) err := socket.SendMsg(fmt.Sprintf("service %s exception: %s", serviceName, errorContent))
if err != nil {
return fmt.Errorf("failed to send exception message: %v", err)
}
return nil
} }
func GetActiveMonitors() []string { func GetActiveMonitors() []string {

View File

@@ -1,7 +1,6 @@
package socket package socket
import ( import (
"Watchdog_Linux-systemd/command"
"Watchdog_Linux-systemd/postLog" "Watchdog_Linux-systemd/postLog"
"bufio" "bufio"
"fmt" "fmt"
@@ -9,6 +8,11 @@ import (
"strings" "strings"
) )
var (
Conn net.Conn
CommandHandler func(string) error
)
func BootSocket(networkType, listenAddr string, listenPort int) error { func BootSocket(networkType, listenAddr string, listenPort int) error {
listen, err := net.Listen(networkType, fmt.Sprintf("%s:%d", listenAddr, listenPort)) listen, err := net.Listen(networkType, fmt.Sprintf("%s:%d", listenAddr, listenPort))
if err != nil { if err != nil {
@@ -20,42 +24,64 @@ func BootSocket(networkType, listenAddr string, listenPort int) error {
postLog.Info(fmt.Sprintf("Server is running on %s:%d", listenAddr, listenPort)) postLog.Info(fmt.Sprintf("Server is running on %s:%d", listenAddr, listenPort))
for { for {
conn, err := listen.Accept() Conn, err = listen.Accept()
if err != nil { if err != nil {
postLog.Error(fmt.Sprintf("Failed to accept: %v, err: %v", conn, err)) postLog.Error(fmt.Sprintf("Failed to accept: %v, err: %v", Conn, err))
} }
go handleRequest(conn) go handleRequest()
} }
} }
func handleRequest(conn net.Conn) { func handleRequest() {
defer conn.Close() defer Conn.Close()
reader := bufio.NewReader(conn) reader := bufio.NewReader(Conn)
for { for {
data, err := reader.ReadBytes('\n') data, err := reader.ReadBytes('\n')
if err != nil { if err != nil {
return return
} }
recvMsg := strings.TrimSpace(string(data)) recvMsg := strings.TrimSpace(string(data))
responseMsg := "" responseMsg := ""
if len(recvMsg) != 0 { if len(recvMsg) != 0 {
postLog.Debug(fmt.Sprintf("Received message: %s", recvMsg)) postLog.Debug(fmt.Sprintf("Received message: %s", recvMsg))
if recvMsg == "watchdogAgentConnectionTest" { if recvMsg == "watchdogAgentConnectionTest" {
responseMsg = "success" responseMsg = "success"
} else { } else {
err := command.ExecuteCommand(recvMsg) if CommandHandler != nil {
if err != nil { err := CommandHandler(recvMsg)
responseMsg = fmt.Sprintf("error: %v", err) if err != nil {
} else { responseMsg = fmt.Sprintf("error: %v", err)
responseMsg = "success" } else {
} responseMsg = "success"
} }
} else {
responseMsg = "error: command handler not initialized"
}
}
} }
conn.Write([]byte(responseMsg + "\n")) Conn.Write([]byte(responseMsg + "\n"))
} }
}
func SendMsg(msg string) error {
if Conn == nil {
return fmt.Errorf("connection is nil")
}
data := []byte(msg + "\n")
n, err := Conn.Write(data)
if err != nil {
return fmt.Errorf("failed to write message: %v", err)
}
if n != len(data) {
return fmt.Errorf("incomplete write: wrote %d bytes out of %d", n, len(data))
}
return nil
} }