Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

service: forwarders carry a spec, and can run as a Windows service

shukieshah44c4a2b7cda6
diff --git a/cli/beacon/internal/endpoint/service/forwarder.go b/cli/beacon/internal/endpoint/service/forwarder.go
index 6623a874..2bf3be57 100644
--- a/cli/beacon/internal/endpoint/service/forwarder.go
+++ b/cli/beacon/internal/endpoint/service/forwarder.go
@@ -6,6 +6,7 @@ import (
"path/filepath"
"runtime"
"strings"
+ "time"
)
const (
@@ -16,14 +17,79 @@ const (
ForwarderSystemdUnit = "beacon-asymptote-forwarder.service"
)
-// ForwarderManager manages the long-running Vector process that ships Beacon JSONL to
-// Asymptote. It follows UpdaterManager's shape (unit write/load/unload/status) but is resident
-// like the collector rather than scheduled, and unlike the collector it exists in both user and
-// system modes, because a per-user Beacon install forwards that user's log.
+// forwarderStartTimeout bounds the wait for a Windows forwarder to reach RUNNING after a start.
+const forwarderStartTimeout = 60 * time.Second
+
+// ForwarderManager manages a long-running Vector process that ships Beacon JSONL. It follows
+// UpdaterManager's shape (unit write/load/unload/status) but is resident like the collector rather
+// than scheduled. The Asymptote forwarder exists in both user and system modes, because a per-user
+// Beacon install forwards that user's log.
type ForwarderManager struct {
UserMode bool
// Kind selects the backend; the zero value auto-detects.
Kind Kind
+ // Spec names the forwarder. The zero value is the Asymptote managed-ingest forwarder.
+ Spec ForwarderSpec
+}
+
+// ForwarderSpec is one forwarder's identity under each service manager, and how Vector is run.
+type ForwarderSpec struct {
+ // Label is the launchd label.
+ Label string
+ // SystemdUnit is the systemd unit name.
+ SystemdUnit string
+ // WindowsService is the Service Control Manager name. Empty means the forwarder is not offered
+ // on Windows.
+ WindowsService string
+ // Description names the forwarder in the systemd unit and the Windows service.
+ Description string
+ // Documentation is the systemd Documentation= URL.
+ Documentation string
+ // Args follow `--config <path>` on Vector's command line.
+ Args []string
+ // Env is added to Vector's environment, as NAME=value entries in a fixed order.
+ Env []string
+ // StopTimeout bounds a Windows stop; zero means serviceStopTimeout. It has to outlast Vector's
+ // own drain limit, or a stop gives up while Vector is still flushing.
+ StopTimeout time.Duration
+}
+
+// AsymptoteForwarderSpec is the Asymptote managed-ingest forwarder. It has no Windows service:
+// connect stays refused there.
+func AsymptoteForwarderSpec() ForwarderSpec {
+ return ForwarderSpec{
+ Label: ForwarderLabel,
+ SystemdUnit: ForwarderSystemdUnit,
+ Description: "Beacon endpoint forwarder to Asymptote managed ingest",
+ Documentation: "https://docs.asymptotelabs.ai/cli/endpoint-connect",
+ }
+}
+
+func (m ForwarderManager) spec() ForwarderSpec {
+ if m.Spec.Label == "" && m.Spec.SystemdUnit == "" && m.Spec.WindowsService == "" {
+ return AsymptoteForwarderSpec()
+ }
+ return m.Spec
+}
+
+func (m ForwarderManager) scmService(vectorBin, configPath string) scmService {
+ spec := m.spec()
+ return scmService{
+ Name: spec.WindowsService,
+ DisplayName: spec.Description,
+ Description: spec.Description,
+ Program: vectorBin,
+ Args: append([]string{"--config", configPath}, spec.Args...),
+ Env: spec.Env,
+ OwnsEnv: true,
+ }
+}
+
+func (m ForwarderManager) stopTimeout() time.Duration {
+ if timeout := m.spec().StopTimeout; timeout > 0 {
+ return timeout
+ }
+ return serviceStopTimeout
}
func (m ForwarderManager) resolvedKind() Kind {
@@ -44,6 +110,9 @@ func (m ForwarderManager) Supported() bool {
return runtime.GOOS == "darwin"
case KindSystemd:
return systemdIsInit()
+ case KindWindowsService:
+ // System mode only: Windows has no per-user service manager.
+ return runtime.GOOS == "windows" && !m.UserMode && m.spec().WindowsService != ""
default:
return false
}
@@ -56,6 +125,16 @@ func (m ForwarderManager) UnsupportedReason() string {
return "launchd service management is supported only on macOS"
case KindSystemd:
return "systemd is not PID 1 on this host, so the forwarder cannot be installed as a service"
+ case KindWindowsService:
+ switch {
+ case m.spec().WindowsService == "":
+ // The Asymptote forwarder; keeps the message it has always had.
+ case runtime.GOOS != "windows":
+ return "Windows service management is available only on Windows"
+ case m.UserMode:
+ return "Windows has no per-user service manager, so the forwarder runs only with a system install; use --system from an elevated shell"
+ }
+ return "the Asymptote forwarder needs launchd or systemd to stay running; on this host run Vector yourself with the config from `beacon endpoint asymptote install-pack`"
default:
return "the Asymptote forwarder needs launchd or systemd to stay running; on this host run Vector yourself with the config from `beacon endpoint asymptote install-pack`"
}
@@ -63,14 +142,20 @@ func (m ForwarderManager) UnsupportedReason() string {
// Label is the service identifier for status output.
func (m ForwarderManager) Label() string {
- if m.resolvedKind() == KindSystemd {
- return ForwarderSystemdUnit
+ switch m.resolvedKind() {
+ case KindSystemd:
+ return m.spec().SystemdUnit
+ case KindWindowsService:
+ if name := m.spec().WindowsService; name != "" {
+ return name
+ }
}
- return ForwarderLabel
+ return m.spec().Label
}
// UnitPath returns where the forwarder's service definition lives.
func (m ForwarderManager) UnitPath() (string, error) {
+ spec := m.spec()
switch m.resolvedKind() {
case KindSystemd:
if m.UserMode {
@@ -78,23 +163,36 @@ func (m ForwarderManager) UnitPath() (string, error) {
if err != nil {
return "", err
}
- return filepath.Join(home, ".config", "systemd", "user", ForwarderSystemdUnit), nil
+ return filepath.Join(home, ".config", "systemd", "user", spec.SystemdUnit), nil
}
- return filepath.Join("/etc/systemd/system", ForwarderSystemdUnit), nil
+ return filepath.Join("/etc/systemd/system", spec.SystemdUnit), nil
+ case KindWindowsService:
+ if spec.WindowsService != "" {
+ // The definition lives in the registry; this names where, as the collector's backend does.
+ return `HKLM\SYSTEM\CurrentControlSet\Services\` + spec.WindowsService, nil
+ }
+ fallthrough
default:
if m.UserMode {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
- return filepath.Join(home, "Library", "LaunchAgents", ForwarderLabel+".plist"), nil
+ return filepath.Join(home, "Library", "LaunchAgents", spec.Label+".plist"), nil
}
- return filepath.Join("/Library/LaunchDaemons", ForwarderLabel+".plist"), nil
+ return filepath.Join("/Library/LaunchDaemons", spec.Label+".plist"), nil
}
}
-// RemoveUnits deletes the service definition. Missing files are not an error.
+// RemoveUnits deletes the service definition. Missing files are not an error. On Windows the
+// definition is the SCM registration, so this stops and deletes the service.
func (m ForwarderManager) RemoveUnits() {
+ if m.resolvedKind() == KindWindowsService {
+ if m.Supported() {
+ _ = removeService(m.spec().WindowsService, m.stopTimeout())
+ }
+ return
+ }
if path, err := m.UnitPath(); err == nil {
_ = os.Remove(path)
}
@@ -109,11 +207,14 @@ func (m ForwarderManager) WriteUnit(vectorBin, configPath string) (string, error
if err != nil {
return "", err
}
+ if m.resolvedKind() == KindWindowsService {
+ return path, createOrUpdateService(m.scmService(vectorBin, configPath))
+ }
if err := ensureDir(path); err != nil {
return "", err
}
if m.resolvedKind() == KindLaunchd {
- if err := ensureLaunchdLogDir(m.UserMode, ForwarderLabel); err != nil {
+ if err := ensureLaunchdLogDir(m.UserMode, m.spec().Label); err != nil {
return "", err
}
}
@@ -136,6 +237,9 @@ func (m ForwarderManager) WriteUnit(vectorBin, configPath string) (string, error
// rewrites one that is not, so a unit an earlier release wrote, such as one logging to /tmp, is
// brought up to date by an upgrade rather than only by a fresh connect.
func (m ForwarderManager) UnitCurrent(vectorBin, configPath string) (bool, error) {
+ if m.resolvedKind() == KindWindowsService {
+ return serviceCurrent(m.scmService(vectorBin, configPath))
+ }
path, err := m.UnitPath()
if err != nil {
return false, err
@@ -152,14 +256,15 @@ func (m ForwarderManager) UnitCurrent(vectorBin, configPath string) (bool, error
}
func (m ForwarderManager) unitContent(vectorBin, configPath string) (string, error) {
+ spec := m.spec()
if m.resolvedKind() == KindSystemd {
- return forwarderUnitFile(vectorBin, configPath, m.UserMode), nil
+ return forwarderUnitFile(spec, vectorBin, configPath, m.UserMode), nil
}
- stdout, stderr, err := launchdLogPaths(m.UserMode, ForwarderLabel)
+ stdout, stderr, err := launchdLogPaths(m.UserMode, spec.Label)
if err != nil {
return "", err
}
- return forwarderPlist(ForwarderLabel, vectorBin, configPath, stdout, stderr), nil
+ return forwarderPlist(spec, vectorBin, configPath, stdout, stderr), nil
}
// Load registers and starts the forwarder. An already-loaded launchd job is re-bootstrapped so a
@@ -168,33 +273,44 @@ func (m ForwarderManager) Load() error {
if !m.Supported() {
return fmt.Errorf("%s", m.UnsupportedReason())
}
- if m.resolvedKind() == KindSystemd {
- if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "enable", "--now", ForwarderSystemdUnit)...); err != nil {
- return systemctlError(out, err, "enable --now "+ForwarderSystemdUnit)
+ spec := m.spec()
+ switch m.resolvedKind() {
+ case KindSystemd:
+ unit := spec.SystemdUnit
+ if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "enable", "--now", unit)...); err != nil {
+ return systemctlError(out, err, "enable --now "+unit)
}
- if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "restart", ForwarderSystemdUnit)...); err != nil {
- return systemctlError(out, err, "restart "+ForwarderSystemdUnit)
+ if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "restart", unit)...); err != nil {
+ return systemctlError(out, err, "restart "+unit)
}
return nil
+ case KindWindowsService:
+ // A restart, not a start, so a rewritten config takes effect, then a wait for RUNNING: the
+ // SCM reports a start as accepted long before Vector has loaded its config.
+ if err := restartService(spec.WindowsService, m.stopTimeout()); err != nil {
+ return err
+ }
+ return waitForServiceRunning(spec.WindowsService, forwarderStartTimeout)
}
path, err := m.UnitPath()
if err != nil {
return err
}
domain := serviceDomain(m.UserMode)
- target := domain + "/" + ForwarderLabel
+ label := spec.Label
+ target := domain + "/" + label
// bootout first so a config rewrite (re-enrollment rotates the key) restarts Vector, then
// wait for the old instance to be gone: it drains in-flight requests for up to a minute,
// and a bootstrap issued while it is still registered is silently lost with it. Finally
// confirm the new instance is actually running rather than trusting the old pid.
- _ = runLaunchctlWithContext(domain, ForwarderLabel, "", "bootout", target)
- if !waitForLaunchdJobGone(domain, ForwarderLabel) {
+ _ = runLaunchctlWithContext(domain, label, "", "bootout", target)
+ if !waitForLaunchdJobGone(domain, label) {
return fmt.Errorf("the previous forwarder did not stop within %s; check `launchctl print %s`", launchdStopTimeout, target)
}
- if err := loadLaunchdJob(domain, ForwarderLabel, path); err != nil {
+ if err := loadLaunchdJob(domain, label, path); err != nil {
return err
}
- if !waitForLaunchdJobRunning(domain, ForwarderLabel) {
+ if !waitForLaunchdJobRunning(domain, label) {
return fmt.Errorf("the forwarder was loaded but has not started within %s; check `launchctl print %s` and Vector's log", launchdStartTimeout, target)
}
return nil
@@ -202,23 +318,32 @@ func (m ForwarderManager) Load() error {
// Unload stops and deregisters the forwarder. A missing unit is not an error.
func (m ForwarderManager) Unload() error {
+ spec := m.spec()
switch m.resolvedKind() {
case KindSystemd:
if !systemdIsInit() {
return nil
}
- if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "stop", ForwarderSystemdUnit)...); err != nil && !systemdUnitMissing(out) {
- return systemctlError(out, err, "stop "+ForwarderSystemdUnit)
+ unit := spec.SystemdUnit
+ if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "stop", unit)...); err != nil && !systemdUnitMissing(out) {
+ return systemctlError(out, err, "stop "+unit)
}
- if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "disable", ForwarderSystemdUnit)...); err != nil && !systemdUnitMissing(out) {
- return systemctlError(out, err, "disable "+ForwarderSystemdUnit)
+ if out, err := runSystemctlCommand(systemctlArgs(m.UserMode, "disable", unit)...); err != nil && !systemdUnitMissing(out) {
+ return systemctlError(out, err, "disable "+unit)
}
return nil
case KindLaunchd:
if runtime.GOOS != "darwin" {
return nil
}
- return bootoutLaunchdJob(serviceDomain(m.UserMode), ForwarderLabel)
+ return bootoutLaunchdJob(serviceDomain(m.UserMode), spec.Label)
+ case KindWindowsService:
+ // Stops, waits for Vector's process to exit so vector.exe can be replaced, and deletes the
+ // registration. A missing service is success.
+ if !m.Supported() {
+ return nil
+ }
+ return removeService(spec.WindowsService, m.stopTimeout())
default:
return nil
}
@@ -230,14 +355,22 @@ func (m ForwarderManager) Status() Status {
if !m.Supported() {
return Status{Label: m.Label(), Kind: string(kind), Message: m.UnsupportedReason()}
}
+ spec := m.spec()
+ if kind == KindWindowsService {
+ status := queryService(spec.WindowsService)
+ if !status.Loaded && !status.Running && status.Message == "service not installed" {
+ status.Message = "forwarder not installed"
+ }
+ return status
+ }
if kind == KindSystemd {
- status := Status{Label: ForwarderSystemdUnit, Kind: string(KindSystemd)}
- enabledOut, _ := runSystemctlCommand(systemctlArgs(m.UserMode, "is-enabled", ForwarderSystemdUnit)...)
+ status := Status{Label: spec.SystemdUnit, Kind: string(KindSystemd)}
+ enabledOut, _ := runSystemctlCommand(systemctlArgs(m.UserMode, "is-enabled", spec.SystemdUnit)...)
switch strings.TrimSpace(enabledOut) {
case "enabled", "enabled-runtime", "static":
status.Loaded = true
}
- activeOut, _ := runSystemctlCommand(systemctlArgs(m.UserMode, "is-active", ForwarderSystemdUnit)...)
+ activeOut, _ := runSystemctlCommand(systemctlArgs(m.UserMode, "is-active", spec.SystemdUnit)...)
status.Running = strings.TrimSpace(activeOut) == "active"
if status.Running {
status.Loaded = true
@@ -247,8 +380,8 @@ func (m ForwarderManager) Status() Status {
}
return status
}
- status := Status{Label: ForwarderLabel, Kind: string(KindLaunchd)}
- out, err := runLaunchctlCommand("print", serviceDomain(m.UserMode)+"/"+ForwarderLabel)
+ status := Status{Label: spec.Label, Kind: string(KindLaunchd)}
+ out, err := runLaunchctlCommand("print", serviceDomain(m.UserMode)+"/"+spec.Label)
if err != nil {
status.Message = strings.TrimSpace(out)
return status
@@ -258,18 +391,27 @@ func (m ForwarderManager) Status() Status {
return status
}
-// forwarderUnitFile renders the systemd unit. Vector reads its own config, so the unit needs no
-// environment; the rendered vector.toml carries literal paths and URLs.
-func forwarderUnitFile(vectorBin, configPath string, userMode bool) string {
+// forwarderUnitFile renders the systemd unit. Vector reads its own config; the unit adds only the
+// spec's environment.
+func forwarderUnitFile(spec ForwarderSpec, vectorBin, configPath string, userMode bool) string {
var b strings.Builder
b.WriteString("[Unit]\n")
- b.WriteString("Description=Beacon endpoint forwarder to Asymptote managed ingest\n")
- b.WriteString("Documentation=https://docs.asymptotelabs.ai/cli/endpoint-connect\n")
+ fmt.Fprintf(&b, "Description=%s\n", spec.Description)
+ if spec.Documentation != "" {
+ fmt.Fprintf(&b, "Documentation=%s\n", spec.Documentation)
+ }
b.WriteString("After=network-online.target\n")
b.WriteString("Wants=network-online.target\n")
b.WriteString("\n[Service]\n")
b.WriteString("Type=simple\n")
- fmt.Fprintf(&b, "ExecStart=%s --config %s\n", systemdArg(vectorBin), systemdArg(configPath))
+ args := []string{systemdArg(vectorBin), "--config", systemdArg(configPath)}
+ for _, arg := range spec.Args {
+ args = append(args, systemdArg(arg))
+ }
+ fmt.Fprintf(&b, "ExecStart=%s\n", strings.Join(args, " "))
+ for _, entry := range spec.Env {
+ fmt.Fprintf(&b, "Environment=%s\n", systemdArg(entry))
+ }
b.WriteString("Restart=always\n")
b.WriteString("RestartSec=5\n")
b.WriteString("StandardOutput=journal\n")
@@ -288,7 +430,22 @@ func forwarderUnitFile(vectorBin, configPath string, userMode bool) string {
}
// forwarderPlist renders the launchd job: resident, restarted by launchd, started at load.
-func forwarderPlist(label, vectorBin, configPath, stdoutPath, stderrPath string) string {
+func forwarderPlist(spec ForwarderSpec, vectorBin, configPath, stdoutPath, stderrPath string) string {
+ var args strings.Builder
+ for _, arg := range append([]string{vectorBin, "--config", configPath}, spec.Args...) {
+ fmt.Fprintf(&args, " <string>%s</string>\n", xmlEscape(arg))
+ }
+ var env string
+ if len(spec.Env) > 0 {
+ var b strings.Builder
+ b.WriteString(" <key>EnvironmentVariables</key>\n <dict>\n")
+ for _, entry := range spec.Env {
+ name, value, _ := strings.Cut(entry, "=")
+ fmt.Fprintf(&b, " <key>%s</key>\n <string>%s</string>\n", xmlEscape(name), xmlEscape(value))
+ }
+ b.WriteString(" </dict>\n")
+ env = b.String()
+ }
return fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
@@ -297,11 +454,8 @@ func forwarderPlist(label, vectorBin, configPath, stdoutPath, stderrPath string)
<string>%s</string>
<key>ProgramArguments</key>
<array>
- <string>%s</string>
- <string>--config</string>
- <string>%s</string>
- </array>
- <key>RunAtLoad</key>
+%s </array>
+%s <key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
@@ -313,7 +467,7 @@ func forwarderPlist(label, vectorBin, configPath, stdoutPath, stderrPath string)
<string>%s</string>
</dict>
</plist>
-`, xmlEscape(label), xmlEscape(vectorBin), xmlEscape(configPath), xmlEscape(stdoutPath), xmlEscape(stderrPath))
+`, xmlEscape(spec.Label), args.String(), env, xmlEscape(stdoutPath), xmlEscape(stderrPath))
}
func xmlEscape(s string) string {
diff --git a/cli/beacon/internal/endpoint/service/forwarder_test.go b/cli/beacon/internal/endpoint/service/forwarder_test.go
index 30de0443..a3a69772 100644
--- a/cli/beacon/internal/endpoint/service/forwarder_test.go
+++ b/cli/beacon/internal/endpoint/service/forwarder_test.go
@@ -13,7 +13,7 @@ import (
)
func TestForwarderPlistRunsVectorResidentWithKeepAlive(t *testing.T) {
- got := forwarderPlist(ForwarderLabel, "/opt/beacon/bin/vector", "/Users/me/.beacon/endpoint/asymptote/vector.toml", "/Users/me/Library/Logs/Beacon/f.out", "/Users/me/Library/Logs/Beacon/f.err")
+ got := forwarderPlist(AsymptoteForwarderSpec(), "/opt/beacon/bin/vector", "/Users/me/.beacon/endpoint/asymptote/vector.toml", "/Users/me/Library/Logs/Beacon/f.out", "/Users/me/Library/Logs/Beacon/f.err")
for _, want := range []string{
"<string>com.beacon.endpoint.asymptote-forwarder</string>",
"<string>/opt/beacon/bin/vector</string>",
@@ -30,7 +30,7 @@ func TestForwarderPlistRunsVectorResidentWithKeepAlive(t *testing.T) {
if strings.Contains(got, "StartCalendarInterval") {
t.Fatal("forwarder must be resident, not scheduled")
}
- escaped := forwarderPlist("l", "/tmp/a&b", "/tmp/<c>.toml", `/x/"o".out`, "/x/e&.err")
+ escaped := forwarderPlist(ForwarderSpec{Label: "l"}, "/tmp/a&b", "/tmp/<c>.toml", `/x/"o".out`, "/x/e&.err")
if !strings.Contains(escaped, "/tmp/a&amp;b") || !strings.Contains(escaped, "&lt;c&gt;") ||
!strings.Contains(escaped, "/x/&quot;o&quot;.out") || !strings.Contains(escaped, "/x/e&amp;.err") {
t.Fatalf("plist must XML-escape paths:\n%s", escaped)
@@ -38,7 +38,7 @@ func TestForwarderPlistRunsVectorResidentWithKeepAlive(t *testing.T) {
}
func TestForwarderSystemdUnitRestartsAlwaysAndScopesByMode(t *testing.T) {
- system := forwarderUnitFile("/usr/bin/vector", "/var/lib/beacon/asymptote/vector.toml", false)
+ system := forwarderUnitFile(AsymptoteForwarderSpec(), "/usr/bin/vector", "/var/lib/beacon/asymptote/vector.toml", false)
for _, want := range []string{
`ExecStart="/usr/bin/vector" --config "/var/lib/beacon/asymptote/vector.toml"`,
"Restart=always",
@@ -50,7 +50,7 @@ func TestForwarderSystemdUnitRestartsAlwaysAndScopesByMode(t *testing.T) {
t.Fatalf("system unit missing %q:\n%s", want, system)
}
}
- user := forwarderUnitFile("/usr/bin/vector", "/home/me/.beacon/endpoint/asymptote/vector.toml", true)
+ user := forwarderUnitFile(AsymptoteForwarderSpec(), "/usr/bin/vector", "/home/me/.beacon/endpoint/asymptote/vector.toml", true)
if strings.Contains(user, "User=root") || !strings.Contains(user, "WantedBy=default.target") {
t.Fatalf("user unit must not run as root and must hook default.target:\n%s", user)
}
@@ -192,3 +192,115 @@ func TestForwarderLoadFailsWhenTheNewInstanceNeverStarts(t *testing.T) {
t.Fatalf("Load should report a forwarder that never started, got %v", err)
}
}
+
+// The Asymptote forwarder's unit and plist are what connect wrote before forwarders had a spec.
+// UnitCurrent compares them byte for byte, so any change here would rewrite and restart every
+// connected endpoint's forwarder on its next upgrade.
+func TestAsymptoteForwarderUnitsAreUnchangedBySpecs(t *testing.T) {
+ unit := forwarderUnitFile(AsymptoteForwarderSpec(), "/opt/beacon/bin/vector", "/etc/beacon/endpoint/asymptote/vector.toml", false)
+ wantUnit := `[Unit]
+Description=Beacon endpoint forwarder to Asymptote managed ingest
+Documentation=https://docs.asymptotelabs.ai/cli/endpoint-connect
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=simple
+ExecStart="/opt/beacon/bin/vector" --config "/etc/beacon/endpoint/asymptote/vector.toml"
+Restart=always
+RestartSec=5
+StandardOutput=journal
+StandardError=journal
+User=root
+
+[Install]
+WantedBy=multi-user.target
+`
+ if unit != wantUnit {
+ t.Fatalf("systemd unit changed:\n%s\nwant:\n%s", unit, wantUnit)
+ }
+ plist := forwarderPlist(AsymptoteForwarderSpec(), "/opt/beacon/bin/vector", "/a/vector.toml", "/l/f.out", "/l/f.err")
+ if !strings.Contains(plist, " <string>/a/vector.toml</string>\n </array>\n <key>RunAtLoad</key>") ||
+ strings.Contains(plist, "EnvironmentVariables") {
+ t.Fatalf("plist changed:\n%s", plist)
+ }
+ if (ForwarderManager{}).spec().WindowsService != "" {
+ t.Fatal("the Asymptote forwarder must not be offered as a Windows service")
+ }
+}
+
+// Another forwarder carries its own names, extra Vector arguments and environment into every unit.
+func TestForwarderSpecReachesTheUnitPlistAndNames(t *testing.T) {
+ spec := ForwarderSpec{
+ Label: "com.beacon.endpoint.test-forwarder",
+ SystemdUnit: "beacon-test-forwarder.service",
+ WindowsService: "BeaconTestForwarder",
+ Description: "Beacon test forwarder",
+ Args: []string{"--graceful-shutdown-limit-secs", "10"},
+ Env: []string{"AZURE_AUTHORITY_HOST=https://login.example.test"},
+ }
+ unit := forwarderUnitFile(spec, "/opt/beacon/bin/vector", "/etc/f/vector.toml", false)
+ for _, want := range []string{
+ "Description=Beacon test forwarder\n",
+ `ExecStart="/opt/beacon/bin/vector" --config "/etc/f/vector.toml" "--graceful-shutdown-limit-secs" "10"`,
+ `Environment="AZURE_AUTHORITY_HOST=https://login.example.test"`,
+ } {
+ if !strings.Contains(unit, want) {
+ t.Fatalf("unit missing %q:\n%s", want, unit)
+ }
+ }
+ if strings.Contains(unit, "Documentation=") {
+ t.Fatalf("a spec without documentation must not write an empty Documentation=:\n%s", unit)
+ }
+ plist := forwarderPlist(spec, "/opt/beacon/bin/vector", "/etc/f/vector.toml", "/l/o", "/l/e")
+ for _, want := range []string{
+ "<string>com.beacon.endpoint.test-forwarder</string>",
+ " <string>--graceful-shutdown-limit-secs</string>\n <string>10</string>\n </array>",
+ "<key>EnvironmentVariables</key>\n <dict>\n <key>AZURE_AUTHORITY_HOST</key>\n <string>https://login.example.test</string>\n </dict>",
+ } {
+ if !strings.Contains(plist, want) {
+ t.Fatalf("plist missing %q:\n%s", want, plist)
+ }
+ }
+ names := map[Kind]string{KindSystemd: spec.SystemdUnit, KindLaunchd: spec.Label, KindWindowsService: spec.WindowsService}
+ for kind, want := range names {
+ if got := (ForwarderManager{Kind: kind, Spec: spec}).Label(); got != want {
+ t.Errorf("%s label = %q, want %q", kind, got, want)
+ }
+ }
+ path, err := ForwarderManager{Kind: KindWindowsService, Spec: spec}.UnitPath()
+ if err != nil || path != `HKLM\SYSTEM\CurrentControlSet\Services\BeaconTestForwarder` {
+ t.Fatalf("Windows unit path = %q (%v)", path, err)
+ }
+}
+
+// A forwarder with a Windows service is supported only by a system install on Windows; the
+// Asymptote forwarder keeps refusing there with the message it always had.
+func TestForwarderWindowsServiceSupport(t *testing.T) {
+ spec := ForwarderSpec{WindowsService: "BeaconTestForwarder", Label: "l", SystemdUnit: "u.service"}
+ system := ForwarderManager{Kind: KindWindowsService, Spec: spec}
+ user := ForwarderManager{Kind: KindWindowsService, Spec: spec, UserMode: true}
+ asymptote := ForwarderManager{Kind: KindWindowsService}
+
+ if asymptote.Supported() || !strings.Contains(asymptote.UnsupportedReason(), "install-pack") {
+ t.Fatalf("Asymptote forwarder on Windows: supported=%t reason=%q", asymptote.Supported(), asymptote.UnsupportedReason())
+ }
+ if user.Supported() {
+ t.Fatal("a user-mode forwarder must be refused on Windows")
+ }
+ if runtime.GOOS == "windows" {
+ if !system.Supported() {
+ t.Fatalf("system forwarder unsupported: %s", system.UnsupportedReason())
+ }
+ if !strings.Contains(user.UnsupportedReason(), "--system") {
+ t.Fatalf("user-mode reason should point at --system: %q", user.UnsupportedReason())
+ }
+ return
+ }
+ if system.Supported() || !strings.Contains(system.UnsupportedReason(), "only on Windows") {
+ t.Fatalf("off Windows: supported=%t reason=%q", system.Supported(), system.UnsupportedReason())
+ }
+ if err := system.Unload(); err != nil {
+ t.Fatalf("Unload off Windows must be a no-op, got %v", err)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/service/launchd_logs_test.go b/cli/beacon/internal/endpoint/service/launchd_logs_test.go
index 6aaf27c7..bf2c3904 100644
--- a/cli/beacon/internal/endpoint/service/launchd_logs_test.go
+++ b/cli/beacon/internal/endpoint/service/launchd_logs_test.go
@@ -35,7 +35,7 @@ func TestSystemLaunchDaemonsNeverLogToTmp(t *testing.T) {
out, errPath := paths(SystemLabel)
plists[SystemLabel] = plist(SystemLabel, "/opt/beacon/bin/beacon-otelcol", "/etc/beacon/endpoint/otelcol.yaml", out, errPath)
out, errPath = paths(ForwarderLabel)
- plists[ForwarderLabel] = forwarderPlist(ForwarderLabel, "/opt/beacon/bin/vector", "/etc/beacon/endpoint/asymptote/vector.toml", out, errPath)
+ plists[ForwarderLabel] = forwarderPlist(AsymptoteForwarderSpec(), "/opt/beacon/bin/vector", "/etc/beacon/endpoint/asymptote/vector.toml", out, errPath)
out, errPath = paths(UpdaterLabel)
plists[UpdaterLabel] = updaterPlist(UpdaterLabel, "/opt/beacon/bin/beacon", out, errPath)
out, errPath = paths(InventoryLabel)
diff --git a/cli/beacon/internal/endpoint/service/windows.go b/cli/beacon/internal/endpoint/service/windows.go
index 26c6865b..1d015dd8 100644
--- a/cli/beacon/internal/endpoint/service/windows.go
+++ b/cli/beacon/internal/endpoint/service/windows.go
@@ -5,6 +5,32 @@ import (
"runtime"
)
+// scmService is one service registration with the Windows Service Control Manager: the collector,
+// or a forwarder. Env holds NAME=value entries the SCM adds to the service's environment.
+type scmService struct {
+ Name string
+ DisplayName string
+ Description string
+ Program string
+ Args []string
+ Env []string
+ // OwnsEnv says the service's Environment value is Beacon's: rewritten on every registration
+ // and removed when Env is empty. The collector leaves it alone, as it always has, so a value an
+ // administrator set there survives an upgrade.
+ OwnsEnv bool
+}
+
+// collectorService is the collector's registration.
+func collectorService(program, configPath string) scmService {
+ return scmService{
+ Name: WindowsServiceName,
+ DisplayName: WindowsServiceDisplayName,
+ Description: "Collects local AI agent telemetry and writes the Beacon endpoint log.",
+ Program: program,
+ Args: []string{"--config", configPath},
+ }
+}
+
// windowsBackend manages the collector through the Windows Service Control Manager.
//
// Mapping from the two backends it joins:
@@ -58,7 +84,7 @@ func (b windowsBackend) writeUnit(userMode bool, program, configPath string) (st
if !b.available() {
return "", fmt.Errorf("%s", b.unsupportedReason())
}
- if err := createOrUpdateService(program, configPath); err != nil {
+ if err := createOrUpdateService(collectorService(program, configPath)); err != nil {
return "", err
}
return b.unitPath(userMode)
@@ -68,7 +94,7 @@ func (b windowsBackend) load(userMode bool) error {
if !b.available() {
return fmt.Errorf("%s", b.unsupportedReason())
}
- return startService()
+ return startService(WindowsServiceName)
}
// unload stops and deletes the service, tolerating its absence.
@@ -79,14 +105,14 @@ func (b windowsBackend) unload(userMode bool) error {
if !b.available() {
return nil
}
- return removeService()
+ return removeService(WindowsServiceName, serviceStopTimeout)
}
func (b windowsBackend) restart(userMode bool) error {
if !b.available() {
return fmt.Errorf("%s", b.unsupportedReason())
}
- return restartService()
+ return restartService(WindowsServiceName, serviceStopTimeout)
}
func (b windowsBackend) status(userMode bool) Status {
@@ -95,5 +121,5 @@ func (b windowsBackend) status(userMode bool) Status {
status.Message = b.unsupportedReason()
return status
}
- return queryService()
+ return queryService(WindowsServiceName)
}
diff --git a/cli/beacon/internal/endpoint/service/windows_other.go b/cli/beacon/internal/endpoint/service/windows_other.go
index 2769413f..3b4f0474 100644
--- a/cli/beacon/internal/endpoint/service/windows_other.go
+++ b/cli/beacon/internal/endpoint/service/windows_other.go
@@ -2,7 +2,13 @@
package service
-import "fmt"
+import (
+ "fmt"
+ "time"
+)
+
+// serviceStopTimeout matches the Windows value so callers compile everywhere; nothing waits on it here.
+const serviceStopTimeout = 20 * time.Second
// The Service Control Manager exists only on Windows, so these report rather than pretend.
//
@@ -18,20 +24,24 @@ func errNotWindows(action string) error {
"use --service=auto, or systemd/launchd/none as appropriate", action)
}
-func createOrUpdateService(program, configPath string) error { return errNotWindows("register") }
+func createOrUpdateService(scmService) error { return errNotWindows("register") }
+
+func startService(string) error { return errNotWindows("start") }
+
+func waitForServiceRunning(string, time.Duration) error { return errNotWindows("start") }
-func startService() error { return errNotWindows("start") }
+func serviceCurrent(scmService) (bool, error) { return false, errNotWindows("inspect") }
// removeService is the one exception, and deliberately so: uninstall and repair call unload
// speculatively on every backend, and failing there would block removing an endpoint that was
// never a Windows service to begin with.
-func removeService() error { return nil }
+func removeService(string, time.Duration) error { return nil }
-func restartService() error { return errNotWindows("restart") }
+func restartService(string, time.Duration) error { return errNotWindows("restart") }
-func queryService() Status {
+func queryService(name string) Status {
return Status{
- Label: WindowsServiceName,
+ Label: name,
Message: "Windows service management is available only on Windows",
}
}
diff --git a/cli/beacon/internal/endpoint/service/windows_scm.go b/cli/beacon/internal/endpoint/service/windows_scm.go
index bdc67834..630eb160 100644
--- a/cli/beacon/internal/endpoint/service/windows_scm.go
+++ b/cli/beacon/internal/endpoint/service/windows_scm.go
@@ -5,10 +5,12 @@ package service
import (
"errors"
"fmt"
+ "slices"
"strings"
"time"
"golang.org/x/sys/windows"
+ "golang.org/x/sys/windows/registry"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/mgr"
)
@@ -32,18 +34,18 @@ func withManager(fn func(*mgr.Mgr) error) error {
return fn(m)
}
-// createOrUpdateService registers the collector, or points an existing registration at the new
-// binary and config.
+// createOrUpdateService registers a service, or points an existing registration at the new binary,
+// arguments and environment.
//
// Updating in place rather than delete-and-recreate: a delete only takes effect once every handle
// to the service closes, so a recreate immediately afterwards can fail with "marked for deletion"
// on a machine where services.msc happens to be open. Reconfiguring has no such window, and an
// upgrade that changes the binary path is the common case.
-func createOrUpdateService(program, configPath string) error {
+func createOrUpdateService(spec scmService) error {
return withManager(func(m *mgr.Mgr) error {
cfg := mgr.Config{
- DisplayName: WindowsServiceDisplayName,
- Description: "Collects local AI agent telemetry and writes the Beacon endpoint log.",
+ DisplayName: spec.DisplayName,
+ Description: spec.Description,
// Automatic is the equivalent of launchd's RunAtLoad and systemd's
// WantedBy=multi-user.target: the endpoint must come back after a reboot without
// anyone logging in.
@@ -54,31 +56,105 @@ func createOrUpdateService(program, configPath string) error {
DelayedAutoStart: true,
}
- existing, err := m.OpenService(WindowsServiceName)
+ existing, err := m.OpenService(spec.Name)
if err == nil {
defer existing.Close()
current, cerr := existing.Config()
if cerr != nil {
- return fmt.Errorf("read the existing %s service configuration: %w", WindowsServiceName, cerr)
+ return fmt.Errorf("read the existing %s service configuration: %w", spec.Name, cerr)
}
current.DisplayName = cfg.DisplayName
current.Description = cfg.Description
current.StartType = cfg.StartType
current.DelayedAutoStart = cfg.DelayedAutoStart
- current.BinaryPathName = serviceBinaryPath(program, configPath)
+ current.BinaryPathName = serviceBinaryPath(spec.Program, spec.Args...)
if err := existing.UpdateConfig(current); err != nil {
- return fmt.Errorf("update the %s service: %w", WindowsServiceName, err)
+ return fmt.Errorf("update the %s service: %w", spec.Name, err)
}
- return setRecoveryActions(existing)
+ if err := setServiceEnvironment(spec); err != nil {
+ return err
+ }
+ return setRecoveryActions(existing, spec.Name)
}
- created, err := m.CreateService(WindowsServiceName, program, cfg, "--config", configPath)
+ created, err := m.CreateService(spec.Name, spec.Program, cfg, spec.Args...)
if err != nil {
- return fmt.Errorf("register the %s service: %w", WindowsServiceName, err)
+ return fmt.Errorf("register the %s service: %w", spec.Name, err)
}
defer created.Close()
- return setRecoveryActions(created)
+ if err := setServiceEnvironment(spec); err != nil {
+ return err
+ }
+ return setRecoveryActions(created, spec.Name)
+ })
+}
+
+// setServiceEnvironment writes the variables the SCM adds to the service process's environment:
+// the Environment value under the service's key, one NAME=value string per entry. No variables
+// removes the value, so a registration that once carried some does not keep them.
+func setServiceEnvironment(spec scmService) error {
+ if !spec.OwnsEnv {
+ return nil
+ }
+ name, env := spec.Name, spec.Env
+ key, err := registry.OpenKey(registry.LOCAL_MACHINE, serviceRegistryKey(name), registry.SET_VALUE)
+ if err != nil {
+ return fmt.Errorf("open the %s service's registry key: %w", name, err)
+ }
+ defer key.Close()
+ if len(env) == 0 {
+ if err := key.DeleteValue("Environment"); err != nil && !errors.Is(err, registry.ErrNotExist) {
+ return fmt.Errorf("clear the %s service's environment: %w", name, err)
+ }
+ return nil
+ }
+ if err := key.SetStringsValue("Environment", env); err != nil {
+ return fmt.Errorf("set the %s service's environment: %w", name, err)
+ }
+ return nil
+}
+
+// serviceEnvironment reads back what setServiceEnvironment wrote.
+func serviceEnvironment(name string) ([]string, error) {
+ key, err := registry.OpenKey(registry.LOCAL_MACHINE, serviceRegistryKey(name), registry.QUERY_VALUE)
+ if err != nil {
+ return nil, err
+ }
+ defer key.Close()
+ env, _, err := key.GetStringsValue("Environment")
+ if errors.Is(err, registry.ErrNotExist) {
+ return nil, nil
+ }
+ return env, err
+}
+
+func serviceRegistryKey(name string) string {
+ return `SYSTEM\CurrentControlSet\Services\` + name
+}
+
+// serviceCurrent reports whether the registered service runs what spec describes, so a reconcile
+// rewrites only a registration that changed.
+func serviceCurrent(spec scmService) (bool, error) {
+ var current bool
+ err := withManager(func(m *mgr.Mgr) error {
+ s, err := m.OpenService(spec.Name)
+ if err != nil {
+ return err
+ }
+ defer s.Close()
+ cfg, err := s.Config()
+ if err != nil {
+ return err
+ }
+ env, err := serviceEnvironment(spec.Name)
+ if err != nil {
+ return err
+ }
+ current = strings.EqualFold(cfg.BinaryPathName, serviceBinaryPath(spec.Program, spec.Args...)) &&
+ cfg.StartType == mgr.StartAutomatic && slices.Equal(env, spec.Env)
+ return nil
})
+ return current, err
}
// setRecoveryActions is the KeepAlive / Restart=always equivalent.
@@ -88,7 +164,7 @@ func createOrUpdateService(program, configPath string) error {
// the supervised backend. Three escalating restarts rather than infinite immediate ones: a
// collector that cannot start at all should stop thrashing and leave a visible stopped service,
// not loop forever writing the same error.
-func setRecoveryActions(s *mgr.Service) error {
+func setRecoveryActions(s *mgr.Service, name string) error {
actions := []mgr.RecoveryAction{
{Type: mgr.ServiceRestart, Delay: 5 * time.Second},
{Type: mgr.ServiceRestart, Delay: 15 * time.Second},
@@ -97,7 +173,7 @@ func setRecoveryActions(s *mgr.Service) error {
// The reset period returns the failure count to zero after a day of health, so a service that
// dies once a week does not eventually exhaust its restarts.
if err := s.SetRecoveryActions(actions, uint32((24 * time.Hour).Seconds())); err != nil {
- return fmt.Errorf("set restart-on-failure for %s: %w", WindowsServiceName, err)
+ return fmt.Errorf("set restart-on-failure for %s: %w", name, err)
}
return nil
}
@@ -115,19 +191,19 @@ func setRecoveryActions(s *mgr.Service) error {
// upgrade would report success, and the service would fail to start after the next reboot with a
// file-not-found the operator has no reason to connect to an upgrade. Sharing the escaper also
// means create and update cannot drift apart.
-func serviceBinaryPath(program, configPath string) string {
- parts := make([]string, 0, 3)
- for _, arg := range []string{program, "--config", configPath} {
+func serviceBinaryPath(program string, args ...string) string {
+ parts := make([]string, 0, 1+len(args))
+ for _, arg := range append([]string{program}, args...) {
parts = append(parts, windows.EscapeArg(arg))
}
return strings.Join(parts, " ")
}
-func startService() error {
+func startService(name string) error {
return withManager(func(m *mgr.Mgr) error {
- s, err := m.OpenService(WindowsServiceName)
+ s, err := m.OpenService(name)
if err != nil {
- return fmt.Errorf("open the %s service (was it installed?): %w", WindowsServiceName, err)
+ return fmt.Errorf("open the %s service (was it installed?): %w", name, err)
}
defer s.Close()
@@ -140,27 +216,58 @@ func startService() error {
if errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) {
return nil
}
- return fmt.Errorf("start the %s service: %w", WindowsServiceName, err)
+ return fmt.Errorf("start the %s service: %w", name, err)
}
return nil
})
}
+// waitForServiceRunning waits until the service reports running. A service that stops instead, or
+// is still starting when the time is up, is an error naming its state: a process that hangs in
+// START_PENDING cannot be stopped and never triggers its recovery actions, so it must not be
+// reported as started.
+func waitForServiceRunning(name string, timeout time.Duration) error {
+ return withManager(func(m *mgr.Mgr) error {
+ s, err := m.OpenService(name)
+ if err != nil {
+ return fmt.Errorf("open the %s service: %w", name, err)
+ }
+ defer s.Close()
+ deadline := time.Now().Add(timeout)
+ for {
+ status, err := s.Query()
+ if err != nil {
+ return fmt.Errorf("query the %s service: %w", name, err)
+ }
+ switch status.State {
+ case svc.Running:
+ return nil
+ case svc.Stopped:
+ return fmt.Errorf("the %s service stopped while starting (exit code %d)", name, status.Win32ExitCode)
+ }
+ if time.Now().After(deadline) {
+ return fmt.Errorf("the %s service is still %s after %s", name, serviceStateName(status.State), timeout)
+ }
+ time.Sleep(300 * time.Millisecond)
+ }
+ })
+}
+
// removeService stops and deletes the registration, treating an absent service as success.
-func removeService() error {
+func removeService(name string, stopTimeout time.Duration) error {
return withManager(func(m *mgr.Mgr) error {
- s, err := m.OpenService(WindowsServiceName)
+ s, err := m.OpenService(name)
if err != nil {
// Nothing registered. Uninstall and repair both call this speculatively.
return nil
}
defer s.Close()
- if err := stopAndWait(s); err != nil {
+ if err := stopAndWait(s, name, stopTimeout); err != nil {
return err
}
if err := s.Delete(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_MARKED_FOR_DELETE) {
- return fmt.Errorf("delete the %s service: %w", WindowsServiceName, err)
+ return fmt.Errorf("delete the %s service: %w", name, err)
}
return nil
})
@@ -176,10 +283,10 @@ func removeService() error {
// MSI uninstall or upgrade that reaches beacon-otelcol.exe in that window cannot remove it,
// schedules the delete for the next boot, and -- under msiexec /qn without /norestart, which is how
// fleet tooling runs it -- restarts the machine on the spot.
-func stopAndWait(s *mgr.Service) error {
+func stopAndWait(s *mgr.Service, name string, timeout time.Duration) error {
status, err := s.Query()
if err != nil {
- return fmt.Errorf("query the %s service: %w", WindowsServiceName, err)
+ return fmt.Errorf("query the %s service: %w", name, err)
}
if status.State == svc.Stopped {
return nil
@@ -191,28 +298,28 @@ func stopAndWait(s *mgr.Service) error {
if process != 0 {
defer windows.CloseHandle(process)
}
- deadline := time.Now().Add(serviceStopTimeout)
+ deadline := time.Now().Add(timeout)
if _, err := s.Control(svc.Stop); err != nil {
// Already stopped between the query and the control request; that is the outcome we want,
// once its process is gone.
if errors.Is(err, windows.ERROR_SERVICE_NOT_ACTIVE) {
- return waitForServiceProcess(process, deadline)
+ return waitForServiceProcess(process, name, deadline, timeout)
}
- return fmt.Errorf("stop the %s service: %w", WindowsServiceName, err)
+ return fmt.Errorf("stop the %s service: %w", name, err)
}
for time.Now().Before(deadline) {
status, err := s.Query()
if err != nil {
- return fmt.Errorf("query the %s service while stopping: %w", WindowsServiceName, err)
+ return fmt.Errorf("query the %s service while stopping: %w", name, err)
}
if status.State == svc.Stopped {
- return waitForServiceProcess(process, deadline)
+ return waitForServiceProcess(process, name, deadline, timeout)
}
time.Sleep(300 * time.Millisecond)
}
- return fmt.Errorf("the %s service did not stop within %s", WindowsServiceName, serviceStopTimeout)
+ return fmt.Errorf("the %s service did not stop within %s", name, timeout)
}
// openServiceProcess returns a handle that can wait on the service's process, or 0 when there is no
@@ -229,7 +336,7 @@ func openServiceProcess(pid uint32) windows.Handle {
}
// waitForServiceProcess waits, until deadline, for the process behind a stopped service to exit.
-func waitForServiceProcess(process windows.Handle, deadline time.Time) error {
+func waitForServiceProcess(process windows.Handle, name string, deadline time.Time, timeout time.Duration) error {
if process == 0 {
return nil
}
@@ -239,41 +346,41 @@ func waitForServiceProcess(process windows.Handle, deadline time.Time) error {
}
event, err := windows.WaitForSingleObject(process, uint32(remaining.Milliseconds()))
if err != nil {
- return fmt.Errorf("wait for the %s service's process to exit: %w", WindowsServiceName, err)
+ return fmt.Errorf("wait for the %s service's process to exit: %w", name, err)
}
if event == uint32(windows.WAIT_TIMEOUT) {
- return fmt.Errorf("the %s service stopped but its process did not exit within %s", WindowsServiceName, serviceStopTimeout)
+ return fmt.Errorf("the %s service stopped but its process did not exit within %s", name, timeout)
}
return nil
}
-func restartService() error {
+func restartService(name string, stopTimeout time.Duration) error {
if err := withManager(func(m *mgr.Mgr) error {
- s, err := m.OpenService(WindowsServiceName)
+ s, err := m.OpenService(name)
if err != nil {
// Not installed. Installing it is the right recovery, and mirrors the systemd
// backend's restart-falls-back-to-load behavior.
return errServiceNotInstalled
}
defer s.Close()
- return stopAndWait(s)
+ return stopAndWait(s, name, stopTimeout)
}); err != nil {
if errors.Is(err, errServiceNotInstalled) {
- return startService()
+ return startService(name)
}
return err
}
- return startService()
+ return startService(name)
}
// errServiceNotInstalled distinguishes "there is nothing to restart" from a real failure, so
// restart can fall back to starting rather than reporting an error for a recoverable state.
var errServiceNotInstalled = errors.New("service is not installed")
-func queryService() Status {
- status := Status{Label: WindowsServiceName}
+func queryService(name string) Status {
+ status := Status{Label: name, Kind: string(KindWindowsService)}
err := withManager(func(m *mgr.Mgr) error {
- s, err := m.OpenService(WindowsServiceName)
+ s, err := m.OpenService(name)
if err != nil {
status.Message = "service not installed"
return nil
diff --git a/cli/beacon/internal/endpoint/service/windows_scm_test.go b/cli/beacon/internal/endpoint/service/windows_scm_test.go
index 456d17a0..99fb3a3c 100644
--- a/cli/beacon/internal/endpoint/service/windows_scm_test.go
+++ b/cli/beacon/internal/endpoint/service/windows_scm_test.go
@@ -21,7 +21,8 @@ func TestServiceBinaryPathIsEscapedTheWayTheSCMReadsIt(t *testing.T) {
program = `C:\Program Files\Beacon\bin\beacon-otelcol.exe`
config = `C:\ProgramData\Beacon\Endpoint\collector.yaml`
)
- got := serviceBinaryPath(program, config)
+ collector := collectorService(program, config)
+ got := serviceBinaryPath(collector.Program, collector.Args...)
// Quoted because of the space, and left alone because there is not one.
want := `"` + program + `" --config ` + config
@@ -40,7 +41,8 @@ func TestServiceBinaryPathIsEscapedTheWayTheSCMReadsIt(t *testing.T) {
}
func TestServiceBinaryPathQuotesOnlyWhenItMustAndAlwaysCarriesTheConfig(t *testing.T) {
- got := serviceBinaryPath(`C:\Beacon\beacon-otelcol.exe`, `C:\Beacon\collector.yaml`)
+ collector := collectorService(`C:\Beacon\beacon-otelcol.exe`, `C:\Beacon\collector.yaml`)
+ got := serviceBinaryPath(collector.Program, collector.Args...)
if got != `C:\Beacon\beacon-otelcol.exe --config C:\Beacon\collector.yaml` {
t.Fatalf("serviceBinaryPath = %s", got)
}
@@ -49,3 +51,22 @@ func TestServiceBinaryPathQuotesOnlyWhenItMustAndAlwaysCarriesTheConfig(t *testi
"the collector would start with its default configuration and write nowhere Beacon reads", got)
}
}
+
+// A forwarder registration carries Vector's config and the spec's extra arguments, escaped the same
+// way, so an upgrade's UpdateConfig writes what CreateService would have.
+func TestForwarderServiceRunsVectorWithTheConfigAndSpecArguments(t *testing.T) {
+ m := ForwarderManager{Kind: KindWindowsService, Spec: ForwarderSpec{
+ WindowsService: "BeaconTestForwarder",
+ Description: "Beacon test forwarder",
+ Args: []string{"--graceful-shutdown-limit-secs", "10"},
+ Env: []string{"AZURE_AUTHORITY_HOST=https://login.example.test"},
+ }}
+ spec := m.scmService(`C:\Program Files\Beacon\bin\vector.exe`, `C:\ProgramData\Beacon\Endpoint\forwarders\sentinel\vector.toml`)
+ want := `"C:\Program Files\Beacon\bin\vector.exe" --config C:\ProgramData\Beacon\Endpoint\forwarders\sentinel\vector.toml --graceful-shutdown-limit-secs 10`
+ if got := serviceBinaryPath(spec.Program, spec.Args...); got != want {
+ t.Fatalf("ImagePath = %s, want %s", got, want)
+ }
+ if spec.Name != "BeaconTestForwarder" || len(spec.Env) != 1 {
+ t.Fatalf("spec = %+v", spec)
+ }
+}