mirror of
https://github.com/EnumeratedDev/enit.git
synced 2026-09-16 10:36:12 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bcff6fecf8
|
||
|
|
5ee42a5966
|
||
|
|
7bbfa9f198
|
||
|
|
81421b0cc4
|
||
|
|
2aef0c0ff9
|
||
|
|
33e7479044
|
||
|
|
92587d8099
|
||
|
|
7f37da2091
|
||
|
|
285ede0e9a
|
||
|
|
93ab1c0607
|
||
|
|
dea5760d75
|
||
|
|
70ef610ce6
|
||
|
|
5ed1128e43
|
||
|
|
87412f20f8
|
@@ -5,3 +5,4 @@ start_cmd: /usr/bin/setsid /sbin/agetty --noclear tty1
|
||||
exit_method: kill
|
||||
crash_on_safe_exit: false
|
||||
restart: always
|
||||
setpgid: false
|
||||
|
||||
@@ -5,3 +5,4 @@ start_cmd: /usr/bin/setsid /sbin/agetty tty2
|
||||
exit_method: kill
|
||||
crash_on_safe_exit: false
|
||||
restart: always
|
||||
setpgid: false
|
||||
|
||||
@@ -5,3 +5,4 @@ start_cmd: /usr/bin/setsid /sbin/agetty tty3
|
||||
exit_method: kill
|
||||
crash_on_safe_exit: false
|
||||
restart: always
|
||||
setpgid: false
|
||||
|
||||
@@ -5,3 +5,4 @@ start_cmd: /usr/bin/setsid /sbin/agetty tty4
|
||||
exit_method: kill
|
||||
crash_on_safe_exit: false
|
||||
restart: always
|
||||
setpgid: false
|
||||
|
||||
@@ -5,3 +5,4 @@ start_cmd: /usr/bin/setsid /sbin/agetty tty5
|
||||
exit_method: kill
|
||||
crash_on_safe_exit: false
|
||||
restart: always
|
||||
setpgid: false
|
||||
|
||||
@@ -5,3 +5,4 @@ start_cmd: /usr/bin/setsid /sbin/agetty tty6
|
||||
exit_method: kill
|
||||
crash_on_safe_exit: false
|
||||
restart: always
|
||||
setpgid: false
|
||||
|
||||
+93
-37
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
@@ -57,7 +58,57 @@ func main() {
|
||||
return
|
||||
} else if flag.Args()[0] == "service" || flag.Args()[0] == "sv" {
|
||||
if len(flag.Args()) <= 1 {
|
||||
fmt.Println("Usage: ectl service <start/stop/enable/disable/status/list> [service]")
|
||||
fmt.Println("Usage: ectl service <reload/start/stop/enable/disable/status/list> [service]")
|
||||
return
|
||||
}
|
||||
if flag.Arg(1) == "reload" {
|
||||
type ServiceCommandJsonStruct struct {
|
||||
Command string `json:"command"`
|
||||
Service string `json:"service"`
|
||||
}
|
||||
serviceCommandJson := ServiceCommandJsonStruct{
|
||||
Command: flag.Arg(1),
|
||||
}
|
||||
|
||||
// Encode struct to json string
|
||||
jsonData, err := json.Marshal(serviceCommandJson)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not encode JSON data! Error: %s\n", err)
|
||||
}
|
||||
|
||||
_, err = conn.Write(jsonData)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not write JSON data to socket! Error: %s\n", err)
|
||||
}
|
||||
|
||||
// Read data from the connection.
|
||||
data, err := readAllConn(conn)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not read data from socket! Error: %s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Print json data if flag is set
|
||||
if *printJson {
|
||||
fmt.Println(string(data))
|
||||
return
|
||||
}
|
||||
|
||||
// Decoode JSON data
|
||||
var returnedJsonData map[string]any
|
||||
err = json.Unmarshal(data, &returnedJsonData)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not decode JSON data from connection!")
|
||||
}
|
||||
|
||||
if err, ok := returnedJsonData["error"]; ok {
|
||||
log.Fatal(err)
|
||||
} else if msg, ok := returnedJsonData["success"]; ok {
|
||||
fmt.Println(msg)
|
||||
} else {
|
||||
log.Fatal("Connection returned empty string!")
|
||||
}
|
||||
|
||||
return
|
||||
} else if flag.Arg(1) == "start" || flag.Arg(1) == "stop" || flag.Arg(1) == "restart" {
|
||||
// Ensure service name argument has been set
|
||||
@@ -86,27 +137,22 @@ func main() {
|
||||
log.Fatalf("Could not write JSON data to socket! Error: %s\n", err)
|
||||
}
|
||||
|
||||
// Create a buffer for incoming data.
|
||||
buf := make([]byte, 4096)
|
||||
|
||||
// Read data from the connection.
|
||||
n, err := conn.Read(buf)
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
data, err := readAllConn(conn)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not read data from socket! Error: %s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Print json data if flag is set
|
||||
if *printJson {
|
||||
fmt.Println(string(buf[:n]))
|
||||
fmt.Println(string(data))
|
||||
return
|
||||
}
|
||||
|
||||
// Decoode JSON data
|
||||
var returnedJsonData map[string]any
|
||||
err = json.Unmarshal(buf[:n], &returnedJsonData)
|
||||
err = json.Unmarshal(data, &returnedJsonData)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not decode JSON data from connection!")
|
||||
}
|
||||
@@ -162,27 +208,22 @@ func main() {
|
||||
log.Fatalf("Could not write JSON data to socket! Error: %s\n", err)
|
||||
}
|
||||
|
||||
// Create a buffer for incoming data.
|
||||
buf := make([]byte, 4096)
|
||||
|
||||
// Read data from the connection.
|
||||
n, err := conn.Read(buf)
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
data, err := readAllConn(conn)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not read data from socket! Error: %s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Print json data if flag is set
|
||||
if *printJson {
|
||||
fmt.Println(string(buf[:n]))
|
||||
fmt.Println(string(data))
|
||||
return
|
||||
}
|
||||
|
||||
// Decoode JSON data
|
||||
var returnedJsonData map[string]any
|
||||
err = json.Unmarshal(buf[:n], &returnedJsonData)
|
||||
err = json.Unmarshal(data, &returnedJsonData)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not decode JSON data from connection!")
|
||||
}
|
||||
@@ -223,27 +264,22 @@ func main() {
|
||||
log.Fatalf("Could not write JSON data to socket! Error: %s\n", err)
|
||||
}
|
||||
|
||||
// Create a buffer for incoming data.
|
||||
buf := make([]byte, 4096)
|
||||
|
||||
// Read data from the connection.
|
||||
n, err := conn.Read(buf)
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
data, err := readAllConn(conn)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not read data from socket! Error: %s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Print json data if flag is set
|
||||
if *printJson {
|
||||
fmt.Println(string(buf[:n]))
|
||||
fmt.Println(string(data))
|
||||
return
|
||||
}
|
||||
|
||||
// Decoode JSON data
|
||||
var returnedJsonData map[string]any
|
||||
err = json.Unmarshal(buf[:n], &returnedJsonData)
|
||||
err = json.Unmarshal(data, &returnedJsonData)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not decode JSON data from connection!")
|
||||
}
|
||||
@@ -253,11 +289,13 @@ func main() {
|
||||
}
|
||||
|
||||
serviceState := returnedJsonData["state"].(string)
|
||||
serviceDescription := returnedJsonData["description"].(string)
|
||||
serviceEnabled := returnedJsonData["is_enabled"].(bool)
|
||||
serviceStage := int(returnedJsonData["stage"].(float64))
|
||||
processID := int(returnedJsonData["process_id"].(float64))
|
||||
|
||||
fmt.Printf("Name: %s\n", flag.Arg(2))
|
||||
fmt.Printf("Description: %s\n", serviceDescription)
|
||||
fmt.Printf("State: %s\n", serviceState)
|
||||
if serviceEnabled {
|
||||
fmt.Printf("Enabled: %t (Stage %d)\n", serviceEnabled, serviceStage)
|
||||
@@ -288,27 +326,22 @@ func main() {
|
||||
log.Fatalf("Could not write JSON data to socket! Error: %s\n", err)
|
||||
}
|
||||
|
||||
// Create a buffer for incoming data.
|
||||
buf := make([]byte, 4096)
|
||||
|
||||
// Read data from the connection.
|
||||
n, err := conn.Read(buf)
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
data, err := readAllConn(conn)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not read data from socket! Error: %s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Print json data if flag is set
|
||||
if *printJson {
|
||||
fmt.Println(string(buf[:n]))
|
||||
fmt.Println(string(data))
|
||||
return
|
||||
}
|
||||
|
||||
// Decoode JSON data
|
||||
var returnedJsonData map[string]any
|
||||
err = json.Unmarshal(buf[:n], &returnedJsonData)
|
||||
err = json.Unmarshal(data, &returnedJsonData)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not decode JSON data from connection!")
|
||||
}
|
||||
@@ -319,12 +352,14 @@ func main() {
|
||||
|
||||
for _, serviceMap := range returnedJsonData["services"].([]any) {
|
||||
serviceName := serviceMap.(map[string]any)["name"].(string)
|
||||
serviceDescription := serviceMap.(map[string]any)["description"].(string)
|
||||
serviceState := serviceMap.(map[string]any)["state"].(string)
|
||||
serviceEnabled := serviceMap.(map[string]any)["is_enabled"].(bool)
|
||||
serviceStage := int(serviceMap.(map[string]any)["stage"].(float64))
|
||||
processID := int(serviceMap.(map[string]any)["process_id"].(float64))
|
||||
|
||||
fmt.Printf("Name: %s\n", serviceName)
|
||||
fmt.Printf("Description: %s\n", serviceDescription)
|
||||
fmt.Printf("State: %s\n", serviceState)
|
||||
if serviceEnabled {
|
||||
fmt.Printf("Enabled: %t (Stage %d)\n", serviceEnabled, serviceStage)
|
||||
@@ -374,3 +409,24 @@ func dialSocket() {
|
||||
log.Fatalf("Failed to set write deadline! Error: %s\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
func readAllConn(conn net.Conn) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
for {
|
||||
dataChunk := make([]byte, 1024)
|
||||
|
||||
n, err := conn.Read(dataChunk)
|
||||
if err != nil && err != io.EOF {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
buf.Write(dataChunk[:n])
|
||||
|
||||
if n < 1024 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
+4
-1
@@ -2,4 +2,7 @@ module enit
|
||||
|
||||
go 1.23.4
|
||||
|
||||
require golang.org/x/sys v0.31.0
|
||||
require (
|
||||
github.com/mitchellh/go-ps v1.0.0
|
||||
golang.org/x/sys v0.31.0
|
||||
)
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc=
|
||||
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
|
||||
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
|
||||
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
|
||||
+67
-19
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
@@ -12,6 +13,8 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/mitchellh/go-ps"
|
||||
)
|
||||
|
||||
// Build-time variables
|
||||
@@ -78,42 +81,42 @@ func mountVirtualFilesystems() {
|
||||
|
||||
// Mount /proc
|
||||
if err := mount("proc", "/proc", "proc", commonOptions+",nodev,noexec", false); err != nil {
|
||||
panic(err)
|
||||
printErrorAndReboot("Error: could not mount /proc: %s", err)
|
||||
}
|
||||
|
||||
// Mount /sys
|
||||
if err := mount("sys", "/sys", "sysfs", commonOptions+",nodev,noexec", false); err != nil {
|
||||
panic(err)
|
||||
printErrorAndReboot("Error: could not mount /sys: %s", err)
|
||||
}
|
||||
|
||||
// Mount /dev
|
||||
if err := mount("dev", "/dev", "devtmpfs", commonOptions+",mode=755,inode64", false); err != nil {
|
||||
panic(err)
|
||||
printErrorAndReboot("Error: could not mount /dev: %s", err)
|
||||
}
|
||||
|
||||
// Mount /run
|
||||
if err := mount("run", "/run", "tmpfs", commonOptions+",nodev,mode=755,inode64", false); err != nil {
|
||||
panic(err)
|
||||
printErrorAndReboot("Error: could not mount /run: %s", err)
|
||||
}
|
||||
|
||||
// Mount /dev/pts
|
||||
if err := mount("devpts", "/dev/pts", "devpts", commonOptions+",gid=5,mode=620,ptmxmode=000", true); err != nil {
|
||||
panic(err)
|
||||
printErrorAndReboot("Error: could not mount /dev/pts: %s", err)
|
||||
}
|
||||
|
||||
// Mount /dev/shm
|
||||
if err := mount("shm", "/dev/shm", "tmpfs", commonOptions+",nodev,inode64", true); err != nil {
|
||||
panic(err)
|
||||
printErrorAndReboot("Error: could not mount /dev/shm: %s", err)
|
||||
}
|
||||
|
||||
// Mount securityfs
|
||||
if err := mount("securityfs", "/sys/kernel/security", "securityfs", commonOptions, false); err != nil {
|
||||
panic(err)
|
||||
printErrorAndReboot("Error: could not mount /sys/kernel/security: %s", err)
|
||||
}
|
||||
|
||||
// Mount cgroups v2
|
||||
if err := mount("cgroup2", "/sys/fs/cgroup", "cgroup2", commonOptions+",noexec,nsdelegate,memory_recursiveprot", false); err != nil {
|
||||
panic(err)
|
||||
printErrorAndReboot("Error: could not mount /sys/fs/cgroup: %s", err)
|
||||
}
|
||||
|
||||
fmt.Println("Done.")
|
||||
@@ -122,9 +125,8 @@ func mountVirtualFilesystems() {
|
||||
func mountFilesystems() {
|
||||
fmt.Print("Mounting fstab entries... ")
|
||||
|
||||
if err := mountFstabEntries(); err != nil {
|
||||
log.Println("Could not mount fstab entries!")
|
||||
panic(err)
|
||||
if err, line := mountFstabEntries(); err != nil {
|
||||
printErrorAndReboot("Error: could not mount fstab entry on line %d: %s", line, err)
|
||||
}
|
||||
|
||||
fmt.Println("Done.")
|
||||
@@ -138,8 +140,7 @@ func startServiceManager() {
|
||||
cmd.Stderr = os.Stderr
|
||||
err := cmd.Start()
|
||||
if err != nil {
|
||||
log.Println("Could not initialize service manager!")
|
||||
panic(err)
|
||||
printErrorAndReboot("Error: could not initialize service manager: %s", err)
|
||||
}
|
||||
serviceManagerPid = cmd.Process.Pid
|
||||
|
||||
@@ -185,6 +186,42 @@ func stopServiceManager() {
|
||||
|
||||
}
|
||||
|
||||
func killProcesses() {
|
||||
fmt.Print("Killing processes... ")
|
||||
|
||||
// Send sigterm to all processes
|
||||
processes, err := ps.Processes()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, process := range processes {
|
||||
sid, _, _ := syscall.Syscall(syscall.SYS_GETSID, uintptr(process.Pid()), 0, 0)
|
||||
if process.Pid() == 1 || sid == 1 {
|
||||
continue
|
||||
}
|
||||
|
||||
syscall.Kill(process.Pid(), syscall.SIGTERM)
|
||||
}
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
// Send sigkill to remaining processes
|
||||
processes, err = ps.Processes()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, process := range processes {
|
||||
sid, _, _ := syscall.Syscall(syscall.SYS_GETSID, uintptr(process.Pid()), 0, 0)
|
||||
if process.Pid() == 1 || sid == 1 {
|
||||
continue
|
||||
}
|
||||
|
||||
syscall.Kill(process.Pid(), syscall.SIGKILL)
|
||||
}
|
||||
|
||||
fmt.Println("Done.")
|
||||
}
|
||||
|
||||
func setHostname() {
|
||||
fmt.Print("Setting hostname... ")
|
||||
|
||||
@@ -215,16 +252,12 @@ func waitZombieProcesses() {
|
||||
func catchSignals() {
|
||||
sigc := make(chan os.Signal, 1)
|
||||
signal.Notify(sigc, syscall.SIGUSR1, syscall.SIGTERM, syscall.SIGINT, syscall.SIGCHLD)
|
||||
defer close(sigc)
|
||||
defer signal.Stop(sigc)
|
||||
for {
|
||||
switch <-sigc {
|
||||
case syscall.SIGUSR1:
|
||||
close(sigc)
|
||||
signal.Stop(sigc)
|
||||
shutdownSystem()
|
||||
case syscall.SIGTERM, syscall.SIGINT:
|
||||
close(sigc)
|
||||
signal.Stop(sigc)
|
||||
rebootSystem()
|
||||
case syscall.SIGCHLD:
|
||||
@@ -237,9 +270,13 @@ func shutdownSystem() {
|
||||
fmt.Println("Shutting down...")
|
||||
|
||||
stopServiceManager()
|
||||
killProcesses()
|
||||
unmountFilesystems()
|
||||
remountRootReadonly()
|
||||
|
||||
fmt.Println("Syncing disks...")
|
||||
fmt.Print("Syncing disks... ")
|
||||
syscall.Sync()
|
||||
fmt.Println("Done.")
|
||||
|
||||
fmt.Println("Sending shutdown syscall...")
|
||||
err := syscall.Reboot(syscall.LINUX_REBOOT_CMD_POWER_OFF)
|
||||
@@ -252,9 +289,13 @@ func rebootSystem() {
|
||||
fmt.Println("Rebooting...")
|
||||
|
||||
stopServiceManager()
|
||||
killProcesses()
|
||||
unmountFilesystems()
|
||||
remountRootReadonly()
|
||||
|
||||
fmt.Println("Syncing disks...")
|
||||
fmt.Print("Syncing disks... ")
|
||||
syscall.Sync()
|
||||
fmt.Println("Done.")
|
||||
|
||||
fmt.Println("Sending reboot syscall...")
|
||||
err := syscall.Reboot(syscall.LINUX_REBOOT_CMD_RESTART)
|
||||
@@ -262,3 +303,10 @@ func rebootSystem() {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func printErrorAndReboot(format string, v ...any) {
|
||||
log.Printf(format, v...)
|
||||
fmt.Println("Press 'Enter' to reboot...")
|
||||
bufio.NewReader(os.Stdin).ReadBytes('\n')
|
||||
rebootSystem()
|
||||
}
|
||||
|
||||
+221
-18
@@ -1,10 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
@@ -28,12 +32,14 @@ var flagsEquivalence = map[string]uintptr{
|
||||
}
|
||||
|
||||
// Split string flags to mount flags and mount data
|
||||
func convertMountOptions(options string) (flags []uintptr, data string) {
|
||||
func convertMountOptions(options string) (flags []uintptr, data string, extra []string) {
|
||||
for _, flag := range strings.Split(options, ",") {
|
||||
if unixFlag, ok := flagsEquivalence[flag]; ok {
|
||||
flags = append(flags, unixFlag)
|
||||
} else {
|
||||
if data == "" {
|
||||
if flag == "noauto" || flag == "nofail" {
|
||||
extra = append(extra, flag)
|
||||
} else if data == "" {
|
||||
data = flag
|
||||
} else {
|
||||
data += "," + flag
|
||||
@@ -41,7 +47,7 @@ func convertMountOptions(options string) (flags []uintptr, data string) {
|
||||
}
|
||||
}
|
||||
|
||||
return flags, data
|
||||
return flags, data, extra
|
||||
}
|
||||
|
||||
// Combine a unix flag slice or array into a single uintptr
|
||||
@@ -84,7 +90,7 @@ func isMountpoint(mountpoint string) bool {
|
||||
}
|
||||
|
||||
func mount(source, target, fstype string, options string, mkdir bool) error {
|
||||
flags, data := convertMountOptions(options)
|
||||
flags, data, _ := convertMountOptions(options)
|
||||
|
||||
if isMountpoint(target) && !slices.Contains(flags, unix.MS_REMOUNT) {
|
||||
flags = append(flags, unix.MS_REMOUNT)
|
||||
@@ -104,34 +110,68 @@ func mount(source, target, fstype string, options string, mkdir bool) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func mountFstabEntries() error {
|
||||
func mountFstabEntries() (error, int) {
|
||||
if _, err := os.Stat("/etc/fstab"); os.IsNotExist(err) {
|
||||
return nil
|
||||
return nil, 0
|
||||
} else if err != nil {
|
||||
return err
|
||||
return err, 0
|
||||
}
|
||||
|
||||
bytes, err := os.ReadFile("/etc/fstab")
|
||||
if err != nil {
|
||||
return err
|
||||
return err, 0
|
||||
}
|
||||
|
||||
swapPriority := -2
|
||||
|
||||
for _, line := range strings.Split(string(bytes), "\n") {
|
||||
for i, line := range strings.Split(string(bytes), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if strings.HasPrefix(line, "#") || line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
source := strings.Split(line, " ")[0]
|
||||
target := strings.Split(line, " ")[1]
|
||||
fstype := strings.Split(line, " ")[2]
|
||||
options := strings.Split(line, " ")[3]
|
||||
// Get fields from line
|
||||
fields := []string{}
|
||||
sb := &strings.Builder{}
|
||||
quoted := false
|
||||
for _, r := range line {
|
||||
if r == '"' {
|
||||
quoted = !quoted
|
||||
} else if !quoted && r == ' ' {
|
||||
str := sb.String()
|
||||
if len(strings.TrimSpace(str)) > 0 {
|
||||
fields = append(fields, sb.String())
|
||||
}
|
||||
sb.Reset()
|
||||
} else {
|
||||
sb.WriteRune(r)
|
||||
}
|
||||
}
|
||||
if sb.Len() > 0 {
|
||||
fields = append(fields, sb.String())
|
||||
}
|
||||
if len(fields) < 4 {
|
||||
return fmt.Errorf("Not enough fields"), i + 1
|
||||
}
|
||||
source := fields[0]
|
||||
target := fields[1]
|
||||
fstype := fields[2]
|
||||
options := fields[3]
|
||||
|
||||
flags, data := convertMountOptions(options)
|
||||
// Replace device prefixes
|
||||
if cutSource, ok := strings.CutPrefix(source, "LABEL="); ok {
|
||||
source = "/dev/disk/by-label/" + strings.ReplaceAll(cutSource, " ", "\\x20")
|
||||
} else if cutSource, ok := strings.CutPrefix(source, "UUID="); ok {
|
||||
source = "/dev/disk/by-uuid/" + cutSource
|
||||
} else if cutSource, ok := strings.CutPrefix(source, "PARTLABEL="); ok {
|
||||
source = "/dev/disk/by-partlabel/" + cutSource
|
||||
} else if cutSource, ok := strings.CutPrefix(source, "PARTUUID="); ok {
|
||||
source = "/dev/disk/by-partuuid/" + cutSource
|
||||
}
|
||||
|
||||
if slices.Contains(strings.Split(data, ","), "noauto") {
|
||||
flags, data, extra := convertMountOptions(options)
|
||||
|
||||
if slices.Contains(extra, "noauto") {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -142,7 +182,11 @@ func mountFstabEntries() error {
|
||||
_, _, err := unix.Syscall(unix.SYS_SWAPON, uintptr(unsafe.Pointer(&b[0])), uintptr((swapPriority<<SwapFlagPrioShift)&SwapFlagPrioMask), 0)
|
||||
swapPriority--
|
||||
if err != 0 {
|
||||
return fmt.Errorf("swapon syscall returned none-zero error code: %d", err)
|
||||
if slices.Contains(extra, "nofail") {
|
||||
fmt.Printf("Warning: could not mount fstab entry on line %d: swapon syscall returned non-zero exit code: %d\n", i+1, err)
|
||||
} else {
|
||||
return fmt.Errorf("swapon syscall returned non-zero exit code: %d", err), i + 1
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
@@ -152,9 +196,168 @@ func mountFstabEntries() error {
|
||||
}
|
||||
|
||||
if err := unix.Mount(source, target, fstype, combineUnixFlags(flags), data); err != nil {
|
||||
return err
|
||||
if slices.Contains(extra, "nofail") {
|
||||
log.Printf("Warning: could not mount fstab entry on line %d: %s\n", i+1, err)
|
||||
} else {
|
||||
return err, i + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
return nil, 0
|
||||
}
|
||||
|
||||
func unmountFilesystems() {
|
||||
// Disable all swap memory
|
||||
data, err := os.ReadFile("/proc/swaps")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for i, entry := range strings.Split(string(data), "\n") {
|
||||
if i == 0 {
|
||||
continue
|
||||
}
|
||||
entry = strings.TrimSpace(entry)
|
||||
if len(entry) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
mountpoint := strings.Fields(entry)[0]
|
||||
|
||||
// Unmount swap at mountpoint
|
||||
fmt.Printf("Disabling swap at %s... ", mountpoint)
|
||||
b := append([]byte(mountpoint), 0)
|
||||
_, _, err := unix.Syscall(unix.SYS_SWAPOFF, uintptr(unsafe.Pointer(&b[0])), 0, 0)
|
||||
if err == 0 {
|
||||
fmt.Println("Done.")
|
||||
} else {
|
||||
fmt.Printf("Error: %s\n", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
data, err = os.ReadFile("/proc/self/mountinfo")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Unmount filesystems
|
||||
entries := strings.Split(string(data), "\n")
|
||||
slices.Reverse(entries)
|
||||
for _, entry := range entries {
|
||||
entry = strings.TrimSpace(entry)
|
||||
if len(entry) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Get entry fields
|
||||
fields := strings.Fields(entry)
|
||||
mountpoint := fields[4]
|
||||
filesystem := ""
|
||||
for i := 6; i < len(fields); i++ {
|
||||
if fields[i] == "-" {
|
||||
filesystem = fields[i+1]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Skip root filesystem
|
||||
if mountpoint == "/" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Skip root and ignored filesystems
|
||||
ignoredFilesystems := []string{
|
||||
"devtmpfs",
|
||||
"proc",
|
||||
"sysfs",
|
||||
"tmpfs",
|
||||
}
|
||||
|
||||
if slices.Contains(ignoredFilesystems, filesystem) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Unmount filesystem at mountpoint
|
||||
fmt.Printf("Unmounting %s...", mountpoint)
|
||||
tries := 0
|
||||
for {
|
||||
err := unix.Unmount(mountpoint, 0)
|
||||
if errors.Is(err, syscall.EBUSY) {
|
||||
fmt.Print(".")
|
||||
tries++
|
||||
time.Sleep(1 * time.Second)
|
||||
if tries >= 60 {
|
||||
unix.Unmount(mountpoint, syscall.MNT_FORCE)
|
||||
fmt.Println(" Timeout.")
|
||||
break
|
||||
}
|
||||
} else if err != nil {
|
||||
fmt.Printf(" Error: %s\n", err.Error())
|
||||
break
|
||||
} else {
|
||||
fmt.Println(" Done.")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func remountRootReadonly() {
|
||||
fmt.Print("Remounting root as read-only...")
|
||||
|
||||
data, err := os.ReadFile("/proc/self/mountinfo")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
filesystem := ""
|
||||
source := ""
|
||||
fsData := ""
|
||||
|
||||
// Get root filesystems
|
||||
entries := strings.Split(string(data), "\n")
|
||||
slices.Reverse(entries)
|
||||
for _, entry := range entries {
|
||||
entry = strings.TrimSpace(entry)
|
||||
if len(entry) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Get entry fields
|
||||
fields := strings.Fields(entry)
|
||||
mountpoint := fields[4]
|
||||
for i := 6; i < len(fields); i++ {
|
||||
if fields[i] == "-" {
|
||||
filesystem = fields[i+1]
|
||||
source = fields[i+2]
|
||||
fsData = fields[i+3]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if mountpoint == "/" {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
tries := 0
|
||||
for {
|
||||
err := unix.Mount(source, "/", filesystem, syscall.MS_RDONLY|syscall.MS_REMOUNT, fsData)
|
||||
if errors.Is(err, syscall.EBUSY) {
|
||||
fmt.Print(".")
|
||||
tries++
|
||||
time.Sleep(1 * time.Second)
|
||||
if tries >= 60 {
|
||||
fmt.Println(" Timeout.")
|
||||
break
|
||||
}
|
||||
} else if err != nil {
|
||||
fmt.Printf(" Error: %s\n", err.Error())
|
||||
break
|
||||
} else {
|
||||
fmt.Println(" Done.")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+35
-65
@@ -14,8 +14,6 @@ import (
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// Build-time variables
|
||||
@@ -135,67 +133,13 @@ func Init() {
|
||||
// Read and initialize service files
|
||||
for _, entry := range dirEntries {
|
||||
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".esv") {
|
||||
logger.Printf("Initializing service (%s)...\n", entry.Name())
|
||||
bytes, err := os.ReadFile(path.Join(serviceConfigDir, "services", entry.Name()))
|
||||
if err != nil {
|
||||
logger.Printf("Error: Could not read service file (%s)", path.Join(serviceConfigDir, "services", entry.Name()))
|
||||
continue
|
||||
}
|
||||
|
||||
service := EnitService{
|
||||
Name: "",
|
||||
Description: "",
|
||||
Dependencies: make([]string, 0),
|
||||
Type: "",
|
||||
StartCmd: "",
|
||||
ExitMethod: "",
|
||||
StopCmd: "",
|
||||
Restart: "",
|
||||
CrashOnSafeExit: true,
|
||||
restartCount: 0,
|
||||
stopChannel: make(chan bool),
|
||||
LogOutput: true,
|
||||
state: EnitServiceUnloaded,
|
||||
}
|
||||
if err := yaml.Unmarshal(bytes, &service); err != nil {
|
||||
logger.Printf("Error: could not read service file %s", path.Join(serviceConfigDir, "services", entry.Name()))
|
||||
continue
|
||||
}
|
||||
|
||||
for _, sv := range Services {
|
||||
if sv.Name == service.Name {
|
||||
logger.Printf("Error: service with name (%s) has already been initialized", service.Name)
|
||||
}
|
||||
}
|
||||
|
||||
switch service.Type {
|
||||
case "simple", "background":
|
||||
default:
|
||||
logger.Printf("Error: unknown service type (%s)", service.Type)
|
||||
continue
|
||||
}
|
||||
|
||||
switch service.ExitMethod {
|
||||
case "stop_command", "kill":
|
||||
default:
|
||||
logger.Printf("Error: unknown exit method (%s)\n", service.ExitMethod)
|
||||
continue
|
||||
}
|
||||
|
||||
switch service.Restart {
|
||||
case "true", "always":
|
||||
default:
|
||||
service.Restart = "false"
|
||||
}
|
||||
|
||||
Services = append(Services, &service)
|
||||
|
||||
logger.Printf("Service (%s) has been initialized!\n", service.Name)
|
||||
filepath := path.Join(serviceConfigDir, "services", entry.Name())
|
||||
LoadService(filepath)
|
||||
}
|
||||
}
|
||||
|
||||
// Read enabled services
|
||||
ReadEnabledServices()
|
||||
EnabledServices := ReadEnabledServices()
|
||||
|
||||
// Start enabled services
|
||||
stages := slices.Collect(maps.Keys(EnabledServices))
|
||||
@@ -213,13 +157,11 @@ func Init() {
|
||||
continue
|
||||
}
|
||||
|
||||
if len(service.GetUnmetDependencies()) == 0 {
|
||||
err := service.StartService()
|
||||
if err != nil {
|
||||
logger.Printf("Error: could not start service (%s): %s", service.Name, err)
|
||||
}
|
||||
remainingServices--
|
||||
err := service.StartService()
|
||||
if err != nil {
|
||||
logger.Printf("Error: could not start service (%s): %s", service.Name, err)
|
||||
}
|
||||
remainingServices--
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -227,6 +169,34 @@ func Init() {
|
||||
logger.Println("ESVM initialized successfully!")
|
||||
}
|
||||
|
||||
func Reload() {
|
||||
logger.Println("Reloading all ESVM services...")
|
||||
|
||||
dirEntries, err := os.ReadDir(path.Join(serviceConfigDir, "services"))
|
||||
if err != nil {
|
||||
logger.Fatalf("Error: Could not initialize ESVM: %s", err)
|
||||
}
|
||||
|
||||
// Read and load service files
|
||||
servicesToRemove := slices.Clone(Services)
|
||||
for _, entry := range dirEntries {
|
||||
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".esv") {
|
||||
filepath := path.Join(serviceConfigDir, "services", entry.Name())
|
||||
LoadService(filepath)
|
||||
servicesToRemove = slices.DeleteFunc(servicesToRemove, func(sv *EnitService) bool {
|
||||
return sv.Filepath == filepath
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Reload services that had their esv file removed
|
||||
for _, service := range servicesToRemove {
|
||||
LoadService(service.Filepath)
|
||||
}
|
||||
|
||||
logger.Println("All ESVM services have been reloaded!")
|
||||
}
|
||||
|
||||
func Destroy() {
|
||||
logger.Println("Stopping all ESVM services...")
|
||||
|
||||
|
||||
+209
-64
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -37,46 +38,29 @@ var EnitServiceStateNames map[EnitServiceState]string = map[EnitServiceState]str
|
||||
}
|
||||
|
||||
type EnitService struct {
|
||||
Name string `yaml:"name"`
|
||||
Description string `yaml:"description,omitempty"`
|
||||
Dependencies []string `yaml:"dependencies,omitempty"`
|
||||
Type string `yaml:"type"`
|
||||
StartCmd string `yaml:"start_cmd"`
|
||||
ExitMethod string `yaml:"exit_method"`
|
||||
CrashOnSafeExit bool `yaml:"crash_on_safe_exit"`
|
||||
StopCmd string `yaml:"stop_cmd,omitempty"`
|
||||
Restart string `yaml:"restart,omitempty"`
|
||||
ReadyFd int `yaml:"ready_fd"`
|
||||
LogOutput bool `yaml:"log_output,omitempty"`
|
||||
state EnitServiceState
|
||||
processID int
|
||||
restartCount int
|
||||
stopChannel chan bool
|
||||
Name string `yaml:"name"`
|
||||
Description string `yaml:"description,omitempty"`
|
||||
Type string `yaml:"type"`
|
||||
StartCmd string `yaml:"start_cmd"`
|
||||
ExitMethod string `yaml:"exit_method"`
|
||||
CrashOnSafeExit bool `yaml:"crash_on_safe_exit"`
|
||||
StopCmd string `yaml:"stop_cmd,omitempty"`
|
||||
Restart string `yaml:"restart,omitempty"`
|
||||
ReadyFd int `yaml:"ready_fd"`
|
||||
Setpgid bool `yaml:"setpgid"`
|
||||
LogOutput bool `yaml:"log_output,omitempty"`
|
||||
Filepath string
|
||||
filepathChecksum [32]byte
|
||||
state EnitServiceState
|
||||
processID int
|
||||
restartCount int
|
||||
stopChannel chan bool
|
||||
shouldReload bool
|
||||
}
|
||||
|
||||
var Services = make([]*EnitService, 0)
|
||||
var EnabledServices = make(map[int][]string)
|
||||
var startedServicesOrder = make([]string, 0)
|
||||
|
||||
func (service *EnitService) GetUnmetDependencies() (missingDependencies []string) {
|
||||
for _, dependency := range service.Dependencies {
|
||||
if strings.HasPrefix(dependency, "/") {
|
||||
// File dependency
|
||||
if _, err := os.Stat(dependency); err != nil {
|
||||
missingDependencies = append(missingDependencies, dependency)
|
||||
}
|
||||
} else {
|
||||
// Service dependency
|
||||
depService := GetServiceByName(dependency)
|
||||
if depService == nil {
|
||||
missingDependencies = append(missingDependencies, dependency)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return missingDependencies
|
||||
}
|
||||
|
||||
func (service *EnitService) GetProcess() *os.Process {
|
||||
process, _ := os.FindProcess(service.processID)
|
||||
|
||||
@@ -117,6 +101,120 @@ func (service *EnitService) GetLogFile() (file *os.File, err error) {
|
||||
return file, nil
|
||||
}
|
||||
|
||||
func LoadService(filepath string) {
|
||||
bytes, err := os.ReadFile(filepath)
|
||||
checksum := sha256.Sum256(bytes)
|
||||
|
||||
var serviceToReload *EnitService
|
||||
|
||||
// Check if service is already loaded
|
||||
for _, service := range Services {
|
||||
if service.Filepath != filepath {
|
||||
continue
|
||||
}
|
||||
|
||||
if slices.Equal(checksum[:], service.filepathChecksum[:]) {
|
||||
return
|
||||
}
|
||||
|
||||
if service.state == EnitServiceStarting || service.state == EnitServiceRunning {
|
||||
service.shouldReload = true
|
||||
logger.Printf("Warning: Service (%s) is currently running and will be reloaded when stopped\n", service.Name)
|
||||
return
|
||||
}
|
||||
service.shouldReload = false
|
||||
serviceToReload = service
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
if serviceToReload == nil {
|
||||
logger.Printf("Loading service (%s)...\n", filepath)
|
||||
} else {
|
||||
logger.Printf("Reloading service (%s)...\n", filepath)
|
||||
}
|
||||
|
||||
if os.IsNotExist(err) {
|
||||
Services = slices.DeleteFunc(Services, func(sv *EnitService) bool {
|
||||
if sv.Filepath == filepath {
|
||||
logger.Printf("Service (%s) has been removed\n", sv.Name)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
return
|
||||
} else if err != nil {
|
||||
logger.Printf("Error: Could not read service file (%s)", filepath)
|
||||
return
|
||||
}
|
||||
|
||||
newService := EnitService{
|
||||
Name: "",
|
||||
Description: "",
|
||||
Type: "",
|
||||
StartCmd: "",
|
||||
ExitMethod: "",
|
||||
StopCmd: "",
|
||||
Restart: "",
|
||||
Setpgid: true,
|
||||
CrashOnSafeExit: true,
|
||||
LogOutput: true,
|
||||
Filepath: filepath,
|
||||
filepathChecksum: sha256.Sum256(bytes),
|
||||
restartCount: 0,
|
||||
stopChannel: make(chan bool),
|
||||
state: EnitServiceUnloaded,
|
||||
}
|
||||
if serviceToReload != nil {
|
||||
newService.restartCount = serviceToReload.restartCount
|
||||
newService.stopChannel = serviceToReload.stopChannel
|
||||
newService.state = serviceToReload.state
|
||||
}
|
||||
if err := yaml.Unmarshal(bytes, &newService); err != nil {
|
||||
logger.Printf("Error: could not read service file %s", filepath)
|
||||
return
|
||||
}
|
||||
|
||||
for _, sv := range Services {
|
||||
if sv.Name == newService.Name && sv != serviceToReload {
|
||||
logger.Printf("Error: service with name (%s) has already been loaded", newService.Name)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
switch newService.Type {
|
||||
case "simple", "background":
|
||||
default:
|
||||
logger.Printf("Error: unknown service type (%s)", newService.Type)
|
||||
return
|
||||
}
|
||||
|
||||
switch newService.ExitMethod {
|
||||
case "stop_command", "kill":
|
||||
default:
|
||||
logger.Printf("Error: unknown exit method (%s)\n", newService.ExitMethod)
|
||||
return
|
||||
}
|
||||
|
||||
switch newService.Restart {
|
||||
case "true", "always":
|
||||
default:
|
||||
newService.Restart = "false"
|
||||
}
|
||||
|
||||
for i, sv := range Services {
|
||||
if sv == serviceToReload {
|
||||
Services[i] = &newService
|
||||
logger.Printf("Service (%s) has been reloaded!\n", newService.Name)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
Services = append(Services, &newService)
|
||||
logger.Printf("Service (%s) has been loaded!\n", newService.Name)
|
||||
}
|
||||
|
||||
func (service *EnitService) StartService() (err error) {
|
||||
if service == nil {
|
||||
return nil
|
||||
@@ -137,6 +235,7 @@ func (service *EnitService) StartService() (err error) {
|
||||
}
|
||||
|
||||
cmd := exec.Command("/bin/sh", "-c", "exec "+service.StartCmd)
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: service.Setpgid, Pgid: 0}
|
||||
if logFile != nil {
|
||||
cmd.Stdout = logFile
|
||||
cmd.Stderr = logFile
|
||||
@@ -177,6 +276,7 @@ func (service *EnitService) StartService() (err error) {
|
||||
return err
|
||||
}
|
||||
|
||||
pid := cmd.Process.Pid
|
||||
service.processID = cmd.Process.Pid
|
||||
service.state = EnitServiceStarting
|
||||
|
||||
@@ -190,8 +290,8 @@ func (service *EnitService) StartService() (err error) {
|
||||
logFile.Close()
|
||||
}
|
||||
|
||||
// Kill process
|
||||
cmd.Process.Kill()
|
||||
// Kill process and children
|
||||
syscall.Kill(-pid, syscall.SIGKILL)
|
||||
|
||||
service.processID = 0
|
||||
service.state = EnitServiceCrashed
|
||||
@@ -214,10 +314,21 @@ func (service *EnitService) StartService() (err error) {
|
||||
case <-service.stopChannel:
|
||||
service.restartCount = 0
|
||||
default:
|
||||
// Kill remaining child processes
|
||||
syscall.Kill(-pid, syscall.SIGKILL)
|
||||
|
||||
if service.Type == "simple" && err == nil {
|
||||
service.restartCount = 0
|
||||
if service.ExitMethod != "stop_command" {
|
||||
service.state = EnitServiceCompleted
|
||||
|
||||
// Reload service if needed
|
||||
if service.shouldReload {
|
||||
LoadService(service.Filepath)
|
||||
if GetServiceByName(service.Name) == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
service.state = EnitServiceRunning
|
||||
}
|
||||
@@ -231,6 +342,15 @@ func (service *EnitService) StartService() (err error) {
|
||||
service.state = EnitServiceCrashed
|
||||
}
|
||||
|
||||
// Reload service if needed
|
||||
if service.shouldReload {
|
||||
LoadService(service.Filepath)
|
||||
if GetServiceByName(service.Name) == nil {
|
||||
return
|
||||
}
|
||||
service = GetServiceByName(service.Name)
|
||||
}
|
||||
|
||||
if service.Restart == "always" {
|
||||
_ = service.StartService()
|
||||
} else if service.Restart == "true" && service.restartCount < 5 {
|
||||
@@ -258,11 +378,26 @@ func (service *EnitService) StopService() error {
|
||||
}
|
||||
|
||||
logger.Printf("Stopping service (%s)...", service.Name)
|
||||
pid := service.processID
|
||||
|
||||
newServiceStatus := EnitServiceCrashed
|
||||
defer func() {
|
||||
// Kill remaining child processes
|
||||
if pid != 0 {
|
||||
syscall.Kill(-pid, syscall.SIGKILL)
|
||||
}
|
||||
|
||||
service.state = newServiceStatus
|
||||
service.processID = 0
|
||||
|
||||
// Reload service if needed
|
||||
if service.shouldReload {
|
||||
LoadService(service.Filepath)
|
||||
if GetServiceByName(service.Name) == nil {
|
||||
return
|
||||
}
|
||||
service = GetServiceByName(service.Name)
|
||||
}
|
||||
}()
|
||||
|
||||
if service.ExitMethod == "kill" {
|
||||
@@ -279,31 +414,33 @@ func (service *EnitService) StopService() error {
|
||||
service.GetProcess().Signal(syscall.SIGKILL)
|
||||
return fmt.Errorf("could not stop process gracefully")
|
||||
}
|
||||
|
||||
// Check if the process has stopped gracefully, otherwise send sigkill on timeout
|
||||
exited := make(chan bool)
|
||||
go func() {
|
||||
for {
|
||||
if err := service.GetProcess().Signal(syscall.Signal(0)); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
exited <- true
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-exited:
|
||||
case <-time.After(5 * time.Second):
|
||||
service.GetProcess().Signal(syscall.SIGKILL)
|
||||
return fmt.Errorf("could not stop process gracefully")
|
||||
}
|
||||
} else {
|
||||
go func() { service.stopChannel <- true }()
|
||||
|
||||
cmd := exec.Command("/bin/sh", "-c", service.StopCmd)
|
||||
if err := cmd.Run(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the process has stopped gracefully, otherwise send sigkill on timeout
|
||||
exited := make(chan bool)
|
||||
go func() {
|
||||
for {
|
||||
if err := syscall.Kill(pid, syscall.Signal(0)); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
exited <- true
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-exited:
|
||||
case <-time.After(5 * time.Second):
|
||||
service.GetProcess().Signal(syscall.SIGKILL)
|
||||
return fmt.Errorf("could not stop process gracefully")
|
||||
}
|
||||
|
||||
newServiceStatus = EnitServiceStopped
|
||||
logger.Printf("Service (%s) has stopped!\n", service.Name)
|
||||
|
||||
@@ -315,6 +452,12 @@ func (service *EnitService) RestartService() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Get service from list in case of a reload
|
||||
if GetServiceByName(service.Name) == nil {
|
||||
return fmt.Errorf("service was removed")
|
||||
}
|
||||
service = GetServiceByName(service.Name)
|
||||
|
||||
if err := service.StartService(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -322,10 +465,8 @@ func (service *EnitService) RestartService() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Functions will be rewritten at some point to allow enabling unloaded services
|
||||
|
||||
func (service *EnitService) isEnabled() (bool, int) {
|
||||
for stage, services := range EnabledServices {
|
||||
for stage, services := range ReadEnabledServices() {
|
||||
if slices.Contains(services, service.Name) {
|
||||
return true, stage
|
||||
}
|
||||
@@ -343,6 +484,8 @@ func (service *EnitService) SetEnabled(stage int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
EnabledServices := ReadEnabledServices()
|
||||
|
||||
// Remove service from current stage
|
||||
EnabledServices[s] = slices.DeleteFunc(EnabledServices[s], func(name string) bool {
|
||||
return name == service.Name
|
||||
@@ -369,10 +512,12 @@ func (service *EnitService) SetEnabled(stage int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func ReadEnabledServices() error {
|
||||
func ReadEnabledServices() (EnabledServices map[int][]string) {
|
||||
EnabledServices = make(map[int][]string)
|
||||
|
||||
data, err := os.ReadFile(path.Join(serviceConfigDir, "enabled_services"))
|
||||
if err != nil {
|
||||
return err
|
||||
return EnabledServices
|
||||
}
|
||||
|
||||
err = yaml.Unmarshal(data, &EnabledServices)
|
||||
@@ -385,15 +530,15 @@ func ReadEnabledServices() error {
|
||||
// Update enabled_services file
|
||||
data, err := yaml.Marshal(EnabledServices)
|
||||
if err != nil {
|
||||
return err
|
||||
return EnabledServices
|
||||
}
|
||||
err = os.WriteFile(path.Join(serviceConfigDir, "enabled_services"), data, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
return EnabledServices
|
||||
}
|
||||
|
||||
return nil
|
||||
return EnabledServices
|
||||
}
|
||||
|
||||
return nil
|
||||
return EnabledServices
|
||||
}
|
||||
|
||||
+36
-8
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -17,6 +18,7 @@ func initSocket() (socket net.Listener, err error) {
|
||||
}
|
||||
|
||||
// Register command handlers
|
||||
commandHandlers["reload"] = handleReloadServicesCommand
|
||||
commandHandlers["start"] = handleStartServiceCommand
|
||||
commandHandlers["stop"] = handleStopServiceCommand
|
||||
commandHandlers["restart"] = handleRestartServiceCommand
|
||||
@@ -31,27 +33,23 @@ func listenToSocket() {
|
||||
conn, err := socket.Accept()
|
||||
if err != nil {
|
||||
logger.Println("Could not accept socket connection!")
|
||||
panic(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Handle the connection in a separate goroutine.
|
||||
go func(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
// Create a buffer for incoming data.
|
||||
buf := make([]byte, 4096)
|
||||
|
||||
// Read data from the connection.
|
||||
n, err := conn.Read(buf)
|
||||
if err == io.EOF {
|
||||
return
|
||||
}
|
||||
data, err := readAllConn(conn)
|
||||
if err != nil {
|
||||
logger.Fatalf("Could not read data from socket! Error: %s\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Decoode JSON data
|
||||
var jsonData map[string]any
|
||||
err = json.Unmarshal(buf[:n], &jsonData)
|
||||
err = json.Unmarshal(data, &jsonData)
|
||||
if err != nil {
|
||||
conn.Write(wrapErrorInJson(fmt.Errorf("Invalid JSON")))
|
||||
return
|
||||
@@ -74,6 +72,13 @@ func listenToSocket() {
|
||||
}(conn)
|
||||
}
|
||||
|
||||
func handleReloadServicesCommand(conn net.Conn, jsonData map[string]any) {
|
||||
// Reload services
|
||||
Reload()
|
||||
|
||||
conn.Write(wrapSuccessMsgInJson("Services reloaded successfully"))
|
||||
}
|
||||
|
||||
func handleStartServiceCommand(conn net.Conn, jsonData map[string]any) {
|
||||
// Get service name from json data
|
||||
serviceName, ok := jsonData["service"]
|
||||
@@ -222,6 +227,7 @@ func handleStatusServiceCommand(conn net.Conn, jsonData map[string]any) {
|
||||
|
||||
statusMap := make(map[string]any)
|
||||
statusMap["name"] = service.Name
|
||||
statusMap["description"] = service.Description
|
||||
statusMap["state"] = EnitServiceStateNames[service.state]
|
||||
statusMap["process_id"] = service.processID
|
||||
statusMap["is_enabled"], statusMap["stage"] = service.isEnabled()
|
||||
@@ -244,6 +250,7 @@ func handleListServicesCommand(conn net.Conn, _ map[string]any) {
|
||||
for _, service := range Services {
|
||||
statusMap := make(map[string]any)
|
||||
statusMap["name"] = service.Name
|
||||
statusMap["description"] = service.Description
|
||||
statusMap["state"] = EnitServiceStateNames[service.state]
|
||||
statusMap["process_id"] = service.processID
|
||||
statusMap["is_enabled"], statusMap["stage"] = service.isEnabled()
|
||||
@@ -293,3 +300,24 @@ func wrapSuccessMsgInJson(msg string) []byte {
|
||||
}
|
||||
return jsonData
|
||||
}
|
||||
|
||||
func readAllConn(conn net.Conn) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
for {
|
||||
dataChunk := make([]byte, 1024)
|
||||
|
||||
n, err := conn.Read(dataChunk)
|
||||
if err != nil && err != io.EOF {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
buf.Write(dataChunk[:n])
|
||||
|
||||
if n < 1024 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user