Files
wg-portal/cmd/wg-portal/main.go

101 lines
2.1 KiB
Go
Raw Normal View History

2020-11-05 19:37:51 +01:00
package main
import (
2021-02-22 22:25:08 +01:00
"context"
2021-01-13 17:27:01 +01:00
"io/ioutil"
"os"
2021-02-22 22:25:08 +01:00
"os/signal"
"syscall"
"time"
2021-01-13 17:27:01 +01:00
2020-11-05 19:37:51 +01:00
"github.com/h44z/wg-portal/internal/server"
2021-01-13 17:27:01 +01:00
"github.com/sirupsen/logrus"
2020-11-05 19:37:51 +01:00
)
2021-02-26 22:17:04 +01:00
var Version = "unknown (local build)"
2020-11-05 19:37:51 +01:00
func main() {
2021-01-13 17:27:01 +01:00
_ = setupLogger(logrus.StandardLogger())
2021-02-22 22:25:08 +01:00
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
2021-02-26 22:17:04 +01:00
logrus.Infof("starting WireGuard Portal Server [%s]...", Version)
2020-11-05 19:37:51 +01:00
2021-02-22 22:25:08 +01:00
// Context for clean shutdown
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
2020-11-05 19:37:51 +01:00
service := server.Server{}
2021-02-22 22:25:08 +01:00
if err := service.Setup(ctx); err != nil {
2021-02-26 22:17:04 +01:00
logrus.Fatalf("setup failed: %v", err)
2020-11-05 19:37:51 +01:00
}
2021-02-22 22:25:08 +01:00
// Attach signal handlers to context
go func() {
osCall := <-c
logrus.Tracef("received system call: %v", osCall)
cancel() // cancel the context
}()
// Start main process in background
go service.Run()
<-ctx.Done() // Wait until the context gets canceled
// Give goroutines some time to stop gracefully
2021-02-26 22:17:04 +01:00
logrus.Info("stopping WireGuard Portal Server...")
2021-02-22 22:25:08 +01:00
time.Sleep(2 * time.Second)
2020-11-05 19:37:51 +01:00
2021-02-26 22:17:04 +01:00
logrus.Infof("stopped WireGuard Portal Server...")
2021-02-22 22:25:08 +01:00
logrus.Exit(0)
2021-01-13 17:27:01 +01:00
}
func setupLogger(logger *logrus.Logger) error {
// Check environment variables for logrus settings
level, ok := os.LookupEnv("LOG_LEVEL")
if !ok {
level = "debug" // Default logrus level
}
useJSON, ok := os.LookupEnv("LOG_JSON")
if !ok {
useJSON = "false" // Default use human readable logging
}
useColor, ok := os.LookupEnv("LOG_COLOR")
if !ok {
useColor = "true"
}
switch level {
case "off":
logger.SetOutput(ioutil.Discard)
case "info":
logger.SetLevel(logrus.InfoLevel)
case "debug":
logger.SetLevel(logrus.DebugLevel)
case "trace":
logger.SetLevel(logrus.TraceLevel)
}
var formatter logrus.Formatter
if useJSON == "false" {
f := new(logrus.TextFormatter)
f.TimestampFormat = "2006-01-02 15:04:05"
f.FullTimestamp = true
if useColor == "true" {
f.ForceColors = true
}
formatter = f
} else {
f := new(logrus.JSONFormatter)
f.TimestampFormat = "2006-01-02 15:04:05"
formatter = f
2021-01-13 17:27:01 +01:00
}
logger.SetFormatter(formatter)
return nil
2020-11-05 19:37:51 +01:00
}