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
|
||
|
|
2be3e0c947
|
@@ -4,4 +4,5 @@ type: background
|
|||||||
start_cmd: /usr/bin/setsid /sbin/agetty --noclear tty1
|
start_cmd: /usr/bin/setsid /sbin/agetty --noclear tty1
|
||||||
exit_method: kill
|
exit_method: kill
|
||||||
crash_on_safe_exit: false
|
crash_on_safe_exit: false
|
||||||
restart: always
|
restart: always
|
||||||
|
setpgid: false
|
||||||
|
|||||||
@@ -4,4 +4,5 @@ type: background
|
|||||||
start_cmd: /usr/bin/setsid /sbin/agetty tty2
|
start_cmd: /usr/bin/setsid /sbin/agetty tty2
|
||||||
exit_method: kill
|
exit_method: kill
|
||||||
crash_on_safe_exit: false
|
crash_on_safe_exit: false
|
||||||
restart: always
|
restart: always
|
||||||
|
setpgid: false
|
||||||
|
|||||||
@@ -4,4 +4,5 @@ type: background
|
|||||||
start_cmd: /usr/bin/setsid /sbin/agetty tty3
|
start_cmd: /usr/bin/setsid /sbin/agetty tty3
|
||||||
exit_method: kill
|
exit_method: kill
|
||||||
crash_on_safe_exit: false
|
crash_on_safe_exit: false
|
||||||
restart: always
|
restart: always
|
||||||
|
setpgid: false
|
||||||
|
|||||||
@@ -4,4 +4,5 @@ type: background
|
|||||||
start_cmd: /usr/bin/setsid /sbin/agetty tty4
|
start_cmd: /usr/bin/setsid /sbin/agetty tty4
|
||||||
exit_method: kill
|
exit_method: kill
|
||||||
crash_on_safe_exit: false
|
crash_on_safe_exit: false
|
||||||
restart: always
|
restart: always
|
||||||
|
setpgid: false
|
||||||
|
|||||||
@@ -4,4 +4,5 @@ type: background
|
|||||||
start_cmd: /usr/bin/setsid /sbin/agetty tty5
|
start_cmd: /usr/bin/setsid /sbin/agetty tty5
|
||||||
exit_method: kill
|
exit_method: kill
|
||||||
crash_on_safe_exit: false
|
crash_on_safe_exit: false
|
||||||
restart: always
|
restart: always
|
||||||
|
setpgid: false
|
||||||
|
|||||||
@@ -4,4 +4,5 @@ type: background
|
|||||||
start_cmd: /usr/bin/setsid /sbin/agetty tty6
|
start_cmd: /usr/bin/setsid /sbin/agetty tty6
|
||||||
exit_method: kill
|
exit_method: kill
|
||||||
crash_on_safe_exit: false
|
crash_on_safe_exit: false
|
||||||
restart: always
|
restart: always
|
||||||
|
setpgid: false
|
||||||
|
|||||||
+93
-37
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -57,7 +58,57 @@ func main() {
|
|||||||
return
|
return
|
||||||
} else if flag.Args()[0] == "service" || flag.Args()[0] == "sv" {
|
} else if flag.Args()[0] == "service" || flag.Args()[0] == "sv" {
|
||||||
if len(flag.Args()) <= 1 {
|
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
|
return
|
||||||
} else if flag.Arg(1) == "start" || flag.Arg(1) == "stop" || flag.Arg(1) == "restart" {
|
} else if flag.Arg(1) == "start" || flag.Arg(1) == "stop" || flag.Arg(1) == "restart" {
|
||||||
// Ensure service name argument has been set
|
// 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)
|
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.
|
// Read data from the connection.
|
||||||
n, err := conn.Read(buf)
|
data, err := readAllConn(conn)
|
||||||
if err == io.EOF {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Fatalf("Could not read data from socket! Error: %s\n", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Print json data if flag is set
|
// Print json data if flag is set
|
||||||
if *printJson {
|
if *printJson {
|
||||||
fmt.Println(string(buf[:n]))
|
fmt.Println(string(data))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decoode JSON data
|
// Decoode JSON data
|
||||||
var returnedJsonData map[string]any
|
var returnedJsonData map[string]any
|
||||||
err = json.Unmarshal(buf[:n], &returnedJsonData)
|
err = json.Unmarshal(data, &returnedJsonData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Could not decode JSON data from connection!")
|
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)
|
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.
|
// Read data from the connection.
|
||||||
n, err := conn.Read(buf)
|
data, err := readAllConn(conn)
|
||||||
if err == io.EOF {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Fatalf("Could not read data from socket! Error: %s\n", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Print json data if flag is set
|
// Print json data if flag is set
|
||||||
if *printJson {
|
if *printJson {
|
||||||
fmt.Println(string(buf[:n]))
|
fmt.Println(string(data))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decoode JSON data
|
// Decoode JSON data
|
||||||
var returnedJsonData map[string]any
|
var returnedJsonData map[string]any
|
||||||
err = json.Unmarshal(buf[:n], &returnedJsonData)
|
err = json.Unmarshal(data, &returnedJsonData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Could not decode JSON data from connection!")
|
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)
|
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.
|
// Read data from the connection.
|
||||||
n, err := conn.Read(buf)
|
data, err := readAllConn(conn)
|
||||||
if err == io.EOF {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Fatalf("Could not read data from socket! Error: %s\n", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Print json data if flag is set
|
// Print json data if flag is set
|
||||||
if *printJson {
|
if *printJson {
|
||||||
fmt.Println(string(buf[:n]))
|
fmt.Println(string(data))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decoode JSON data
|
// Decoode JSON data
|
||||||
var returnedJsonData map[string]any
|
var returnedJsonData map[string]any
|
||||||
err = json.Unmarshal(buf[:n], &returnedJsonData)
|
err = json.Unmarshal(data, &returnedJsonData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Could not decode JSON data from connection!")
|
log.Fatalf("Could not decode JSON data from connection!")
|
||||||
}
|
}
|
||||||
@@ -253,11 +289,13 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
serviceState := returnedJsonData["state"].(string)
|
serviceState := returnedJsonData["state"].(string)
|
||||||
|
serviceDescription := returnedJsonData["description"].(string)
|
||||||
serviceEnabled := returnedJsonData["is_enabled"].(bool)
|
serviceEnabled := returnedJsonData["is_enabled"].(bool)
|
||||||
serviceStage := int(returnedJsonData["stage"].(float64))
|
serviceStage := int(returnedJsonData["stage"].(float64))
|
||||||
processID := int(returnedJsonData["process_id"].(float64))
|
processID := int(returnedJsonData["process_id"].(float64))
|
||||||
|
|
||||||
fmt.Printf("Name: %s\n", flag.Arg(2))
|
fmt.Printf("Name: %s\n", flag.Arg(2))
|
||||||
|
fmt.Printf("Description: %s\n", serviceDescription)
|
||||||
fmt.Printf("State: %s\n", serviceState)
|
fmt.Printf("State: %s\n", serviceState)
|
||||||
if serviceEnabled {
|
if serviceEnabled {
|
||||||
fmt.Printf("Enabled: %t (Stage %d)\n", serviceEnabled, serviceStage)
|
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)
|
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.
|
// Read data from the connection.
|
||||||
n, err := conn.Read(buf)
|
data, err := readAllConn(conn)
|
||||||
if err == io.EOF {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
log.Fatalf("Could not read data from socket! Error: %s\n", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Print json data if flag is set
|
// Print json data if flag is set
|
||||||
if *printJson {
|
if *printJson {
|
||||||
fmt.Println(string(buf[:n]))
|
fmt.Println(string(data))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decoode JSON data
|
// Decoode JSON data
|
||||||
var returnedJsonData map[string]any
|
var returnedJsonData map[string]any
|
||||||
err = json.Unmarshal(buf[:n], &returnedJsonData)
|
err = json.Unmarshal(data, &returnedJsonData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Could not decode JSON data from connection!")
|
log.Fatalf("Could not decode JSON data from connection!")
|
||||||
}
|
}
|
||||||
@@ -319,12 +352,14 @@ func main() {
|
|||||||
|
|
||||||
for _, serviceMap := range returnedJsonData["services"].([]any) {
|
for _, serviceMap := range returnedJsonData["services"].([]any) {
|
||||||
serviceName := serviceMap.(map[string]any)["name"].(string)
|
serviceName := serviceMap.(map[string]any)["name"].(string)
|
||||||
|
serviceDescription := serviceMap.(map[string]any)["description"].(string)
|
||||||
serviceState := serviceMap.(map[string]any)["state"].(string)
|
serviceState := serviceMap.(map[string]any)["state"].(string)
|
||||||
serviceEnabled := serviceMap.(map[string]any)["is_enabled"].(bool)
|
serviceEnabled := serviceMap.(map[string]any)["is_enabled"].(bool)
|
||||||
serviceStage := int(serviceMap.(map[string]any)["stage"].(float64))
|
serviceStage := int(serviceMap.(map[string]any)["stage"].(float64))
|
||||||
processID := int(serviceMap.(map[string]any)["process_id"].(float64))
|
processID := int(serviceMap.(map[string]any)["process_id"].(float64))
|
||||||
|
|
||||||
fmt.Printf("Name: %s\n", serviceName)
|
fmt.Printf("Name: %s\n", serviceName)
|
||||||
|
fmt.Printf("Description: %s\n", serviceDescription)
|
||||||
fmt.Printf("State: %s\n", serviceState)
|
fmt.Printf("State: %s\n", serviceState)
|
||||||
if serviceEnabled {
|
if serviceEnabled {
|
||||||
fmt.Printf("Enabled: %t (Stage %d)\n", serviceEnabled, serviceStage)
|
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)
|
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
|
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 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
|
||||||
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||||
|
|||||||
+67
-19
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bufio"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
@@ -12,6 +13,8 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/mitchellh/go-ps"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Build-time variables
|
// Build-time variables
|
||||||
@@ -78,42 +81,42 @@ func mountVirtualFilesystems() {
|
|||||||
|
|
||||||
// Mount /proc
|
// Mount /proc
|
||||||
if err := mount("proc", "/proc", "proc", commonOptions+",nodev,noexec", false); err != nil {
|
if err := mount("proc", "/proc", "proc", commonOptions+",nodev,noexec", false); err != nil {
|
||||||
panic(err)
|
printErrorAndReboot("Error: could not mount /proc: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mount /sys
|
// Mount /sys
|
||||||
if err := mount("sys", "/sys", "sysfs", commonOptions+",nodev,noexec", false); err != nil {
|
if err := mount("sys", "/sys", "sysfs", commonOptions+",nodev,noexec", false); err != nil {
|
||||||
panic(err)
|
printErrorAndReboot("Error: could not mount /sys: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mount /dev
|
// Mount /dev
|
||||||
if err := mount("dev", "/dev", "devtmpfs", commonOptions+",mode=755,inode64", false); err != nil {
|
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
|
// Mount /run
|
||||||
if err := mount("run", "/run", "tmpfs", commonOptions+",nodev,mode=755,inode64", false); err != nil {
|
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
|
// Mount /dev/pts
|
||||||
if err := mount("devpts", "/dev/pts", "devpts", commonOptions+",gid=5,mode=620,ptmxmode=000", true); err != nil {
|
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
|
// Mount /dev/shm
|
||||||
if err := mount("shm", "/dev/shm", "tmpfs", commonOptions+",nodev,inode64", true); err != nil {
|
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
|
// Mount securityfs
|
||||||
if err := mount("securityfs", "/sys/kernel/security", "securityfs", commonOptions, false); err != nil {
|
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
|
// Mount cgroups v2
|
||||||
if err := mount("cgroup2", "/sys/fs/cgroup", "cgroup2", commonOptions+",noexec,nsdelegate,memory_recursiveprot", false); err != nil {
|
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.")
|
fmt.Println("Done.")
|
||||||
@@ -122,9 +125,8 @@ func mountVirtualFilesystems() {
|
|||||||
func mountFilesystems() {
|
func mountFilesystems() {
|
||||||
fmt.Print("Mounting fstab entries... ")
|
fmt.Print("Mounting fstab entries... ")
|
||||||
|
|
||||||
if err := mountFstabEntries(); err != nil {
|
if err, line := mountFstabEntries(); err != nil {
|
||||||
log.Println("Could not mount fstab entries!")
|
printErrorAndReboot("Error: could not mount fstab entry on line %d: %s", line, err)
|
||||||
panic(err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println("Done.")
|
fmt.Println("Done.")
|
||||||
@@ -138,8 +140,7 @@ func startServiceManager() {
|
|||||||
cmd.Stderr = os.Stderr
|
cmd.Stderr = os.Stderr
|
||||||
err := cmd.Start()
|
err := cmd.Start()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Could not initialize service manager!")
|
printErrorAndReboot("Error: could not initialize service manager: %s", err)
|
||||||
panic(err)
|
|
||||||
}
|
}
|
||||||
serviceManagerPid = cmd.Process.Pid
|
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() {
|
func setHostname() {
|
||||||
fmt.Print("Setting hostname... ")
|
fmt.Print("Setting hostname... ")
|
||||||
|
|
||||||
@@ -215,16 +252,12 @@ func waitZombieProcesses() {
|
|||||||
func catchSignals() {
|
func catchSignals() {
|
||||||
sigc := make(chan os.Signal, 1)
|
sigc := make(chan os.Signal, 1)
|
||||||
signal.Notify(sigc, syscall.SIGUSR1, syscall.SIGTERM, syscall.SIGINT, syscall.SIGCHLD)
|
signal.Notify(sigc, syscall.SIGUSR1, syscall.SIGTERM, syscall.SIGINT, syscall.SIGCHLD)
|
||||||
defer close(sigc)
|
|
||||||
defer signal.Stop(sigc)
|
|
||||||
for {
|
for {
|
||||||
switch <-sigc {
|
switch <-sigc {
|
||||||
case syscall.SIGUSR1:
|
case syscall.SIGUSR1:
|
||||||
close(sigc)
|
|
||||||
signal.Stop(sigc)
|
signal.Stop(sigc)
|
||||||
shutdownSystem()
|
shutdownSystem()
|
||||||
case syscall.SIGTERM, syscall.SIGINT:
|
case syscall.SIGTERM, syscall.SIGINT:
|
||||||
close(sigc)
|
|
||||||
signal.Stop(sigc)
|
signal.Stop(sigc)
|
||||||
rebootSystem()
|
rebootSystem()
|
||||||
case syscall.SIGCHLD:
|
case syscall.SIGCHLD:
|
||||||
@@ -237,9 +270,13 @@ func shutdownSystem() {
|
|||||||
fmt.Println("Shutting down...")
|
fmt.Println("Shutting down...")
|
||||||
|
|
||||||
stopServiceManager()
|
stopServiceManager()
|
||||||
|
killProcesses()
|
||||||
|
unmountFilesystems()
|
||||||
|
remountRootReadonly()
|
||||||
|
|
||||||
fmt.Println("Syncing disks...")
|
fmt.Print("Syncing disks... ")
|
||||||
syscall.Sync()
|
syscall.Sync()
|
||||||
|
fmt.Println("Done.")
|
||||||
|
|
||||||
fmt.Println("Sending shutdown syscall...")
|
fmt.Println("Sending shutdown syscall...")
|
||||||
err := syscall.Reboot(syscall.LINUX_REBOOT_CMD_POWER_OFF)
|
err := syscall.Reboot(syscall.LINUX_REBOOT_CMD_POWER_OFF)
|
||||||
@@ -252,9 +289,13 @@ func rebootSystem() {
|
|||||||
fmt.Println("Rebooting...")
|
fmt.Println("Rebooting...")
|
||||||
|
|
||||||
stopServiceManager()
|
stopServiceManager()
|
||||||
|
killProcesses()
|
||||||
|
unmountFilesystems()
|
||||||
|
remountRootReadonly()
|
||||||
|
|
||||||
fmt.Println("Syncing disks...")
|
fmt.Print("Syncing disks... ")
|
||||||
syscall.Sync()
|
syscall.Sync()
|
||||||
|
fmt.Println("Done.")
|
||||||
|
|
||||||
fmt.Println("Sending reboot syscall...")
|
fmt.Println("Sending reboot syscall...")
|
||||||
err := syscall.Reboot(syscall.LINUX_REBOOT_CMD_RESTART)
|
err := syscall.Reboot(syscall.LINUX_REBOOT_CMD_RESTART)
|
||||||
@@ -262,3 +303,10 @@ func rebootSystem() {
|
|||||||
panic(err)
|
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
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
@@ -28,12 +32,14 @@ var flagsEquivalence = map[string]uintptr{
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Split string flags to mount flags and mount data
|
// 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, ",") {
|
for _, flag := range strings.Split(options, ",") {
|
||||||
if unixFlag, ok := flagsEquivalence[flag]; ok {
|
if unixFlag, ok := flagsEquivalence[flag]; ok {
|
||||||
flags = append(flags, unixFlag)
|
flags = append(flags, unixFlag)
|
||||||
} else {
|
} else {
|
||||||
if data == "" {
|
if flag == "noauto" || flag == "nofail" {
|
||||||
|
extra = append(extra, flag)
|
||||||
|
} else if data == "" {
|
||||||
data = flag
|
data = flag
|
||||||
} else {
|
} else {
|
||||||
data += "," + flag
|
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
|
// 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 {
|
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) {
|
if isMountpoint(target) && !slices.Contains(flags, unix.MS_REMOUNT) {
|
||||||
flags = append(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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func mountFstabEntries() error {
|
func mountFstabEntries() (error, int) {
|
||||||
if _, err := os.Stat("/etc/fstab"); os.IsNotExist(err) {
|
if _, err := os.Stat("/etc/fstab"); os.IsNotExist(err) {
|
||||||
return nil
|
return nil, 0
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
return err
|
return err, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
bytes, err := os.ReadFile("/etc/fstab")
|
bytes, err := os.ReadFile("/etc/fstab")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
swapPriority := -2
|
swapPriority := -2
|
||||||
|
|
||||||
for _, line := range strings.Split(string(bytes), "\n") {
|
for i, line := range strings.Split(string(bytes), "\n") {
|
||||||
line = strings.TrimSpace(line)
|
line = strings.TrimSpace(line)
|
||||||
if strings.HasPrefix(line, "#") || line == "" {
|
if strings.HasPrefix(line, "#") || line == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
source := strings.Split(line, " ")[0]
|
// Get fields from line
|
||||||
target := strings.Split(line, " ")[1]
|
fields := []string{}
|
||||||
fstype := strings.Split(line, " ")[2]
|
sb := &strings.Builder{}
|
||||||
options := strings.Split(line, " ")[3]
|
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
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,7 +182,11 @@ func mountFstabEntries() error {
|
|||||||
_, _, err := unix.Syscall(unix.SYS_SWAPON, uintptr(unsafe.Pointer(&b[0])), uintptr((swapPriority<<SwapFlagPrioShift)&SwapFlagPrioMask), 0)
|
_, _, err := unix.Syscall(unix.SYS_SWAPON, uintptr(unsafe.Pointer(&b[0])), uintptr((swapPriority<<SwapFlagPrioShift)&SwapFlagPrioMask), 0)
|
||||||
swapPriority--
|
swapPriority--
|
||||||
if err != 0 {
|
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
|
continue
|
||||||
}
|
}
|
||||||
@@ -152,9 +196,168 @@ func mountFstabEntries() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err := unix.Mount(source, target, fstype, combineUnixFlags(flags), data); err != nil {
|
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"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gopkg.in/yaml.v3"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Build-time variables
|
// Build-time variables
|
||||||
@@ -135,67 +133,13 @@ func Init() {
|
|||||||
// Read and initialize service files
|
// Read and initialize service files
|
||||||
for _, entry := range dirEntries {
|
for _, entry := range dirEntries {
|
||||||
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".esv") {
|
if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".esv") {
|
||||||
logger.Printf("Initializing service (%s)...\n", entry.Name())
|
filepath := path.Join(serviceConfigDir, "services", entry.Name())
|
||||||
bytes, err := os.ReadFile(path.Join(serviceConfigDir, "services", entry.Name()))
|
LoadService(filepath)
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read enabled services
|
// Read enabled services
|
||||||
ReadEnabledServices()
|
EnabledServices := ReadEnabledServices()
|
||||||
|
|
||||||
// Start enabled services
|
// Start enabled services
|
||||||
stages := slices.Collect(maps.Keys(EnabledServices))
|
stages := slices.Collect(maps.Keys(EnabledServices))
|
||||||
@@ -213,13 +157,11 @@ func Init() {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(service.GetUnmetDependencies()) == 0 {
|
err := service.StartService()
|
||||||
err := service.StartService()
|
if err != nil {
|
||||||
if err != nil {
|
logger.Printf("Error: could not start service (%s): %s", service.Name, err)
|
||||||
logger.Printf("Error: could not start service (%s): %s", service.Name, err)
|
|
||||||
}
|
|
||||||
remainingServices--
|
|
||||||
}
|
}
|
||||||
|
remainingServices--
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -227,6 +169,34 @@ func Init() {
|
|||||||
logger.Println("ESVM initialized successfully!")
|
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() {
|
func Destroy() {
|
||||||
logger.Println("Stopping all ESVM services...")
|
logger.Println("Stopping all ESVM services...")
|
||||||
|
|
||||||
|
|||||||
+260
-63
@@ -1,7 +1,9 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path"
|
"path"
|
||||||
@@ -18,6 +20,7 @@ type EnitServiceState uint8
|
|||||||
const (
|
const (
|
||||||
EnitServiceUnknown EnitServiceState = iota
|
EnitServiceUnknown EnitServiceState = iota
|
||||||
EnitServiceUnloaded
|
EnitServiceUnloaded
|
||||||
|
EnitServiceStarting
|
||||||
EnitServiceRunning
|
EnitServiceRunning
|
||||||
EnitServiceStopped
|
EnitServiceStopped
|
||||||
EnitServiceCrashed
|
EnitServiceCrashed
|
||||||
@@ -27,6 +30,7 @@ const (
|
|||||||
var EnitServiceStateNames map[EnitServiceState]string = map[EnitServiceState]string{
|
var EnitServiceStateNames map[EnitServiceState]string = map[EnitServiceState]string{
|
||||||
EnitServiceUnknown: "unknown",
|
EnitServiceUnknown: "unknown",
|
||||||
EnitServiceUnloaded: "unloaded",
|
EnitServiceUnloaded: "unloaded",
|
||||||
|
EnitServiceStarting: "starting",
|
||||||
EnitServiceRunning: "running",
|
EnitServiceRunning: "running",
|
||||||
EnitServiceStopped: "stopped",
|
EnitServiceStopped: "stopped",
|
||||||
EnitServiceCrashed: "crashed",
|
EnitServiceCrashed: "crashed",
|
||||||
@@ -34,45 +38,29 @@ var EnitServiceStateNames map[EnitServiceState]string = map[EnitServiceState]str
|
|||||||
}
|
}
|
||||||
|
|
||||||
type EnitService struct {
|
type EnitService struct {
|
||||||
Name string `yaml:"name"`
|
Name string `yaml:"name"`
|
||||||
Description string `yaml:"description,omitempty"`
|
Description string `yaml:"description,omitempty"`
|
||||||
Dependencies []string `yaml:"dependencies,omitempty"`
|
Type string `yaml:"type"`
|
||||||
Type string `yaml:"type"`
|
StartCmd string `yaml:"start_cmd"`
|
||||||
StartCmd string `yaml:"start_cmd"`
|
ExitMethod string `yaml:"exit_method"`
|
||||||
ExitMethod string `yaml:"exit_method"`
|
CrashOnSafeExit bool `yaml:"crash_on_safe_exit"`
|
||||||
CrashOnSafeExit bool `yaml:"crash_on_safe_exit"`
|
StopCmd string `yaml:"stop_cmd,omitempty"`
|
||||||
StopCmd string `yaml:"stop_cmd,omitempty"`
|
Restart string `yaml:"restart,omitempty"`
|
||||||
Restart string `yaml:"restart,omitempty"`
|
ReadyFd int `yaml:"ready_fd"`
|
||||||
LogOutput bool `yaml:"log_output,omitempty"`
|
Setpgid bool `yaml:"setpgid"`
|
||||||
state EnitServiceState
|
LogOutput bool `yaml:"log_output,omitempty"`
|
||||||
processID int
|
Filepath string
|
||||||
restartCount int
|
filepathChecksum [32]byte
|
||||||
stopChannel chan bool
|
state EnitServiceState
|
||||||
|
processID int
|
||||||
|
restartCount int
|
||||||
|
stopChannel chan bool
|
||||||
|
shouldReload bool
|
||||||
}
|
}
|
||||||
|
|
||||||
var Services = make([]*EnitService, 0)
|
var Services = make([]*EnitService, 0)
|
||||||
var EnabledServices = make(map[int][]string)
|
|
||||||
var startedServicesOrder = make([]string, 0)
|
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 {
|
func (service *EnitService) GetProcess() *os.Process {
|
||||||
process, _ := os.FindProcess(service.processID)
|
process, _ := os.FindProcess(service.processID)
|
||||||
|
|
||||||
@@ -113,7 +101,121 @@ func (service *EnitService) GetLogFile() (file *os.File, err error) {
|
|||||||
return file, nil
|
return file, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (service *EnitService) StartService() error {
|
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 {
|
if service == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -126,7 +228,6 @@ func (service *EnitService) StartService() error {
|
|||||||
// Get log file if service logs output
|
// Get log file if service logs output
|
||||||
var logFile *os.File
|
var logFile *os.File
|
||||||
if service.LogOutput {
|
if service.LogOutput {
|
||||||
var err error
|
|
||||||
logFile, err = service.GetLogFile()
|
logFile, err = service.GetLogFile()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -134,10 +235,38 @@ func (service *EnitService) StartService() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cmd := exec.Command("/bin/sh", "-c", "exec "+service.StartCmd)
|
cmd := exec.Command("/bin/sh", "-c", "exec "+service.StartCmd)
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: service.Setpgid, Pgid: 0}
|
||||||
if logFile != nil {
|
if logFile != nil {
|
||||||
cmd.Stdout = logFile
|
cmd.Stdout = logFile
|
||||||
cmd.Stderr = logFile
|
cmd.Stderr = logFile
|
||||||
}
|
}
|
||||||
|
var pipeReader, pipeWriter *os.File
|
||||||
|
if service.ReadyFd > 2 {
|
||||||
|
pipeReader, pipeWriter, err = os.Pipe()
|
||||||
|
if err != nil {
|
||||||
|
// Close log file if not nil
|
||||||
|
if logFile != nil {
|
||||||
|
logFile.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err := pipeReader.SetDeadline(time.Now().Add(10 * time.Second))
|
||||||
|
if err != nil {
|
||||||
|
// Close log file if not nil
|
||||||
|
if logFile != nil {
|
||||||
|
logFile.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 3; i < service.ReadyFd; i++ {
|
||||||
|
cmd.ExtraFiles = append(cmd.ExtraFiles, nil)
|
||||||
|
}
|
||||||
|
cmd.ExtraFiles = append(cmd.ExtraFiles, pipeWriter)
|
||||||
|
}
|
||||||
if err := cmd.Start(); err != nil {
|
if err := cmd.Start(); err != nil {
|
||||||
// Close log file if not nil
|
// Close log file if not nil
|
||||||
if logFile != nil {
|
if logFile != nil {
|
||||||
@@ -147,7 +276,30 @@ func (service *EnitService) StartService() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pid := cmd.Process.Pid
|
||||||
service.processID = cmd.Process.Pid
|
service.processID = cmd.Process.Pid
|
||||||
|
service.state = EnitServiceStarting
|
||||||
|
|
||||||
|
// Wait for data from pipe
|
||||||
|
if pipeReader != nil {
|
||||||
|
buffer := make([]byte, 1)
|
||||||
|
_, err := io.ReadAtLeast(pipeReader, buffer, 1)
|
||||||
|
if err != nil {
|
||||||
|
// Close log file if not nil
|
||||||
|
if logFile != nil {
|
||||||
|
logFile.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kill process and children
|
||||||
|
syscall.Kill(-pid, syscall.SIGKILL)
|
||||||
|
|
||||||
|
service.processID = 0
|
||||||
|
service.state = EnitServiceCrashed
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
service.state = EnitServiceRunning
|
service.state = EnitServiceRunning
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
@@ -162,10 +314,21 @@ func (service *EnitService) StartService() error {
|
|||||||
case <-service.stopChannel:
|
case <-service.stopChannel:
|
||||||
service.restartCount = 0
|
service.restartCount = 0
|
||||||
default:
|
default:
|
||||||
|
// Kill remaining child processes
|
||||||
|
syscall.Kill(-pid, syscall.SIGKILL)
|
||||||
|
|
||||||
if service.Type == "simple" && err == nil {
|
if service.Type == "simple" && err == nil {
|
||||||
service.restartCount = 0
|
service.restartCount = 0
|
||||||
if service.ExitMethod != "stop_command" {
|
if service.ExitMethod != "stop_command" {
|
||||||
service.state = EnitServiceCompleted
|
service.state = EnitServiceCompleted
|
||||||
|
|
||||||
|
// Reload service if needed
|
||||||
|
if service.shouldReload {
|
||||||
|
LoadService(service.Filepath)
|
||||||
|
if GetServiceByName(service.Name) == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
service.state = EnitServiceRunning
|
service.state = EnitServiceRunning
|
||||||
}
|
}
|
||||||
@@ -179,6 +342,15 @@ func (service *EnitService) StartService() error {
|
|||||||
service.state = EnitServiceCrashed
|
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" {
|
if service.Restart == "always" {
|
||||||
_ = service.StartService()
|
_ = service.StartService()
|
||||||
} else if service.Restart == "true" && service.restartCount < 5 {
|
} else if service.Restart == "true" && service.restartCount < 5 {
|
||||||
@@ -206,11 +378,26 @@ func (service *EnitService) StopService() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
logger.Printf("Stopping service (%s)...", service.Name)
|
logger.Printf("Stopping service (%s)...", service.Name)
|
||||||
|
pid := service.processID
|
||||||
|
|
||||||
newServiceStatus := EnitServiceCrashed
|
newServiceStatus := EnitServiceCrashed
|
||||||
defer func() {
|
defer func() {
|
||||||
|
// Kill remaining child processes
|
||||||
|
if pid != 0 {
|
||||||
|
syscall.Kill(-pid, syscall.SIGKILL)
|
||||||
|
}
|
||||||
|
|
||||||
service.state = newServiceStatus
|
service.state = newServiceStatus
|
||||||
service.processID = 0
|
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" {
|
if service.ExitMethod == "kill" {
|
||||||
@@ -227,31 +414,33 @@ func (service *EnitService) StopService() error {
|
|||||||
service.GetProcess().Signal(syscall.SIGKILL)
|
service.GetProcess().Signal(syscall.SIGKILL)
|
||||||
return fmt.Errorf("could not stop process gracefully")
|
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 {
|
} else {
|
||||||
|
go func() { service.stopChannel <- true }()
|
||||||
|
|
||||||
cmd := exec.Command("/bin/sh", "-c", service.StopCmd)
|
cmd := exec.Command("/bin/sh", "-c", service.StopCmd)
|
||||||
if err := cmd.Run(); err != nil {
|
if err := cmd.Run(); err != nil {
|
||||||
return err
|
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
|
newServiceStatus = EnitServiceStopped
|
||||||
logger.Printf("Service (%s) has stopped!\n", service.Name)
|
logger.Printf("Service (%s) has stopped!\n", service.Name)
|
||||||
|
|
||||||
@@ -263,6 +452,12 @@ func (service *EnitService) RestartService() error {
|
|||||||
return err
|
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 {
|
if err := service.StartService(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -270,10 +465,8 @@ func (service *EnitService) RestartService() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Functions will be rewritten at some point to allow enabling unloaded services
|
|
||||||
|
|
||||||
func (service *EnitService) isEnabled() (bool, int) {
|
func (service *EnitService) isEnabled() (bool, int) {
|
||||||
for stage, services := range EnabledServices {
|
for stage, services := range ReadEnabledServices() {
|
||||||
if slices.Contains(services, service.Name) {
|
if slices.Contains(services, service.Name) {
|
||||||
return true, stage
|
return true, stage
|
||||||
}
|
}
|
||||||
@@ -291,6 +484,8 @@ func (service *EnitService) SetEnabled(stage int) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
EnabledServices := ReadEnabledServices()
|
||||||
|
|
||||||
// Remove service from current stage
|
// Remove service from current stage
|
||||||
EnabledServices[s] = slices.DeleteFunc(EnabledServices[s], func(name string) bool {
|
EnabledServices[s] = slices.DeleteFunc(EnabledServices[s], func(name string) bool {
|
||||||
return name == service.Name
|
return name == service.Name
|
||||||
@@ -317,10 +512,12 @@ func (service *EnitService) SetEnabled(stage int) error {
|
|||||||
return nil
|
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"))
|
data, err := os.ReadFile(path.Join(serviceConfigDir, "enabled_services"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return EnabledServices
|
||||||
}
|
}
|
||||||
|
|
||||||
err = yaml.Unmarshal(data, &EnabledServices)
|
err = yaml.Unmarshal(data, &EnabledServices)
|
||||||
@@ -333,15 +530,15 @@ func ReadEnabledServices() error {
|
|||||||
// Update enabled_services file
|
// Update enabled_services file
|
||||||
data, err := yaml.Marshal(EnabledServices)
|
data, err := yaml.Marshal(EnabledServices)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return EnabledServices
|
||||||
}
|
}
|
||||||
err = os.WriteFile(path.Join(serviceConfigDir, "enabled_services"), data, 0644)
|
err = os.WriteFile(path.Join(serviceConfigDir, "enabled_services"), data, 0644)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return EnabledServices
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return EnabledServices
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return EnabledServices
|
||||||
}
|
}
|
||||||
|
|||||||
+36
-8
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -17,6 +18,7 @@ func initSocket() (socket net.Listener, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Register command handlers
|
// Register command handlers
|
||||||
|
commandHandlers["reload"] = handleReloadServicesCommand
|
||||||
commandHandlers["start"] = handleStartServiceCommand
|
commandHandlers["start"] = handleStartServiceCommand
|
||||||
commandHandlers["stop"] = handleStopServiceCommand
|
commandHandlers["stop"] = handleStopServiceCommand
|
||||||
commandHandlers["restart"] = handleRestartServiceCommand
|
commandHandlers["restart"] = handleRestartServiceCommand
|
||||||
@@ -31,27 +33,23 @@ func listenToSocket() {
|
|||||||
conn, err := socket.Accept()
|
conn, err := socket.Accept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Println("Could not accept socket connection!")
|
logger.Println("Could not accept socket connection!")
|
||||||
panic(err)
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle the connection in a separate goroutine.
|
// Handle the connection in a separate goroutine.
|
||||||
go func(conn net.Conn) {
|
go func(conn net.Conn) {
|
||||||
defer conn.Close()
|
defer conn.Close()
|
||||||
// Create a buffer for incoming data.
|
|
||||||
buf := make([]byte, 4096)
|
|
||||||
|
|
||||||
// Read data from the connection.
|
// Read data from the connection.
|
||||||
n, err := conn.Read(buf)
|
data, err := readAllConn(conn)
|
||||||
if err == io.EOF {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
logger.Fatalf("Could not read data from socket! Error: %s\n", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decoode JSON data
|
// Decoode JSON data
|
||||||
var jsonData map[string]any
|
var jsonData map[string]any
|
||||||
err = json.Unmarshal(buf[:n], &jsonData)
|
err = json.Unmarshal(data, &jsonData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
conn.Write(wrapErrorInJson(fmt.Errorf("Invalid JSON")))
|
conn.Write(wrapErrorInJson(fmt.Errorf("Invalid JSON")))
|
||||||
return
|
return
|
||||||
@@ -74,6 +72,13 @@ func listenToSocket() {
|
|||||||
}(conn)
|
}(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) {
|
func handleStartServiceCommand(conn net.Conn, jsonData map[string]any) {
|
||||||
// Get service name from json data
|
// Get service name from json data
|
||||||
serviceName, ok := jsonData["service"]
|
serviceName, ok := jsonData["service"]
|
||||||
@@ -222,6 +227,7 @@ func handleStatusServiceCommand(conn net.Conn, jsonData map[string]any) {
|
|||||||
|
|
||||||
statusMap := make(map[string]any)
|
statusMap := make(map[string]any)
|
||||||
statusMap["name"] = service.Name
|
statusMap["name"] = service.Name
|
||||||
|
statusMap["description"] = service.Description
|
||||||
statusMap["state"] = EnitServiceStateNames[service.state]
|
statusMap["state"] = EnitServiceStateNames[service.state]
|
||||||
statusMap["process_id"] = service.processID
|
statusMap["process_id"] = service.processID
|
||||||
statusMap["is_enabled"], statusMap["stage"] = service.isEnabled()
|
statusMap["is_enabled"], statusMap["stage"] = service.isEnabled()
|
||||||
@@ -244,6 +250,7 @@ func handleListServicesCommand(conn net.Conn, _ map[string]any) {
|
|||||||
for _, service := range Services {
|
for _, service := range Services {
|
||||||
statusMap := make(map[string]any)
|
statusMap := make(map[string]any)
|
||||||
statusMap["name"] = service.Name
|
statusMap["name"] = service.Name
|
||||||
|
statusMap["description"] = service.Description
|
||||||
statusMap["state"] = EnitServiceStateNames[service.state]
|
statusMap["state"] = EnitServiceStateNames[service.state]
|
||||||
statusMap["process_id"] = service.processID
|
statusMap["process_id"] = service.processID
|
||||||
statusMap["is_enabled"], statusMap["stage"] = service.isEnabled()
|
statusMap["is_enabled"], statusMap["stage"] = service.isEnabled()
|
||||||
@@ -293,3 +300,24 @@ func wrapSuccessMsgInJson(msg string) []byte {
|
|||||||
}
|
}
|
||||||
return jsonData
|
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