Skip to content

Commit

Permalink
Pull request 2303: AGDNS-2505-upd-next
Browse files Browse the repository at this point in the history
Squashed commit of the following:

commit 586b0eb
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Tue Nov 12 19:58:56 2024 +0300

    next: upd more

commit d729aa1
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Tue Nov 12 16:53:15 2024 +0300

    next/websvc: upd more

commit 0c64e6c
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Mon Nov 11 21:08:51 2024 +0300

    next: upd more

commit 05eec75
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Fri Nov 8 19:20:02 2024 +0300

    next: upd code
  • Loading branch information
ainar-g committed Nov 13, 2024
1 parent ac5a96f commit 1d6d85c
Show file tree
Hide file tree
Showing 34 changed files with 638 additions and 602 deletions.
3 changes: 1 addition & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@ go 1.23.3

require (
github.com/AdguardTeam/dnsproxy v0.73.3
github.com/AdguardTeam/golibs v0.30.2
github.com/AdguardTeam/golibs v0.30.3
github.com/AdguardTeam/urlfilter v0.20.0
github.com/NYTimes/gziphandler v1.1.1
github.com/ameshkov/dnscrypt/v2 v2.3.0
github.com/bluele/gcache v0.0.2
github.com/c2h5oh/datasize v0.0.0-20231215233829-aa82cc1e6500
github.com/digineo/go-ipset/v2 v2.2.1
github.com/dimfeld/httptreemux/v5 v5.5.0
github.com/fsnotify/fsnotify v1.8.0
github.com/go-ping/ping v1.1.0
github.com/google/go-cmp v0.6.0
Expand Down
6 changes: 2 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
github.com/AdguardTeam/dnsproxy v0.73.3 h1:aacr6Wu0ed94DDD+gSB6EwF8nvyq0+DAc7oFOgtgUpA=
github.com/AdguardTeam/dnsproxy v0.73.3/go.mod h1:18ssqhDgOCiVIwYmmVuXVM05wSwrzkO2yjKhVRWJX/g=
github.com/AdguardTeam/golibs v0.30.2 h1:urU/NAyIvQOeArBqDmKCDpaRkfTCJ26uSiSuDMKQfuY=
github.com/AdguardTeam/golibs v0.30.2/go.mod h1:FkwcNQEJoGsgDGXcalrVa/4gWbE68KsmE2guXWtBQUE=
github.com/AdguardTeam/golibs v0.30.3 h1:pRxLjMCJ1cZccjZWMMuKxzQQGEpFbmtyj4Tg7nk5rY0=
github.com/AdguardTeam/golibs v0.30.3/go.mod h1:Ir9dlHfb8nRQsG3Qgo1zoGL+k1qMbcBtb8tcnsvzdAE=
github.com/AdguardTeam/urlfilter v0.20.0 h1:X32qiuVCVd8WDYCEsbdZKfXMzwdVqrdulamtUi4rmzs=
github.com/AdguardTeam/urlfilter v0.20.0/go.mod h1:gjrywLTxfJh6JOkwi9SU+frhP7kVVEZ5exFGkR99qpk=
github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I=
Expand All @@ -25,8 +25,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/digineo/go-ipset/v2 v2.2.1 h1:k6skY+0fMqeUjjeWO/m5OuWPSZUAn7AucHMnQ1MX77g=
github.com/digineo/go-ipset/v2 v2.2.1/go.mod h1:wBsNzJlZlABHUITkesrggFnZQtgW5wkqw1uo8Qxe0VU=
github.com/dimfeld/httptreemux/v5 v5.5.0 h1:p8jkiMrCuZ0CmhwYLcbNbl7DDo21fozhKHQ2PccwOFQ=
github.com/dimfeld/httptreemux/v5 v5.5.0/go.mod h1:QeEylH57C0v3VO0tkKraVz9oD3Uu93CKPnTLbsidvSw=
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
Expand Down
10 changes: 0 additions & 10 deletions internal/aghos/os.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,16 +146,6 @@ func IsOpenWrt() (ok bool) {
return isOpenWrt()
}

// NotifyReconfigureSignal notifies c on receiving reconfigure signals.
func NotifyReconfigureSignal(c chan<- os.Signal) {
notifyReconfigureSignal(c)
}

// IsReconfigureSignal returns true if sig is a reconfigure signal.
func IsReconfigureSignal(sig os.Signal) (ok bool) {
return isReconfigureSignal(sig)
}

// SendShutdownSignal sends the shutdown signal to the channel.
func SendShutdownSignal(c chan<- os.Signal) {
sendShutdownSignal(c)
Expand Down
13 changes: 1 addition & 12 deletions internal/aghos/os_unix.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,11 @@
//go:build darwin || freebsd || linux || openbsd
//go:build unix

package aghos

import (
"os"
"os/signal"

"golang.org/x/sys/unix"
)

func notifyReconfigureSignal(c chan<- os.Signal) {
signal.Notify(c, unix.SIGHUP)
}

func isReconfigureSignal(sig os.Signal) (ok bool) {
return sig == unix.SIGHUP
}

func sendShutdownSignal(_ chan<- os.Signal) {
// On Unix we are already notified by the system.
}
11 changes: 1 addition & 10 deletions internal/aghos/os_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ package aghos

import (
"os"
"os/signal"

"golang.org/x/sys/windows"
)

func setRlimit(val uint64) (err error) {
func setRlimit(_ uint64) (err error) {
return Unsupported("setrlimit")
}

Expand Down Expand Up @@ -38,14 +37,6 @@ func isOpenWrt() (ok bool) {
return false
}

func notifyReconfigureSignal(c chan<- os.Signal) {
signal.Notify(c, windows.SIGHUP)
}

func isReconfigureSignal(sig os.Signal) (ok bool) {
return sig == windows.SIGHUP
}

func sendShutdownSignal(c chan<- os.Signal) {
c <- os.Interrupt
}
6 changes: 3 additions & 3 deletions internal/aghtest/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func (w *FSWatcher) Add(name string) (err error) {

// ServiceWithConfig is a fake [agh.ServiceWithConfig] implementation for tests.
type ServiceWithConfig[ConfigType any] struct {
OnStart func() (err error)
OnStart func(ctx context.Context) (err error)
OnShutdown func(ctx context.Context) (err error)
OnConfig func() (c ConfigType)
}
Expand All @@ -68,8 +68,8 @@ var _ agh.ServiceWithConfig[struct{}] = (*ServiceWithConfig[struct{}])(nil)

// Start implements the [agh.ServiceWithConfig] interface for
// *ServiceWithConfig.
func (s *ServiceWithConfig[_]) Start() (err error) {
return s.OnStart()
func (s *ServiceWithConfig[_]) Start(ctx context.Context) (err error) {
return s.OnStart(ctx)
}

// Shutdown implements the [agh.ServiceWithConfig] interface for
Expand Down
2 changes: 1 addition & 1 deletion internal/dhcpsvc/dhcpsvc.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ type Empty struct{}
var _ agh.ServiceWithConfig[*Config] = Empty{}

// Start implements the [Service] interface for Empty.
func (Empty) Start() (err error) { return nil }
func (Empty) Start(_ context.Context) (err error) { return nil }

// Shutdown implements the [Service] interface for Empty.
func (Empty) Shutdown(_ context.Context) (err error) { return nil }
Expand Down
37 changes: 5 additions & 32 deletions internal/next/agh/agh.go
Original file line number Diff line number Diff line change
@@ -1,44 +1,17 @@
// Package agh contains common entities and interfaces of AdGuard Home.
package agh

import "context"

// Service is the interface for API servers.
//
// TODO(a.garipov): Consider adding a context to Start.
//
// TODO(a.garipov): Consider adding a Wait method or making an extension
// interface for that.
type Service interface {
// Start starts the service. It does not block.
Start() (err error)

// Shutdown gracefully stops the service. ctx is used to determine
// a timeout before trying to stop the service less gracefully.
Shutdown(ctx context.Context) (err error)
}

// type check
var _ Service = EmptyService{}

// EmptyService is a [Service] that does nothing.
//
// TODO(a.garipov): Remove if unnecessary.
type EmptyService struct{}

// Start implements the [Service] interface for EmptyService.
func (EmptyService) Start() (err error) { return nil }

// Shutdown implements the [Service] interface for EmptyService.
func (EmptyService) Shutdown(_ context.Context) (err error) { return nil }
import (
"github.com/AdguardTeam/golibs/service"
)

// ServiceWithConfig is an extension of the [Service] interface for services
// that can return their configuration.
//
// TODO(a.garipov): Consider removing this generic interface if we figure out
// how to make it testable in a better way.
type ServiceWithConfig[ConfigType any] interface {
Service
service.Interface

Config() (c ConfigType)
}
Expand All @@ -51,7 +24,7 @@ var _ ServiceWithConfig[struct{}] = (*EmptyServiceWithConfig[struct{}])(nil)
//
// TODO(a.garipov): Remove if unnecessary.
type EmptyServiceWithConfig[ConfigType any] struct {
EmptyService
service.Empty

Conf ConfigType
}
Expand Down
81 changes: 42 additions & 39 deletions internal/next/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,15 @@ import (

"github.com/AdguardTeam/AdGuardHome/internal/next/configmgr"
"github.com/AdguardTeam/AdGuardHome/internal/version"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/service"
)

// Main is the entry point of AdGuard Home.
func Main(embeddedFrontend fs.FS) {
ctx := context.Background()

start := time.Now()

cmdName := os.Args[0]
Expand All @@ -26,70 +30,69 @@ func Main(embeddedFrontend fs.FS) {
os.Exit(exitCode)
}

err = setLog(opts)
check(err)
baseLogger := newBaseLogger(opts)

log.Info("starting adguard home, version %s, pid %d", version.Version(), os.Getpid())
baseLogger.InfoContext(
ctx,
"starting adguard home",
"version", version.Version(),
"pid", os.Getpid(),
)

if opts.workDir != "" {
log.Info("changing working directory to %q", opts.workDir)
baseLogger.InfoContext(ctx, "changing working directory", "dir", opts.workDir)

err = os.Chdir(opts.workDir)
check(err)
errors.Check(err)
}

frontend, err := frontendFromOpts(opts, embeddedFrontend)
check(err)
frontend, err := frontendFromOpts(ctx, baseLogger, opts, embeddedFrontend)
errors.Check(err)

startCtx, startCancel := context.WithTimeout(ctx, defaultTimeoutStart)
defer startCancel()

confMgrConf := &configmgr.Config{
Frontend: frontend,
WebAddr: opts.webAddr,
Start: start,
FileName: opts.confFile,
BaseLogger: baseLogger,
Logger: baseLogger.With(slogutil.KeyPrefix, "configmgr"),
Frontend: frontend,
WebAddr: opts.webAddr,
Start: start,
FileName: opts.confFile,
}

confMgr, err := newConfigMgr(confMgrConf)
check(err)
confMgr, err := configmgr.New(startCtx, confMgrConf)
errors.Check(err)

web := confMgr.Web()
err = web.Start()
check(err)
err = web.Start(startCtx)
errors.Check(err)

dns := confMgr.DNS()
err = dns.Start()
check(err)
err = dns.Start(startCtx)
errors.Check(err)

sigHdlr := newSignalHandler(
baseLogger.With(slogutil.KeyPrefix, service.SignalHandlerPrefix),
confMgrConf,
opts.pidFile,
web,
dns,
)

sigHdlr.handle()
os.Exit(sigHdlr.handle(ctx))
}

// defaultTimeout is the timeout used for some operations where another timeout
// hasn't been defined yet.
const defaultTimeout = 5 * time.Second

// ctxWithDefaultTimeout is a helper function that returns a context with
// timeout set to defaultTimeout.
func ctxWithDefaultTimeout() (ctx context.Context, cancel context.CancelFunc) {
return context.WithTimeout(context.Background(), defaultTimeout)
}
// Default timeouts.
//
// TODO(a.garipov): Make configurable.
const (
defaultTimeoutStart = 1 * time.Minute
defaultTimeoutShutdown = 5 * time.Second
)

// newConfigMgr returns a new configuration manager using defaultTimeout as the
// context timeout.
func newConfigMgr(c *configmgr.Config) (m *configmgr.Manager, err error) {
ctx, cancel := ctxWithDefaultTimeout()
defer cancel()

func newConfigMgr(ctx context.Context, c *configmgr.Config) (m *configmgr.Manager, err error) {
return configmgr.New(ctx, c)
}

// check is a simple error-checking helper. It must only be used within Main.
func check(err error) {
if err != nil {
panic(err)
}
}
42 changes: 21 additions & 21 deletions internal/next/cmd/log.go
Original file line number Diff line number Diff line change
@@ -1,39 +1,39 @@
package cmd

import (
"fmt"
"io"
"log/slog"
"os"

"github.com/AdguardTeam/AdGuardHome/internal/aghos"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/logutil/slogutil"
)

// syslogServiceName is the name of the AdGuard Home service used for writing
// logs to the system log.
const syslogServiceName = "AdGuardHome"

// setLog sets up the text logging.
//
// TODO(a.garipov): Add parameters from configuration file.
func setLog(opts *options) (err error) {
// newBaseLogger constructs a base logger based on the command-line options.
// opts must not be nil.
func newBaseLogger(opts *options) (baseLogger *slog.Logger) {
var output io.Writer
switch opts.confFile {
case "stdout":
log.SetOutput(os.Stdout)
output = os.Stdout
case "stderr":
log.SetOutput(os.Stderr)
output = os.Stderr
case "syslog":
err = aghos.ConfigureSyslog(syslogServiceName)
if err != nil {
return fmt.Errorf("initializing syslog: %w", err)
}
// TODO(a.garipov): Add a syslog handler to golibs.
default:
// TODO(a.garipov): Use the path.
// TODO(a.garipov): Use the path.
}

lvl := slog.LevelInfo
if opts.verbose {
log.SetLevel(log.DEBUG)
log.Debug("verbose logging enabled")
lvl = slog.LevelDebug
}

return nil
return slogutil.New(&slogutil.Config{
Output: output,
// TODO(a.garipov): Get from config?
Format: slogutil.FormatText,
Level: lvl,
// TODO(a.garipov): Get from config.
AddTimestamp: true,
})
}
Loading

0 comments on commit 1d6d85c

Please sign in to comment.