all: imp code

This commit is contained in:
Stanislav Chzhen 2024-12-05 18:24:01 +03:00
parent f3af1bf3dd
commit bcd3d29dfd
5 changed files with 29 additions and 26 deletions

View File

@ -18,6 +18,7 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/updater" "github.com/AdguardTeam/AdGuardHome/internal/updater"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/logutil/slogutil" "github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/osutil"
) )
// temporaryError is the interface for temporary errors from the Go standard // temporaryError is the interface for temporary errors from the Go standard
@ -95,7 +96,7 @@ func (web *webAPI) requestVersionInfo(
const sleepTime = 2 * time.Second const sleepTime = 2 * time.Second
err = fmt.Errorf("temp net error: %w; sleeping for %s and retrying", err, sleepTime) err = fmt.Errorf("temp net error: %w; sleeping for %s and retrying", err, sleepTime)
web.logger.ErrorContext(ctx, "updating version info", slogutil.KeyError, err) web.logger.InfoContext(ctx, "updating version info", slogutil.KeyError, err)
time.Sleep(sleepTime) time.Sleep(sleepTime)
@ -187,22 +188,17 @@ func tlsConfUsesPrivilegedPorts(c *tlsConfigSettings) (ok bool) {
return c.Enabled && (c.PortHTTPS < 1024 || c.PortDNSOverTLS < 1024 || c.PortDNSOverQUIC < 1024) return c.Enabled && (c.PortHTTPS < 1024 || c.PortDNSOverTLS < 1024 || c.PortDNSOverQUIC < 1024)
} }
// finishUpdate completes an update procedure. // finishUpdate completes an update procedure. It is intended to be used as a
// goroutine.
func finishUpdate(ctx context.Context, l *slog.Logger, execPath string, runningAsService bool) { func finishUpdate(ctx context.Context, l *slog.Logger, execPath string, runningAsService bool) {
var err error defer slogutil.RecoverAndExit(ctx, l, osutil.ExitCodeFailure)
defer func() {
if err != nil {
l.ErrorContext(ctx, "restarting", slogutil.KeyError, err)
os.Exit(1)
}
}()
l.InfoContext(ctx, "stopping all tasks") l.InfoContext(ctx, "stopping all tasks")
cleanup(ctx) cleanup(ctx)
cleanupAlways() cleanupAlways()
var err error
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
if runningAsService { if runningAsService {
// NOTE: We can't restart the service via "kardianos/service" // NOTE: We can't restart the service via "kardianos/service"
@ -213,10 +209,10 @@ func finishUpdate(ctx context.Context, l *slog.Logger, execPath string, runningA
cmd := exec.Command("cmd", "/c", "net stop AdGuardHome & net start AdGuardHome") cmd := exec.Command("cmd", "/c", "net stop AdGuardHome & net start AdGuardHome")
err = cmd.Start() err = cmd.Start()
if err != nil { if err != nil {
return panic(fmt.Errorf("restarting service: %w", err))
} }
os.Exit(0) os.Exit(osutil.ExitCodeSuccess)
} }
cmd := exec.Command(execPath, os.Args[1:]...) cmd := exec.Command(execPath, os.Args[1:]...)
@ -226,15 +222,15 @@ func finishUpdate(ctx context.Context, l *slog.Logger, execPath string, runningA
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
err = cmd.Start() err = cmd.Start()
if err != nil { if err != nil {
return panic(fmt.Errorf("restarting: %w", err))
} }
os.Exit(0) os.Exit(osutil.ExitCodeSuccess)
} }
l.InfoContext(ctx, "restarting", "exec_path", execPath, "args", os.Args[1:]) l.InfoContext(ctx, "restarting", "exec_path", execPath, "args", os.Args[1:])
err = syscall.Exec(execPath, os.Args, os.Environ()) err = syscall.Exec(execPath, os.Args, os.Environ())
if err != nil { if err != nil {
return panic(fmt.Errorf("restarting: %w", err))
} }
} }

View File

@ -167,13 +167,13 @@ func setupContext(opts options) (err error) {
if err != nil { if err != nil {
log.Error("parsing configuration file: %s", err) log.Error("parsing configuration file: %s", err)
os.Exit(1) os.Exit(osutil.ExitCodeFailure)
} }
if opts.checkConfig { if opts.checkConfig {
log.Info("configuration file is ok") log.Info("configuration file is ok")
os.Exit(0) os.Exit(osutil.ExitCodeSuccess)
} }
return nil return nil
@ -978,7 +978,7 @@ func loadCmdLineOpts() (opts options) {
exitWithError() exitWithError()
} }
os.Exit(0) os.Exit(osutil.ExitCodeSuccess)
} }
return opts return opts

View File

@ -10,6 +10,7 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/configmigrate" "github.com/AdguardTeam/AdGuardHome/internal/configmigrate"
"github.com/AdguardTeam/AdGuardHome/internal/version" "github.com/AdguardTeam/AdGuardHome/internal/version"
"github.com/AdguardTeam/golibs/log" "github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/osutil"
"github.com/AdguardTeam/golibs/stringutil" "github.com/AdguardTeam/golibs/stringutil"
) )
@ -329,7 +330,7 @@ var cmdLineOpts = []cmdLineOpt{{
fmt.Println(version.Full()) fmt.Println(version.Full())
} }
os.Exit(0) os.Exit(osutil.ExitCodeSuccess)
return nil return nil
}, nil }, nil

View File

@ -20,6 +20,7 @@ import (
"github.com/AdguardTeam/golibs/netutil" "github.com/AdguardTeam/golibs/netutil"
"github.com/AdguardTeam/golibs/netutil/httputil" "github.com/AdguardTeam/golibs/netutil/httputil"
"github.com/AdguardTeam/golibs/netutil/urlutil" "github.com/AdguardTeam/golibs/netutil/urlutil"
"github.com/AdguardTeam/golibs/osutil"
"github.com/NYTimes/gziphandler" "github.com/NYTimes/gziphandler"
"github.com/quic-go/quic-go/http3" "github.com/quic-go/quic-go/http3"
"golang.org/x/net/http2" "golang.org/x/net/http2"
@ -112,8 +113,8 @@ type webAPI struct {
httpsServer httpsServer httpsServer httpsServer
} }
// newWebAPI creates a new instance of the web UI and API server. conf must not // newWebAPI creates a new instance of the web UI and API server. conf must be
// be nil and must be valid // valid.
// //
// TODO(a.garipov): Return a proper error. // TODO(a.garipov): Return a proper error.
func newWebAPI(ctx context.Context, conf *webConfig) (w *webAPI) { func newWebAPI(ctx context.Context, conf *webConfig) (w *webAPI) {
@ -172,7 +173,7 @@ func webCheckPortAvailable(port uint16) (ok bool) {
// tlsConfigChanged updates the TLS configuration and restarts the HTTPS server // tlsConfigChanged updates the TLS configuration and restarts the HTTPS server
// if necessary. // if necessary.
func (web *webAPI) tlsConfigChanged(ctx context.Context, tlsConf tlsConfigSettings) { func (web *webAPI) tlsConfigChanged(ctx context.Context, tlsConf tlsConfigSettings) {
defer slogutil.RecoverAndLog(ctx, web.logger) defer slogutil.RecoverAndExit(ctx, web.logger, osutil.ExitCodeFailure)
web.logger.DebugContext(ctx, "applying new tls configuration") web.logger.DebugContext(ctx, "applying new tls configuration")
@ -210,7 +211,7 @@ const loggerKeyServer = "server"
// start - start serving HTTP requests // start - start serving HTTP requests
func (web *webAPI) start(ctx context.Context) { func (web *webAPI) start(ctx context.Context) {
defer slogutil.RecoverAndLog(ctx, web.logger) defer slogutil.RecoverAndExit(ctx, web.logger, osutil.ExitCodeFailure)
web.logger.InfoContext(ctx, "AdGuard Home is available at the following addresses:") web.logger.InfoContext(ctx, "AdGuard Home is available at the following addresses:")
@ -237,6 +238,8 @@ func (web *webAPI) start(ctx context.Context) {
ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelError), ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelError),
} }
go func() { go func() {
defer slogutil.RecoverAndLog(ctx, web.logger)
errs <- web.httpServer.ListenAndServe() errs <- web.httpServer.ListenAndServe()
}() }()
@ -271,7 +274,7 @@ func (web *webAPI) close(ctx context.Context) {
} }
func (web *webAPI) tlsServerLoop(ctx context.Context) { func (web *webAPI) tlsServerLoop(ctx context.Context) {
defer slogutil.RecoverAndLog(ctx, web.logger) defer slogutil.RecoverAndExit(ctx, web.logger, osutil.ExitCodeFailure)
for { for {
web.httpsServer.cond.L.Lock() web.httpsServer.cond.L.Lock()
@ -333,6 +336,8 @@ func (web *webAPI) tlsServerLoop(ctx context.Context) {
} }
func (web *webAPI) mustStartHTTP3(ctx context.Context, address string) { func (web *webAPI) mustStartHTTP3(ctx context.Context, address string) {
defer slogutil.RecoverAndExit(ctx, web.logger, osutil.ExitCodeFailure)
web.httpsServer.server3 = &http3.Server{ web.httpsServer.server3 = &http3.Server{
// TODO(a.garipov): See if there is a way to use the error log as // TODO(a.garipov): See if there is a way to use the error log as
// well as timeouts here. // well as timeouts here.

View File

@ -22,6 +22,7 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/errors" "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/logutil/slogutil" "github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/osutil"
) )
const ( const (
@ -124,12 +125,12 @@ Commands:
if addStr != "" { if addStr != "" {
fmt.Printf("%s\n%s\n", addStr, usageStr) fmt.Printf("%s\n%s\n", addStr, usageStr)
os.Exit(1) os.Exit(osutil.ExitCodeFailure)
} }
fmt.Println(usageStr) fmt.Println(usageStr)
os.Exit(0) os.Exit(osutil.ExitCodeSuccess)
} }
// twoskyConfig is the configuration structure for localization. // twoskyConfig is the configuration structure for localization.