Daemonize with environment variable

This commit is contained in:
Jason A. Donenfeld 2018-05-03 14:50:57 +02:00
parent 258a9223b9
commit 209dd22ea0
2 changed files with 19 additions and 31 deletions

View file

@ -1,25 +0,0 @@
package main
import (
"os"
)
func Daemonize(attr *os.ProcAttr) error {
path, err := os.Executable()
if err != nil {
return err
}
argv := []string{os.Args[0], "--foreground"}
argv = append(argv, os.Args[1:]...)
process, err := os.StartProcess(
path,
argv,
attr,
)
if err != nil {
return err
}
process.Release()
return nil
}

25
main.go
View file

@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"os" "os"
"os/signal" "os/signal"
"runtime"
"strconv" "strconv"
) )
@ -16,6 +15,7 @@ const (
const ( const (
ENV_WG_TUN_FD = "WG_TUN_FD" ENV_WG_TUN_FD = "WG_TUN_FD"
ENV_WG_UAPI_FD = "WG_UAPI_FD" ENV_WG_UAPI_FD = "WG_UAPI_FD"
ENV_WG_PROCESS_FOREGROUND = "WG_PROCESS_FOREGROUND"
) )
func printUsage() { func printUsage() {
@ -55,6 +55,10 @@ func main() {
interfaceName = os.Args[1] interfaceName = os.Args[1]
} }
if !foreground {
foreground = os.Getenv(ENV_WG_PROCESS_FOREGROUND) == "1"
}
// get log level (default: info) // get log level (default: info)
logLevel := func() int { logLevel := func() int {
@ -129,6 +133,7 @@ func main() {
env := os.Environ() env := os.Environ()
env = append(env, fmt.Sprintf("%s=3", ENV_WG_TUN_FD)) env = append(env, fmt.Sprintf("%s=3", ENV_WG_TUN_FD))
env = append(env, fmt.Sprintf("%s=4", ENV_WG_UAPI_FD)) env = append(env, fmt.Sprintf("%s=4", ENV_WG_UAPI_FD))
env = append(env, fmt.Sprintf("%s=1", ENV_WG_PROCESS_FOREGROUND))
attr := &os.ProcAttr{ attr := &os.ProcAttr{
Files: []*os.File{ Files: []*os.File{
nil, // stdin nil, // stdin
@ -140,18 +145,26 @@ func main() {
Dir: ".", Dir: ".",
Env: env, Env: env,
} }
err = Daemonize(attr)
path, err := os.Executable()
if err != nil {
logger.Error.Println("Failed to determine executable:", err)
os.Exit(ExitSetupFailed)
}
process, err := os.StartProcess(
path,
os.Args,
attr,
)
if err != nil { if err != nil {
logger.Error.Println("Failed to daemonize:", err) logger.Error.Println("Failed to daemonize:", err)
os.Exit(ExitSetupFailed) os.Exit(ExitSetupFailed)
} }
process.Release()
return return
} }
// increase number of go workers (for Go <1.5)
runtime.GOMAXPROCS(runtime.NumCPU())
// create wireguard device // create wireguard device
device := NewDevice(tun, logger) device := NewDevice(tun, logger)