Compare commits

...

16 Commits

Author SHA1 Message Date
Sasha Koshka
1978e263d6 sahd;ljasl;dkj 2023-06-01 03:44:33 -04:00
Sasha Koshka
7726d732d4 we got some dhrek we got some doneky we got some fienona 2023-06-01 03:37:08 -04:00
Sasha Koshka
32bc44c90f Oops lol 2023-06-01 03:00:15 -04:00
Sasha Koshka
805f42d828 Changed name of router to hn-router 2023-06-01 02:59:18 -04:00
Sasha Koshka
e8349360cc hnctl prints line breaks after errors 2023-06-01 01:01:08 -04:00
Sasha Koshka
4e58df9c9b Fix hnctl 2023-06-01 00:59:03 -04:00
Sasha Koshka
f90421e5db Add gitignore 2023-05-31 22:35:25 -04:00
Sasha Koshka
c9f2c56d65 Services no longer print out errors when they shut down 2023-05-31 22:00:21 -04:00
Sasha Koshka
92b645f34c Routine manager now recovers from panicking goroutines 2023-05-31 18:49:00 -04:00
Sasha Koshka
3cd53b3dd9 Fixed router 2023-05-31 18:09:56 -04:00
Sasha Koshka
8a528e2b4e Services can now write to pidfiles 2023-05-31 18:08:29 -04:00
Sasha Koshka
631796a726 Routine manager can now be shut down 2023-05-31 18:07:38 -04:00
Sasha Koshka
066247a08f Add daemon utilities 2023-05-31 18:07:06 -04:00
Sasha Koshka
8c9b85d7ca Ported hivectl 2023-05-31 15:52:33 -04:00
Sasha Koshka
1a5502211e Updated wrench to use cli 2023-05-30 18:03:26 -04:00
Sasha Koshka
9d8e6e8e24 Added cli package 2023-05-30 18:00:26 -04:00
12 changed files with 621 additions and 113 deletions

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
/hnctl
/router
/wrench

81
cli/cli.go Normal file
View File

@@ -0,0 +1,81 @@
// Package cli provides utilities for writing command line utilities that
// interact with services.
package cli
import "os"
import "fmt"
import "flag"
import "os/user"
import "strings"
import "strconv"
import "path/filepath"
// Sayf is like Printf, but prints the program name before the message. This is
// used for printing messages and errors.
func Sayf (format string, values ...any) {
Printf(os.Args[0] + ": " + format, values...)
}
// Printf prints to stderr.
func Printf (format string, values ...any) {
fmt.Fprintf(flag.CommandLine.Output(), format, values...)
}
// ServiceUser returns the system user that corresponds to the given service
// name. This is not necissarily equivalent Hnakra user, although it is good
// practice to have a 1:1 correspondance between them.
func ServiceUser (service string) string {
return "hn-" + strings.ToLower(service)
}
// DataDir returns the standard Hnakra data directory.
func DataDir () string {
return "/var/hnakra"
}
// ServiceDir returns the standard data directory of a service.
func ServiceDir (service string) string {
return filepath.Join(DataDir(), "services", ServiceUser(service))
}
// NeedRoot halts the program and displays an error if it is not being run as
// root. This should be called whenever an operation takes place that requires
// root privelages.
func NeedRoot() {
uid := os.Getuid()
if uid != 0 {
Sayf("this utility must be run as root")
os.Exit(1)
}
}
// MkdirFor makes a directory makes the specified directory (if it doesnt
// already exist) and gives ownership of it to the specified uid and gid.
func MkdirFor (directory string, uid, gid int) error {
err := os.MkdirAll(directory, 0755)
if err != nil { return err }
err = os.Chmod(directory, 0770)
if err != nil { return err }
err = os.Chown(directory, uid, gid)
if err != nil { return err }
return nil
}
// LookupUID returns the uid and gid of the given username, if it exists.
func LookupUID (name string) (uid, gid uint32, err error) {
user, err := user.Lookup(name)
if err != nil {
return 0, 0, err
}
puid, err := strconv.Atoi(user.Uid)
if err != nil {
return 0, 0, err
}
pgid, err := strconv.Atoi(user.Gid)
if err != nil {
return 0, 0, err
}
return uint32(puid), uint32(pgid), nil
}

View File

@@ -4,13 +4,14 @@ import "io"
import "os"
import "log"
import "time"
import "hnakra/rotate"
import "hnakra/router"
import "hnakra/rotate"
import "hnakra/daemon"
import "hnakra/routines"
import "hnakra/router/rcon"
import "hnakra/router/config"
import "hnakra/cmd/router/srvhttps"
import "hnakra/cmd/router/srvhnakra"
import "hnakra/cmd/hn-router/srvhttps"
import "hnakra/cmd/hn-router/srvhnakra"
const banner = "\n" +
" -=\\\n" +
@@ -59,10 +60,10 @@ func main () {
manager := routines.Manager { RestartDeadline: time.Second * 8 }
rout := router.New(conf)
srvhnakra := &srvhnakra.Server { Config: conf, Router: rout }
manager.Append(srvhnakra.ListenAndServe)
manager.Append(srvhnakra)
if conf.HTTPSEnable() {
srvhttps := &srvhttps.Server { Config: conf, Handler: rout }
manager.Append(srvhttps.ListenAndServe)
manager.Append(srvhttps)
}
// set up rcon
@@ -74,12 +75,19 @@ func main () {
log.SetOutput(originalWriter)
}
// be a daemon
daemon.ShutdownOnSigint(&manager)
pidfile := daemon.PidFile(os.Getenv("HNAKRA_PIDFILE"))
if !pidfile.Empty() {
err := pidfile.Start()
if err != nil { log.Println("!!! could not write pid:", err) }
defer func () {
err := pidfile.Close()
if err != nil { log.Println("!!! could not delete pidfile:", err) }
} ()
}
// run servers
err = manager.Run()
if err != nil { log.Println("XXX", err) }
}
func httpsRoutine (server *srvhttps.Server) {
err := server.ListenAndServe()
if err != nil { log.Println("XXX", err) }
}

View File

@@ -11,24 +11,34 @@ type Server struct {
underlying net.Listener
Config config.Config
Router *router.Router
running bool
}
func (server *Server) ListenAndServe () (err error) {
func (server *Server) Run () (err error) {
server.underlying, err = tls.Listen (
"tcp", fmt.Sprint(":", server.Config.RouterPort()),
config.TLSConfigFor(server.Config))
if err != nil { return err }
server.running = true
log.Println(".// router on", server.underlying.Addr())
for {
conn, err := server.underlying.Accept()
if err != nil { return err }
if err != nil {
if server.running {
return err
} else {
return nil
}
}
log.Println("-=E incoming connection from", conn.RemoteAddr())
server.Router.Accept(conn)
}
}
func (server *Server) Close () error {
func (server *Server) Shutdown () error {
server.running = false
return server.underlying.Close()
}

View File

@@ -9,9 +9,11 @@ type Server struct {
underlying *http.Server
Config config.Config
Handler http.Handler
running bool
}
func (server *Server) ListenAndServe () error {
func (server *Server) Run () error {
server.underlying = &http.Server {
Addr: fmt.Sprint(":", server.Config.HTTPSPort()),
// ReadHeaderTimeout: timeoutReadHeader * time.Second,
@@ -22,10 +24,17 @@ func (server *Server) ListenAndServe () error {
Handler: server.Handler,
}
server.running = true
log.Println(".// https on", server.underlying.Addr)
return server.underlying.ListenAndServeTLS("", "")
err := server.underlying.ListenAndServeTLS("", "")
if server.running {
return err
} else {
return nil
}
}
func (server *Server) Close () error {
func (server *Server) Shutdown () error {
server.running = false
return server.underlying.Close()
}

140
cmd/hnctl/main.go Normal file
View File

@@ -0,0 +1,140 @@
package main
import "os"
import "fmt"
import "time"
import "flag"
import "os/exec"
import "hnakra/cli"
import "path/filepath"
import "hnakra/cmd/hnctl/spawn"
func main () {
flag.Usage = func () {
out := flag.CommandLine.Output()
fmt.Fprintf(out, "Usage of %s:\n", os.Args[0])
fmt.Fprintf(out, " start\n")
fmt.Fprintf(out, " Start a service\n")
fmt.Fprintf(out, " stop\n")
fmt.Fprintf(out, " Stop a service\n")
fmt.Fprintf(out, " restart\n")
fmt.Fprintf(out, " Start and then stop a service\n")
os.Exit(1)
}
// define commands
startCommand := flag.NewFlagSet("start", flag.ExitOnError)
startService := startCommand.String("s", "router", "Service to start")
stopCommand := flag.NewFlagSet("stop", flag.ExitOnError)
stopService := stopCommand.String("s", "router", "Service to stop")
restartCommand := flag.NewFlagSet("restart", flag.ExitOnError)
restartService := restartCommand.String("s", "router", "Service to restart")
flag.Parse()
// execute correct command
if len(os.Args) < 2 {
flag.Usage()
os.Exit(1)
}
subCommandArgs := os.Args[2:]
switch os.Args[1] {
case "start":
startCommand.Parse(subCommandArgs)
execStart(*startService)
case "stop":
stopCommand.Parse(subCommandArgs)
execStop(*stopService)
case "restart":
restartCommand.Parse(subCommandArgs)
execStop(*restartService)
execStart(*restartService)
}
}
func execStart (service string) {
fullName := cli.ServiceUser(service)
cli.NeedRoot()
pid, err := spawn.PidOf(fullName)
if err == nil && spawn.Running(pid) {
cli.Sayf("service is already running\n")
return
}
uid, gid, err := cli.LookupUID(fullName)
if err != nil {
cli.Sayf("cannot start service: %v\n", err)
os.Exit(1)
}
path, err := exec.LookPath(fullName)
if err != nil {
cli.Sayf("cannot start service: %v\n", err)
os.Exit(1)
}
logDir := filepath.Join("/var/log/", fullName)
env := append(os.Environ(), "HNAKRA_LOG_DIR=" + logDir)
err = cli.MkdirFor(logDir, int(uid), int(gid))
if err != nil {
cli.Sayf("cannot start service: %v\n", err)
os.Exit(1)
}
// prepare pidfile. the service will be responsible for actually writing
// to it
err = ensurePidFile(spawn.PidFile(fullName), int(uid), int(gid))
if err != nil {
cli.Sayf("cannot start service: %v\n", err)
os.Exit(1)
}
// spawn the service
pid, err = spawn.Spawn(path, uid, gid, env)
if err != nil {
cli.Sayf("cannot start service: %v\n", err)
os.Exit(1)
}
fmt.Println(pid)
}
func execStop (service string) {
fullName := cli.ServiceUser(service)
cli.NeedRoot()
pid, err := spawn.PidOf(fullName)
if err != nil || !spawn.Running(pid) {
cli.Sayf("service is not running\n")
return
}
process, err := os.FindProcess(pid)
if err != nil {
cli.Sayf("service is not running\n")
return
}
err = spawn.KillAndWait(process, 16 * time.Second)
if err != nil {
cli.Sayf("could not stop service: %v\n", err)
os.Exit(1)
}
}
func ensurePidFile (file string, uid, gid int) error {
pidFile, err := os.Create(file)
if err != nil { return err }
err = pidFile.Close()
if err != nil { return err }
err = os.Chmod(file, 0660)
if err != nil { return err }
err = os.Chown(file, uid, gid)
if err != nil { return err }
return nil
}

113
cmd/hnctl/spawn/spawn.go Normal file
View File

@@ -0,0 +1,113 @@
// Package spawn provides utilities for daemonizing services.
package spawn
import "os"
import "fmt"
import "time"
import "errors"
import "syscall"
import "strconv"
import "path/filepath"
// Spawn spawns a process in the background and returns its PID.
func Spawn (path string, uid, gid uint32, env []string, args ...string) (pid int, err error) {
cred := &syscall.Credential{
Uid: uid,
Gid: gid,
Groups: []uint32{},
NoSetGroups: false,
}
// the Noctty flag is used to detach the process from parent tty
sysproc := &syscall.SysProcAttr{
Credential: cred,
Noctty: true,
}
attr := os.ProcAttr{
Dir: ".",
Env: os.Environ(),
Files: []*os.File{
os.Stdin,
nil,
nil,
},
Sys: sysproc,
}
process, err := os.StartProcess(path, args, &attr)
if err != nil {
return 0, err
}
// Release() is what actually detatches the process and places it under
// init
return process.Pid, process.Release()
}
// PidFile returns the path of a pidfile under the specified name. More
// specifically, it returns `/run/<name>.pid`.
func PidFile (name string) string {
return filepath.Join("/run/", name + ".pid")
}
// PidOf returns the PID stored in the pidfile of the given name as defined by
// PidFile.
func PidOf (name string) (pid int, err error) {
content, err := os.ReadFile(PidFile(name))
if err != nil {
return 0, err
}
pid, err = strconv.Atoi(string(content))
if err != nil {
return 0, err
}
return pid, nil
}
// Running returns whether or not a process with the given PID is running.
func Running (pid int) bool {
directoryInfo, err := os.Stat("/proc/")
if os.IsNotExist(err) || !directoryInfo.IsDir() {
// if /proc/ does not exist, fallback to sending a signal
process, err := os.FindProcess(pid)
if err != nil {
return false
}
err = process.Signal(syscall.Signal(0))
if err != nil {
return false
}
} else {
// if /proc/ exists, see if the process's directory exists there
_, err = os.Stat("/proc/" + strconv.Itoa(pid))
if err != nil {
return false
}
}
return true
}
// KillAndWait kills a process and waits for it to finish, with a timeout. If
// the timeout is zero, it will wait indefinetly. This function will poll every
// 100 milliseconds to see if the process has finished.
func KillAndWait (process *os.Process, timeout time.Duration) error {
pid := process.Pid
err := process.Kill()
if err != nil {
return err
}
// wait for the process to exit, with a timeout
timeoutPoint := time.Now()
for timeout == 0 || time.Since(timeoutPoint) < 16 * time.Second {
if !Running(pid) {
return nil
}
time.Sleep(100 * time.Millisecond)
}
return errors.New(fmt.Sprintf (
"timeout exceeded while waiting for process %d to finish", pid))
}

View File

@@ -6,24 +6,14 @@ import "flag"
import "strconv"
import "os/exec"
import "os/user"
import "hnakra/cli"
import "path/filepath"
import "golang.org/x/crypto/bcrypt"
func printErr (format string, values ...any) {
fmt.Fprintf (
flag.CommandLine.Output(),
os.Args[0] + ": " + format + "\n",
values...)
}
func serviceUser (service string) string {
return "hn-" + service
}
func tryCommand (cmd *exec.Cmd, failReason string) {
output, err := cmd.CombinedOutput()
if err != nil {
printErr("%s: %s", failReason, string(output))
cli.Sayf("%s: %s\n", failReason, string(output))
os.Exit(1)
}
}
@@ -31,13 +21,13 @@ func tryCommand (cmd *exec.Cmd, failReason string) {
func ownOne (path string, uid, gid int) {
file, err := os.Stat(path)
if err != nil {
printErr("could not stat %s: %v", path, err)
cli.Sayf("could not stat %s: %v\n", path, err)
return
}
err = os.Chown(path, uid, gid)
if err != nil {
printErr("could not change ownership of %s: %v", path, err)
cli.Sayf("could not change ownership of %s: %v\n", path, err)
return
}
@@ -47,7 +37,7 @@ func ownOne (path string, uid, gid int) {
err = os.Chmod(path, 0660)
}
if err != nil {
printErr("could not change mode of %s: %v", path, err)
cli.Sayf("could not change mode of %s: %v\n", path, err)
return
}
}
@@ -55,23 +45,22 @@ func ownOne (path string, uid, gid int) {
func main () {
user, err := user.Current()
if err != nil {
printErr("could not get username %v", err)
cli.Sayf("could not get username %v\n", err)
os.Exit(1)
}
flag.Usage = func () {
out := flag.CommandLine.Output()
fmt.Fprintf(out, "Usage of %s:\n", os.Args[0])
fmt.Fprintf(out, " hash\n")
fmt.Fprintf(out, " Generate a bcrypt hash of a key\n")
fmt.Fprintf(out, " adduser\n")
fmt.Fprintf(out, " Add a system user to run a service as\n")
fmt.Fprintf(out, " deluser\n")
fmt.Fprintf(out, " Remove a user added with adduser\n")
fmt.Fprintf(out, " auth\n")
fmt.Fprintf(out, " Authorize a system user to access a service's files\n")
fmt.Fprintf(out, " own\n")
fmt.Fprintf(out, " Give ownership of a file to a service\n")
cli.Printf("Usage of %s:\n", os.Args[0])
cli.Printf(" hash\n")
cli.Printf(" Generate a bcrypt hash of a key\n")
cli.Printf(" adduser\n")
cli.Printf(" Add a system user to run a service as\n")
cli.Printf(" deluser\n")
cli.Printf(" Remove a user added with adduser\n")
cli.Printf(" auth\n")
cli.Printf(" Authorize a system user to access a service's files\n")
cli.Printf(" own\n")
cli.Printf(" Give ownership of a file to a service\n")
os.Exit(1)
}
@@ -87,6 +76,8 @@ func main () {
delUserCommand := flag.NewFlagSet("deluser", flag.ExitOnError)
delUserService := delUserCommand.String ("s", "router",
"Service to delete the user for")
delUserRmData := delUserCommand.Bool ("D", false,
"Whether to remove the service's data directory")
authCommand := flag.NewFlagSet("auth", flag.ExitOnError)
authService := authCommand.String ("s", "router",
@@ -119,7 +110,7 @@ func main () {
execAdduser(*addUserService)
case "deluser":
delUserCommand.Parse(subCommandArgs)
execDeluser(*delUserService)
execDeluser(*delUserService, *delUserRmData)
case "auth":
authCommand.Parse(subCommandArgs)
execAuth(*authService, *authUser)
@@ -131,22 +122,22 @@ func main () {
func execHash (cost int, key string) {
if key == "" {
printErr("please specify key text content")
cli.Sayf("please specify key text content\n")
os.Exit(1)
}
if cost < bcrypt.MinCost {
printErr("cost is too low, must be at least %v", bcrypt.MinCost)
cli.Sayf("cost is too low, must be at least %v\n", bcrypt.MinCost)
os.Exit(1)
}
if cost > bcrypt.MaxCost {
printErr("cost is too hight, can be at most %v", bcrypt.MaxCost)
cli.Sayf("cost is too hight, can be at most %v\n", bcrypt.MaxCost)
os.Exit(1)
}
hash, err := bcrypt.GenerateFromPassword([]byte(key), cost)
if err != nil {
printErr("could not hash key: %v", err)
cli.Sayf("could not hash key: %v\n", err)
os.Exit(1)
}
@@ -154,60 +145,73 @@ func execHash (cost int, key string) {
}
func execAdduser (service string) {
fullName := serviceUser(service)
fullName := cli.ServiceUser(service)
dataDir := cli.ServiceDir(service)
// BUSYBOX
adduser, err := exec.LookPath("adduser")
if err == nil {
if adduser, err := exec.LookPath("adduser"); err == nil {
// BUSYBOX
addgroup, _ := exec.LookPath("addgroup")
tryCommand (exec.Command(addgroup, fullName, "-S"),
"could not add group")
tryCommand (exec.Command(adduser, fullName, "-SHDG", fullName),
tryCommand (exec.Command (
adduser, fullName, "-SHDG", fullName, "-h", dataDir),
"could not add user")
return
}
// GNU
useradd, err := exec.LookPath("useradd")
if err == nil {
} else if useradd, err := exec.LookPath("useradd"); err == nil {
// GNU
tryCommand (exec.Command (
useradd, fullName, "-rUM",
"--shell", "/sbin/nologin"), "could not add user")
return
"--shell", "/sbin/nologin",
"-d", dataDir), "could not add user")
} else {
cli.Sayf("could not add user: no command adduser or useradd\n")
os.Exit(1)
}
printErr("could not add user: no command adduser or useradd")
os.Exit(1)
// create data directory
uid, gid, err := cli.LookupUID(fullName)
if err != nil {
cli.Sayf("could not create data dir: %v\n", err)
os.Exit(1)
}
err = cli.MkdirFor(dataDir, int(uid), int(gid))
if err != nil {
cli.Sayf("could not create data dir: %v\n", err)
os.Exit(1)
}
}
func execDeluser (service string) {
fullName := serviceUser(service)
func execDeluser (service string, rmData bool) {
fullName := cli.ServiceUser(service)
dataDir := cli.ServiceDir(service)
// BUSYBOX
deluser, err := exec.LookPath("deluser")
if err == nil {
if deluser, err := exec.LookPath("deluser"); err == nil {
// BUSYBOX
tryCommand (exec.Command(deluser, fullName, "--remove-home"),
"could not delete user")
return
}
// GNU
userdel, err := exec.LookPath("userdel")
if err == nil {
} else if userdel, err := exec.LookPath("userdel"); err == nil {
// GNU
tryCommand (exec.Command(userdel, fullName, "-r"),
"could not delete user")
groupdel, _ := exec.LookPath("groupdel")
tryCommand (exec.Command(groupdel, fullName),
"could not delete group")
return
} else {
cli.Sayf("could not delete user: no command deluser or userdel\n")
os.Exit(1)
}
printErr("could not delete user: no command deluser or userdel")
os.Exit(1)
// delete data directory
if rmData {
err := os.RemoveAll(dataDir)
if err != nil {
cli.Sayf("could not delete data dir: %v\n", err)
os.Exit(1)
}
}
}
func execAuth (service, user string) {
fullName := serviceUser(service)
fullName := cli.ServiceUser(service)
adduser, err := exec.LookPath("adduser")
if err == nil {
@@ -224,19 +228,19 @@ func execAuth (service, user string) {
return
}
printErr("could not auth user: no command adduser or usermod")
cli.Sayf("could not auth user: no command adduser or usermod\n")
os.Exit(1)
}
func execOwn (service, file string, recurse bool) {
fullName := serviceUser(service)
fullName := cli.ServiceUser(service)
userInfo, err := user.Lookup(fullName)
uid, _ := strconv.Atoi(userInfo.Uid)
gid, _ := strconv.Atoi(userInfo.Gid)
if err != nil {
printErr("could not get user info: %v", err)
cli.Sayf("could not get user info: %v\n", err)
os.Exit(1)
}
@@ -251,7 +255,7 @@ func execOwn (service, file string, recurse bool) {
err error,
) error {
if err != nil {
printErr("could not traverse filesystem: %v", err)
cli.Sayf("could not traverse filesystem: %v\n", err)
return nil
}
@@ -260,7 +264,7 @@ func execOwn (service, file string, recurse bool) {
})
if err != nil {
printErr("could not traverse filesystem: %v", err)
cli.Sayf("could not traverse filesystem: %v\n", err)
os.Exit(1)
}
}

50
daemon/daemon.go Normal file
View File

@@ -0,0 +1,50 @@
// Package daemon provides utilities for daemons.
package daemon
import "io"
import "os"
import "syscall"
import "strconv"
import "os/signal"
// PidFile is a string that contains a path to a pidfile.
type PidFile string
// Start writes to the pidfile.
func (pidfile PidFile) Start () error {
return os.WriteFile(string(pidfile), []byte(strconv.Itoa(os.Getpid())), 0644)
}
// Close deletes the pidfile.
func (pidfile PidFile) Close () error {
return os.Remove(string(pidfile))
}
// Empty returns true if the object is zero value (an empty string).
func (pidfile PidFile) Empty () bool {
return pidfile == ""
}
// OnSigint calls the specified function once sigint is recieved. This function
// does not block, and spawns a goroutine that waits. For this reason, the
// callback must be safe to call concurrently.
func OnSigint (callback func ()) {
go func () {
sigintNotify := make(chan os.Signal, 1)
signal.Notify(sigintNotify, os.Interrupt, syscall.SIGTERM)
<-sigintNotify
callback()
} ()
}
// CloseOnSigint is like OnSigint, but takes an io.Closer.
func CloseOnSigint (closer io.Closer) {
OnSigint(func () { closer.Close() })
}
// ShutdownOnSigint is like OnSigint, but takes an object with a Shutdown()
// method.
func ShutdownOnSigint (shutdowner interface { Shutdown() error }) {
OnSigint(func () { shutdowner.Shutdown() })
}

View File

@@ -6,10 +6,45 @@ import "fmt"
import "log"
import "time"
import "sync"
import "errors"
// Routine is a long-running function that does not return until it is finished.
// An error is returned if the routine exited due to an error.
type Routine func () error
type routine struct {
run, shutdown func () error
}
func (routine routine) Run () error {
if routine.run == nil {
return nil
} else {
return routine.run()
}
}
func (routine routine) Shutdown () error {
if routine.shutdown == nil {
return nil
} else {
return routine.shutdown()
}
}
// From creates a routine from a separate run and shutdown function.
func From (run, shutdown func () error) Routine {
return routine {
run: run,
shutdown: shutdown,
}
}
// Routine is an object that can be run and stopped.
type Routine interface {
// Run is a long-running function that does not return until it is
// finished. An error is returned if the routine exited due to an error.
Run () error
// Shutdown stops Run.
Shutdown () error
}
// Manager is a system capable of managing multiple routines, and restarting
// them if they fail.
@@ -27,6 +62,9 @@ type Manager struct {
// is nil, messages will be written to the standard logger. To disable
// logging altogether, this can be set to io.Discard.
Logger io.Writer
stoppingMutex sync.Mutex
stopping bool
}
// Run spawns all routines in the Routines slice. If a routine exits with an
@@ -34,17 +72,31 @@ type Manager struct {
// Run returns only when all routines have exited.
func (manager *Manager) Run () error {
var waitGroup sync.WaitGroup
var errExit error
for _, routine := range manager.Routines {
if routine != nil {
waitGroup.Add(1)
go manager.runRoutine(routine, &waitGroup, &errExit)
go manager.runRoutine(routine, &waitGroup)
}
}
waitGroup.Wait()
return errExit
return nil
}
// Shutdown shuts down all routines in the manager.
func (manager *Manager) Shutdown () (err error) {
manager.stoppingMutex.Lock()
manager.stopping = true
manager.stoppingMutex.Unlock()
for _, routine := range manager.Routines {
routineErr := routine.Shutdown()
if routineErr != nil {
err = routineErr
}
}
return
}
// Append adds one or more routines to the Routines slice. This has no effect if
@@ -61,15 +113,26 @@ func (manager *Manager) log (message ...any) {
}
}
func (manager *Manager) runRoutine (routine Routine, group *sync.WaitGroup, errExit *error) {
func (manager *Manager) runRoutine (routine Routine, group *sync.WaitGroup) {
defer group.Done()
var err error
for {
// TODO: recover from panics
lastStart := time.Now()
err = routine()
err := panicWrap(routine.Run)
stopping := false
manager.stoppingMutex.Lock()
stopping = manager.stopping
manager.stoppingMutex.Unlock()
if stopping {
if err == nil {
manager.log("(i) stopped routine")
} else {
manager.log("!!! stopped routine, with error:", err)
}
break
}
if err == nil {
manager.log("(i) routine exited")
break
@@ -84,8 +147,15 @@ func (manager *Manager) runRoutine (routine Routine, group *sync.WaitGroup, errE
manager.log("(i) routine is being restarted")
}
}
if err != nil {
*errExit = err
}
}
func panicWrap (f func () error) (err error) {
defer func () {
if pan := recover(); pan != nil {
err = errors.New(fmt.Sprint(pan))
}
} ()
err = f()
return
}

View File

@@ -19,11 +19,13 @@ type HTTP struct {
Handler http.Handler
conn *Conn
running bool
requests requestManager
}
// Close closes the mount abruptly, interrupting any active connections.
func (htmount *HTTP) Close () error {
htmount.running = false
return htmount.conn.Close()
}
@@ -44,12 +46,19 @@ func (htmount *HTTP) Run (service ServiceInfo) (err error) {
}
htmount.conn, err = Dial(htmount.MountInfo, service)
if err != nil { return }
htmount.running = true
htmount.requests.init()
for {
message, err := htmount.conn.Receive()
if err != nil { return err }
if err != nil {
if htmount.running {
return err
} else {
return nil
}
}
switch message.(type) {
case protocol.MessageHTTPRequest:

View File

@@ -5,6 +5,7 @@ import "os"
import "log"
import "time"
import "hnakra/rotate"
import "hnakra/daemon"
import "hnakra/routines"
// Service is capable of managing multiple mounts. It also sets up logging
@@ -12,6 +13,8 @@ import "hnakra/routines"
type Service struct {
ServiceInfo
Mounts []Mount
manager routines.Manager
}
// NewService provides a shorthand for creating a new service, leaving most
@@ -29,6 +32,8 @@ func NewService (name, description string, mounts ...Mount) *Service {
// Run runs the mounts within the service, and only exits when all of them have
// exited. It will automatically start logging to the directory specified by
// $HNAKRA_LOG_DIR. If that variable is unset, it will just log to stdout.
// Additionally, if $HNAKRA_PIDFILE is set, it will write the process PID to the
// file specified by it.
func (service *Service) Run () error {
// set up logging
logDir := os.Getenv("HNAKRA_LOG_DIR")
@@ -41,16 +46,28 @@ func (service *Service) Run () error {
log.Println("... starting service", service.Name)
// set up routine manager
manager := routines.Manager { RestartDeadline: time.Second * 8 }
manager.Routines = make([]routines.Routine, len(service.Mounts))
service.manager = routines.Manager { RestartDeadline: time.Second * 8 }
service.manager.Routines = make([]routines.Routine, len(service.Mounts))
for index, mount := range service.Mounts {
manager.Routines[index] = func () error {
service.manager.Routines[index] = routines.From (func () error {
return mount.Run(service.ServiceInfo)
}
}, mount.Shutdown)
}
// be a daemon
daemon.ShutdownOnSigint(service)
pidfile := daemon.PidFile(os.Getenv("HNAKRA_PIDFILE"))
if !pidfile.Empty() {
err := pidfile.Start()
if err != nil { log.Println("!!! could not write pid:", err) }
defer func () {
err := pidfile.Close()
if err != nil { log.Println("!!! could not delete pidfile:", err) }
} ()
}
// send it
err := manager.Run()
err := service.manager.Run()
if err != nil { log.Println("XXX", err) }
return err
}
@@ -70,11 +87,5 @@ func (service *Service) Close () (err error) {
// Shutdown gracefully shuts down each mount in the service. This will cause
// Run() to exit.
func (service *Service) Shutdown () (err error) {
for _, mount := range service.Mounts {
singleErr := mount.Shutdown()
if singleErr != nil {
err = singleErr
}
}
return
return service.manager.Shutdown()
}