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
|
+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
-15
@@ -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... ")
|
||||||
|
|
||||||
@@ -233,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)
|
||||||
@@ -248,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)
|
||||||
@@ -258,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
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+22
-63
@@ -1,7 +1,6 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/sha256"
|
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -15,8 +14,6 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gopkg.in/yaml.v3"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Build-time variables
|
// Build-time variables
|
||||||
@@ -136,64 +133,8 @@ 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: "",
|
|
||||||
Type: "",
|
|
||||||
StartCmd: "",
|
|
||||||
ExitMethod: "",
|
|
||||||
StopCmd: "",
|
|
||||||
Restart: "",
|
|
||||||
Setpgid: true,
|
|
||||||
CrashOnSafeExit: true,
|
|
||||||
LogOutput: true,
|
|
||||||
Filepath: path.Join(serviceConfigDir, "services", entry.Name()),
|
|
||||||
filepathChecksum: sha256.Sum256(bytes),
|
|
||||||
restartCount: 0,
|
|
||||||
stopChannel: make(chan bool),
|
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,8 +172,26 @@ func Init() {
|
|||||||
func Reload() {
|
func Reload() {
|
||||||
logger.Println("Reloading all ESVM services...")
|
logger.Println("Reloading all ESVM services...")
|
||||||
|
|
||||||
for _, service := range Services {
|
dirEntries, err := os.ReadDir(path.Join(serviceConfigDir, "services"))
|
||||||
service.ReloadService()
|
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!")
|
logger.Println("All ESVM services have been reloaded!")
|
||||||
|
|||||||
+89
-48
@@ -101,30 +101,51 @@ func (service *EnitService) GetLogFile() (file *os.File, err error) {
|
|||||||
return file, nil
|
return file, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (service *EnitService) ReloadService() {
|
func LoadService(filepath string) {
|
||||||
bytes, err := os.ReadFile(service.Filepath)
|
bytes, err := os.ReadFile(filepath)
|
||||||
checksum := sha256.Sum256(bytes)
|
checksum := sha256.Sum256(bytes)
|
||||||
if slices.Equal(checksum[:], service.filepathChecksum[:]) {
|
|
||||||
return
|
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 service.state == EnitServiceStarting || service.state == EnitServiceRunning {
|
if serviceToReload == nil {
|
||||||
service.shouldReload = true
|
logger.Printf("Loading service (%s)...\n", filepath)
|
||||||
logger.Printf("Warning: Service (%s) is currently running and will be reloaded when stopped\n", service.Name)
|
} else {
|
||||||
return
|
logger.Printf("Reloading service (%s)...\n", filepath)
|
||||||
}
|
}
|
||||||
service.shouldReload = false
|
|
||||||
|
|
||||||
logger.Printf("Reloading service (%s)...\n", service.Filepath)
|
|
||||||
|
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
Services = slices.DeleteFunc(Services, func(sv *EnitService) bool {
|
Services = slices.DeleteFunc(Services, func(sv *EnitService) bool {
|
||||||
return sv == service
|
if sv.Filepath == filepath {
|
||||||
|
logger.Printf("Service (%s) has been removed\n", sv.Name)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
})
|
})
|
||||||
logger.Printf("Service (%s) has been removed\n", service.Name)
|
|
||||||
return
|
return
|
||||||
} else if err != nil {
|
} else if err != nil {
|
||||||
logger.Printf("Error: Could not read service file (%s)", service.Filepath)
|
logger.Printf("Error: Could not read service file (%s)", filepath)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,20 +160,26 @@ func (service *EnitService) ReloadService() {
|
|||||||
Setpgid: true,
|
Setpgid: true,
|
||||||
CrashOnSafeExit: true,
|
CrashOnSafeExit: true,
|
||||||
LogOutput: true,
|
LogOutput: true,
|
||||||
Filepath: service.Filepath,
|
Filepath: filepath,
|
||||||
filepathChecksum: checksum,
|
filepathChecksum: sha256.Sum256(bytes),
|
||||||
restartCount: service.restartCount,
|
restartCount: 0,
|
||||||
stopChannel: service.stopChannel,
|
stopChannel: make(chan bool),
|
||||||
state: service.state,
|
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 {
|
if err := yaml.Unmarshal(bytes, &newService); err != nil {
|
||||||
logger.Printf("Error: could not read service file %s", service.Filepath)
|
logger.Printf("Error: could not read service file %s", filepath)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, sv := range Services {
|
for _, sv := range Services {
|
||||||
if sv.Name == newService.Name && sv != service {
|
if sv.Name == newService.Name && sv != serviceToReload {
|
||||||
logger.Printf("Error: service with name (%s) has already been initialized", service.Name)
|
logger.Printf("Error: service with name (%s) has already been loaded", newService.Name)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,12 +204,15 @@ func (service *EnitService) ReloadService() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for i, sv := range Services {
|
for i, sv := range Services {
|
||||||
if sv == service {
|
if sv == serviceToReload {
|
||||||
Services[i] = &newService
|
Services[i] = &newService
|
||||||
|
logger.Printf("Service (%s) has been reloaded!\n", newService.Name)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Printf("Service (%s) has been reloaded!\n", newService.Name)
|
Services = append(Services, &newService)
|
||||||
|
logger.Printf("Service (%s) has been loaded!\n", newService.Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (service *EnitService) StartService() (err error) {
|
func (service *EnitService) StartService() (err error) {
|
||||||
@@ -246,6 +276,7 @@ func (service *EnitService) StartService() (err error) {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pid := cmd.Process.Pid
|
||||||
service.processID = cmd.Process.Pid
|
service.processID = cmd.Process.Pid
|
||||||
service.state = EnitServiceStarting
|
service.state = EnitServiceStarting
|
||||||
|
|
||||||
@@ -260,7 +291,7 @@ func (service *EnitService) StartService() (err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Kill process and children
|
// Kill process and children
|
||||||
syscall.Kill(-service.processID, syscall.SIGKILL)
|
syscall.Kill(-pid, syscall.SIGKILL)
|
||||||
|
|
||||||
service.processID = 0
|
service.processID = 0
|
||||||
service.state = EnitServiceCrashed
|
service.state = EnitServiceCrashed
|
||||||
@@ -284,7 +315,7 @@ func (service *EnitService) StartService() (err error) {
|
|||||||
service.restartCount = 0
|
service.restartCount = 0
|
||||||
default:
|
default:
|
||||||
// Kill remaining child processes
|
// Kill remaining child processes
|
||||||
syscall.Kill(-service.processID, syscall.SIGKILL)
|
syscall.Kill(-pid, syscall.SIGKILL)
|
||||||
|
|
||||||
if service.Type == "simple" && err == nil {
|
if service.Type == "simple" && err == nil {
|
||||||
service.restartCount = 0
|
service.restartCount = 0
|
||||||
@@ -293,7 +324,7 @@ func (service *EnitService) StartService() (err error) {
|
|||||||
|
|
||||||
// Reload service if needed
|
// Reload service if needed
|
||||||
if service.shouldReload {
|
if service.shouldReload {
|
||||||
service.ReloadService()
|
LoadService(service.Filepath)
|
||||||
if GetServiceByName(service.Name) == nil {
|
if GetServiceByName(service.Name) == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -313,7 +344,7 @@ func (service *EnitService) StartService() (err error) {
|
|||||||
|
|
||||||
// Reload service if needed
|
// Reload service if needed
|
||||||
if service.shouldReload {
|
if service.shouldReload {
|
||||||
service.ReloadService()
|
LoadService(service.Filepath)
|
||||||
if GetServiceByName(service.Name) == nil {
|
if GetServiceByName(service.Name) == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -352,14 +383,16 @@ func (service *EnitService) StopService() error {
|
|||||||
newServiceStatus := EnitServiceCrashed
|
newServiceStatus := EnitServiceCrashed
|
||||||
defer func() {
|
defer func() {
|
||||||
// Kill remaining child processes
|
// Kill remaining child processes
|
||||||
syscall.Kill(-pid, syscall.SIGKILL)
|
if pid != 0 {
|
||||||
|
syscall.Kill(-pid, syscall.SIGKILL)
|
||||||
|
}
|
||||||
|
|
||||||
service.state = newServiceStatus
|
service.state = newServiceStatus
|
||||||
service.processID = 0
|
service.processID = 0
|
||||||
|
|
||||||
// Reload service if needed
|
// Reload service if needed
|
||||||
if service.shouldReload {
|
if service.shouldReload {
|
||||||
service.ReloadService()
|
LoadService(service.Filepath)
|
||||||
if GetServiceByName(service.Name) == nil {
|
if GetServiceByName(service.Name) == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -381,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)
|
||||||
|
|
||||||
@@ -417,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
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user