Add functionality to parse and execute commands for adding/removing service monitors and shutting down the watchdog. The ExecuteCommand function now handles "monitor.add", "monitor.remove" and "watchdog.shutdown" commands by interacting with the monitor package and system operations.
65 lines
1.4 KiB
Go
65 lines
1.4 KiB
Go
package command
|
|
|
|
import (
|
|
"Watchdog_Linux-systemd/monitor"
|
|
"fmt"
|
|
"strings"
|
|
"os"
|
|
)
|
|
|
|
func getTextMiddle(text, left, right string) string {
|
|
start := 0
|
|
if left != "" {
|
|
idx := strings.Index(text, left)
|
|
if idx == -1 {
|
|
return ""
|
|
}
|
|
start = idx + len(left)
|
|
}
|
|
|
|
if right == "" {
|
|
if start > len(text) {
|
|
return ""
|
|
}
|
|
return text[start:]
|
|
}
|
|
|
|
endIdx := strings.Index(text[start:], right)
|
|
if endIdx == -1 {
|
|
return ""
|
|
}
|
|
return text[start : start+endIdx]
|
|
}
|
|
|
|
func getCommand(content string) string {
|
|
return getTextMiddle(content, "[", "]")
|
|
}
|
|
|
|
func getContent(content, cmdType string) string {
|
|
return getTextMiddle(content, "<" + cmdType + ">", "</" + cmdType + ">")
|
|
}
|
|
|
|
func ExecuteCommand(input string) error {
|
|
cmdType := getCommand(input)
|
|
switch cmdType {
|
|
case "monitor.add":
|
|
serviceName := getContent(input, "serviceName")
|
|
if len(serviceName) != 0 {
|
|
err := monitor.AddServiceMonitor(serviceName)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to add service monitor: %v", err)
|
|
}
|
|
}
|
|
case "monitor.remove":
|
|
serviceName := getContent(input, "serviceName")
|
|
if len(serviceName) != 0 {
|
|
err := monitor.RemoveServiceMonitor(serviceName)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to remove service monitor: %v", err)
|
|
}
|
|
}
|
|
case "watchdog.shutdown":
|
|
os.Exit(0)
|
|
}
|
|
return fmt.Errorf("unknown command")
|
|
} |