From 282e2445170f7ddea1ce0af85a4f973bfb8bb551 Mon Sep 17 00:00:00 2001 From: Alireza Ahmadi Date: Tue, 29 Oct 2024 13:14:25 +0100 Subject: [PATCH] improve systemd or docker detection --- backend/config/config.go | 9 +++++++++ backend/logger/logger.go | 4 ++-- backend/service/config.go | 2 ++ backend/service/server.go | 3 +-- 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/backend/config/config.go b/backend/config/config.go index 188699c2..8917bd36 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -79,3 +79,12 @@ func GetDefaultConfig() string { func GetEnvApi() string { return os.Getenv("SINGBOX_API") } + +func IsSystemd() bool { + pid := os.Getppid() + cmdline, err := os.ReadFile(fmt.Sprintf("/proc/%d/comm", pid)) + if err != nil { + return false + } + return string(cmdline) == "systemd\n" +} diff --git a/backend/logger/logger.go b/backend/logger/logger.go index 66791a04..a9d7a0c0 100644 --- a/backend/logger/logger.go +++ b/backend/logger/logger.go @@ -3,6 +3,7 @@ package logger import ( "fmt" "os" + "s-ui/config" "time" "github.com/op/go-logging" @@ -22,14 +23,13 @@ func InitLogger(level logging.Level) { var err error var backend logging.Backend var format logging.Formatter - ppid := os.Getppid() backend, err = logging.NewSyslogBackend("") if err != nil { println("Unable to use syslog: " + err.Error()) backend = logging.NewLogBackend(os.Stderr, "", 0) } - if ppid > 1 && err != nil { + if config.IsSystemd() && err != nil { format = logging.MustStringFormatter(`%{time:2006/01/02 15:04:05} %{level} - %{message}`) } else { format = logging.MustStringFormatter(`%{level} - %{message}`) diff --git a/backend/service/config.go b/backend/service/config.go index dd31a695..91daab0b 100644 --- a/backend/service/config.go +++ b/backend/service/config.go @@ -14,6 +14,7 @@ import ( var ApiAddr string var LastUpdate int64 +var IsSystemd bool type ConfigService struct { ClientService @@ -38,6 +39,7 @@ func NewConfigService() *ConfigService { } func (s *ConfigService) InitConfig() error { + IsSystemd = config.IsSystemd() configPath := config.GetBinFolderPath() data, err := os.ReadFile(configPath + "/config.json") if err != nil { diff --git a/backend/service/server.go b/backend/service/server.go index e59c4e23..33bc5a05 100644 --- a/backend/service/server.go +++ b/backend/service/server.go @@ -145,10 +145,9 @@ func (s *ServerService) GetLogs(service string, count string, level string) []st if service == "s-ui" { return logger.GetLogs(c, level) } - ppid := os.Getppid() var lines []string var cmdArgs []string - if ppid > 1 { + if IsSystemd { cmdArgs = []string{"journalctl", "-u", service, "--no-pager", "-n", count, "-p", level} } else { cmdArgs = []string{"tail", "/logs/" + service + ".log", "-n", count}