Files
spinifex/hive/utils/process.go
T
Julian Sommer c4027a0380 test: add gateway core routing, IAM auth, and handler test coverage
Squash of dev commits: gateway core routing/policy/middleware tests,
IAM auth and handler tests, awserrors tests, respondWithJSON helper,
utils refactor into focused files, and daemon test speedups.
2026-03-05 14:20:00 +10:00

92 lines
1.4 KiB
Go

package utils
import (
"fmt"
"os"
"runtime"
"strconv"
"syscall"
"time"
)
// SetOOMScore sets the OOM score adjustment for a process.
// Score range: -1000 (never kill) to 1000 (always kill first).
// Linux-only; returns an error on non-Linux systems.
func SetOOMScore(pid int, score int) error {
if runtime.GOOS != "linux" {
return fmt.Errorf("OOM score adjustment is only supported on Linux")
}
path := fmt.Sprintf("/proc/%d/oom_score_adj", pid)
return os.WriteFile(path, []byte(strconv.Itoa(score)), 0600)
}
func StopProcess(serviceName string) error {
pid, err := ReadPidFile(serviceName)
if err != nil {
return err
}
err = KillProcess(pid)
if err != nil {
return err
}
// Remove PID file
err = RemovePidFile(serviceName)
if err != nil {
return err
}
return nil
}
func KillProcess(pid int) error {
process, err := os.FindProcess(pid)
if err != nil {
return err
}
// Send SIGTERM first (graceful)
err = process.Signal(syscall.SIGTERM)
if err != nil {
return err
}
// Check process terminated
checks := 0
for {
time.Sleep(1 * time.Second)
process, err = os.FindProcess(pid)
if err != nil {
return err
}
err = process.Signal(syscall.Signal(0))
if err != nil {
// Process terminated, break
break
}
checks++
// If process is still running after 120 seconds, force kill
if checks > 120 {
err = process.Kill() // SIGKILL
if err != nil {
return err
}
break
}
}
return nil
}