diff --git a/internal/ossvc/config.go b/internal/ossvc/config.go new file mode 100644 index 000000000..fee9b969d --- /dev/null +++ b/internal/ossvc/config.go @@ -0,0 +1,18 @@ +package ossvc + +import ( + "fmt" + "time" + + "github.com/kardianos/service" +) + +// configureServiceOptions defines additional settings of the service +// configuration. conf must not be nil. +// +//lint:ignore U1000 TODO(e.burkov): Use. +func configureServiceOptions(conf *service.Config, versionInfo string) { + conf.Option["SvcInfo"] = fmt.Sprintf("%s %s", versionInfo, time.Now()) + + configureOSOptions(conf) +} diff --git a/internal/ossvc/config_darwin.go b/internal/ossvc/config_darwin.go new file mode 100644 index 000000000..36e2f65fc --- /dev/null +++ b/internal/ossvc/config_darwin.go @@ -0,0 +1,48 @@ +//go:build darwin + +package ossvc + +import ( + "github.com/kardianos/service" +) + +// configureServiceOptions defines additional settings of the service +// configuration on macOS. conf must not be nil. +func configureOSOptions(conf *service.Config) { + conf.Option["LaunchdConfig"] = launchdConfig +} + +// launchdConfig is the template for Launchd service file. Basically the same +// template as the one defined in github.com/kardianos/service but with two +// additional keys: +// - StandardOutPath +// - StandardErrorPath +// +//lint:ignore U1000 TODO(e.burkov): Use. +const launchdConfig = ` + + + +Label{{html .Name}} +ProgramArguments + + {{html .Path}} +{{range .Config.Arguments}} + {{html .}} +{{end}} + +{{if .UserName}}UserName{{html .UserName}}{{end}} +{{if .ChRoot}}RootDirectory{{html .ChRoot}}{{end}} +{{if .WorkingDirectory}}WorkingDirectory{{html .WorkingDirectory}}{{end}} +SessionCreate<{{bool .SessionCreate}}/> +KeepAlive<{{bool .KeepAlive}}/> +RunAtLoad<{{bool .RunAtLoad}}/> +Disabled +StandardOutPath +` + launchdStdoutPath + ` +StandardErrorPath +` + launchdStderrPath + ` + + +` diff --git a/internal/ossvc/config_freebsd.go b/internal/ossvc/config_freebsd.go new file mode 100644 index 000000000..4658c4547 --- /dev/null +++ b/internal/ossvc/config_freebsd.go @@ -0,0 +1,36 @@ +//go:build freebsd + +package ossvc + +import ( + "github.com/kardianos/service" +) + +// configureServiceOptions defines additional settings of the service +// configuration on FreeBSD. conf must not be nil. +func configureOSOptions(conf *service.Config) { + conf.Option["SysvScript"] = freeBSDScript +} + +// freeBSDScript is the source of the daemon script for FreeBSD. Keep as close +// as possible to the https://github.com/kardianos/service/blob/18c957a3dc1120a2efe77beb401d476bade9e577/service_freebsd.go#L204. +// +//lint:ignore U1000 TODO(e.burkov): Use. +const freeBSDScript = `#!/bin/sh +# PROVIDE: {{.Name}} +# REQUIRE: networking +# KEYWORD: shutdown + +. /etc/rc.subr + +name="{{.Name}}" +{{.Name}}_env="IS_DAEMON=1" +{{.Name}}_user="root" +pidfile_child="/var/run/${name}.pid" +pidfile="/var/run/${name}_daemon.pid" +command="/usr/sbin/daemon" +daemon_args="-P ${pidfile} -p ${pidfile_child} -r -t ${name}" +command_args="${daemon_args} {{.Path}}{{range .Arguments}} {{.}}{{end}}" + +run_rc_command "$1" +` diff --git a/internal/ossvc/config_linux.go b/internal/ossvc/config_linux.go new file mode 100644 index 000000000..ba5e16538 --- /dev/null +++ b/internal/ossvc/config_linux.go @@ -0,0 +1,228 @@ +//go:build linux + +package ossvc + +import ( + "github.com/AdguardTeam/AdGuardHome/internal/aghos" + "github.com/kardianos/service" +) + +// configureServiceOptions defines additional settings of the service +// configuration on Linux. conf must not be nil. +func configureOSOptions(conf *service.Config) { + conf.Option["LogOutput"] = true + conf.Option["Restart"] = "always" + + conf.Dependencies = []string{ + "After=syslog.target network-online.target", + } + + conf.Option["SystemdScript"] = systemdScript + + // Use different scripts on OpenWrt. + if aghos.IsOpenWrt() { + conf.Option["SysvScript"] = openWrtScript + } else { + conf.Option["SysvScript"] = sysvScript + } +} + +// systemdScript is an improved version of the systemd script originally from +// the systemdScript constant in file service_systemd_linux.go in module +// github.com/kardianos/service. The following changes have been made: +// +// 1. The RestartSec setting is set to a lower value of 10 to make sure we +// always restart quickly. +// +// 2. The StandardOutput and StandardError settings are set to redirect the +// output to the systemd journal, see +// https://man7.org/linux/man-pages/man5/systemd.exec.5.html#LOGGING_AND_STANDARD_INPUT/OUTPUT. +// +//lint:ignore U1000 TODO(e.burkov): Use. +const systemdScript = `[Unit] +Description={{.Description}} +ConditionFileIsExecutable={{.Path|cmdEscape}} +{{range $i, $dep := .Dependencies}} +{{$dep}} {{end}} + +[Service] +StartLimitInterval=5 +StartLimitBurst=10 +ExecStart={{.Path|cmdEscape}}{{range .Arguments}} {{.|cmd}}{{end}} +{{if .ChRoot}}RootDirectory={{.ChRoot|cmd}}{{end}} +{{if .WorkingDirectory}}WorkingDirectory={{.WorkingDirectory|cmdEscape}}{{end}} +{{if .UserName}}User={{.UserName}}{{end}} +{{if .ReloadSignal}}ExecReload=/bin/kill -{{.ReloadSignal}} "$MAINPID"{{end}} +{{if .PIDFile}}PIDFile={{.PIDFile|cmd}}{{end}} +{{if and .LogOutput .HasOutputFileSupport -}} +StandardOutput=journal +StandardError=journal +{{- end}} +{{if gt .LimitNOFILE -1 }}LimitNOFILE={{.LimitNOFILE}}{{end}} +{{if .Restart}}Restart={{.Restart}}{{end}} +{{if .SuccessExitStatus}}SuccessExitStatus={{.SuccessExitStatus}}{{end}} +RestartSec=10 +EnvironmentFile=-/etc/sysconfig/{{.Name}} + +[Install] +WantedBy=multi-user.target +` + +// sysvScript is the source of the daemon script for SysV-based Linux systems. +// Keep as close as possible to the https://github.com/kardianos/service/blob/29f8c79c511bc18422bb99992779f96e6bc33921/service_sysv_linux.go#L187. +// +// Use ps command instead of reading the procfs since it's a more +// implementation-independent approach. +// +//lint:ignore U1000 TODO(e.burkov): Use. +const sysvScript = `#!/bin/sh +# For RedHat and cousins: +# chkconfig: - 99 01 +# description: {{.Description}} +# processname: {{.Path}} + +### BEGIN INIT INFO +# Provides: {{.Path}} +# Required-Start: +# Required-Stop: +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: {{.DisplayName}} +# Description: {{.Description}} +### END INIT INFO + +cmd="{{.Path}}{{range .Arguments}} {{.|cmd}}{{end}}" + +name=$(basename $(readlink -f $0)) +pid_file="/var/run/$name.pid" +stdout_log="/var/log/$name.log" +stderr_log="/var/log/$name.err" + +[ -e /etc/sysconfig/$name ] && . /etc/sysconfig/$name + +get_pid() { + cat "$pid_file" +} + +is_running() { + [ -f "$pid_file" ] && ps -p "$(get_pid)" > /dev/null 2>&1 +} + +case "$1" in + start) + if is_running; then + echo "Already started" + else + echo "Starting $name" + {{if .WorkingDirectory}}cd '{{.WorkingDirectory}}'{{end}} + $cmd >> "$stdout_log" 2>> "$stderr_log" & + echo $! > "$pid_file" + if ! is_running; then + echo "Unable to start, see $stdout_log and $stderr_log" + exit 1 + fi + fi + ;; + stop) + if is_running; then + echo -n "Stopping $name.." + kill $(get_pid) + for i in $(seq 1 10) + do + if ! is_running; then + break + fi + echo -n "." + sleep 1 + done + echo + if is_running; then + echo "Not stopped; may still be shutting down or shutdown may have failed" + exit 1 + else + echo "Stopped" + if [ -f "$pid_file" ]; then + rm "$pid_file" + fi + fi + else + echo "Not running" + fi + ;; + restart) + $0 stop + if is_running; then + echo "Unable to stop, will not attempt to start" + exit 1 + fi + $0 start + ;; + status) + if is_running; then + echo "Running" + else + echo "Stopped" + exit 1 + fi + ;; + *) + echo "Usage: $0 {start|stop|restart|status}" + exit 1 + ;; +esac +exit 0 +` + +// OpenWrt procd init script +// https://github.com/AdguardTeam/AdGuardHome/internal/issues/1386 +// +//lint:ignore U1000 TODO(e.burkov): Use. +const openWrtScript = `#!/bin/sh /etc/rc.common + +USE_PROCD=1 + +START=95 +STOP=01 + +cmd="{{.Path}}{{range .Arguments}} {{.|cmd}}{{end}}" +name="{{.Name}}" +pid_file="/var/run/${name}.pid" + +start_service() { + echo "Starting ${name}" + + procd_open_instance + procd_set_param command ${cmd} + procd_set_param respawn # respawn automatically if something died + procd_set_param stdout 1 # forward stdout of the command to logd + procd_set_param stderr 1 # same for stderr + procd_set_param pidfile ${pid_file} # write a pid file on instance start and remove it on stop + + procd_close_instance + echo "${name} has been started" +} + +stop_service() { + echo "Stopping ${name}" +} + +EXTRA_COMMANDS="status" +EXTRA_HELP=" status Print the service status" + +get_pid() { + cat "${pid_file}" +} + +is_running() { + [ -f "${pid_file}" ] && ps | grep -v grep | grep $(get_pid) >/dev/null 2>&1 +} + +status() { + if is_running; then + echo "Running" + else + echo "Stopped" + exit 1 + fi +} +` diff --git a/internal/ossvc/config_openbsd.go b/internal/ossvc/config_openbsd.go new file mode 100644 index 000000000..09157884b --- /dev/null +++ b/internal/ossvc/config_openbsd.go @@ -0,0 +1,31 @@ +//go:build openbsd + +package ossvc + +import ( + "github.com/kardianos/service" +) + +// configureServiceOptions defines additional settings of the service +// configuration on OpenBSD. conf must not be nil. +func configureOSOptions(conf *service.Config) { + conf.Option["RunComScript"] = openBSDScript +} + +// openBSDScript is the source of the daemon script for OpenBSD. +// +//lint:ignore U1000 TODO(e.burkov): Use. +const openBSDScript = `#!/bin/ksh +# +# $OpenBSD: {{ .SvcInfo }} + +daemon="{{.Path}}" +daemon_flags={{ .Arguments | args }} +daemon_logger="daemon.info" + +. /etc/rc.d/rc.subr + +rc_bg=YES + +rc_cmd $1 +` diff --git a/internal/ossvc/config_windows.go b/internal/ossvc/config_windows.go new file mode 100644 index 000000000..b9c767a64 --- /dev/null +++ b/internal/ossvc/config_windows.go @@ -0,0 +1,9 @@ +//go:build windows + +package ossvc + +import "github.com/kardianos/service" + +// configureOSOptions defines additional settings of the service +// configuration on Windows. +func configureOSOptions(_ *service.Config) {} diff --git a/internal/ossvc/defaultmanager.go b/internal/ossvc/defaultmanager.go index 41df0f6fd..dc2362ce7 100644 --- a/internal/ossvc/defaultmanager.go +++ b/internal/ossvc/defaultmanager.go @@ -5,8 +5,12 @@ import ( _ "embed" "fmt" "log/slog" + "os" + "runtime" + "github.com/AdguardTeam/AdGuardHome/internal/aghos" "github.com/AdguardTeam/golibs/errors" + "github.com/AdguardTeam/golibs/osutil/executil" "github.com/kardianos/service" ) @@ -14,15 +18,21 @@ import ( // manager is the implementation of [Manager] that wraps [service.Service]. type manager struct { - logger *slog.Logger + logger *slog.Logger + cmdCons executil.CommandConstructor } // newManager creates a new [Manager] that wraps [service.Service]. // // TODO(e.burkov): Return error. func newManager(_ 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() + return &manager{ - logger: conf.Logger, + logger: conf.Logger, + cmdCons: conf.CommandConstructor, } } @@ -47,43 +57,6 @@ func (m *manager) Perform(ctx context.Context, action Action) (err error) { } } -// install installs the service in the service manager. -func (m *manager) install(ctx context.Context, action *ActionInstall) (err error) { - m.logger.InfoContext(ctx, "installing service", "name", action.ServiceConf.Name) - - s, err := service.New(nil, action.ServiceConf) - if err != nil { - return fmt.Errorf("creating service: %w", err) - } - - return s.Install() -} - -// reload stops, if not yet, and starts the configured service in the service -// manager. -func (m *manager) reload(ctx context.Context, action *ActionReload) (err error) { - m.logger.InfoContext(ctx, "reloading service", "name", action.ServiceConf.Name) - - s, err := service.New(nil, action.ServiceConf) - if err != nil { - return fmt.Errorf("creating service: %w", err) - } - - return s.Restart() -} - -// start starts the configured service in the service manager. -func (m *manager) start(ctx context.Context, action *ActionStart) (err error) { - m.logger.InfoContext(ctx, "starting service", "name", action.ServiceConf.Name) - - s, err := service.New(nil, action.ServiceConf) - if err != nil { - return fmt.Errorf("creating service: %w", err) - } - - return s.Start() -} - // Status implements the [Manager] interface for *manager. func (m *manager) Status(ctx context.Context, name ServiceName) (status Status, err error) { m.logger.InfoContext(ctx, "getting service status", "name", name) @@ -96,6 +69,16 @@ func (m *manager) Status(ctx context.Context, name ServiceName) (status Status, } svcStatus, err := s.Status() + if err != nil && service.Platform() == "unix-systemv" { + var code int + code, err = m.runInitdCommand(ctx, string(name), "status") + if err != nil || code != 0 { + return StatusStopped, nil + } + + return StatusRunning, nil + } + if err != nil { if errors.Is(err, service.ErrNotInstalled) { return StatusNotInstalled, nil @@ -114,6 +97,72 @@ func (m *manager) Status(ctx context.Context, name ServiceName) (status Status, } } +// install installs the service in the service manager. +func (m *manager) install(ctx context.Context, action *ActionInstall) (err error) { + m.logger.InfoContext(ctx, "installing service", "name", action.ServiceConf.Name) + + s, err := service.New(nil, action.ServiceConf) + if err != nil { + return fmt.Errorf("creating service: %w", err) + } + + if err = s.Install(); err != nil { + return fmt.Errorf("installing service: %w", err) + } + + if aghos.IsOpenWrt() { + // 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, action.ServiceConf.Name, "enable") + if err != nil { + return fmt.Errorf("enabling service on openwrt: %w", err) + } + } + + return nil +} + +// reload stops, if not yet, and starts the configured service in the service +// manager. +func (m *manager) reload(ctx context.Context, action *ActionReload) (err error) { + m.logger.InfoContext(ctx, "reloading service", "name", action.ServiceConf.Name) + + s, err := service.New(nil, action.ServiceConf) + if err != nil { + return fmt.Errorf("creating service: %w", err) + } + + err = s.Restart() + if err != nil && service.Platform() == "unix-systemv" { + _, err = m.runInitdCommand(ctx, action.ServiceConf.Name, "restart") + } + + return err +} + +// start starts the configured service in the service manager. +func (m *manager) start(ctx context.Context, action *ActionStart) (err error) { + m.logger.InfoContext(ctx, "starting service", "name", action.ServiceConf.Name) + + // Perform pre-check before starting service. + if err = aghos.PreCheckActionStart(); err != nil { + m.logger.ErrorContext(ctx, "pre-check failed", "err", err) + } + + s, err := service.New(nil, action.ServiceConf) + if err != nil { + return fmt.Errorf("creating service: %w", err) + } + + err = s.Start() + if err != nil && service.Platform() == "unix-systemv" { + _, err = m.runInitdCommand(ctx, action.ServiceConf.Name, "start") + } + + return err +} + // stop stops the service in the service manager. func (m *manager) stop(ctx context.Context, action *ActionStop) (err error) { m.logger.InfoContext(ctx, "stopping service", "name", action.ServiceConf.Name) @@ -123,17 +172,85 @@ func (m *manager) stop(ctx context.Context, action *ActionStop) (err error) { return fmt.Errorf("creating service: %w", err) } - return s.Stop() + err = s.Stop() + if err != nil && service.Platform() == "unix-systemv" { + _, err = m.runInitdCommand(ctx, action.ServiceConf.Name, "stop") + } + + return err } // uninstall uninstalls the service from the service manager. func (m *manager) uninstall(ctx context.Context, action *ActionUninstall) (err error) { m.logger.InfoContext(ctx, "uninstalling service", "name", action.ServiceConf.Name) + if aghos.IsOpenWrt() { + // On OpenWrt it is important to run disable command first as it will + // remove the symlink. + _, err = m.runInitdCommand(ctx, action.ServiceConf.Name, "disable") + if err != nil { + return fmt.Errorf("disabling service on openwrt: %w", err) + } + } + s, err := service.New(nil, action.ServiceConf) if err != nil { return fmt.Errorf("creating service: %w", err) } - return s.Uninstall() + if err = s.Stop(); err != nil { + m.logger.DebugContext(ctx, "stopping service", "err", err) + } + + if err = s.Uninstall(); err != nil { + return fmt.Errorf("uninstalling service: %w", err) + } + + removeLaunchdStdLogs(ctx, m.logger) + + return nil +} + +// Paths to stdout and stderr logs for Darwin service manager. +// +// TODO(e.burkov): Move to config_darwin.go. +const ( + launchdStdoutPath = "/var/log/AdGuardHome.stdout.log" + launchdStderrPath = "/var/log/AdGuardHome.stderr.log" +) + +// removeLaunchdStdLogs removes launchd stdout and stderr log files, if needed, +// and logs errors at warning level. +// +// TODO(e.burkov): Move to manager_darwin.go. +func removeLaunchdStdLogs(ctx context.Context, logger *slog.Logger) { + if runtime.GOOS != "darwin" { + return + } + + err := os.Remove(launchdStdoutPath) + if err != nil && !errors.Is(err, os.ErrNotExist) { + logger.WarnContext(ctx, "removing stdout file", "err", err) + } + + err = os.Remove(launchdStderrPath) + if err != nil && !errors.Is(err, os.ErrNotExist) { + logger.WarnContext(ctx, "removing stderr file", "err", err) + } +} + +// runInitdCommand runs init.d service command. It returns command code or +// 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) { + confPath := "/etc/init.d/" + serviceName + // Pass the script and action as a single string argument. + code, _, err = aghos.RunCommand(ctx, m.cmdCons, "sh", "-c", confPath, action) + + return code, err } diff --git a/internal/ossvc/service_linux.go b/internal/ossvc/service_linux.go new file mode 100644 index 000000000..053b76c6e --- /dev/null +++ b/internal/ossvc/service_linux.go @@ -0,0 +1,270 @@ +//go:build linux + +package ossvc + +import ( + "bufio" + "bytes" + "context" + "fmt" + "io" + "strings" + + "github.com/AdguardTeam/AdGuardHome/internal/aghos" + "github.com/AdguardTeam/golibs/osutil/executil" + "github.com/kardianos/service" +) + +// chooseSystem checks the current system detected and substitutes it with local +// implementation if needed. +func chooseSystem() { + sys := service.ChosenSystem() + switch sys.String() { + case "unix-systemv": + // By default, package service uses the SysV system if it cannot detect + // anything other, but the update-rc.d fix should not be applied on + // OpenWrt, so exclude it explicitly. + // + // See https://github.com/AdguardTeam/AdGuardHome/issues/4480 and + // https://github.com/AdguardTeam/AdGuardHome/issues/4677. + if !aghos.IsOpenWrt() { + service.ChooseSystem(&sysvSystem{System: sys}) + } + case "linux-systemd": + service.ChooseSystem(&systemdSystem{System: sys}) + default: + // Do nothing. + } +} + +// sysvSystem is a wrapper for a [service.System] that returns the custom +// implementation of the [service.Service] interface. +// +// TODO(e.burkov): File a PR to github.com/kardianos/service. +type sysvSystem struct { + // System must have an unexported type *service.linuxSystemService. + service.System +} + +// type check +var _ service.System = (*sysvSystem)(nil) + +// New implements the [service.System] interface for *sysvSystem. i and c must +// not be nil. +func (sys *sysvSystem) New(i service.Interface, c *service.Config) (s service.Service, err error) { + s, err = sys.System.New(i, c) + if err != nil { + // Don't wrap the error to keep it as close to the original one as + // possible. + return s, err + } + + return &sysvService{ + cmdCons: executil.SystemCommandConstructor{}, + Service: s, + name: c.Name, + }, nil +} + +// sysvService is a wrapper for a SysV [service.Service] that supplements the +// installation and uninstallation. +type sysvService struct { + // cmdCons is used to run external commands. It must not be nil. + cmdCons executil.CommandConstructor + + // Service must have an unexported type *service.sysv. + service.Service + + // name stores the name of the service to call updating script with it. + name string +} + +// type check +var _ service.Service = (*sysvService)(nil) + +// Install implements the [service.Service] interface for *sysvService. +func (svc *sysvService) Install() (err error) { + err = svc.Service.Install() + if err != nil { + // Don't wrap the error to keep it as close to the original one as + // possible. + return err + } + + // 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 +} + +// Uninstall implements the [service.Service] interface for *sysvService. +func (svc *sysvService) Uninstall() (err error) { + err = svc.Service.Uninstall() + if err != nil { + // Don't wrap the error to keep it as close to the original one as + // possible. + return err + } + + // 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 +} + +// systemdSystem is a wrapper for a [service.System] that returns the custom +// implementation of the [service.Service] interface. +type systemdSystem struct { + // System must have an unexported type *service.linuxSystemService. + service.System +} + +// type check +var _ service.System = (*systemdSystem)(nil) + +// New implements the [service.System] interface for *systemdSystem. i and c +// must not be nil. +func (sys *systemdSystem) New(i service.Interface, c *service.Config) (s service.Service, err error) { + s, err = sys.System.New(i, c) + if err != nil { + // Don't wrap the error to keep it as close to the original one as + // possible. + return s, err + } + + return &systemdService{ + cmdCons: executil.SystemCommandConstructor{}, + Service: s, + unitName: fmt.Sprintf("%s.service", c.Name), + }, nil +} + +// type check +var _ service.Service = (*systemdService)(nil) + +// systemdService is a wrapper for a systemd [service.Service] that enriches the +// service status information. +type systemdService struct { + // cmdCons is used to run external commands. It must not be nil. + cmdCons executil.CommandConstructor + + // Service is expected to have an unexported type *service.systemd. + service.Service + + // unitName stores the name of the systemd daemon. + unitName string +} + +// type check +var _ service.Service = (*systemdService)(nil) + +// Status implements the [service.Service] interface for *systemdService. +func (s *systemdService) Status() (status service.Status, err error) { + const systemctlCmd = "systemctl" + + var ( + systemctlArgs = []string{"show", s.unitName} + systemctlStdout bytes.Buffer + ) + + // TODO(s.chzhen): Consider streaming the output if needed. Using + // [io.Pipe] here is unnecessary; it complicates lifecycle management + // because the output must be read concurrently, and the PipeWriter must be + // explicitly closed to signal EOF. Since this command's output is small, a + // bytes.Buffer via executil.Run is sufficient. + err = executil.Run( + // TODO(s.chzhen): Pass context. + context.TODO(), + s.cmdCons, + &executil.CommandConfig{ + Path: systemctlCmd, + Args: systemctlArgs, + Stdout: &systemctlStdout, + }, + ) + if err != nil { + return service.StatusUnknown, fmt.Errorf("executing command: %w", err) + } + + status, err = parseSystemctlShow(&systemctlStdout) + if err != nil { + return service.StatusUnknown, fmt.Errorf("parsing command output: %w", err) + } + + return status, nil +} + +// Searched property names. See man systemctl(1). +const ( + propNameLoadState = "LoadState" + propNameActiveState = "ActiveState" + propNameSubState = "SubState" +) + +// parseSystemctlShow parses the output of the systemctl show command. It +// expects the key=value pairs separated by newlines. +func parseSystemctlShow(output io.Reader) (status service.Status, err error) { + var loadState, activeState, subState string + + scanner := bufio.NewScanner(output) + for scanner.Scan() { + line := scanner.Text() + + propName, propValue, ok := strings.Cut(line, "=") + if !ok { + return service.StatusUnknown, fmt.Errorf("unexpected line format: %q", line) + } + + switch propName { + case propNameLoadState: + loadState = propValue + case propNameActiveState: + activeState = propValue + case propNameSubState: + subState = propValue + default: + // Go on. + } + } + if err = scanner.Err(); err != nil { + return service.StatusUnknown, err + } + + return statusFromState(loadState, activeState, subState) +} + +// statusRestartOnFail is a custom status value used to indicate the service's +// state of restarting after failed start. +const statusRestartOnFail = service.StatusStopped + 1 + +// statusFromState returns the service status based on the systemctl state +// property values. +func statusFromState(loadState, activeState, subState string) (status service.Status, err error) { + // Desired property values. See man systemctl(1). + const ( + propValueLoadStateNotFound = "not-found" + propValueActiveStateActive = "active" + propValueActiveStateInactive = "inactive" + propValueSubStateAutoRestart = "auto-restart" + ) + + switch { + case loadState == propValueLoadStateNotFound: + return service.StatusUnknown, service.ErrNotInstalled + case activeState == propValueActiveStateActive: + return service.StatusRunning, nil + case activeState == propValueActiveStateInactive: + return service.StatusStopped, nil + case subState == propValueSubStateAutoRestart: + return statusRestartOnFail, nil + default: + return service.StatusUnknown, fmt.Errorf( + "unexpected state: %s=%q, %s=%q, %s=%q", + propNameLoadState, loadState, + propNameActiveState, activeState, + propNameSubState, subState, + ) + } +} diff --git a/internal/ossvc/service_openbsd.go b/internal/ossvc/service_openbsd.go new file mode 100644 index 000000000..d29431091 --- /dev/null +++ b/internal/ossvc/service_openbsd.go @@ -0,0 +1,442 @@ +//go:build openbsd + +package ossvc + +import ( + "cmp" + "context" + "fmt" + "os" + "os/signal" + "path/filepath" + "strings" + "syscall" + "text/template" + + "github.com/AdguardTeam/AdGuardHome/internal/aghos" + "github.com/AdguardTeam/golibs/errors" + "github.com/AdguardTeam/golibs/log" + "github.com/AdguardTeam/golibs/osutil/executil" + "github.com/kardianos/service" +) + +// OpenBSD Service Implementation +// +// The file contains OpenBSD implementations for service.System and +// service.Service interfaces. It uses the default approach for RunCom-based +// services systems, e.g. rc.d script. It's written as if it was in a separate +// package and has only one internal dependency. +// +// TODO(e.burkov): Perhaps, file a PR to github.com/kardianos/service. + +// sysVersion is the version of local service.System interface implementation. +const sysVersion = "openbsd-runcom" + +// chooseSystem checks the current system detected and substitutes it with local +// implementation if needed. +func chooseSystem() { + service.ChooseSystem(openbsdSystem{}) +} + +// openbsdSystem is the service.System to be used on the OpenBSD. +type openbsdSystem struct{} + +// String implements service.System interface for openbsdSystem. +func (openbsdSystem) String() string { + return sysVersion +} + +// Detect implements service.System interface for openbsdSystem. +func (openbsdSystem) Detect() (ok bool) { + return true +} + +// Interactive implements service.System interface for openbsdSystem. +func (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) { + return &openbsdRunComService{ + cmdCons: executil.SystemCommandConstructor{}, + i: i, + cfg: c, + }, nil +} + +// openbsdRunComService is the RunCom-based service.Service to be used on the +// OpenBSD. +type openbsdRunComService struct { + cmdCons executil.CommandConstructor + i service.Interface + cfg *service.Config +} + +// Platform implements service.Service interface for *openbsdRunComService. +func (*openbsdRunComService) Platform() (p string) { + return "openbsd" +} + +// String implements service.Service interface for *openbsdRunComService. +func (s *openbsdRunComService) String() string { + return cmp.Or(s.cfg.DisplayName, s.cfg.Name) +} + +// getBool returns the value of the given name from kv, assuming the value is a +// boolean. If the value isn't found or is not of the type, the defaultValue is +// returned. +func getBool(kv service.KeyValue, name string, defaultValue bool) (val bool) { + var ok bool + if val, ok = kv[name].(bool); ok { + return val + } + + return defaultValue +} + +// getString returns the value of the given name from kv, assuming the value is +// a string. If the value isn't found or is not of the type, the defaultValue +// is returned. +func getString(kv service.KeyValue, name, defaultValue string) (val string) { + var ok bool + if val, ok = kv[name].(string); ok { + return val + } + + return defaultValue +} + +// getFuncNiladic returns the value of the given name from kv, assuming the +// value is a func(). If the value isn't found or is not of the type, the +// defaultValue is returned. +func getFuncNiladic(kv service.KeyValue, name string, defaultValue func()) (val func()) { + var ok bool + if val, ok = kv[name].(func()); ok { + return val + } + + return defaultValue +} + +const ( + // optionUserService is the UserService option name. + optionUserService = "UserService" + + // optionUserServiceDefault is the UserService option default value. + optionUserServiceDefault = false + + // errNoUserServiceRunCom is returned when the service uses some custom + // path to script. + errNoUserServiceRunCom errors.Error = "user services are not supported on " + sysVersion +) + +// scriptPath returns the absolute path to the script. It's commonly used to +// send commands to the service. +func (s *openbsdRunComService) scriptPath() (cp string, err error) { + if getBool(s.cfg.Option, optionUserService, optionUserServiceDefault) { + return "", errNoUserServiceRunCom + } + + const scriptPathPref = "/etc/rc.d" + + return filepath.Join(scriptPathPref, s.cfg.Name), nil +} + +const ( + // optionRunComScript is the RunCom script option name. + optionRunComScript = "RunComScript" + + // runComScript is the default RunCom script. + runComScript = `#!/bin/sh +# +# $OpenBSD: {{ .SvcInfo }} + +daemon="{{.Path}}" +daemon_flags={{ .Arguments | args }} + +. /etc/rc.d/rc.subr + +rc_bg=YES + +rc_cmd $1 +` +) + +// template returns the script template to put into rc.d. +func (s *openbsdRunComService) template() (t *template.Template) { + tf := map[string]any{ + "args": func(sl []string) string { + return `"` + strings.Join(sl, " ") + `"` + }, + } + + return template.Must(template.New("").Funcs(tf).Parse(getString( + s.cfg.Option, + optionRunComScript, + runComScript, + ))) +} + +// execPath returns the absolute path to the executable to be run as a service. +func (s *openbsdRunComService) execPath() (path string, err error) { + if c := s.cfg; c != nil && len(c.Executable) != 0 { + return filepath.Abs(c.Executable) + } + + if path, err = os.Executable(); err != nil { + return "", err + } + + return filepath.Abs(path) +} + +// annotate wraps errors.Annotate applying a common error format. +func (s *openbsdRunComService) annotate(action string, err error) (annotated error) { + return errors.Annotate(err, "%s %s %s service: %w", action, sysVersion, s.cfg.Name) +} + +// Install implements service.Service interface for *openbsdRunComService. +func (s *openbsdRunComService) Install() (err error) { + defer func() { err = s.annotate("installing", err) }() + + if err = s.writeScript(); err != nil { + return err + } + + return s.configureSysStartup(true) +} + +// configureSysStartup adds s into the group of packages started with system. +func (s *openbsdRunComService) configureSysStartup(enable bool) (err error) { + cmd := "enable" + if !enable { + cmd = "disable" + } + + // 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 +} + +// writeScript tries to write the script for the service. +func (s *openbsdRunComService) writeScript() (err error) { + var scriptPath string + if scriptPath, err = s.scriptPath(); err != nil { + return err + } + + if _, err = os.Stat(scriptPath); !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("script already exists at %s", scriptPath) + } + + var execPath string + if execPath, err = s.execPath(); err != nil { + return err + } + + t := s.template() + f, err := os.Create(scriptPath) + if err != nil { + return fmt.Errorf("creating rc.d script file: %w", err) + } + defer f.Close() + + err = t.Execute(f, &struct { + *service.Config + Path string + SvcInfo string + }{ + Config: s.cfg, + Path: execPath, + SvcInfo: getString(s.cfg.Option, "SvcInfo", s.String()), + }) + if err != nil { + return err + } + + return errors.Annotate( + os.Chmod(scriptPath, 0o755), + "changing rc.d script file permissions: %w", + ) +} + +// Uninstall implements service.Service interface for *openbsdRunComService. +func (s *openbsdRunComService) Uninstall() (err error) { + defer func() { err = s.annotate("uninstalling", err) }() + + if err = s.configureSysStartup(false); err != nil { + return err + } + + var scriptPath string + if scriptPath, err = s.scriptPath(); err != nil { + return err + } + + if err = os.Remove(scriptPath); errors.Is(err, os.ErrNotExist) { + return service.ErrNotInstalled + } + + return errors.Annotate(err, "removing rc.d script: %w") +} + +// optionRunWait is the name of the option associated with function which waits +// for the service to be stopped. +const optionRunWait = "RunWait" + +// runWait is the default function to wait for service to be stopped. +func runWait() { + sigChan := make(chan os.Signal, 3) + signal.Notify(sigChan, syscall.SIGTERM, os.Interrupt) + <-sigChan +} + +// Run implements service.Service interface for *openbsdRunComService. +func (s *openbsdRunComService) Run() (err error) { + if err = s.i.Start(s); err != nil { + return err + } + + getFuncNiladic(s.cfg.Option, optionRunWait, runWait)() + + return s.i.Stop(s) +} + +// runCom calls the script with the specified cmd. +func (s *openbsdRunComService) runCom(cmd string) (out string, err error) { + var scriptPath string + if scriptPath, err = s.scriptPath(); err != nil { + return "", err + } + + // TODO(s.chzhen): Pass context. + ctx := context.TODO() + + // 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) { + return "", service.ErrNotInstalled + } + + return string(outData), err +} + +// Status implements service.Service interface for *openbsdRunComService. +func (s *openbsdRunComService) Status() (status service.Status, err error) { + defer func() { err = s.annotate("getting status of", err) }() + + var out string + if out, err = s.runCom("check"); err != nil { + return service.StatusUnknown, err + } + + name := s.cfg.Name + switch out { + case fmt.Sprintf("%s(ok)\n", name): + return service.StatusRunning, nil + case fmt.Sprintf("%s(failed)\n", name): + return service.StatusStopped, nil + default: + return service.StatusUnknown, service.ErrNotInstalled + } +} + +// Start implements service.Service interface for *openbsdRunComService. +func (s *openbsdRunComService) Start() (err error) { + _, err = s.runCom("start") + + return s.annotate("starting", err) +} + +// Stop implements service.Service interface for *openbsdRunComService. +func (s *openbsdRunComService) Stop() (err error) { + _, err = s.runCom("stop") + + return s.annotate("stopping", err) +} + +// Restart implements service.Service interface for *openbsdRunComService. +func (s *openbsdRunComService) Restart() (err error) { + if err = s.Stop(); err != nil { + return err + } + + return s.Start() +} + +// Logger implements service.Service interface for *openbsdRunComService. +func (s *openbsdRunComService) Logger(errs chan<- error) (l service.Logger, err error) { + if service.ChosenSystem().Interactive() { + return service.ConsoleLogger, nil + } + + return s.SystemLogger(errs) +} + +// SystemLogger implements service.Service interface for *openbsdRunComService. +func (s *openbsdRunComService) SystemLogger(errs chan<- error) (l service.Logger, err error) { + return newSysLogger(s.cfg.Name, errs) +} + +// newSysLogger returns a stub service.Logger implementation. +func newSysLogger(_ string, _ chan<- error) (service.Logger, error) { + return sysLogger{}, nil +} + +// sysLogger wraps calls of the logging functions understandable for service +// interfaces. +type sysLogger struct{} + +// Error implements service.Logger interface for sysLogger. +func (sysLogger) Error(v ...any) error { + log.Error("%s", fmt.Sprint(v...)) + + return nil +} + +// Warning implements service.Logger interface for sysLogger. +func (sysLogger) Warning(v ...any) error { + log.Info("warning: %s", fmt.Sprint(v...)) + + return nil +} + +// Info implements service.Logger interface for sysLogger. +func (sysLogger) Info(v ...any) error { + log.Info("%s", fmt.Sprint(v...)) + + return nil +} + +// Errorf implements service.Logger interface for sysLogger. +func (sysLogger) Errorf(format string, a ...any) error { + log.Error(format, a...) + + return nil +} + +// Warningf implements service.Logger interface for sysLogger. +func (sysLogger) Warningf(format string, a ...any) error { + log.Info("warning: %s", fmt.Sprintf(format, a...)) + + return nil +} + +// Infof implements service.Logger interface for sysLogger. +func (sysLogger) Infof(format string, a ...any) error { + log.Info(format, a...) + + return nil +} diff --git a/internal/ossvc/service_others.go b/internal/ossvc/service_others.go new file mode 100644 index 000000000..4ec6c5914 --- /dev/null +++ b/internal/ossvc/service_others.go @@ -0,0 +1,7 @@ +//go:build !openbsd && !linux + +package ossvc + +// chooseSystem checks the current system detected and substitutes it with local +// implementation if needed. +func chooseSystem() {}