Skip to content

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

feat(portability): compile Beacon for Windows

shukieshahf8638987f5aa
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index adfa1afd..8050c7cc 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -135,6 +135,9 @@ jobs:
- goos: linux
goarch: arm64
make_target: build-linux-arm64
+ - goos: windows
+ goarch: amd64
+ make_target: build-windows-amd64
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
@@ -172,6 +175,47 @@ jobs:
working-directory: pkg/asymptoteobserve
run: go test ./...
+ # Runs the unit suites on a real Windows runner. The cross-build matrix proves the code compiles
+ # for windows/amd64; this proves the per-OS implementations behave -- file locking through
+ # LockFileEx, file identity through GetFileInformationByHandle, and process liveness through
+ # OpenProcess, none of which a cross-compile exercises at all.
+ windows-test:
+ runs-on: windows-2025
+ defaults:
+ run:
+ shell: pwsh
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version-file: cli/beacon/go.mod
+ # The embedded hooks binary must match the platform under test: the CLI validates its
+ # architecture at runtime, so a placeholder fails hook installation on Windows.
+ - name: Build platform-matched hooks binary
+ working-directory: cli/beacon-hooks
+ run: |
+ go build -ldflags "-s -w" -o beacon-hooks.exe .
+ Copy-Item beacon-hooks.exe ..\beacon\internal\embedded\hooks.bin -Force
+ - name: Test beacon CLI on Windows
+ working-directory: cli/beacon
+ run: go test ./...
+ - name: Test endpoint packages with the race detector
+ working-directory: cli/beacon
+ run: go test -race ./internal/endpoint/...
+ - name: Test hook adapter on Windows
+ working-directory: cli/beacon-hooks
+ run: go test ./...
+ - name: Test collector exporter on Windows
+ working-directory: collector-builder/exporter/beaconjsonexporter
+ run: go test ./...
+ - name: Test observe SDK and threat rules on Windows
+ working-directory: pkg/asymptoteobserve
+ run: go test ./...
+ # Runs the generated-PowerShell parse test, which skips on a machine without pwsh.
+ - name: Test the sandbox harness on Windows
+ working-directory: beacon-sandbox
+ run: go test ./...
+
# Exercises the real systemd install path: unit generation, systemctl enable/active,
# Restart=always actually restarting, and uninstall leaving nothing behind. Needs systemd as
# PID 1, which only a privileged container provides -- the GitHub runner's own systemd is not
diff --git a/.github/workflows/windows-sandbox.yml b/.github/workflows/windows-sandbox.yml
index 7cd8631a..753a9253 100644
--- a/.github/workflows/windows-sandbox.yml
+++ b/.github/workflows/windows-sandbox.yml
@@ -60,18 +60,15 @@ jobs:
working-directory: beacon-sandbox
run: go test ./...
- # Beacon does not compile for Windows yet: internal/endpoint/writer, inventory, ingest and
- # service/supervised all use POSIX-only syscalls. Until that is fixed the build is expected
- # to fail, and the run continues so the probe can still report everything that does not
- # depend on a Beacon binary. Once the portability layer lands, remove continue-on-error --
- # a silently missing binary must not read as a passing run.
# The Makefile's build-windows-amd64 target is not used: GNU make is not guaranteed on the
# Windows image, and the two steps it performs are clearer spelled out than shimmed. The
# ordering is the part that matters -- the hooks binary is embedded into the CLI, so it has
# to exist before the CLI is built or the CLI embeds the placeholder.
+ #
+ # Not continue-on-error: Beacon compiles for Windows now, so a build failure is a real
+ # regression and a silently missing binary must not read as a passing run.
- name: Build beacon and beacon-hooks for Windows
id: build
- continue-on-error: true
run: |
Set-Location cli\beacon-hooks
go build -ldflags "-s -w" -o beacon-hooks.exe .
@@ -83,7 +80,6 @@ jobs:
- name: Build the collector for Windows
id: collector
- continue-on-error: true
run: |
go install go.opentelemetry.io/collector/cmd/[email protected]
Set-Location collector-builder
@@ -103,12 +99,10 @@ jobs:
- name: Stage the guest layout
run: |
New-Item -ItemType Directory -Force -Path C:\beacon-sandbox\bin, C:\beacon-sandbox\work | Out-Null
- if (Test-Path cli\beacon\beacon-windows-amd64.exe) {
- Copy-Item cli\beacon\beacon-windows-amd64.exe C:\beacon-sandbox\bin\beacon.exe
- }
- if (Test-Path collector-builder\dist\beacon-otelcol\windows_amd64\beacon-otelcol.exe) {
- Copy-Item collector-builder\dist\beacon-otelcol\windows_amd64\beacon-otelcol.exe C:\beacon-sandbox\bin\beacon-otelcol.exe
- }
+ # Both binaries must be present. A missing one would surface much later as a confusing
+ # capture gap, and the run would look like a Beacon bug rather than a staging failure.
+ Copy-Item cli\beacon\beacon-windows-amd64.exe C:\beacon-sandbox\bin\beacon.exe
+ Copy-Item collector-builder\dist\beacon-otelcol\windows_amd64\beacon-otelcol.exe C:\beacon-sandbox\bin\beacon-otelcol.exe
"C:\beacon-sandbox\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
# A seeded git repo gives scenarios somewhere realistic to work and exercises Beacon's
# repository/branch enrichment, mirroring the Linux image's fixture.
@@ -144,10 +138,8 @@ jobs:
Write-Output "identity: $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)"
$principal = New-Object Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
Write-Output "elevated: $($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))"
- Write-Output "beacon build: ${{ steps.build.outcome }}"
- Write-Output "collector build: ${{ steps.collector.outcome }}"
& claude --version
- if (Test-Path C:\beacon-sandbox\bin\beacon.exe) { & C:\beacon-sandbox\bin\beacon.exe version }
+ & C:\beacon-sandbox\bin\beacon.exe version
- name: Run the scenario
id: run
diff --git a/cli/beacon-hooks/go.mod b/cli/beacon-hooks/go.mod
index a6c1a96d..ecef7fba 100644
--- a/cli/beacon-hooks/go.mod
+++ b/cli/beacon-hooks/go.mod
@@ -1,6 +1,6 @@
module github.com/asymptote-labs/agent-beacon/cli/beacon-hooks
-go 1.24
+go 1.24.0
require (
github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve v0.0.0
@@ -12,4 +12,5 @@ replace github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve => ../../pkg
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
+ golang.org/x/sys v0.41.0 // indirect
)
diff --git a/cli/beacon-hooks/go.sum b/cli/beacon-hooks/go.sum
index 912390a7..530aa134 100644
--- a/cli/beacon-hooks/go.sum
+++ b/cli/beacon-hooks/go.sum
@@ -6,5 +6,7 @@ github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
+golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
+golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/cli/beacon-hooks/internal/cloudshuttle/shuttle.go b/cli/beacon-hooks/internal/cloudshuttle/shuttle.go
index 20396ddb..0c166fd1 100644
--- a/cli/beacon-hooks/internal/cloudshuttle/shuttle.go
+++ b/cli/beacon-hooks/internal/cloudshuttle/shuttle.go
@@ -24,8 +24,9 @@ import (
"path/filepath"
"sort"
"strings"
- "syscall"
"time"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
)
const (
@@ -212,16 +213,20 @@ func snapshotLog(logPath string) (string, func(), error) {
if err != nil {
return "", func() {}, err
}
- if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_SH); err != nil {
+ held, err := filelock.Shared(lock)
+ if err != nil {
_ = lock.Close()
return "", func() {}, err
}
- defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)
+ // Registered close-first so LIFO runs it last: the lock is released, then the handle closed.
+ // The previous order relied on closing the descriptor to drop the lock implicitly, which left
+ // the explicit unlock failing on a closed handle with its error discarded.
defer func() {
if err := lock.Close(); err != nil {
fmt.Fprintf(os.Stderr, "cloudshuttle: failed to close lock file %s.lock: %v\n", logPath, err)
}
}()
+ defer held.Release()
source, err := os.Open(logPath)
if err != nil {
diff --git a/cli/beacon-hooks/internal/logging/endpoint_event_test.go b/cli/beacon-hooks/internal/logging/endpoint_event_test.go
index 066fbfc8..ab9c747b 100644
--- a/cli/beacon-hooks/internal/logging/endpoint_event_test.go
+++ b/cli/beacon-hooks/internal/logging/endpoint_event_test.go
@@ -5,7 +5,6 @@ import (
"os"
"path/filepath"
"strings"
- "syscall"
"testing"
)
@@ -85,31 +84,6 @@ func TestEndpointEventCompactsOversizedRetainedContent(t *testing.T) {
}
}
-func TestEndpointEventCreatesSharedRuntimeFilesDespiteUmask(t *testing.T) {
- oldUmask := syscall.Umask(0022)
- t.Cleanup(func() {
- syscall.Umask(oldUmask)
- })
-
- logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
- t.Setenv("BEACON_ENDPOINT_LOG", logPath)
-
- logger := NewLoggerForPlatform("agent-thought", "cursor")
- if err := logger.EndpointEvent("agent.reasoning", "session", "info", "Agent reasoning captured", nil); err != nil {
- t.Fatalf("EndpointEvent returned error: %v", err)
- }
-
- for _, target := range []string{logPath, logPath + ".lock"} {
- info, err := os.Stat(target)
- if err != nil {
- t.Fatalf("stat %s: %v", target, err)
- }
- if got := info.Mode().Perm(); got != endpointRuntimeFileMode {
- t.Fatalf("%s mode = %o, want %o", target, got, endpointRuntimeFileMode)
- }
- }
-}
-
func TestEndpointEventAddsCloudRunMetadataFromEnvironment(t *testing.T) {
logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
t.Setenv("BEACON_ENDPOINT_LOG", logPath)
diff --git a/cli/beacon-hooks/internal/logging/endpoint_event_unix_test.go b/cli/beacon-hooks/internal/logging/endpoint_event_unix_test.go
new file mode 100644
index 00000000..ee4449fd
--- /dev/null
+++ b/cli/beacon-hooks/internal/logging/endpoint_event_unix_test.go
@@ -0,0 +1,43 @@
+//go:build !windows
+
+package logging
+
+import (
+ "os"
+ "path/filepath"
+ "syscall"
+ "testing"
+)
+
+// The hook adapter appends to a log a system-mode collector created while running elevated, so the
+// file has to stay writable by both. A restrictive umask on whichever process creates it first
+// would otherwise produce a log the other cannot write, and telemetry would stop while status kept
+// reporting healthy.
+//
+// Unix-only because umask is. On Windows the same property is an ACL on the system log directory
+// rather than a file mode, and there it is a real gap rather than a non-issue.
+
+func TestEndpointEventCreatesSharedRuntimeFilesDespiteUmask(t *testing.T) {
+ oldUmask := syscall.Umask(0022)
+ t.Cleanup(func() {
+ syscall.Umask(oldUmask)
+ })
+
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+
+ logger := NewLoggerForPlatform("agent-thought", "cursor")
+ if err := logger.EndpointEvent("agent.reasoning", "session", "info", "Agent reasoning captured", nil); err != nil {
+ t.Fatalf("EndpointEvent returned error: %v", err)
+ }
+
+ for _, target := range []string{logPath, logPath + ".lock"} {
+ info, err := os.Stat(target)
+ if err != nil {
+ t.Fatalf("stat %s: %v", target, err)
+ }
+ if got := info.Mode().Perm(); got != endpointRuntimeFileMode {
+ t.Fatalf("%s mode = %o, want %o", target, got, endpointRuntimeFileMode)
+ }
+ }
+}
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.go
index b47920d2..b45a2738 100644
--- a/cli/beacon-hooks/internal/logging/logging.go
+++ b/cli/beacon-hooks/internal/logging/logging.go
@@ -8,11 +8,11 @@ import (
"runtime"
"strconv"
"strings"
- "syscall"
"time"
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
)
const (
@@ -353,12 +353,14 @@ func appendEndpointJSONL(path string, line []byte, rotateBytes int64, rotateArch
if err != nil {
return err
}
- if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
+ held, err := filelock.Exclusive(lock)
+ if err != nil {
_ = lock.Close()
return err
}
- defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)
+ // Unlock before closing: LIFO defer ordering means the close listed first runs last.
defer lock.Close()
+ defer held.Release()
if asymptoteobserve.IsDuplicateEndpointEvent(path, line, asymptoteobserve.EndpointDuplicateWindow) {
return nil
}
diff --git a/cli/beacon/Makefile b/cli/beacon/Makefile
index b66c7c59..e630eb4f 100644
--- a/cli/beacon/Makefile
+++ b/cli/beacon/Makefile
@@ -89,13 +89,18 @@ build-linux-arm64:
$(MAKE) build-hooks-for-platform TARGET_OS=linux TARGET_ARCH=arm64
GOOS=linux GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-linux-arm64 .
-build-windows: build-windows-amd64
+build-windows: build-windows-amd64 build-windows-arm64
build-windows-amd64:
@echo "Building for Windows (amd64)..."
$(MAKE) build-hooks-for-platform TARGET_OS=windows TARGET_ARCH=amd64
GOOS=windows GOARCH=amd64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-windows-amd64.exe .
+build-windows-arm64:
+ @echo "Building for Windows (arm64)..."
+ $(MAKE) build-hooks-for-platform TARGET_OS=windows TARGET_ARCH=arm64
+ GOOS=windows GOARCH=arm64 go build -ldflags "$(LDFLAGS)" -o $(BINARY)-windows-arm64.exe .
+
# Clean build artifacts
clean:
rm -f $(BINARY) $(BINARY)-*
diff --git a/cli/beacon/cmd/endpoint_user_config.go b/cli/beacon/cmd/endpoint_user_config.go
index ad9b9f28..6e9d8266 100644
--- a/cli/beacon/cmd/endpoint_user_config.go
+++ b/cli/beacon/cmd/endpoint_user_config.go
@@ -4,12 +4,9 @@ import (
"encoding/json"
"fmt"
"os"
- "os/user"
"path/filepath"
"sort"
- "strconv"
"strings"
- "syscall"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
@@ -222,19 +219,6 @@ func collapseUserConfigBackups(path string) error {
return nil
}
-func chownUserConfigArtifacts(info consoleUserInfo, path string) error {
- uid, gid, err := userOwnership(info)
- if err != nil {
- return err
- }
- for _, candidate := range userConfigArtifacts(path) {
- if err := os.Chown(candidate, uid, gid); err != nil && !os.IsNotExist(err) {
- return err
- }
- }
- return nil
-}
-
func userConfigArtifacts(path string) []string {
artifacts := []string{filepath.Dir(path), path}
if matches, err := filepath.Glob(path + ".beacon.*.bak"); err == nil {
@@ -243,22 +227,3 @@ func userConfigArtifacts(path string) []string {
artifacts = append(artifacts, path+".beacon.bak")
return artifacts
}
-
-func userOwnership(info consoleUserInfo) (int, int, error) {
- if u, err := user.Lookup(info.Username); err == nil {
- uid, uidErr := strconv.Atoi(u.Uid)
- gid, gidErr := strconv.Atoi(u.Gid)
- if uidErr == nil && gidErr == nil {
- return uid, gid, nil
- }
- }
- stat, err := os.Stat(info.HomeDir)
- if err != nil {
- return 0, 0, err
- }
- sys, ok := stat.Sys().(*syscall.Stat_t)
- if !ok {
- return 0, 0, fmt.Errorf("could not determine ownership for %s", info.HomeDir)
- }
- return int(sys.Uid), int(sys.Gid), nil
-}
diff --git a/cli/beacon/cmd/endpoint_user_config_unix.go b/cli/beacon/cmd/endpoint_user_config_unix.go
new file mode 100644
index 00000000..c573333a
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_user_config_unix.go
@@ -0,0 +1,54 @@
+//go:build !windows
+
+package cmd
+
+import (
+ "fmt"
+ "os"
+ "os/user"
+ "strconv"
+ "syscall"
+)
+
+// chownUserConfigArtifacts gives the console user ownership of the settings files a system-mode
+// install just wrote on their behalf.
+//
+// Load-bearing rather than cosmetic. The install runs as root, so every file it creates is
+// root-owned; the person whose agent sessions matter then cannot edit their own settings, and their
+// agent may not be able to write alongside them. This is the step that hands them back.
+func chownUserConfigArtifacts(info consoleUserInfo, path string) error {
+ uid, gid, err := userOwnership(info)
+ if err != nil {
+ return err
+ }
+ for _, candidate := range userConfigArtifacts(path) {
+ if err := os.Chown(candidate, uid, gid); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+ return nil
+}
+
+// userOwnership resolves the console user's numeric uid and gid.
+//
+// The user database first, since that is the authoritative answer. Falling back to the home
+// directory's owner covers a user whose account is not in the local database -- LDAP, SSSD, a
+// container with a bare passwd file -- where the directory itself still records who they are.
+func userOwnership(info consoleUserInfo) (int, int, error) {
+ if u, err := user.Lookup(info.Username); err == nil {
+ uid, uidErr := strconv.Atoi(u.Uid)
+ gid, gidErr := strconv.Atoi(u.Gid)
+ if uidErr == nil && gidErr == nil {
+ return uid, gid, nil
+ }
+ }
+ stat, err := os.Stat(info.HomeDir)
+ if err != nil {
+ return 0, 0, err
+ }
+ sys, ok := stat.Sys().(*syscall.Stat_t)
+ if !ok {
+ return 0, 0, fmt.Errorf("could not determine ownership for %s", info.HomeDir)
+ }
+ return int(sys.Uid), int(sys.Gid), nil
+}
diff --git a/cli/beacon/cmd/endpoint_user_config_windows.go b/cli/beacon/cmd/endpoint_user_config_windows.go
new file mode 100644
index 00000000..d5da14f3
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_user_config_windows.go
@@ -0,0 +1,19 @@
+//go:build windows
+
+package cmd
+
+// chownUserConfigArtifacts is a no-op on Windows, and the reason it can be is specific rather than
+// general.
+//
+// The POSIX version exists because a system-mode install runs as root and leaves root-owned files
+// in a user's home directory, which that user then cannot edit. Windows has no uid/gid to assign --
+// ownership is a SID and access is an ACL -- but it also does not create the problem in the same
+// way: a file written under %USERPROFILE% inherits that profile's ACL, which already grants the
+// profile's owner full control. So there is nothing to hand back.
+//
+// This is not the same question as whether a *system* log directory is writable by a non-admin
+// agent process. That one Windows does get wrong by default, and it is a real gap rather than a
+// non-issue -- but it belongs with the system paths, not here.
+func chownUserConfigArtifacts(_ consoleUserInfo, _ string) error {
+ return nil
+}
diff --git a/cli/beacon/go.mod b/cli/beacon/go.mod
index 00f11086..0c1674bc 100644
--- a/cli/beacon/go.mod
+++ b/cli/beacon/go.mod
@@ -1,11 +1,12 @@
module github.com/asymptote-labs/agent-beacon/cli/beacon
-go 1.24
+go 1.24.0
require (
github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve v0.0.0
github.com/pelletier/go-toml/v2 v2.3.1
github.com/spf13/cobra v1.8.1
+ golang.org/x/sys v0.41.0
golang.org/x/term v0.33.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -22,7 +23,6 @@ require (
github.com/spf13/pflag v1.0.5 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 // indirect
- golang.org/x/sys v0.34.0 // indirect
golang.org/x/text v0.22.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240826202546-f6391c0de4c7 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240826202546-f6391c0de4c7 // indirect
diff --git a/cli/beacon/go.sum b/cli/beacon/go.sum
index 512a7bfe..a4aceac9 100644
--- a/cli/beacon/go.sum
+++ b/cli/beacon/go.sum
@@ -22,8 +22,8 @@ go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA=
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ=
-golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
-golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
+golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
diff --git a/cli/beacon/internal/endpoint/inventory/heartbeat.go b/cli/beacon/internal/endpoint/inventory/heartbeat.go
index e4cb3fd1..3b063b27 100644
--- a/cli/beacon/internal/endpoint/inventory/heartbeat.go
+++ b/cli/beacon/internal/endpoint/inventory/heartbeat.go
@@ -7,10 +7,10 @@ import (
"os"
"path/filepath"
"strings"
- "syscall"
"time"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
)
const stateFileName = "inventory-state.json"
@@ -31,6 +31,7 @@ type State struct {
type LockedState struct {
path string
file *os.File
+ lock *filelock.Lock
}
func StatePath(userMode bool) string {
@@ -63,17 +64,18 @@ func LockState(path string) (*LockedState, State, error) {
if err != nil {
return nil, State{}, err
}
- if err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX); err != nil {
+ held, err := filelock.Exclusive(file)
+ if err != nil {
_ = file.Close()
return nil, State{}, err
}
state, err := ReadState(path)
if err != nil {
- _ = syscall.Flock(int(file.Fd()), syscall.LOCK_UN)
+ _ = held.Release()
_ = file.Close()
return nil, State{}, err
}
- return &LockedState{path: path, file: file}, state, nil
+ return &LockedState{path: path, file: file, lock: held}, state, nil
}
func (s *LockedState) Save(state State) error {
@@ -94,7 +96,7 @@ func (s *LockedState) Close() error {
if s == nil || s.file == nil {
return nil
}
- unlockErr := syscall.Flock(int(s.file.Fd()), syscall.LOCK_UN)
+ unlockErr := s.lock.Release()
closeErr := s.file.Close()
if unlockErr != nil {
return unlockErr
diff --git a/cli/beacon/internal/endpoint/selfupdate/fsutil.go b/cli/beacon/internal/endpoint/selfupdate/fsutil.go
index d22f0b15..56852928 100644
--- a/cli/beacon/internal/endpoint/selfupdate/fsutil.go
+++ b/cli/beacon/internal/endpoint/selfupdate/fsutil.go
@@ -8,7 +8,8 @@ import (
"os"
"path/filepath"
"strings"
- "syscall"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
)
// maxTarEntryBytes bounds a single file extracted from a test artifact.
@@ -22,12 +23,13 @@ func acquireLock(path string) (func(), error) {
if err != nil {
return nil, err
}
- if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
+ held, err := filelock.TryExclusive(f)
+ if err != nil {
_ = f.Close()
return nil, err
}
return func() {
- _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
+ _ = held.Release()
_ = f.Close()
}, nil
}
diff --git a/cli/beacon/internal/endpoint/service/supervised.go b/cli/beacon/internal/endpoint/service/supervised.go
index b668f742..7c21efda 100644
--- a/cli/beacon/internal/endpoint/service/supervised.go
+++ b/cli/beacon/internal/endpoint/service/supervised.go
@@ -9,7 +9,6 @@ import (
"path/filepath"
"strconv"
"strings"
- "syscall"
"time"
)
@@ -122,7 +121,7 @@ func (b supervisedBackend) load(userMode bool) error {
cmd := exec.Command(st.Program, "--config", st.ConfigPath)
// Detach from this process group so the collector outlives the CLI invocation that
// started it. Without this, the collector would die with the shell that ran install.
- cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+ cmd.SysProcAttr = detachAttrs()
// Logs go to a file next to the runtime log, since there is no journal here.
logPath := filepath.Join(stateDir(userMode), "collector.out")
if f, ferr := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644); ferr == nil {
@@ -161,9 +160,10 @@ func (b supervisedBackend) unload(userMode bool) error {
if err != nil {
return nil
}
- // SIGTERM lets the collector flush and shut down cleanly; the exporter closes its file
- // on shutdown, so killing outright risks losing buffered events.
- _ = proc.Signal(syscall.SIGTERM)
+ // Ask the collector to flush and shut down cleanly; the exporter closes its file on
+ // shutdown, so killing outright risks losing buffered events. What "ask" means is
+ // platform-specific -- see terminateGracefully.
+ _ = terminateGracefully(proc)
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
if !processAlive(st.PID) {
@@ -206,15 +206,10 @@ func (b supervisedBackend) status(userMode bool) Status {
return status
}
-// processAlive reports whether a pid is live. Signal 0 performs the permission and existence
-// checks without delivering anything.
+// processAlive reports whether a pid is live.
func processAlive(pid int) bool {
if pid <= 0 {
return false
}
- proc, err := os.FindProcess(pid)
- if err != nil {
- return false
- }
- return proc.Signal(syscall.Signal(0)) == nil
+ return pidAlive(pid)
}
diff --git a/cli/beacon/internal/endpoint/service/supervised_unix.go b/cli/beacon/internal/endpoint/service/supervised_unix.go
new file mode 100644
index 00000000..16e18bcf
--- /dev/null
+++ b/cli/beacon/internal/endpoint/service/supervised_unix.go
@@ -0,0 +1,29 @@
+//go:build !windows
+
+package service
+
+import (
+ "os"
+ "syscall"
+)
+
+// detachAttrs puts the collector in its own session so it outlives the CLI invocation that
+// started it. Without it the collector dies with the shell that ran install.
+func detachAttrs() *syscall.SysProcAttr {
+ return &syscall.SysProcAttr{Setsid: true}
+}
+
+// terminateGracefully asks the collector to shut down cleanly.
+func terminateGracefully(proc *os.Process) error {
+ return proc.Signal(syscall.SIGTERM)
+}
+
+// pidAlive reports whether a pid is live. Signal 0 performs the permission and existence checks
+// without delivering anything.
+func pidAlive(pid int) bool {
+ proc, err := os.FindProcess(pid)
+ if err != nil {
+ return false
+ }
+ return proc.Signal(syscall.Signal(0)) == nil
+}
diff --git a/cli/beacon/internal/endpoint/service/supervised_windows.go b/cli/beacon/internal/endpoint/service/supervised_windows.go
new file mode 100644
index 00000000..4237c35b
--- /dev/null
+++ b/cli/beacon/internal/endpoint/service/supervised_windows.go
@@ -0,0 +1,79 @@
+//go:build windows
+
+package service
+
+import (
+ "os"
+ "syscall"
+
+ "golang.org/x/sys/windows"
+)
+
+// stillActive is the exit code GetExitCodeProcess reports for a process that has not exited.
+//
+// Spelled out because neither syscall nor x/sys/windows exports it under that name, and 259 as a
+// bare literal in the comparison below would read as arbitrary. It is also why a collector must
+// never exit with 259 of its own accord -- that would be indistinguishable from still running,
+// which is a documented Win32 caveat rather than something this code can defend against.
+const stillActive = 259
+
+// detachAttrs starts the collector detached from this process's console.
+//
+// The POSIX equivalent is setsid, and the goal is the same: the collector has to outlive the CLI
+// invocation that started it. On Windows a child shares its parent's console by default and
+// receives that console's Ctrl+C and Ctrl+Break, so closing the shell that ran install would take
+// the collector with it.
+//
+// Both flags are needed and they do different things. DETACHED_PROCESS withholds the parent's
+// console. CREATE_NEW_PROCESS_GROUP makes the child the root of its own group, which is also what
+// makes a targeted Ctrl+Break possible later -- see terminateGracefully.
+func detachAttrs() *syscall.SysProcAttr {
+ return &syscall.SysProcAttr{
+ CreationFlags: windows.DETACHED_PROCESS | windows.CREATE_NEW_PROCESS_GROUP,
+ }
+}
+
+// terminateGracefully asks the collector to shut down cleanly.
+//
+// Windows has no SIGTERM. The closest equivalent for a console program is a Ctrl+Break event sent
+// to its process group, which the Go runtime in the child translates into os.Interrupt -- so the
+// collector runs its normal shutdown and the exporter closes its file. That matters here rather
+// than being a nicety: killing outright loses whatever the exporter had buffered, which shows up as
+// missing events at the end of a log.
+//
+// Sent to the child's own group, which detachAttrs created. Passing 0 would signal *this* process's
+// group and take the CLI down with the collector.
+//
+// A failure is returned rather than swallowed, but it is not fatal to the caller: unload falls back
+// to Kill after a grace period, which is the correct escalation when a process will not stop
+// politely -- and on Windows a process with no console at all cannot receive this event.
+func terminateGracefully(proc *os.Process) error {
+ return windows.GenerateConsoleCtrlEvent(windows.CTRL_BREAK_EVENT, uint32(proc.Pid))
+}
+
+// pidAlive reports whether a pid is live.
+//
+// Signal 0 does not exist on Windows, and os.FindProcess always succeeds there, so the POSIX trick
+// reports every pid as alive -- which would make status claim a dead collector is running. The
+// process is opened and its exit code queried instead: STILL_ACTIVE means running.
+//
+// A pid that cannot be opened is reported dead. That is the right answer for the common cases (the
+// process exited, or the pid was recycled and is now something this user cannot touch), and the
+// alternative -- assuming alive when we cannot tell -- would leave `endpoint install` refusing to
+// start a collector that is not actually there.
+func pidAlive(pid int) bool {
+ // PROCESS_QUERY_LIMITED_INFORMATION rather than PROCESS_QUERY_INFORMATION: it is the narrower
+ // right and is granted for processes this one may not fully inspect, so a collector running as
+ // another user is still visible.
+ h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
+ if err != nil {
+ return false
+ }
+ defer windows.CloseHandle(h)
+
+ var code uint32
+ if err := windows.GetExitCodeProcess(h, &code); err != nil {
+ return false
+ }
+ return code == stillActive
+}
diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.go
index 01d53385..3122e677 100644
--- a/cli/beacon/internal/endpoint/writer/writer.go
+++ b/cli/beacon/internal/endpoint/writer/writer.go
@@ -8,10 +8,10 @@ import (
"path/filepath"
"strconv"
"strings"
- "syscall"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
)
const (
@@ -126,12 +126,17 @@ func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int
if err != nil {
return err
}
- if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
+ held, err := filelock.Exclusive(lock)
+ if err != nil {
_ = lock.Close()
return err
}
- defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)
+ // Unlock before closing. The previous form deferred the unlock first and the close second,
+ // which LIFO ordering ran in the opposite order -- it worked only because closing a descriptor
+ // releases the lock implicitly, leaving the explicit unlock to fail on a closed handle and have
+ // its error discarded.
defer lock.Close()
+ defer held.Release()
if asymptoteobserve.IsDuplicateEndpointEvent(path, line, asymptoteobserve.EndpointDuplicateWindow) {
return nil
}
diff --git a/cli/beacon/internal/endpoint/writer/writer_test.go b/cli/beacon/internal/endpoint/writer/writer_test.go
index 94694570..b3674672 100644
--- a/cli/beacon/internal/endpoint/writer/writer_test.go
+++ b/cli/beacon/internal/endpoint/writer/writer_test.go
@@ -7,7 +7,6 @@ import (
"strconv"
"strings"
"sync"
- "syscall"
"testing"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
@@ -44,53 +43,6 @@ func TestAppendEventWritesSingleJSONLine(t *testing.T) {
}
}
-func TestAppendEventCreatesSharedRuntimeFilesDespiteUmask(t *testing.T) {
- oldUmask := syscall.Umask(0022)
- t.Cleanup(func() {
- syscall.Umask(oldUmask)
- })
-
- path := filepath.Join(t.TempDir(), "runtime.jsonl")
- event := schema.NewEvent(schema.NewEventOptions{
- Action: "agent.detected",
- Harness: schema.HarnessInfo{Name: "test"},
- Message: "test event",
- })
- if _, err := AppendEvent(event, Options{Path: path}); err != nil {
- t.Fatalf("AppendEvent returned error: %v", err)
- }
-
- for _, target := range []string{path, path + ".lock"} {
- info, err := os.Stat(target)
- if err != nil {
- t.Fatalf("stat %s: %v", target, err)
- }
- if got := info.Mode().Perm(); got != runtimeFileMode {
- t.Fatalf("%s mode = %o, want %o", target, got, runtimeFileMode)
- }
- }
-}
-
-func TestEnsureRuntimeFileCreatesSharedRuntimeLogDespiteUmask(t *testing.T) {
- oldUmask := syscall.Umask(0022)
- t.Cleanup(func() {
- syscall.Umask(oldUmask)
- })
-
- path := filepath.Join(t.TempDir(), "runtime.jsonl")
- if err := EnsureRuntimeFile(path); err != nil {
- t.Fatalf("EnsureRuntimeFile returned error: %v", err)
- }
-
- info, err := os.Stat(path)
- if err != nil {
- t.Fatalf("stat %s: %v", path, err)
- }
- if got := info.Mode().Perm(); got != runtimeFileMode {
- t.Fatalf("%s mode = %o, want %o", path, got, runtimeFileMode)
- }
-}
-
func TestAppendEventRedactsSecrets(t *testing.T) {
path := filepath.Join(t.TempDir(), "runtime.jsonl")
event := schema.NewEvent(schema.NewEventOptions{
diff --git a/cli/beacon/internal/endpoint/writer/writer_unix_test.go b/cli/beacon/internal/endpoint/writer/writer_unix_test.go
new file mode 100644
index 00000000..1db95649
--- /dev/null
+++ b/cli/beacon/internal/endpoint/writer/writer_unix_test.go
@@ -0,0 +1,68 @@
+//go:build !windows
+
+package writer
+
+import (
+ "os"
+ "path/filepath"
+ "syscall"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+)
+
+// The runtime log has to be writable by more than its creator: a system-mode collector runs
+// elevated and creates it, while hooks running as the console user append to it. A restrictive
+// umask on the creating process would otherwise silently produce a log the hooks cannot write, and
+// telemetry would stop while status and doctor -- which describe the collector, not who exports to
+// it -- kept reporting healthy.
+//
+// Unix-only because umask is. The Windows equivalent of this property is an ACL on the system log
+// directory rather than a file mode, and it is a real gap there rather than a non-issue: %ProgramData%
+// inherits an ACL that denies non-admins write access. That belongs with the Windows system paths.
+func TestAppendEventCreatesSharedRuntimeFilesDespiteUmask(t *testing.T) {
+ oldUmask := syscall.Umask(0022)
+ t.Cleanup(func() {
+ syscall.Umask(oldUmask)
+ })
+
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "agent.detected",
+ Harness: schema.HarnessInfo{Name: "test"},
+ Message: "test event",
+ })
+ if _, err := AppendEvent(event, Options{Path: path}); err != nil {
+ t.Fatalf("AppendEvent returned error: %v", err)
+ }
+
+ for _, target := range []string{path, path + ".lock"} {
+ info, err := os.Stat(target)
+ if err != nil {
+ t.Fatalf("stat %s: %v", target, err)
+ }
+ if got := info.Mode().Perm(); got != runtimeFileMode {
+ t.Fatalf("%s mode = %o, want %o", target, got, runtimeFileMode)
+ }
+ }
+}
+
+func TestEnsureRuntimeFileCreatesSharedRuntimeLogDespiteUmask(t *testing.T) {
+ oldUmask := syscall.Umask(0022)
+ t.Cleanup(func() {
+ syscall.Umask(oldUmask)
+ })
+
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if err := EnsureRuntimeFile(path); err != nil {
+ t.Fatalf("EnsureRuntimeFile returned error: %v", err)
+ }
+
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatalf("stat %s: %v", path, err)
+ }
+ if got := info.Mode().Perm(); got != runtimeFileMode {
+ t.Fatalf("%s mode = %o, want %o", path, got, runtimeFileMode)
+ }
+}
diff --git a/cli/beacon/internal/ingest/endpoint/identity_unix.go b/cli/beacon/internal/ingest/endpoint/identity_unix.go
new file mode 100644
index 00000000..0046184a
--- /dev/null
+++ b/cli/beacon/internal/ingest/endpoint/identity_unix.go
@@ -0,0 +1,26 @@
+//go:build !windows
+
+package endpoint
+
+import (
+ "fmt"
+ "os"
+ "syscall"
+)
+
+// fileIdentity returns a stable identifier for the file behind an open handle.
+//
+// This is how the reader follows a rotated log. Rotation renames runtime.jsonl to runtime.jsonl.1,
+// so the path a saved byte offset was recorded against now names different content -- resuming from
+// that offset would skip or re-read events. Identity survives the rename, so the offset can follow
+// the content instead of the name.
+//
+// Device and inode are that identity on POSIX. An empty result means "unknown", which callers
+// already handle by falling back to path-based offsets.
+func fileIdentity(_ *os.File, info os.FileInfo) string {
+ stat, ok := info.Sys().(*syscall.Stat_t)
+ if !ok {
+ return ""
+ }
+ return fmt.Sprintf("%d:%d", stat.Dev, stat.Ino)
+}
diff --git a/cli/beacon/internal/ingest/endpoint/identity_windows.go b/cli/beacon/internal/ingest/endpoint/identity_windows.go
new file mode 100644
index 00000000..0842910f
--- /dev/null
+++ b/cli/beacon/internal/ingest/endpoint/identity_windows.go
@@ -0,0 +1,36 @@
+//go:build windows
+
+package endpoint
+
+import (
+ "fmt"
+ "os"
+
+ "golang.org/x/sys/windows"
+)
+
+// fileIdentity returns a stable identifier for the file behind an open handle.
+//
+// See the POSIX implementation for why identity rather than path: it is what lets a saved byte
+// offset follow a log's content across the rename that rotation performs.
+//
+// The Windows equivalent of device-and-inode is the volume serial number plus the 64-bit file
+// index, and unlike POSIX it is not reachable from a FileInfo -- os.Stat's Win32FileAttributeData
+// carries no index at all, which is why this takes the open handle. The handle is the one the
+// caller already opened, so no second open is needed and there is no chance of blocking the
+// collector that is writing the file.
+//
+// An empty result means "unknown", which callers already handle by falling back to path-based
+// offsets. That fallback is why this must not be left unimplemented on Windows: it would work,
+// quietly, while re-reading or skipping events on every rotation.
+func fileIdentity(f *os.File, _ os.FileInfo) string {
+ if f == nil {
+ return ""
+ }
+ var d windows.ByHandleFileInformation
+ if err := windows.GetFileInformationByHandle(windows.Handle(f.Fd()), &d); err != nil {
+ return ""
+ }
+ index := uint64(d.FileIndexHigh)<<32 | uint64(d.FileIndexLow)
+ return fmt.Sprintf("%d:%d", d.VolumeSerialNumber, index)
+}
diff --git a/cli/beacon/internal/ingest/endpoint/reader.go b/cli/beacon/internal/ingest/endpoint/reader.go
index b3877966..b9a3b318 100644
--- a/cli/beacon/internal/ingest/endpoint/reader.go
+++ b/cli/beacon/internal/ingest/endpoint/reader.go
@@ -4,13 +4,11 @@ import (
"bufio"
"bytes"
"encoding/json"
- "fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
- "syscall"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/ingest"
)
@@ -50,7 +48,7 @@ func readFileBatches(path string, activePath string, state ingest.State, maxEven
if err != nil {
return nil, err
}
- fileID := fileIdentity(info)
+ fileID := fileIdentity(file, info)
startOffset := startOffsetForFile(path, activePath, state, info.Size(), fileID)
if startOffset > 0 {
@@ -205,11 +203,3 @@ func boundedOffset(offset int64, fileSize int64) int64 {
}
return offset
}
-
-func fileIdentity(info os.FileInfo) string {
- stat, ok := info.Sys().(*syscall.Stat_t)
- if !ok {
- return ""
- }
- return fmt.Sprintf("%d:%d", stat.Dev, stat.Ino)
-}
diff --git a/cli/beacon/internal/ingest/endpoint/reader_test.go b/cli/beacon/internal/ingest/endpoint/reader_test.go
index ba11705d..2f4d66bc 100644
--- a/cli/beacon/internal/ingest/endpoint/reader_test.go
+++ b/cli/beacon/internal/ingest/endpoint/reader_test.go
@@ -264,14 +264,27 @@ func TestEndpointSourceFollowsSavedOffsetAcrossArchiveRenumbering(t *testing.T)
t.Fatal(err)
}
- info, err := os.Stat(renumberedPath)
+ // Identity is read from an open handle, not from a path: on Windows the file index is only
+ // reachable that way, and a FileInfo carries no equivalent.
+ handle, err := os.Open(renumberedPath)
if err != nil {
t.Fatal(err)
}
+ info, err := handle.Stat()
+ if err != nil {
+ t.Fatal(err)
+ }
+ identity := fileIdentity(handle, info)
+ if err := handle.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if identity == "" {
+ t.Fatal("file identity is empty, so this test cannot check that an offset follows a rotated file")
+ }
source := NewSource(endpointconfig.Config{UserMode: true, LogPath: logPath}, logPath, true)
batches, err := source.Batches(ingest.State{
FileOffsets: map[string]int64{savedPath: int64(len(first))},
- FileIDs: map[string]string{savedPath: fileIdentity(info)},
+ FileIDs: map[string]string{savedPath: identity},
}, 500, 1024)
if err != nil {
t.Fatal(err)
diff --git a/collector-builder/build-release-collectors.sh b/collector-builder/build-release-collectors.sh
index fd9c28ee..e7e99110 100755
--- a/collector-builder/build-release-collectors.sh
+++ b/collector-builder/build-release-collectors.sh
@@ -15,14 +15,20 @@ while read -r goos goarch; do
echo "Building collector for ${goos}/${goarch}"
rm -rf dist/beacon-otelcol
GOOS="$goos" GOARCH="$goarch" CGO_ENABLED=0 "$builder" --config builder.yaml
- test -x dist/beacon-otelcol/beacon-otelcol
+ # The builder appends .exe for windows, so the produced name is target-dependent.
+ binary="beacon-otelcol"
+ if [ "$goos" = "windows" ]; then
+ binary="beacon-otelcol.exe"
+ fi
+ test -f "dist/beacon-otelcol/$binary"
mkdir -p "$targets_dir/$target"
- cp dist/beacon-otelcol/beacon-otelcol "$targets_dir/$target/beacon-otelcol"
+ cp "dist/beacon-otelcol/$binary" "$targets_dir/$target/$binary"
done <<'TARGETS'
darwin amd64
darwin arm64
linux amd64
linux arm64
+windows amd64
TARGETS
rm -rf dist/beacon-otelcol
diff --git a/collector-builder/exporter/beaconjsonexporter/writer.go b/collector-builder/exporter/beaconjsonexporter/writer.go
index de015e14..48afc45d 100644
--- a/collector-builder/exporter/beaconjsonexporter/writer.go
+++ b/collector-builder/exporter/beaconjsonexporter/writer.go
@@ -7,9 +7,9 @@ import (
"path/filepath"
"strconv"
"strings"
- "syscall"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
)
type jsonlWriter struct {
@@ -137,12 +137,14 @@ func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int
if err != nil {
return err
}
- if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
+ held, err := filelock.Exclusive(lock)
+ if err != nil {
_ = lock.Close()
return err
}
- defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)
+ // Unlock before closing: LIFO defer ordering means the close listed first runs last.
defer lock.Close()
+ defer held.Release()
if asymptoteobserve.IsDuplicateEndpointEvent(path, line, asymptoteobserve.EndpointDuplicateWindow) {
return nil
}
diff --git a/collector-builder/exporter/beaconjsonexporter/writer_test.go b/collector-builder/exporter/beaconjsonexporter/writer_unix_test.go
similarity index 62%
rename from collector-builder/exporter/beaconjsonexporter/writer_test.go
rename to collector-builder/exporter/beaconjsonexporter/writer_unix_test.go
index 01967d5c..3d350c64 100644
--- a/collector-builder/exporter/beaconjsonexporter/writer_test.go
+++ b/collector-builder/exporter/beaconjsonexporter/writer_unix_test.go
@@ -1,3 +1,5 @@
+//go:build !windows
+
package beaconjsonexporter
import (
@@ -7,6 +9,13 @@ import (
"testing"
)
+// The collector runs elevated in a system-mode install and creates the runtime log, while hooks
+// running as the console user append to the same file. A restrictive umask would leave the hooks
+// unable to write, and telemetry would stop while the collector looked healthy.
+//
+// Unix-only because umask is. On Windows the equivalent property is an ACL on the system log
+// directory, which is a real gap there rather than a non-issue.
+
func TestAppendJSONLCreatesSharedRuntimeFilesDespiteUmask(t *testing.T) {
oldUmask := syscall.Umask(0022)
t.Cleanup(func() {
diff --git a/pkg/asymptoteobserve/filelock/filelock.go b/pkg/asymptoteobserve/filelock/filelock.go
new file mode 100644
index 00000000..9b8f35a1
--- /dev/null
+++ b/pkg/asymptoteobserve/filelock/filelock.go
@@ -0,0 +1,77 @@
+// Package filelock provides the advisory file locking Beacon uses to serialize appends to a
+// shared log.
+//
+// It exists because four places had hand-rolled the same `syscall.Flock` sequence -- the endpoint
+// writer, the inventory heartbeat, the hook adapter's logger, and the cloud shuttle -- and
+// syscall.Flock does not exist on Windows. One implementation with a per-OS body is both the
+// portability fix and the removal of three copies that had to be kept in step by hand.
+//
+// The contract is deliberately narrow: lock an already-open file, unlock it. Opening is left to
+// the caller because the call sites differ in ways that matter -- the runtime log's lock file is
+// created world-writable so hooks running as the console user can take it, while the others are
+// owner-only -- and folding those differences in here would mean a mode argument that each caller
+// has to get right anyway.
+package filelock
+
+import "os"
+
+// Lock is a held lock. Release unlocks; closing the file is the caller's business, since the
+// caller opened it.
+type Lock struct {
+ file *os.File
+ released bool
+}
+
+// Exclusive blocks until it holds an exclusive lock on f.
+//
+// Blocking is the required behavior, not a convenience: these locks serialize appends to a log
+// several processes write to, and a caller that gave up on contention would drop the event it was
+// about to write.
+func Exclusive(f *os.File) (*Lock, error) {
+ if f == nil {
+ return nil, os.ErrInvalid
+ }
+ if err := lockFile(f, true); err != nil {
+ return nil, err
+ }
+ return &Lock{file: f}, nil
+}
+
+// Shared blocks until it holds a shared lock on f, so several readers can proceed together while
+// excluding writers.
+func Shared(f *os.File) (*Lock, error) {
+ if f == nil {
+ return nil, os.ErrInvalid
+ }
+ if err := lockFile(f, false); err != nil {
+ return nil, err
+ }
+ return &Lock{file: f}, nil
+}
+
+// TryExclusive takes an exclusive lock or fails immediately if another holder has it.
+//
+// The opposite of Exclusive's behavior, and the difference is a design choice at each call site
+// rather than a preference. Blocking is right for a log append, where the work must not be lost.
+// Failing fast is right for the self-updater, where a second concurrent run has nothing useful to
+// add and waiting would just pile up update attempts behind each other.
+func TryExclusive(f *os.File) (*Lock, error) {
+ if f == nil {
+ return nil, os.ErrInvalid
+ }
+ if err := tryLockFile(f); err != nil {
+ return nil, err
+ }
+ return &Lock{file: f}, nil
+}
+
+// Release unlocks. Safe to call more than once, so `defer l.Release()` alongside an explicit
+// release on the success path cannot double-unlock -- on Windows that would return an error for
+// a lock the process no longer holds, which reads as a failure where there is none.
+func (l *Lock) Release() error {
+ if l == nil || l.file == nil || l.released {
+ return nil
+ }
+ l.released = true
+ return unlockFile(l.file)
+}
diff --git a/pkg/asymptoteobserve/filelock/filelock_test.go b/pkg/asymptoteobserve/filelock/filelock_test.go
new file mode 100644
index 00000000..526e498f
--- /dev/null
+++ b/pkg/asymptoteobserve/filelock/filelock_test.go
@@ -0,0 +1,134 @@
+package filelock
+
+import (
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+)
+
+func openLockFile(t *testing.T, path string) *os.File {
+ t.Helper()
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = f.Close() })
+ return f
+}
+
+// The property every call site depends on: two holders cannot be in the critical section at once.
+// Beacon uses these locks to serialize appends to one log from several processes, so an exclusive
+// lock that did not actually exclude would interleave two events on one line -- which the check
+// layer reports as a corrupt log.
+func TestExclusiveLocksSerializeWriters(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl.lock")
+
+ first := openLockFile(t, path)
+ lock, err := Exclusive(first)
+ if err != nil {
+ t.Fatalf("first exclusive lock: %v", err)
+ }
+
+ // A second handle to the same file, from this process. Both flock and LockFileEx arbitrate
+ // per-handle, so this contends exactly as another process would.
+ second := openLockFile(t, path)
+ acquired := make(chan struct{})
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ l, err := Exclusive(second)
+ if err != nil {
+ t.Errorf("second exclusive lock: %v", err)
+ return
+ }
+ close(acquired)
+ _ = l.Release()
+ }()
+
+ select {
+ case <-acquired:
+ t.Fatal("a second exclusive lock was granted while the first was held")
+ case <-time.After(150 * time.Millisecond):
+ // Still blocked, which is correct.
+ }
+
+ if err := lock.Release(); err != nil {
+ t.Fatalf("release: %v", err)
+ }
+ select {
+ case <-acquired:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the second lock was never granted after the first was released")
+ }
+ wg.Wait()
+}
+
+// Shared locks are what the cloud shuttle takes to read a log without blocking other readers, so
+// two of them must be able to coexist. If Shared silently behaved exclusively, snapshotting a log
+// would serialize against every other reader.
+func TestSharedLocksCoexist(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl.lock")
+
+ a, err := Shared(openLockFile(t, path))
+ if err != nil {
+ t.Fatalf("first shared lock: %v", err)
+ }
+ defer a.Release()
+
+ done := make(chan error, 1)
+ go func() {
+ l, err := Shared(openLockFile(t, path))
+ if err == nil {
+ _ = l.Release()
+ }
+ done <- err
+ }()
+
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Errorf("a second shared lock must be granted: %v", err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("a second shared lock blocked, so Shared is behaving exclusively")
+ }
+}
+
+// Release has to tolerate being called twice. Call sites defer it and also release on the success
+// path, and on Windows unlocking a range the process no longer holds returns an error -- which
+// would surface as a failure where nothing is wrong.
+func TestReleaseIsIdempotent(t *testing.T) {
+ lock, err := Exclusive(openLockFile(t, filepath.Join(t.TempDir(), "x.lock")))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := lock.Release(); err != nil {
+ t.Fatalf("first release: %v", err)
+ }
+ if err := lock.Release(); err != nil {
+ t.Errorf("a second release must be a no-op, got %v", err)
+ }
+}
+
+// A nil Lock must be safe, so `defer l.Release()` is writable before checking the error from
+// Exclusive -- otherwise every call site needs a nil guard and one of them will forget.
+func TestNilLockRelease(t *testing.T) {
+ var l *Lock
+ if err := l.Release(); err != nil {
+ t.Errorf("releasing a nil lock must be a no-op, got %v", err)
+ }
+}
+
+// A nil file is a programming error, and it must be reported rather than producing a Lock that
+// unlocks nothing -- a lock that silently holds nothing is worse than no lock.
+func TestNilFileIsRejected(t *testing.T) {
+ if _, err := Exclusive(nil); err == nil {
+ t.Error("Exclusive(nil) must fail")
+ }
+ if _, err := Shared(nil); err == nil {
+ t.Error("Shared(nil) must fail")
+ }
+}
diff --git a/pkg/asymptoteobserve/filelock/filelock_unix.go b/pkg/asymptoteobserve/filelock/filelock_unix.go
new file mode 100644
index 00000000..2449776b
--- /dev/null
+++ b/pkg/asymptoteobserve/filelock/filelock_unix.go
@@ -0,0 +1,27 @@
+//go:build !windows
+
+package filelock
+
+import (
+ "os"
+ "syscall"
+)
+
+// lockFile takes a BSD advisory lock, blocking until it is granted.
+func lockFile(f *os.File, exclusive bool) error {
+ how := syscall.LOCK_SH
+ if exclusive {
+ how = syscall.LOCK_EX
+ }
+ return syscall.Flock(int(f.Fd()), how)
+}
+
+// tryLockFile takes an exclusive lock without waiting, reporting EWOULDBLOCK when another holder
+// has it.
+func tryLockFile(f *os.File) error {
+ return syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
+}
+
+func unlockFile(f *os.File) error {
+ return syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
+}
diff --git a/pkg/asymptoteobserve/filelock/filelock_windows.go b/pkg/asymptoteobserve/filelock/filelock_windows.go
new file mode 100644
index 00000000..ea3f6121
--- /dev/null
+++ b/pkg/asymptoteobserve/filelock/filelock_windows.go
@@ -0,0 +1,52 @@
+//go:build windows
+
+package filelock
+
+import (
+ "os"
+
+ "golang.org/x/sys/windows"
+)
+
+// lockRange is the byte range every lock covers: the whole theoretically-addressable file.
+//
+// The whole range rather than one byte, because LockFileEx locks ranges rather than files and two
+// locks only conflict where they overlap. A one-byte lock would let a caller that picked a
+// different offset proceed concurrently, which is the opposite of what these locks are for. The
+// lock files themselves are empty -- they are pure mutexes, never read or written -- so locking
+// past the end of the file is both legal and free.
+const (
+ lockRangeLow = ^uint32(0)
+ lockRangeHigh = ^uint32(0)
+)
+
+// lockFile takes a byte-range lock, blocking until it is granted.
+//
+// Blocking is the default: without LOCKFILE_FAIL_IMMEDIATELY, LockFileEx waits, which matches
+// flock's behavior on the other platforms. Getting that backwards would turn contention into a
+// dropped event rather than a short wait.
+func lockFile(f *os.File, exclusive bool) error {
+ var flags uint32
+ if exclusive {
+ flags = windows.LOCKFILE_EXCLUSIVE_LOCK
+ }
+ // A zeroed OVERLAPPED means offset 0, which is what the full-range lock above assumes.
+ var overlapped windows.Overlapped
+ return windows.LockFileEx(windows.Handle(f.Fd()), flags,
+ 0, lockRangeLow, lockRangeHigh, &overlapped)
+}
+
+// tryLockFile takes an exclusive lock without waiting, reporting ERROR_LOCK_VIOLATION when another
+// holder has it.
+func tryLockFile(f *os.File) error {
+ var overlapped windows.Overlapped
+ return windows.LockFileEx(windows.Handle(f.Fd()),
+ windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY,
+ 0, lockRangeLow, lockRangeHigh, &overlapped)
+}
+
+func unlockFile(f *os.File) error {
+ var overlapped windows.Overlapped
+ return windows.UnlockFileEx(windows.Handle(f.Fd()),
+ 0, lockRangeLow, lockRangeHigh, &overlapped)
+}
diff --git a/pkg/asymptoteobserve/go.mod b/pkg/asymptoteobserve/go.mod
index 92588bde..78286690 100644
--- a/pkg/asymptoteobserve/go.mod
+++ b/pkg/asymptoteobserve/go.mod
@@ -1,8 +1,12 @@
module github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve
-go 1.24
+go 1.24.0
-require github.com/google/cel-go v0.28.1
+require (
+ github.com/google/cel-go v0.28.1
+ golang.org/x/sys v0.41.0
+ gopkg.in/yaml.v3 v3.0.1
+)
require (
cel.dev/expr v0.25.1 // indirect
@@ -13,5 +17,4 @@ require (
google.golang.org/genproto/googleapis/api v0.0.0-20240826202546-f6391c0de4c7 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240826202546-f6391c0de4c7 // indirect
google.golang.org/protobuf v1.36.10 // indirect
- gopkg.in/yaml.v3 v3.0.1 // indirect
)
diff --git a/pkg/asymptoteobserve/go.sum b/pkg/asymptoteobserve/go.sum
index 9cf16414..50afc119 100644
--- a/pkg/asymptoteobserve/go.sum
+++ b/pkg/asymptoteobserve/go.sum
@@ -10,6 +10,8 @@ go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA=
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ=
+golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
+golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
google.golang.org/genproto/googleapis/api v0.0.0-20240826202546-f6391c0de4c7 h1:YcyjlL1PRr2Q17/I0dPk2JmYS5CDXfcdb2Z3YRioEbw=