mirror of
https://github.com/AdguardTeam/AdGuardHome.git
synced 2026-12-05 06:34:30 +09:00
Pull request: AGDNS-3826-use-executil-run
Squashed commit of the following: commit 59e53b9e5fe5f0ed342c4c4581f847613e3268d5 Merge: b965a7dcda3866c68eAuthor: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Thu Apr 2 10:11:29 2026 +0700 Merge remote-tracking branch 'origin/master' into AGDNS-3826-use-executil-run commit b965a7dcdbbed2058ec0f05800a2c5925a8b2766 Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Thu Apr 2 10:08:26 2026 +0700 scripts: imp code commit ea8efa085bd9fd5bacd6b899c052f0197f2ea9af Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Thu Apr 2 08:50:17 2026 +0700 ossvc: imp code commit 2ba0269f9cd13298dd1aaa0e6d9dd9e0c9879df2 Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Wed Apr 1 08:32:10 2026 +0700 ossvc: imp tests commit 5141a0a86ae17173a502d4a65315917bc36143b0 Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Tue Mar 31 12:33:45 2026 +0700 ossvc: imp tests commit 3ec53df0c200cb59ef0d7841b21aeab9f39bf8ad Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Tue Mar 31 10:53:23 2026 +0700 ossvc: imp tests commit 3030f92f7f8b745e387bb42e6d9af3f0fd8fbb6b Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Tue Mar 31 09:19:16 2026 +0700 ossvc: imp code commit 4644f3fe20e0f711da91adf98faf4a88dad932a2 Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Tue Mar 31 09:18:54 2026 +0700 all: imp code commit 282ee76141dabcaf37df555db41db2c2cc82472d Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Tue Mar 31 09:08:54 2026 +0700 osvc: imp tests commit 8e4634570ac71ce4f16fe3796cc64d774c7dc257 Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Mon Mar 30 16:14:15 2026 +0700 osvc: imp tests commit 3abade03bed5d45e900c2e579c65eb5cc66990a7 Merge: 56ae2eb4f55d0d6ae5Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Mon Mar 30 11:03:35 2026 +0700 Merge remote-tracking branch 'origin/master' into AGDNS-3826-use-executil-run commit 56ae2eb4f8caea427afb87f46e90f21ae8d9fa39 Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Fri Mar 27 10:43:07 2026 +0700 aghnet: imp logs commit 7ead0907d39fab66602ab1d94ec17a477338b371 Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Thu Mar 26 12:47:23 2026 +0700 all: imp code commit afa235d8acfeb8b4286a26b60dddd61545533761 Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Thu Mar 26 12:38:30 2026 +0700 all: rm aghos.RunCommand commit bd36b286f26b068e145b5ffe2d2d23fb7c5525fa Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Thu Mar 26 12:38:21 2026 +0700 ossvc: rm aghos.RunCommand commit bba1e37aa4a34f557cec9653abc2e90816e39054 Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Thu Mar 26 12:13:05 2026 +0700 ossvc: pass cmd cons commit 6cc18f7801d669beb2188f79692a4a590fce2885 Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Thu Mar 26 11:38:21 2026 +0700 scripts: rm aghos.RunCommand commit 37d188db6fa5d5da1138299be549dbc9d00fd1b7 Author: Dimitry Kolyshev <dkolyshev@adguard.com> Date: Thu Mar 26 11:02:46 2026 +0700 aghnet: rm aghos.RunCommand
This commit is contained in:
1 parent
a3866c68ed
commit
1d491ad0f3
18 files changed
+550
-213
No files matched your search
@@ -11,10 +11,6 @@ import (
|
||||
"github.com/AdguardTeam/golibs/testutil/fakeos/fakeexec"
|
||||
)
|
||||
|
||||
// DefaultOutputLimit is the default limit of bytes for commands' standard
|
||||
// output and standard error.
|
||||
const DefaultOutputLimit = 512
|
||||
|
||||
// ConfigModifier defines an interface for updating the global configuration.
|
||||
type ConfigModifier interface {
|
||||
// Apply applies changes to the global configuration.
|
||||
|
||||
@@ -13,9 +13,13 @@ import (
|
||||
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/ioutil"
|
||||
"github.com/AdguardTeam/golibs/osutil/executil"
|
||||
)
|
||||
|
||||
// networkSetupCmd is the command to configure network settings.
|
||||
const networkSetupCmd = "networksetup"
|
||||
|
||||
// hardwarePortInfo contains information about the current state of the internet
|
||||
// connection obtained from macOS networksetup.
|
||||
type hardwarePortInfo struct {
|
||||
@@ -72,14 +76,21 @@ func getNetworkSetupHardwareReports(
|
||||
ctx context.Context,
|
||||
cmdCons executil.CommandConstructor,
|
||||
) (reports map[string]string) {
|
||||
_, out, err := aghos.RunCommand(ctx, cmdCons, "networksetup", "-listallhardwareports")
|
||||
stdout := bytes.Buffer{}
|
||||
stderr := bytes.Buffer{}
|
||||
err := executil.Run(ctx, cmdCons, &executil.CommandConfig{
|
||||
Stderr: &stderr,
|
||||
Stdout: ioutil.NewTruncatedWriter(&stdout, aghos.MaxCmdOutputSize),
|
||||
Path: networkSetupCmd,
|
||||
Args: []string{"-listallhardwareports"},
|
||||
})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
reports = make(map[string]string)
|
||||
|
||||
matches := hardwareReportsReg.FindAllSubmatch(out, -1)
|
||||
matches := hardwareReportsReg.FindAllSubmatch(stdout.Bytes(), -1)
|
||||
for _, m := range matches {
|
||||
reports[string(m[2])] = string(m[1])
|
||||
}
|
||||
@@ -98,11 +109,19 @@ func getHardwarePortInfo(
|
||||
cmdCons executil.CommandConstructor,
|
||||
hardwarePort string,
|
||||
) (h hardwarePortInfo, err error) {
|
||||
_, out, err := aghos.RunCommand(ctx, cmdCons, "networksetup", "-getinfo", hardwarePort)
|
||||
stdout := bytes.Buffer{}
|
||||
stderr := bytes.Buffer{}
|
||||
err = executil.Run(ctx, cmdCons, &executil.CommandConfig{
|
||||
Stderr: &stderr,
|
||||
Stdout: ioutil.NewTruncatedWriter(&stdout, aghos.MaxCmdOutputSize),
|
||||
Path: networkSetupCmd,
|
||||
Args: []string{"-getinfo", hardwarePort},
|
||||
})
|
||||
if err != nil {
|
||||
return h, err
|
||||
}
|
||||
|
||||
out := stdout.Bytes()
|
||||
match := hardwarePortReg.FindSubmatch(out)
|
||||
if len(match) != 4 {
|
||||
return h, errors.Error("could not find hardware port info")
|
||||
@@ -140,19 +159,18 @@ func ifaceSetStaticIP(
|
||||
|
||||
args := append([]string{"-setdnsservers", portInfo.name}, dnsAddrs...)
|
||||
|
||||
// Setting DNS servers is necessary when configuring a static IP
|
||||
code, _, err := aghos.RunCommand(ctx, cmdCons, "networksetup", args...)
|
||||
// Setting DNS servers is necessary when configuring a static IP.
|
||||
err = executil.RunWithPeek(ctx, cmdCons, aghos.MaxCmdOutputSize, networkSetupCmd, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if code != 0 {
|
||||
return fmt.Errorf("failed to set DNS servers, code=%d", code)
|
||||
return fmt.Errorf("networksetup failed to set dns servers: %w", err)
|
||||
}
|
||||
|
||||
// Actually configures hardware port to have static IP
|
||||
code, _, err = aghos.RunCommand(
|
||||
// Actually configures hardware port to have static IP.
|
||||
err = executil.RunWithPeek(
|
||||
ctx,
|
||||
cmdCons,
|
||||
"networksetup",
|
||||
aghos.MaxCmdOutputSize,
|
||||
networkSetupCmd,
|
||||
"-setmanual",
|
||||
portInfo.name,
|
||||
portInfo.ip,
|
||||
@@ -160,9 +178,7 @@ func ifaceSetStaticIP(
|
||||
portInfo.gatewayIP,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if code != 0 {
|
||||
return fmt.Errorf("failed to set DNS servers, code=%d", code)
|
||||
return fmt.Errorf("networksetup failed to configure dns servers: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -81,7 +81,7 @@ func TestIfaceHasStaticIP(t *testing.T) {
|
||||
}),
|
||||
ifaceName: "en0",
|
||||
wantHas: assert.False,
|
||||
wantErrMsg: `command "networksetup" failed: running: can't get: `,
|
||||
wantErrMsg: "running: can't get",
|
||||
}, {
|
||||
name: "port_bad_output",
|
||||
cmdCons: agh.NewMultipleCommandConstructor(agh.ExternalCommand{
|
||||
@@ -215,8 +215,9 @@ func TestIfaceSetStaticIP(t *testing.T) {
|
||||
Out: "",
|
||||
Code: 0,
|
||||
}),
|
||||
fsys: succFsys,
|
||||
wantErrMsg: `command "networksetup" failed: running: can't set: `,
|
||||
fsys: succFsys,
|
||||
wantErrMsg: `networksetup failed to set dns servers: running: can't set; ` +
|
||||
`stderr peek: ""; stdout peek: ""`,
|
||||
}, {
|
||||
name: "set_manual_error",
|
||||
cmdCons: agh.NewMultipleCommandConstructor(agh.ExternalCommand{
|
||||
@@ -240,8 +241,9 @@ func TestIfaceSetStaticIP(t *testing.T) {
|
||||
Out: "",
|
||||
Code: 0,
|
||||
}),
|
||||
fsys: succFsys,
|
||||
wantErrMsg: `command "networksetup" failed: running: can't set: `,
|
||||
fsys: succFsys,
|
||||
wantErrMsg: `networksetup failed to configure dns servers: running: can't set; ` +
|
||||
`stderr peek: ""; stdout peek: ""`,
|
||||
}}
|
||||
|
||||
for _, tc := range testCases {
|
||||
|
||||
@@ -38,9 +38,6 @@ func substRootDirFS(tb testing.TB, fsys fs.FS) {
|
||||
rootDirFS = fsys
|
||||
}
|
||||
|
||||
// RunCmdFunc is the signature of aghos.RunCommand function.
|
||||
type RunCmdFunc func(cmd string, args ...string) (code int, out []byte, err error)
|
||||
|
||||
// ifaceAddrsFunc is the signature of net.InterfaceAddrs function.
|
||||
type ifaceAddrsFunc func() (ifaces []net.Addr, err error)
|
||||
|
||||
|
||||
@@ -19,8 +19,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/ioutil"
|
||||
"github.com/AdguardTeam/golibs/osutil"
|
||||
"github.com/AdguardTeam/golibs/osutil/executil"
|
||||
)
|
||||
|
||||
@@ -52,46 +50,6 @@ func HaveAdminRights() (bool, error) {
|
||||
// bytes.
|
||||
const MaxCmdOutputSize = 64 * 1024
|
||||
|
||||
// RunCommand runs shell command.
|
||||
//
|
||||
// TODO(s.chzhen): Consider removing this after addressing the current behavior
|
||||
// where a non-zero exit code is returned together with a nil error.
|
||||
func RunCommand(
|
||||
ctx context.Context,
|
||||
cmdCons executil.CommandConstructor,
|
||||
command string,
|
||||
arguments ...string,
|
||||
) (code int, output []byte, err error) {
|
||||
stdoutBuf := bytes.Buffer{}
|
||||
stderrBuf := bytes.Buffer{}
|
||||
|
||||
err = executil.Run(
|
||||
ctx,
|
||||
cmdCons,
|
||||
&executil.CommandConfig{
|
||||
Path: command,
|
||||
Args: arguments,
|
||||
Stdout: ioutil.NewTruncatedWriter(&stdoutBuf, MaxCmdOutputSize),
|
||||
Stderr: &stderrBuf,
|
||||
},
|
||||
)
|
||||
|
||||
if err == nil {
|
||||
return osutil.ExitCodeSuccess, stdoutBuf.Bytes(), nil
|
||||
}
|
||||
|
||||
code, ok := executil.ExitCodeFromError(err)
|
||||
if ok {
|
||||
// Mirror the old behavior and return a nil-error on non-zero code
|
||||
// status.
|
||||
return code, stderrBuf.Bytes(), nil
|
||||
}
|
||||
|
||||
code = osutil.ExitCodeFailure
|
||||
|
||||
return code, nil, fmt.Errorf("command %q failed: %w: %s", command, err, &stdoutBuf)
|
||||
}
|
||||
|
||||
// psArgs holds the default ps arguments to avoid per-call slice allocations.
|
||||
//
|
||||
// Don't use -C flag here since it's a feature of linux's ps
|
||||
|
||||
@@ -24,9 +24,6 @@ const testTimeout = 1 * time.Second
|
||||
// testdata is the filesystem containing data for testing the package.
|
||||
var testdata fs.FS = os.DirFS("./testdata")
|
||||
|
||||
// RunCmdFunc is the signature of aghos.RunCommand function.
|
||||
type RunCmdFunc func(cmd string, args ...string) (code int, out []byte, err error)
|
||||
|
||||
func Test_New(t *testing.T) {
|
||||
var a Interface
|
||||
require.NotPanics(t, func() { a = New(slogutil.NewDiscardLogger()) })
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/aghalg"
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/aghnet"
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/version"
|
||||
"github.com/AdguardTeam/golibs/container"
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
@@ -171,7 +172,7 @@ func (req *checkConfReq) validateDNS(
|
||||
}
|
||||
|
||||
// Try to fix automatically.
|
||||
canAutofix = checkDNSStubListener(ctx, l)
|
||||
canAutofix = checkDNSStubListener(ctx, l, cmdCons)
|
||||
if canAutofix && req.DNS.Autofix {
|
||||
if derr := disableDNSStubListener(ctx, l, cmdCons); derr != nil {
|
||||
l.ErrorContext(ctx, "disabling DNSStubListener", slogutil.KeyError, derr)
|
||||
@@ -262,8 +263,13 @@ func handleStaticIP(
|
||||
return ipResp
|
||||
}
|
||||
|
||||
// checkDNSStubListener returns true if DNSStubListener is active.
|
||||
func checkDNSStubListener(ctx context.Context, l *slog.Logger) (ok bool) {
|
||||
// checkDNSStubListener returns true if DNSStubListener is active. l and
|
||||
// cmdCons must not be nil.
|
||||
func checkDNSStubListener(
|
||||
ctx context.Context,
|
||||
l *slog.Logger,
|
||||
cmdCons executil.CommandConstructor,
|
||||
) (ok bool) {
|
||||
if runtime.GOOS != "linux" {
|
||||
return false
|
||||
}
|
||||
@@ -281,8 +287,8 @@ func checkDNSStubListener(ctx context.Context, l *slog.Logger) (ok bool) {
|
||||
|
||||
err := executil.RunWithPeek(
|
||||
ctx,
|
||||
executil.SystemCommandConstructor{},
|
||||
agh.DefaultOutputLimit,
|
||||
cmdCons,
|
||||
aghos.MaxCmdOutputSize,
|
||||
cmd.Key,
|
||||
cmd.Value...,
|
||||
)
|
||||
@@ -339,7 +345,7 @@ func disableDNSStubListener(
|
||||
err = executil.RunWithPeek(
|
||||
ctx,
|
||||
cmdCons,
|
||||
agh.DefaultOutputLimit,
|
||||
aghos.MaxCmdOutputSize,
|
||||
systemctlCmd,
|
||||
systemctlArgs...,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package ossvc_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/ossvc"
|
||||
"github.com/kardianos/service"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConfigureServiceOptions(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const (
|
||||
vInfo = "v1.0.0"
|
||||
serviceName = "test-service"
|
||||
svcInfoKey = "SvcInfo"
|
||||
)
|
||||
|
||||
t.Run("nil_option", func(t *testing.T) {
|
||||
conf := &service.Config{
|
||||
Name: serviceName,
|
||||
}
|
||||
|
||||
ossvc.ConfigureServiceOptions(conf, vInfo)
|
||||
require.NotNil(t, conf.Option)
|
||||
|
||||
svcInfo, ok := conf.Option[svcInfoKey]
|
||||
require.True(t, ok)
|
||||
|
||||
assert.Contains(t, svcInfo, vInfo)
|
||||
})
|
||||
|
||||
t.Run("existing_option", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const (
|
||||
key = "ExistingKey"
|
||||
val = "ExistingValue"
|
||||
)
|
||||
|
||||
conf := &service.Config{
|
||||
Name: serviceName,
|
||||
Option: map[string]any{
|
||||
key: val,
|
||||
},
|
||||
}
|
||||
|
||||
ossvc.ConfigureServiceOptions(conf, vInfo)
|
||||
require.NotNil(t, conf.Option)
|
||||
|
||||
assert.Equal(t, val, conf.Option[key])
|
||||
|
||||
svcInfo, ok := conf.Option[svcInfoKey]
|
||||
require.True(t, ok)
|
||||
|
||||
assert.Contains(t, svcInfo, vInfo)
|
||||
})
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/logutil/slogutil"
|
||||
"github.com/AdguardTeam/golibs/osutil/executil"
|
||||
"github.com/kardianos/service"
|
||||
)
|
||||
@@ -30,7 +31,7 @@ type manager struct {
|
||||
func newManager(ctx context.Context, conf *ManagerConfig) (mgr *manager) {
|
||||
// Call chooseSystem explicitly to introduce platform-specific support for
|
||||
// service package. It's a noop for other GOOS values.
|
||||
chooseSystem(ctx, conf.Logger)
|
||||
chooseSystem(ctx, conf.Logger, conf.CommandConstructor)
|
||||
|
||||
return &manager{
|
||||
logger: conf.Logger,
|
||||
@@ -91,9 +92,12 @@ func (m *manager) Status(ctx context.Context, name ServiceName) (status Status,
|
||||
|
||||
svcStatus, err := s.Status()
|
||||
if err != nil && m.isUnixSystemV {
|
||||
var code int
|
||||
code, err = m.runInitdCommand(ctx, string(name), "status")
|
||||
if err != nil || code != 0 {
|
||||
m.logger.DebugContext(ctx, "got error from status request", slogutil.KeyError, err)
|
||||
|
||||
err = m.runInitdCommand(ctx, string(name), "status")
|
||||
if err != nil {
|
||||
m.logger.DebugContext(ctx, "got error from init.d command", slogutil.KeyError, err)
|
||||
|
||||
// Treat an error or non-zero exit code as stopped status on Unix
|
||||
// System V.
|
||||
//
|
||||
@@ -151,7 +155,7 @@ func (m *manager) install(ctx context.Context, action *ActionInstall) (err error
|
||||
// On OpenWrt it is important to run enable after the service
|
||||
// installation. Otherwise, the service won't start on the system
|
||||
// startup.
|
||||
_, err = m.runInitdCommand(ctx, string(action.ServiceName), "enable")
|
||||
err = m.runInitdCommand(ctx, string(action.ServiceName), "enable")
|
||||
if err != nil {
|
||||
return fmt.Errorf("enabling service on openwrt: %w", err)
|
||||
}
|
||||
@@ -174,7 +178,7 @@ func (m *manager) restart(ctx context.Context, action *ActionRestart) (err error
|
||||
|
||||
err = s.Restart()
|
||||
if err != nil && m.isUnixSystemV {
|
||||
_, initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "restart")
|
||||
initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "restart")
|
||||
if initdErr != nil {
|
||||
return fmt.Errorf("%w (restarting via init.d: %w)", err, initdErr)
|
||||
}
|
||||
@@ -201,7 +205,7 @@ func (m *manager) start(ctx context.Context, action *ActionStart) (err error) {
|
||||
|
||||
err = s.Start()
|
||||
if err != nil && m.isUnixSystemV {
|
||||
_, initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "start")
|
||||
initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "start")
|
||||
if initdErr != nil {
|
||||
return fmt.Errorf("%w (starting via init.d: %w)", err, initdErr)
|
||||
}
|
||||
@@ -225,7 +229,7 @@ func (m *manager) stop(ctx context.Context, action *ActionStop) (err error) {
|
||||
|
||||
err = s.Stop()
|
||||
if err != nil && m.isUnixSystemV {
|
||||
_, initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "stop")
|
||||
initdErr := m.runInitdCommand(ctx, string(action.ServiceName), "stop")
|
||||
if initdErr != nil {
|
||||
return fmt.Errorf("%w (stopping via init.d: %w)", err, initdErr)
|
||||
}
|
||||
@@ -241,7 +245,7 @@ func (m *manager) uninstall(ctx context.Context, action *ActionUninstall) (err e
|
||||
if m.isOpenWrt {
|
||||
// On OpenWrt it is important to run disable command first as it will
|
||||
// remove the symlink.
|
||||
_, err = m.runInitdCommand(ctx, string(action.ServiceName), "disable")
|
||||
err = m.runInitdCommand(ctx, string(action.ServiceName), "disable")
|
||||
if err != nil {
|
||||
return fmt.Errorf("disabling service on openwrt: %w", err)
|
||||
}
|
||||
@@ -299,22 +303,25 @@ func removeLaunchdStdLogs(ctx context.Context, logger *slog.Logger) {
|
||||
}
|
||||
}
|
||||
|
||||
// runInitdCommand runs init.d service command. It returns command code or
|
||||
// error if any.
|
||||
// runInitdCommand runs init.d service command. Returns an error if any.
|
||||
//
|
||||
// TODO(e.burkov): Move to manager_linux.go.
|
||||
func (m *manager) runInitdCommand(
|
||||
ctx context.Context,
|
||||
serviceName string,
|
||||
action string,
|
||||
) (code int, err error) {
|
||||
) (err error) {
|
||||
confPath := filepath.Join("/etc", "init.d", serviceName)
|
||||
// Pass the script and action as a single string argument.
|
||||
//
|
||||
// TODO(e.burkov): Use CommandConstructor.
|
||||
code, _, err = aghos.RunCommand(ctx, m.cmdCons, "sh", "-c", confPath, action)
|
||||
|
||||
return code, err
|
||||
return executil.RunWithPeek(
|
||||
ctx,
|
||||
m.cmdCons,
|
||||
aghos.MaxCmdOutputSize,
|
||||
"sh",
|
||||
"-c",
|
||||
confPath,
|
||||
action,
|
||||
)
|
||||
}
|
||||
|
||||
// emptyInterface is an empty implementation of the [service.Interface], as the
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
package ossvc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/osutil/executil"
|
||||
"github.com/AdguardTeam/golibs/testutil"
|
||||
"github.com/kardianos/service"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestManager_Status(t *testing.T) {
|
||||
const invalidSvcStatus = statusRestartOnFail + 1
|
||||
|
||||
svc := newTestSvc(t)
|
||||
|
||||
m := &manager{
|
||||
logger: testLogger,
|
||||
cmdCons: executil.EmptyCommandConstructor{},
|
||||
isOpenWrt: aghos.IsOpenWrt(),
|
||||
isUnixSystemV: false,
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
onStatus func() (s service.Status, err error)
|
||||
name string
|
||||
wantErrMessage string
|
||||
wantStatus Status
|
||||
}{{
|
||||
onStatus: func() (s service.Status, err error) {
|
||||
return service.StatusUnknown, service.ErrNotInstalled
|
||||
},
|
||||
name: "not_installed",
|
||||
wantStatus: StatusNotInstalled,
|
||||
wantErrMessage: "",
|
||||
}, {
|
||||
onStatus: func() (s service.Status, err error) {
|
||||
return service.StatusRunning, errors.Error("test")
|
||||
},
|
||||
name: "error",
|
||||
wantStatus: "",
|
||||
wantErrMessage: "getting service status: test",
|
||||
}, {
|
||||
onStatus: func() (s service.Status, err error) {
|
||||
return service.StatusRunning, nil
|
||||
},
|
||||
name: "running",
|
||||
wantStatus: StatusRunning,
|
||||
wantErrMessage: "",
|
||||
}, {
|
||||
onStatus: func() (s service.Status, err error) {
|
||||
return service.StatusStopped, nil
|
||||
},
|
||||
name: "stopped",
|
||||
wantStatus: StatusStopped,
|
||||
wantErrMessage: "",
|
||||
}, {
|
||||
onStatus: func() (s service.Status, err error) {
|
||||
return statusRestartOnFail, nil
|
||||
},
|
||||
name: "restart_on_fail",
|
||||
wantStatus: StatusRestartOnFail,
|
||||
wantErrMessage: "",
|
||||
}, {
|
||||
onStatus: func() (s service.Status, err error) {
|
||||
return invalidSvcStatus, nil
|
||||
},
|
||||
name: "invalid_status",
|
||||
wantStatus: "",
|
||||
wantErrMessage: fmt.Sprintf(
|
||||
"service status: %v: %v",
|
||||
errors.ErrBadEnumValue,
|
||||
invalidSvcStatus,
|
||||
),
|
||||
}}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
svc.OnStatus = tc.onStatus
|
||||
|
||||
ctx := testutil.ContextWithTimeout(t, testTimeout)
|
||||
status, err := m.Status(ctx, testServiceName)
|
||||
assert.Equal(t, tc.wantStatus, status)
|
||||
testutil.AssertErrorMsg(t, tc.wantErrMessage, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_Status_unixSystemV(t *testing.T) {
|
||||
svc := newTestSvc(t)
|
||||
svc.OnStatus = func() (s service.Status, err error) {
|
||||
return service.StatusUnknown, errors.Error("test")
|
||||
}
|
||||
|
||||
m := &manager{
|
||||
logger: testLogger,
|
||||
cmdCons: executil.EmptyCommandConstructor{},
|
||||
isOpenWrt: aghos.IsOpenWrt(),
|
||||
isUnixSystemV: true,
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
cmdCons executil.CommandConstructor
|
||||
name string
|
||||
wantStatus Status
|
||||
}{{
|
||||
cmdCons: newTestCmdConstructor(t, "", nil),
|
||||
name: "running",
|
||||
wantStatus: StatusRunning,
|
||||
}, {
|
||||
cmdCons: newTestCmdConstructor(t, "", errors.Error("test")),
|
||||
name: "stopped",
|
||||
wantStatus: StatusStopped,
|
||||
}}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
m.cmdCons = tc.cmdCons
|
||||
|
||||
ctx := testutil.ContextWithTimeout(t, testTimeout)
|
||||
|
||||
status, err := m.Status(ctx, testServiceName)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tc.wantStatus, status)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// newTestSvc creates a new *testService with all methods set to panic, sets it
|
||||
// in the chosen system, and returns it. The caller can then set the desired
|
||||
// behavior of the service via overriding its methods.
|
||||
func newTestSvc(tb testing.TB) (svc *testService) {
|
||||
tb.Helper()
|
||||
|
||||
svc = &testService{
|
||||
OnRun: func() (err error) { panic(testutil.UnexpectedCall()) },
|
||||
OnStart: func() (err error) { panic(testutil.UnexpectedCall()) },
|
||||
OnStop: func() (err error) { panic(testutil.UnexpectedCall()) },
|
||||
OnRestart: func() (err error) { panic(testutil.UnexpectedCall()) },
|
||||
OnInstall: func() (err error) { panic(testutil.UnexpectedCall()) },
|
||||
OnUninstall: func() (err error) { panic(testutil.UnexpectedCall()) },
|
||||
OnStatus: func() (s service.Status, err error) { panic(testutil.UnexpectedCall()) },
|
||||
}
|
||||
|
||||
service.ChooseSystem(&testSystem{
|
||||
OnNew: func(_ service.Interface, _ *service.Config) (s service.Service, err error) {
|
||||
return svc, nil
|
||||
},
|
||||
})
|
||||
|
||||
return svc
|
||||
}
|
||||
@@ -10,8 +10,6 @@ import (
|
||||
// Manager is the interface for communication with the OS service manager.
|
||||
//
|
||||
// TODO(e.burkov): Move to golibs.
|
||||
//
|
||||
// TODO(e.burkov): Use.
|
||||
type Manager interface {
|
||||
// Perform performs the specified action.
|
||||
Perform(ctx context.Context, action Action) (err error)
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package ossvc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/AdguardTeam/golibs/logutil/slogutil"
|
||||
"github.com/AdguardTeam/golibs/osutil/executil"
|
||||
"github.com/AdguardTeam/golibs/testutil/fakeos/fakeexec"
|
||||
"github.com/kardianos/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// testTimeout is the common timeout for tests.
|
||||
const testTimeout = 1 * time.Second
|
||||
|
||||
// testServiceName is a common service name for tests.
|
||||
const testServiceName = "AdGuardHome"
|
||||
|
||||
// testLogger is a common logger for tests.
|
||||
var testLogger = slogutil.NewDiscardLogger()
|
||||
|
||||
// testSystem is a mock implementation of [service.System] for tests.
|
||||
type testSystem struct {
|
||||
OnNew func(_ service.Interface, _ *service.Config) (svc service.Service, err error)
|
||||
}
|
||||
|
||||
// type check
|
||||
var _ service.System = (*testSystem)(nil)
|
||||
|
||||
// New implements the [service.System] interface for *testSystem.
|
||||
func (ts *testSystem) New(i service.Interface, c *service.Config) (svc service.Service, err error) {
|
||||
return ts.OnNew(i, c)
|
||||
}
|
||||
|
||||
// String implements the [service.System] interface for *testSystem.
|
||||
func (ts *testSystem) String() (s string) {
|
||||
return "testSystem"
|
||||
}
|
||||
|
||||
// Detect implements the [service.System] interface for *testSystem.
|
||||
func (ts *testSystem) Detect() (ok bool) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Interactive implements the [service.System] interface for *testSystem.
|
||||
func (ts *testSystem) Interactive() (ok bool) {
|
||||
return true
|
||||
}
|
||||
|
||||
// testService is a mock implementation of [service.Service] for tests.
|
||||
type testService struct {
|
||||
OnRun func() (err error)
|
||||
OnStart func() (err error)
|
||||
OnStop func() (err error)
|
||||
OnRestart func() (err error)
|
||||
OnInstall func() (err error)
|
||||
OnUninstall func() (err error)
|
||||
OnStatus func() (s service.Status, err error)
|
||||
}
|
||||
|
||||
// type check
|
||||
var _ service.Service = (*testService)(nil)
|
||||
|
||||
// Run implements the [service.Service] interface for *testService.
|
||||
func (t *testService) Run() (err error) {
|
||||
return t.OnRun()
|
||||
}
|
||||
|
||||
// Start implements the [service.Service] interface for *testService.
|
||||
func (t *testService) Start() (err error) {
|
||||
return t.OnStart()
|
||||
}
|
||||
|
||||
// Stop implements the [service.Service] interface for *testService.
|
||||
func (t *testService) Stop() (err error) {
|
||||
return t.OnStop()
|
||||
}
|
||||
|
||||
// Restart implements the [service.Service] interface for *testService.
|
||||
func (t *testService) Restart() (err error) {
|
||||
return t.OnRestart()
|
||||
}
|
||||
|
||||
// Install implements the [service.Service] interface for *testService.
|
||||
func (t *testService) Install() (err error) {
|
||||
return t.OnInstall()
|
||||
}
|
||||
|
||||
// Uninstall implements the [service.Service] interface for *testService.
|
||||
func (t *testService) Uninstall() (err error) {
|
||||
return t.OnUninstall()
|
||||
}
|
||||
|
||||
// Logger implements the [service.Service] interface for *testService.
|
||||
func (t *testService) Logger(errs chan<- error) (l service.Logger, err error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// SystemLogger implements the [service.Service] interface for *testService.
|
||||
func (t *testService) SystemLogger(errs chan<- error) (l service.Logger, err error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// String implements the [service.Service] interface for *testService.
|
||||
func (t *testService) String() (s string) {
|
||||
return testServiceName
|
||||
}
|
||||
|
||||
// Platform implements the [service.Service] interface for *testService.
|
||||
func (t *testService) Platform() (s string) {
|
||||
return "testPlatform"
|
||||
}
|
||||
|
||||
// Status implements the [service.Service] interface for *testService.
|
||||
func (t *testService) Status() (s service.Status, err error) {
|
||||
return t.OnStatus()
|
||||
}
|
||||
|
||||
// newTestCmdConstructor is a helper that creates a new command constructor. The
|
||||
// returned constructor creates [fakeexec.Command] instances that print the
|
||||
// given body to the command's standard output and return the error.
|
||||
func newTestCmdConstructor(
|
||||
tb testing.TB,
|
||||
body string,
|
||||
returnErr error,
|
||||
) (c executil.CommandConstructor) {
|
||||
tb.Helper()
|
||||
|
||||
onNew := func(
|
||||
_ context.Context,
|
||||
conf *executil.CommandConfig,
|
||||
) (c executil.Command, err error) {
|
||||
cmd := fakeexec.NewCommand()
|
||||
cmd.OnStart = func(_ context.Context) (err error) {
|
||||
_, err = io.WriteString(conf.Stdout, body)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return returnErr
|
||||
}
|
||||
|
||||
cmd.OnWait = func(_ context.Context) (err error) { return nil }
|
||||
|
||||
return cmd, nil
|
||||
}
|
||||
|
||||
return &fakeexec.CommandConstructor{
|
||||
OnNew: onNew,
|
||||
}
|
||||
}
|
||||
@@ -18,13 +18,14 @@ import (
|
||||
"github.com/kardianos/service"
|
||||
)
|
||||
|
||||
// chooseSystem replaces the currently selected system with a wrapper. l must
|
||||
// not be nil.
|
||||
func chooseSystem(_ context.Context, l *slog.Logger) {
|
||||
// chooseSystem replaces the currently selected system with a wrapper. l and
|
||||
// cmdCons must not be nil.
|
||||
func chooseSystem(_ context.Context, l *slog.Logger, cmdCons executil.CommandConstructor) {
|
||||
sys := service.ChosenSystem()
|
||||
service.ChooseSystem(&darwinSystem{
|
||||
System: sys,
|
||||
logger: l,
|
||||
System: sys,
|
||||
cmdCons: cmdCons,
|
||||
logger: l,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -32,7 +33,8 @@ func chooseSystem(_ context.Context, l *slog.Logger) {
|
||||
// implementation of the [service.Service] interface.
|
||||
type darwinSystem struct {
|
||||
service.System
|
||||
logger *slog.Logger
|
||||
cmdCons executil.CommandConstructor
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// type check
|
||||
@@ -51,7 +53,7 @@ func (d *darwinSystem) New(i service.Interface, c *service.Config) (s service.Se
|
||||
return newDarwinService(&darwinServiceConfig{
|
||||
svc: s,
|
||||
logger: d.logger,
|
||||
cmdCons: executil.SystemCommandConstructor{},
|
||||
cmdCons: d.cmdCons,
|
||||
name: c.Name,
|
||||
plistDir: "/Library/LaunchDaemons",
|
||||
}), nil
|
||||
|
||||
@@ -3,70 +3,23 @@
|
||||
package ossvc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"testing"
|
||||
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/logutil/slogutil"
|
||||
"github.com/AdguardTeam/golibs/osutil/executil"
|
||||
"github.com/AdguardTeam/golibs/testutil"
|
||||
"github.com/AdguardTeam/golibs/testutil/fakeos/fakeexec"
|
||||
"github.com/kardianos/service"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// newTestCmdConstructor is a helper that creates a new command constructor. The
|
||||
// returned constructor creates [fakeexec.Command] instances that print the
|
||||
// given body to the command's standard output and return the error.
|
||||
func newTestCmdConstructor(
|
||||
tb testing.TB,
|
||||
body string,
|
||||
returnErr error,
|
||||
) (c executil.CommandConstructor) {
|
||||
tb.Helper()
|
||||
|
||||
onNew := func(
|
||||
_ context.Context,
|
||||
conf *executil.CommandConfig,
|
||||
) (c executil.Command, err error) {
|
||||
cmd := fakeexec.NewCommand()
|
||||
cmd.OnStart = func(_ context.Context) (err error) {
|
||||
_, err = io.WriteString(conf.Stdout, body)
|
||||
require.NoError(tb, err)
|
||||
|
||||
return returnErr
|
||||
}
|
||||
|
||||
cmd.OnWait = func(_ context.Context) (err error) { return nil }
|
||||
|
||||
return cmd, nil
|
||||
}
|
||||
|
||||
return &fakeexec.CommandConstructor{
|
||||
OnNew: onNew,
|
||||
}
|
||||
}
|
||||
|
||||
func TestDarwinService_Status(t *testing.T) {
|
||||
name := "AdGuardHome"
|
||||
t.Parallel()
|
||||
|
||||
plistDir := t.TempDir()
|
||||
svc := newDarwinService(&darwinServiceConfig{
|
||||
logger: slogutil.NewDiscardLogger(),
|
||||
plistDir: plistDir,
|
||||
name: name,
|
||||
})
|
||||
|
||||
t.Run("not_installed", func(t *testing.T) {
|
||||
status, err := svc.Status()
|
||||
assert.Equal(t, service.StatusUnknown, status)
|
||||
assert.ErrorIs(t, err, service.ErrNotInstalled)
|
||||
})
|
||||
|
||||
plistPath := path.Join(plistDir, name+".plist")
|
||||
plistPath := path.Join(plistDir, testServiceName+".plist")
|
||||
file, err := os.Create(plistPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -102,7 +55,13 @@ func TestDarwinService_Status(t *testing.T) {
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
svc.cmdCons = newTestCmdConstructor(t, tc.body, tc.cmdErr)
|
||||
svc := newDarwinService(&darwinServiceConfig{
|
||||
logger: testLogger,
|
||||
cmdCons: newTestCmdConstructor(t, tc.body, tc.cmdErr),
|
||||
plistDir: plistDir,
|
||||
name: testServiceName,
|
||||
})
|
||||
|
||||
var status service.Status
|
||||
status, err = svc.Status()
|
||||
require.NoError(t, err)
|
||||
@@ -111,3 +70,17 @@ func TestDarwinService_Status(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDarwinService_Status_notInstalled(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
svc := newDarwinService(&darwinServiceConfig{
|
||||
logger: testLogger,
|
||||
cmdCons: executil.EmptyCommandConstructor{},
|
||||
name: testServiceName,
|
||||
})
|
||||
|
||||
status, err := svc.Status()
|
||||
assert.Equal(t, service.StatusUnknown, status)
|
||||
assert.ErrorIs(t, err, service.ErrNotInstalled)
|
||||
}
|
||||
@@ -17,8 +17,8 @@ import (
|
||||
)
|
||||
|
||||
// chooseSystem checks the current system detected and substitutes it with local
|
||||
// implementation if needed. l must not be nil.
|
||||
func chooseSystem(ctx context.Context, l *slog.Logger) {
|
||||
// implementation if needed. l and cmdCons must not be nil.
|
||||
func chooseSystem(ctx context.Context, l *slog.Logger, cmdCons executil.CommandConstructor) {
|
||||
sys := service.ChosenSystem()
|
||||
switch sys.String() {
|
||||
case "unix-systemv":
|
||||
@@ -29,13 +29,13 @@ func chooseSystem(ctx context.Context, l *slog.Logger) {
|
||||
// See https://github.com/AdguardTeam/AdGuardHome/issues/4480 and
|
||||
// https://github.com/AdguardTeam/AdGuardHome/issues/4677.
|
||||
if !aghos.IsOpenWrt() {
|
||||
service.ChooseSystem(&sysvSystem{System: sys})
|
||||
service.ChooseSystem(&sysvSystem{System: sys, cmdCons: cmdCons})
|
||||
l.DebugContext(ctx, "using custom SysV system")
|
||||
|
||||
return
|
||||
}
|
||||
case "linux-systemd":
|
||||
service.ChooseSystem(&systemdSystem{System: sys})
|
||||
service.ChooseSystem(&systemdSystem{System: sys, cmdCons: cmdCons})
|
||||
l.DebugContext(ctx, "using custom systemd system")
|
||||
|
||||
return
|
||||
@@ -51,6 +51,9 @@ func chooseSystem(ctx context.Context, l *slog.Logger) {
|
||||
type sysvSystem struct {
|
||||
// System must have an unexported type *service.linuxSystemService.
|
||||
service.System
|
||||
|
||||
// cmdCons is used to run external commands. It must not be nil.
|
||||
cmdCons executil.CommandConstructor
|
||||
}
|
||||
|
||||
// type check
|
||||
@@ -67,7 +70,7 @@ func (sys *sysvSystem) New(i service.Interface, c *service.Config) (s service.Se
|
||||
}
|
||||
|
||||
return &sysvService{
|
||||
cmdCons: executil.SystemCommandConstructor{},
|
||||
cmdCons: sys.cmdCons,
|
||||
Service: s,
|
||||
name: c.Name,
|
||||
}, nil
|
||||
@@ -99,10 +102,14 @@ func (svc *sysvService) Install() (err error) {
|
||||
}
|
||||
|
||||
// TODO(s.chzhen): Pass context.
|
||||
_, _, err = aghos.RunCommand(context.TODO(), svc.cmdCons, "update-rc.d", svc.name, "defaults")
|
||||
|
||||
// Don't wrap an error since it's informative enough as is.
|
||||
return err
|
||||
return executil.RunWithPeek(
|
||||
context.TODO(),
|
||||
svc.cmdCons,
|
||||
aghos.MaxCmdOutputSize,
|
||||
"update-rc.d",
|
||||
svc.name,
|
||||
"defaults",
|
||||
)
|
||||
}
|
||||
|
||||
// Uninstall implements the [service.Service] interface for *sysvService.
|
||||
@@ -115,10 +122,14 @@ func (svc *sysvService) Uninstall() (err error) {
|
||||
}
|
||||
|
||||
// TODO(s.chzhen): Pass context.
|
||||
_, _, err = aghos.RunCommand(context.TODO(), svc.cmdCons, "update-rc.d", svc.name, "remove")
|
||||
|
||||
// Don't wrap an error since it's informative enough as is.
|
||||
return err
|
||||
return executil.RunWithPeek(
|
||||
context.TODO(),
|
||||
svc.cmdCons,
|
||||
aghos.MaxCmdOutputSize,
|
||||
"update-rc.d",
|
||||
svc.name,
|
||||
"remove",
|
||||
)
|
||||
}
|
||||
|
||||
// systemdSystem is a wrapper for a [service.System] that returns the custom
|
||||
@@ -126,6 +137,9 @@ func (svc *sysvService) Uninstall() (err error) {
|
||||
type systemdSystem struct {
|
||||
// System must have an unexported type *service.linuxSystemService.
|
||||
service.System
|
||||
|
||||
// cmdCons is used to run external commands. It must not be nil.
|
||||
cmdCons executil.CommandConstructor
|
||||
}
|
||||
|
||||
// type check
|
||||
@@ -142,7 +156,7 @@ func (sys *systemdSystem) New(i service.Interface, c *service.Config) (s service
|
||||
}
|
||||
|
||||
return &systemdService{
|
||||
cmdCons: executil.SystemCommandConstructor{},
|
||||
cmdCons: sys.cmdCons,
|
||||
Service: s,
|
||||
unitName: fmt.Sprintf("%s.service", c.Name),
|
||||
}, nil
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
package ossvc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
"fmt"
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/ioutil"
|
||||
"github.com/AdguardTeam/golibs/log"
|
||||
"github.com/AdguardTeam/golibs/osutil/executil"
|
||||
"github.com/kardianos/service"
|
||||
@@ -34,33 +36,37 @@ import (
|
||||
const sysVersion = "openbsd-runcom"
|
||||
|
||||
// chooseSystem checks the current system detected and substitutes it with local
|
||||
// implementation if needed.
|
||||
func chooseSystem(_ context.Context, _ *slog.Logger) {
|
||||
service.ChooseSystem(openbsdSystem{})
|
||||
// implementation if needed. cmdCons must not be nil.
|
||||
func chooseSystem(_ context.Context, _ *slog.Logger, cmdCons executil.CommandConstructor) {
|
||||
service.ChooseSystem(&openbsdSystem{
|
||||
cmdCons: cmdCons,
|
||||
})
|
||||
}
|
||||
|
||||
// openbsdSystem is the service.System to be used on the OpenBSD.
|
||||
type openbsdSystem struct{}
|
||||
type openbsdSystem struct {
|
||||
cmdCons executil.CommandConstructor
|
||||
}
|
||||
|
||||
// String implements service.System interface for openbsdSystem.
|
||||
func (openbsdSystem) String() string {
|
||||
func (sys *openbsdSystem) String() string {
|
||||
return sysVersion
|
||||
}
|
||||
|
||||
// Detect implements service.System interface for openbsdSystem.
|
||||
func (openbsdSystem) Detect() (ok bool) {
|
||||
func (sys *openbsdSystem) Detect() (ok bool) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Interactive implements service.System interface for openbsdSystem.
|
||||
func (openbsdSystem) Interactive() (ok bool) {
|
||||
func (sys *openbsdSystem) Interactive() (ok bool) {
|
||||
return os.Getppid() != 1
|
||||
}
|
||||
|
||||
// New implements service.System interface for openbsdSystem.
|
||||
func (openbsdSystem) New(i service.Interface, c *service.Config) (s service.Service, err error) {
|
||||
func (sys *openbsdSystem) New(i service.Interface, c *service.Config) (s service.Service, err error) {
|
||||
return &openbsdRunComService{
|
||||
cmdCons: executil.SystemCommandConstructor{},
|
||||
cmdCons: sys.cmdCons,
|
||||
i: i,
|
||||
cfg: c,
|
||||
}, nil
|
||||
@@ -216,16 +222,14 @@ func (s *openbsdRunComService) configureSysStartup(enable bool) (err error) {
|
||||
}
|
||||
|
||||
// TODO(s.chzhen): Pass context.
|
||||
ctx := context.TODO()
|
||||
var code int
|
||||
code, _, err = aghos.RunCommand(ctx, s.cmdCons, "rcctl", cmd, s.cfg.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if code != 0 {
|
||||
return fmt.Errorf("rcctl finished with code %d", code)
|
||||
}
|
||||
|
||||
return nil
|
||||
return executil.RunWithPeek(
|
||||
context.TODO(),
|
||||
s.cmdCons,
|
||||
aghos.MaxCmdOutputSize,
|
||||
"rcctl",
|
||||
cmd,
|
||||
s.cfg.Name,
|
||||
)
|
||||
}
|
||||
|
||||
// writeScript tries to write the script for the service.
|
||||
@@ -319,19 +323,25 @@ func (s *openbsdRunComService) runCom(cmd string) (out string, err error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// TODO(s.chzhen): Pass context.
|
||||
ctx := context.TODO()
|
||||
stdoutBuf := bytes.Buffer{}
|
||||
stderrBuf := bytes.Buffer{}
|
||||
|
||||
// TODO(e.burkov): It's possible that os.ErrNotExist is caused by
|
||||
// something different than the service script's non-existence. Keep it
|
||||
// in mind, when replace the aghos.RunCommand.
|
||||
var outData []byte
|
||||
_, outData, err = aghos.RunCommand(ctx, s.cmdCons, scriptPath, cmd)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
// TODO(s.chzhen): Pass context.
|
||||
err = executil.Run(context.TODO(), s.cmdCons, &executil.CommandConfig{
|
||||
Stderr: &stderrBuf,
|
||||
Stdout: ioutil.NewTruncatedWriter(&stdoutBuf, aghos.MaxCmdOutputSize),
|
||||
Path: scriptPath,
|
||||
Args: []string{cmd},
|
||||
})
|
||||
|
||||
switch {
|
||||
case errors.Is(err, os.ErrNotExist):
|
||||
return "", service.ErrNotInstalled
|
||||
case err != nil:
|
||||
return stderrBuf.String(), err
|
||||
}
|
||||
|
||||
return string(outData), err
|
||||
return stdoutBuf.String(), nil
|
||||
}
|
||||
|
||||
// Status implements service.Service interface for *openbsdRunComService.
|
||||
|
||||
@@ -5,8 +5,10 @@ package ossvc
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"github.com/AdguardTeam/golibs/osutil/executil"
|
||||
)
|
||||
|
||||
// chooseSystem checks the current system detected and substitutes it with local
|
||||
// implementation if needed.
|
||||
func chooseSystem(_ context.Context, _ *slog.Logger) {}
|
||||
func chooseSystem(_ context.Context, _ *slog.Logger, _ executil.CommandConstructor) {}
|
||||
@@ -315,16 +315,10 @@ func autoAdd(ctx context.Context, l *slog.Logger, basePath string) (err error) {
|
||||
err = handleAdds(ctx, l, cmdCons, adds)
|
||||
if err != nil {
|
||||
// Don't wrap the error since it's informative enough as is.
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
|
||||
err = handleDels(ctx, l, cmdCons, dels)
|
||||
if err != nil {
|
||||
// Don't wrap the error since it's informative enough as is.
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil
|
||||
return handleDels(ctx, l, cmdCons, dels)
|
||||
}
|
||||
|
||||
// gitCmd is the shell command for Git.
|
||||
@@ -344,10 +338,9 @@ func handleAdds(
|
||||
gitArgs := append([]string{"add"}, locales...)
|
||||
l.DebugContext(ctx, "executing", "cmd", gitCmd, "args", gitArgs)
|
||||
|
||||
code, out, err := aghos.RunCommand(ctx, cmdCons, gitCmd, gitArgs...)
|
||||
|
||||
if err != nil || code != 0 {
|
||||
return fmt.Errorf("git add exited with code %d output %q: %w", code, out, err)
|
||||
err = executil.RunWithPeek(ctx, cmdCons, aghos.MaxCmdOutputSize, gitCmd, gitArgs...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("git add failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -367,10 +360,9 @@ func handleDels(
|
||||
gitArgs := append([]string{"restore"}, locales...)
|
||||
l.DebugContext(ctx, "executing", "cmd", gitCmd, "args", gitArgs)
|
||||
|
||||
code, out, err := aghos.RunCommand(ctx, cmdCons, gitCmd, gitArgs...)
|
||||
|
||||
if err != nil || code != 0 {
|
||||
return fmt.Errorf("git restore exited with code %d output %q: %w", code, out, err)
|
||||
err = executil.RunWithPeek(ctx, cmdCons, aghos.MaxCmdOutputSize, gitCmd, gitArgs...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("git restore failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
Reference in new issue
Block a user