Skip to content

Commit

Permalink
Merge branch 'AdguardTeam:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
hoang-rio authored Dec 10, 2024
2 parents fac6b12 + dab6082 commit 0a9f826
Show file tree
Hide file tree
Showing 10 changed files with 188 additions and 110 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ NOTE: Add new changes BELOW THIS COMMENT.

### Fixed

- Setup guide styles in Firefox.
- Goroutine leak during the upstream DNS server test ([#7357]).
- Goroutine leak during configuration update resulting in increased response
time ([#6818]).
Expand Down
11 changes: 11 additions & 0 deletions client/src/components/SetupGuide/Guide.css
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,17 @@
font-size: 15px;
}

.guide__list {
margin-top: 16px;
padding-left: 0;
}

@media screen and (min-width: 768px) {
.guide__list {
padding-left: 24px;
}
}

.guide__address {
display: block;
margin-bottom: 7px;
Expand Down
4 changes: 2 additions & 2 deletions client/src/components/SetupGuide/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ const SetupGuide = ({
<Trans>install_devices_address</Trans>:
</div>

<div className="mt-3">
<ul className="guide__list">
{dnsAddresses.map((ip: any) => (
<li key={ip} className="guide__address">
{ip}
</li>
))}
</div>
</ul>
</div>

<Guide dnsAddresses={dnsAddresses} />
Expand Down
87 changes: 51 additions & 36 deletions internal/home/controlinstall.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/netip"
"os"
Expand All @@ -19,7 +20,7 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/version"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/quic-go/quic-go/http3"
)

Expand Down Expand Up @@ -124,6 +125,8 @@ func (req *checkConfReq) validateWeb(tcpPorts aghalg.UniqChecker[tcpPort]) (err
// be set. canAutofix is true if the port can be unbound by AdGuard Home
// automatically.
func (req *checkConfReq) validateDNS(
ctx context.Context,
l *slog.Logger,
tcpPorts aghalg.UniqChecker[tcpPort],
) (canAutofix bool, err error) {
defer func() { err = errors.Annotate(err, "validating ports: %w") }()
Expand Down Expand Up @@ -154,10 +157,10 @@ func (req *checkConfReq) validateDNS(
}

// Try to fix automatically.
canAutofix = checkDNSStubListener()
canAutofix = checkDNSStubListener(ctx, l)
if canAutofix && req.DNS.Autofix {
if derr := disableDNSStubListener(); derr != nil {
log.Error("disabling DNSStubListener: %s", err)
if derr := disableDNSStubListener(ctx, l); derr != nil {
l.ErrorContext(ctx, "disabling DNSStubListener", slogutil.KeyError, err)
}

err = aghnet.CheckPort("udp", netip.AddrPortFrom(req.DNS.IP, port))
Expand All @@ -184,7 +187,7 @@ func (web *webAPI) handleInstallCheckConfig(w http.ResponseWriter, r *http.Reque
resp.Web.Status = err.Error()
}

if resp.DNS.CanAutofix, err = req.validateDNS(tcpPorts); err != nil {
if resp.DNS.CanAutofix, err = req.validateDNS(r.Context(), web.logger, tcpPorts); err != nil {
resp.DNS.Status = err.Error()
} else if !req.DNS.IP.IsUnspecified() {
resp.StaticIP = handleStaticIP(req.DNS.IP, req.SetStaticIP)
Expand Down Expand Up @@ -233,27 +236,39 @@ func handleStaticIP(ip netip.Addr, set bool) staticIPJSON {
return resp
}

// Check if DNSStubListener is active
func checkDNSStubListener() bool {
// checkDNSStubListener returns true if DNSStubListener is active.
func checkDNSStubListener(ctx context.Context, l *slog.Logger) (ok bool) {
if runtime.GOOS != "linux" {
return false
}

cmd := exec.Command("systemctl", "is-enabled", "systemd-resolved")
log.Tracef("executing %s %v", cmd.Path, cmd.Args)
l.DebugContext(ctx, "executing", "cmd", cmd.Path, "args", cmd.Args)
_, err := cmd.Output()
if err != nil || cmd.ProcessState.ExitCode() != 0 {
log.Info("command %s has failed: %v code:%d",
cmd.Path, err, cmd.ProcessState.ExitCode())
l.InfoContext(
ctx,
"execution failed",
"cmd", cmd.Path,
"code", cmd.ProcessState.ExitCode(),
slogutil.KeyError, err,
)

return false
}

cmd = exec.Command("grep", "-E", "#?DNSStubListener=yes", "/etc/systemd/resolved.conf")
log.Tracef("executing %s %v", cmd.Path, cmd.Args)
l.DebugContext(ctx, "executing", "cmd", cmd.Path, "args", cmd.Args)
_, err = cmd.Output()
if err != nil || cmd.ProcessState.ExitCode() != 0 {
log.Info("command %s has failed: %v code:%d",
cmd.Path, err, cmd.ProcessState.ExitCode())
l.InfoContext(
ctx,
"execution failed",
"cmd", cmd.Path,
"code", cmd.ProcessState.ExitCode(),
slogutil.KeyError, err,
)

return false
}

Expand All @@ -269,8 +284,9 @@ DNSStubListener=no
)
const resolvConfPath = "/etc/resolv.conf"

// Deactivate DNSStubListener
func disableDNSStubListener() (err error) {
// disableDNSStubListener deactivates DNSStubListerner and returns an error, if
// any.
func disableDNSStubListener(ctx context.Context, l *slog.Logger) (err error) {
dir := filepath.Dir(resolvedConfPath)
err = os.MkdirAll(dir, 0o755)
if err != nil {
Expand All @@ -290,7 +306,7 @@ func disableDNSStubListener() (err error) {
}

cmd := exec.Command("systemctl", "reload-or-restart", "systemd-resolved")
log.Tracef("executing %s %v", cmd.Path, cmd.Args)
l.DebugContext(ctx, "executing", "cmd", cmd.Path, "args", cmd.Args)
_, err = cmd.Output()
if err != nil {
return err
Expand Down Expand Up @@ -327,9 +343,9 @@ func copyInstallSettings(dst, src *configuration) {
// shutdownTimeout is the timeout for shutting HTTP server down operation.
const shutdownTimeout = 5 * time.Second

// shutdownSrv shuts srv down and prints error messages to the log.
func shutdownSrv(ctx context.Context, srv *http.Server) {
defer log.OnPanic("")
// shutdownSrv shuts down srv and logs the error, if any. l must not be nil.
func shutdownSrv(ctx context.Context, l *slog.Logger, srv *http.Server) {
defer slogutil.RecoverAndLog(ctx, l)

if srv == nil {
return
Expand All @@ -340,19 +356,19 @@ func shutdownSrv(ctx context.Context, srv *http.Server) {
return
}

const msgFmt = "shutting down http server %q: %s"
if errors.Is(err, context.Canceled) {
log.Debug(msgFmt, srv.Addr, err)
} else {
log.Error(msgFmt, srv.Addr, err)
lvl := slog.LevelDebug
if !errors.Is(err, context.Canceled) {
lvl = slog.LevelError
}

l.Log(ctx, lvl, "shutting down http server", "addr", srv.Addr, slogutil.KeyError, err)
}

// shutdownSrv3 shuts srv down and prints error messages to the log.
// shutdownSrv3 shuts down srv and logs the error, if any. l must not be nil.
//
// TODO(a.garipov): Think of a good way to merge with [shutdownSrv].
func shutdownSrv3(srv *http3.Server) {
defer log.OnPanic("")
func shutdownSrv3(ctx context.Context, l *slog.Logger, srv *http3.Server) {
defer slogutil.RecoverAndLog(ctx, l)

if srv == nil {
return
Expand All @@ -363,12 +379,12 @@ func shutdownSrv3(srv *http3.Server) {
return
}

const msgFmt = "shutting down http/3 server %q: %s"
if errors.Is(err, context.Canceled) {
log.Debug(msgFmt, srv.Addr, err)
} else {
log.Error(msgFmt, srv.Addr, err)
lvl := slog.LevelDebug
if !errors.Is(err, context.Canceled) {
lvl = slog.LevelError
}

l.Log(ctx, lvl, "shutting down http/3 server", "addr", srv.Addr, slogutil.KeyError, err)
}

// PasswordMinRunes is the minimum length of user's password in runes.
Expand Down Expand Up @@ -436,7 +452,7 @@ func (web *webAPI) handleInstallConfigure(w http.ResponseWriter, r *http.Request
// moment we'll allow setting up TLS in the initial configuration or the
// configuration itself will use HTTPS protocol, because the underlying
// functions potentially restart the HTTPS server.
err = startMods(web.logger)
err = startMods(web.baseLogger)
if err != nil {
Context.firstRun = true
copyInstallSettings(config, curConfig)
Expand Down Expand Up @@ -472,12 +488,11 @@ func (web *webAPI) handleInstallConfigure(w http.ResponseWriter, r *http.Request
// and with its own context, because it waits until all requests are handled
// and will be blocked by it's own caller.
go func(timeout time.Duration) {
defer log.OnPanic("web")

ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer slogutil.RecoverAndLog(ctx, web.logger)
defer cancel()

shutdownSrv(ctx, web.httpServer)
shutdownSrv(ctx, web.logger, web.httpServer)
}(shutdownTimeout)
}

Expand Down
42 changes: 26 additions & 16 deletions internal/home/controlupdate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"os/exec"
Expand All @@ -16,7 +17,8 @@ import (
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
"github.com/AdguardTeam/AdGuardHome/internal/updater"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/golibs/logutil/slogutil"
"github.com/AdguardTeam/golibs/osutil"
)

// temporaryError is the interface for temporary errors from the Go standard
Expand Down Expand Up @@ -52,7 +54,7 @@ func (web *webAPI) handleVersionJSON(w http.ResponseWriter, r *http.Request) {
}
}

err = web.requestVersionInfo(resp, req.Recheck)
err = web.requestVersionInfo(r.Context(), resp, req.Recheck)
if err != nil {
// Don't wrap the error, because it's informative enough as is.
aghhttp.Error(r, w, http.StatusBadGateway, "%s", err)
Expand All @@ -73,7 +75,11 @@ func (web *webAPI) handleVersionJSON(w http.ResponseWriter, r *http.Request) {

// requestVersionInfo sets the VersionInfo field of resp if it can reach the
// update server.
func (web *webAPI) requestVersionInfo(resp *versionResponse, recheck bool) (err error) {
func (web *webAPI) requestVersionInfo(
ctx context.Context,
resp *versionResponse,
recheck bool,
) (err error) {
updater := web.conf.updater
for range 3 {
resp.VersionInfo, err = updater.VersionInfo(recheck)
Expand All @@ -89,7 +95,9 @@ func (web *webAPI) requestVersionInfo(resp *versionResponse, recheck bool) (err
// See https://github.com/AdguardTeam/AdGuardHome/issues/934.
const sleepTime = 2 * time.Second

log.Info("update: temp net error: %v; sleeping for %s and retrying", err, sleepTime)
err = fmt.Errorf("temp net error: %w; sleeping for %s and retrying", err, sleepTime)
web.logger.InfoContext(ctx, "updating version info", slogutil.KeyError, err)

time.Sleep(sleepTime)

continue
Expand Down Expand Up @@ -140,7 +148,7 @@ func (web *webAPI) handleUpdate(w http.ResponseWriter, r *http.Request) {
// The background context is used because the underlying functions wrap it
// with timeout and shut down the server, which handles current request. It
// also should be done in a separate goroutine for the same reason.
go finishUpdate(context.Background(), execPath, web.conf.runningAsService)
go finishUpdate(context.Background(), web.logger, execPath, web.conf.runningAsService)
}

// versionResponse is the response for /control/version.json endpoint.
Expand Down Expand Up @@ -180,15 +188,17 @@ func tlsConfUsesPrivilegedPorts(c *tlsConfigSettings) (ok bool) {
return c.Enabled && (c.PortHTTPS < 1024 || c.PortDNSOverTLS < 1024 || c.PortDNSOverQUIC < 1024)
}

// finishUpdate completes an update procedure.
func finishUpdate(ctx context.Context, execPath string, runningAsService bool) {
var err error
// 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) {
defer slogutil.RecoverAndExit(ctx, l, osutil.ExitCodeFailure)

log.Info("stopping all tasks")
l.InfoContext(ctx, "stopping all tasks")

cleanup(ctx)
cleanupAlways()

var err error
if runtime.GOOS == "windows" {
if runningAsService {
// NOTE: We can't restart the service via "kardianos/service"
Expand All @@ -199,28 +209,28 @@ func finishUpdate(ctx context.Context, execPath string, runningAsService bool) {
cmd := exec.Command("cmd", "/c", "net stop AdGuardHome & net start AdGuardHome")
err = cmd.Start()
if err != nil {
log.Fatalf("restarting: stopping: %s", err)
panic(fmt.Errorf("restarting service: %w", err))
}

os.Exit(0)
os.Exit(osutil.ExitCodeSuccess)
}

cmd := exec.Command(execPath, os.Args[1:]...)
log.Info("restarting: %q %q", execPath, os.Args[1:])
l.InfoContext(ctx, "restarting", "exec_path", execPath, "args", os.Args[1:])
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
log.Fatalf("restarting:: %s", err)
panic(fmt.Errorf("restarting: %w", err))
}

os.Exit(0)
os.Exit(osutil.ExitCodeSuccess)
}

log.Info("restarting: %q %q", execPath, os.Args[1:])
l.InfoContext(ctx, "restarting", "exec_path", execPath, "args", os.Args[1:])
err = syscall.Exec(execPath, os.Args, os.Environ())
if err != nil {
log.Fatalf("restarting: %s", err)
panic(fmt.Errorf("restarting: %w", err))
}
}
2 changes: 1 addition & 1 deletion internal/home/dns.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func onConfigModified() {

// initDNS updates all the fields of the [Context] needed to initialize the DNS
// server and initializes it at last. It also must not be called unless
// [config] and [Context] are initialized. l must not be nil.
// [config] and [Context] are initialized. baseLogger must not be nil.
func initDNS(baseLogger *slog.Logger, statsDir, querylogDir string) (err error) {
anonymizer := config.anonymizer()

Expand Down
Loading

0 comments on commit 0a9f826

Please sign in to comment.