Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Restore QNAP agent boot and update continuity

rcourtman21950c6e4c4a
diff --git a/cmd/pulse-agent/main.go b/cmd/pulse-agent/main.go
index 9ce785a830..7d24980452 100644
--- a/cmd/pulse-agent/main.go
+++ b/cmd/pulse-agent/main.go
@@ -68,8 +68,9 @@ var (
newHostAgent func(hostagent.Config) (Runnable, error) = func(c hostagent.Config) (Runnable, error) {
return hostagent.New(c)
}
- lookPath = exec.LookPath
- runAsWindowsServiceFunc = runAsWindowsService
+ newUpdater func(agentupdate.Config) *agentupdate.Updater = agentupdate.New
+ lookPath = exec.LookPath
+ runAsWindowsServiceFunc = runAsWindowsService
// For testing
retryInitialDelay = 5 * time.Second
@@ -253,11 +254,12 @@ func run(ctx context.Context, args []string, getenv func(string) string) error {
}
// 7. Start Auto-Updater
- updater := agentupdate.New(agentupdate.Config{
+ updater := newUpdater(agentupdate.Config{
PulseURL: cfg.PulseURL,
APIToken: cfg.APIToken,
AgentName: "pulse-agent",
CurrentVersion: Version,
+ StateDir: cfg.StateDir,
CheckInterval: 1 * time.Hour,
InsecureSkipVerify: cfg.InsecureSkipVerify,
CACertPath: cfg.CACertPath,
diff --git a/cmd/pulse-agent/main_test.go b/cmd/pulse-agent/main_test.go
index a165b8cb4c..85e9640d64 100644
--- a/cmd/pulse-agent/main_test.go
+++ b/cmd/pulse-agent/main_test.go
@@ -14,6 +14,7 @@ import (
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentupdate"
"github.com/rcourtman/pulse-go-rewrite/internal/dockeragent"
"github.com/rcourtman/pulse-go-rewrite/internal/hostagent"
"github.com/rcourtman/pulse-go-rewrite/internal/kubernetesagent"
@@ -1335,6 +1336,53 @@ func TestRun_Success(t *testing.T) {
}
}
+func TestRun_PassesStateDirToUpdaterAndHostAgent(t *testing.T) {
+ origUpdater := newUpdater
+ origHost := newHostAgent
+ defer func() {
+ newUpdater = origUpdater
+ newHostAgent = origHost
+ }()
+
+ var updaterCfg agentupdate.Config
+ var hostCfg hostagent.Config
+
+ newUpdater = func(cfg agentupdate.Config) *agentupdate.Updater {
+ updaterCfg = cfg
+ return agentupdate.New(agentupdate.Config{
+ PulseURL: "https://pulse.example.com",
+ AgentName: cfg.AgentName,
+ CurrentVersion: "1.0.0",
+ StateDir: cfg.StateDir,
+ Disabled: true,
+ })
+ }
+ newHostAgent = func(cfg hostagent.Config) (Runnable, error) {
+ hostCfg = cfg
+ return &mockRunnable{}, nil
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ defer cancel()
+
+ err := run(ctx, []string{
+ "-token", "deadbeef",
+ "-enable-docker=false",
+ "-enable-kubernetes=false",
+ "-state-dir", "/share/CACHEDEV1_DATA/.pulse-agent",
+ }, func(string) string { return "" })
+ if err != nil && err != context.Canceled && err != context.DeadlineExceeded {
+ t.Fatalf("run returned error: %v", err)
+ }
+
+ if updaterCfg.StateDir != "/share/CACHEDEV1_DATA/.pulse-agent" {
+ t.Fatalf("updater state dir = %q, want %q", updaterCfg.StateDir, "/share/CACHEDEV1_DATA/.pulse-agent")
+ }
+ if hostCfg.StateDir != "/share/CACHEDEV1_DATA/.pulse-agent" {
+ t.Fatalf("host agent state dir = %q, want %q", hostCfg.StateDir, "/share/CACHEDEV1_DATA/.pulse-agent")
+ }
+}
+
func TestRun_AgentFailure(t *testing.T) {
origDocker := newDockerAgent
defer func() {
diff --git a/cmd/pulse-agent/service_windows.go b/cmd/pulse-agent/service_windows.go
index cc6ce1f0db..0b5adc0458 100644
--- a/cmd/pulse-agent/service_windows.go
+++ b/cmd/pulse-agent/service_windows.go
@@ -40,11 +40,12 @@ func (ws *windowsService) Execute(args []string, r <-chan svc.ChangeRequest, cha
g, ctx := errgroup.WithContext(ctx)
// Start Auto-Updater
- updater := agentupdate.New(agentupdate.Config{
+ updater := newUpdater(agentupdate.Config{
PulseURL: ws.cfg.PulseURL,
APIToken: ws.cfg.APIToken,
AgentName: "pulse-agent",
CurrentVersion: Version,
+ StateDir: ws.cfg.StateDir,
CheckInterval: 1 * time.Hour,
InsecureSkipVerify: ws.cfg.InsecureSkipVerify,
CACertPath: ws.cfg.CACertPath,
diff --git a/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-2026-04-21.md b/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-2026-04-21.md
index be6af201fe..39c8ef7d93 100644
--- a/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-2026-04-21.md
+++ b/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-2026-04-21.md
@@ -98,6 +98,30 @@
- the current v6 candidate no longer knowingly lacks protection for the specific RC-era RAM inflation, disappearing guest disk, or disappearing guest interface symptoms tracked in `#1319`.
- the GitHub issue may still remain open for reporter confirmation on a real v6 build, but it is no longer an unexamined RC3 blocker on the candidate itself.
+10. `#1420` (`[Bug]: Pulse Agent does not auto-update on Qnap Platforms`)
+ - Fixed on the current `pulse/v6-release` candidate by restoring the canonical QNAP persistence contract across both installer bootstrap and self-update:
+ - `scripts/install.sh` again provisions a QNAP-specific persistent state directory and wrapper on the writable data volume instead of assuming `/usr/local/bin` survives reboot
+ - `internal/agentupdate/update.go` now updates that persisted QNAP binary copy after a successful self-update so the next reboot keeps the same version the live runtime just installed
+ - Verification:
+ - `bash -n scripts/install.sh`
+ - `go test ./internal/agentupdate`
+ - `go test ./scripts/installtests`
+ - `go test ./cmd/pulse-agent`
+ - Result:
+ - the current v6 candidate no longer knowingly carries the QNAP auto-update regression where the running agent could update in place but reboot back to the older persisted binary.
+
+11. `#1422` (`[Bug]: agent does not start on QNAP boot, fails due to hard drive encyption?`)
+ - Fixed on the current `pulse/v6-release` candidate by restoring the canonical QNAP boot path in a safer shape than the old implementation:
+ - the installer now writes the QNAP `autorun.sh` entry as a deferred bootstrap on the flash-backed config partition
+ - that bootstrap waits for the persistent data-volume wrapper to become available before launching it, instead of trying to execute the encrypted-volume wrapper directly during early boot
+ - uninstall now removes the same QNAP `autorun.sh` block and persistent state directory through the installer-owned lifecycle path
+ - Verification:
+ - `bash -n scripts/install.sh`
+ - `go test ./scripts/installtests`
+ - `go test ./cmd/pulse-agent`
+ - Result:
+ - the current v6 candidate no longer knowingly depends on the old early-boot QNAP startup path that could fail before the encrypted data volume was available.
+
## Outcome
- The RC-era issue set admitted into the v6 GA bar on `2026-04-21` is now covered by the candidate.
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 2007c8ec0c..e72d6a4134 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -207,7 +207,9 @@ an add-only capacity posture.
shared backend API tree.
6. Keep legacy Unified Agent compatibility names explicitly secondary when touching shared `internal/api/` runtime helpers: the legacy host-route family and `host-agent:*` scope names may remain as ingress or migration aliases, but they must not retake primary ownership in router state, live runtime scope checks, handler commentary, or operator-facing guidance.
7. Add or change the unified agent CLI entrypoint, version/help exit semantics, or startup argument/error routing through `cmd/pulse-agent/main.go`.
+ The CLI entrypoint owns propagation of persistence context into runtime-owned helpers. When installer-selected state roots differ from the default, `cmd/pulse-agent/main.go` must pass that exact `StateDir` through both the host-agent runtime and updater startup paths instead of letting one path silently fall back to `/var/lib/pulse-agent`.
8. Add or change installer flags, persisted service arguments, or upgrade-safe re-entry behavior through `scripts/install.sh` and `scripts/install.ps1`.
+ Persistence-sensitive NAS targets must keep one canonical continuity model here: installer-owned bootstraps may use flash-backed or immutable-root launch hooks only as thin trampolines, while the durable wrapper, state, and reboot-surviving binary copy stay in the governed persistent state directory that updater continuity also refreshes.
9. Add or change profile management, the extracted agent profiles runtime owner, the top-level infrastructure ledger, the pure unified-agent inventory/install model, the connections-ledger workspace shell, the unified ConnectionEditor and its per-type credential slots, route model, shared install section owner, the shared direct-node/discovery infrastructure settings owners plus their model, shared frontend install-command assembly, Proxmox setup/install API transport, TrueNAS platform-connection management, VMware platform-connection management, the shared monitored-system admission preview shell for those platform connections, setup-completion install handoff transport, deploy-fallback manual install transport, and fleet-control presentation through `frontend-modern/src/api/agentProfiles.ts`, `frontend-modern/src/api/nodes.ts`, `frontend-modern/src/components/Settings/AgentProfilesPanel.tsx`, `frontend-modern/src/components/Settings/useAgentProfilesPanelState.ts`, `frontend-modern/src/components/Settings/ConnectionsTable.tsx`, `frontend-modern/src/components/Settings/connectionsTableModel.ts`, `frontend-modern/src/components/Settings/useConnectionsLedger.ts`, `frontend-modern/src/components/Settings/useConnectionRowActions.ts`, `frontend-modern/src/components/Settings/ConnectionEditor/ConnectionEditor.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/AddressProbeStep.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/useConnectionEditor.ts`, `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/NodeCredentialSlot.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/TrueNASCredentialSlot.tsx`, `frontend-modern/src/components/Settings/ConnectionEditor/CredentialSlots/VMwareCredentialSlot.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/InfrastructureInstallerSection.tsx`, `frontend-modern/src/components/Settings/InfrastructureWorkspace.tsx`, `frontend-modern/src/components/Settings/infrastructureWorkspaceModel.ts`, `frontend-modern/src/components/Settings/MonitoredSystemAdmissionPreview.tsx`, `frontend-modern/src/components/Settings/platformConnectionsModel.ts`, `frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts`, `frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts`, `frontend-modern/src/components/Settings/proxmoxSettingsModel.ts`, `frontend-modern/src/components/Settings/ConfiguredNodeTables.tsx`, `frontend-modern/src/components/Settings/SettingsSectionNav.tsx`, `frontend-modern/src/components/Settings/infrastructureSettingsModel.ts`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureSettingsState.ts`, `frontend-modern/src/components/Settings/nodeModalModel.ts`, `frontend-modern/src/components/Settings/useNodeModalState.ts`, `frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx`, and `frontend-modern/src/utils/agentInstallCommand.ts`. Phase 9 retired the legacy reporting/inventory surface (InfrastructureOperationsController, InfrastructureInventorySection, InfrastructureActiveRowDetails, InfrastructureIgnoredRowDetails, InfrastructureStopMonitoringDialog, useInfrastructureReportingState) and the per-type shells (PlatformConnectionsWorkspace, ProxmoxSettingsPanel, ProxmoxDirectWorkspace, ProxmoxConfiguredNodesTable, ProxmoxDirectConnectionsCard, ProxmoxDiscoveryResultsCard, ProxmoxDeleteNodeDialog, ProxmoxNodeModalStack, NodeModal shell, TrueNASSettingsPanel, VMwareSettingsPanel, useProxmoxDirectWorkspaceState); lifecycle extensions must route through the unified aggregator ledger plus ConnectionEditor credential slots rather than reintroducing those retired surfaces.
Those lifecycle-owned settings hooks may consume websocket state only through `frontend-modern/src/contexts/appRuntime.ts`; they must not import `frontend-modern/src/App.tsx` or recreate root-shell providers.
Public demo and other read-only settings posture must stay reporting-first
@@ -2381,3 +2383,9 @@ without breaking navigation.
a single `INFRASTRUCTURE_PATH` constant (`/settings/infrastructure`) for all
install and platform-connection CTAs, replacing the former pair of
`INFRASTRUCTURE_INSTALL_PATH` and `INFRASTRUCTURE_PLATFORMS_PATH` constants.
+Installer-owned runtime continuity on persistence-sensitive NAS platforms is
+also explicit again: `scripts/install.sh` now owns the QNAP bootstrap contract
+that waits for the persistent data volume before launching the stored wrapper,
+and `internal/agentupdate/update.go` keeps the persisted QNAP binary copy in
+sync on self-update so reboot does not roll the runtime back to an older
+binary.
diff --git a/docs/release-control/v6/internal/subsystems/deployment-installability.md b/docs/release-control/v6/internal/subsystems/deployment-installability.md
index ac3d49ce1c..5894671fbc 100644
--- a/docs/release-control/v6/internal/subsystems/deployment-installability.md
+++ b/docs/release-control/v6/internal/subsystems/deployment-installability.md
@@ -1019,3 +1019,10 @@ render release installers with that pinned SSH verifier, emit both `.sig` and
those signatures with the matching release packet so published RC/stable
downloads can keep the updater and installer trust chain fail-closed instead
of downgrading to checksum-only trust.
+The shell-installer boundary now also owns the QNAP boot bootstrap and
+teardown contract end to end: `scripts/install.sh` must persist the wrapper on
+the writable data volume, write a flash-backed `autorun.sh` block that waits
+for that volume before launching the wrapper, recover the same state during
+uninstall, and keep the persisted boot copy aligned with updater-owned runtime
+binary replacements instead of assuming `/usr/local/bin` survives reboot on
+QTS/QuTS hero.
diff --git a/internal/agentupdate/coverage_test.go b/internal/agentupdate/coverage_test.go
index fbdcee0a68..6467fc9996 100644
--- a/internal/agentupdate/coverage_test.go
+++ b/internal/agentupdate/coverage_test.go
@@ -1305,6 +1305,93 @@ func TestPerformUpdateUnraidPaths(t *testing.T) {
})
}
+func TestPerformUpdateQNAPPaths(t *testing.T) {
+ data := testBinary()
+ check := checksum(data)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Checksum-Sha256", check)
+ _, _ = w.Write(data)
+ }))
+ t.Cleanup(server.Close)
+
+ _, execPath := writeTempExec(t)
+ u := newUpdaterForTest(server.URL)
+ u.client = server.Client()
+
+ origQnapGetcfg := qnapGetcfgPath
+ origQnapQpkgConf := qnapQpkgConfPath
+ origQnapPersist := qnapPersistentPathFn
+ origRead := readFileFn
+ origWrite := writeFileFn
+ origRename := renameFn
+ origRestart := restartProcessFn
+ t.Cleanup(func() {
+ qnapGetcfgPath = origQnapGetcfg
+ qnapQpkgConfPath = origQnapQpkgConf
+ qnapPersistentPathFn = origQnapPersist
+ readFileFn = origRead
+ writeFileFn = origWrite
+ renameFn = origRename
+ restartProcessFn = origRestart
+ })
+
+ tmpDir := t.TempDir()
+ qnapGetcfgPath = filepath.Join(tmpDir, "getcfg")
+ if err := os.WriteFile(qnapGetcfgPath, []byte("#!/bin/sh\n"), 0755); err != nil {
+ t.Fatalf("write qnap marker: %v", err)
+ }
+ qnapQpkgConfPath = filepath.Join(tmpDir, "qpkg.conf")
+
+ persistDir := filepath.Join(tmpDir, "state")
+ if err := os.MkdirAll(persistDir, 0755); err != nil {
+ t.Fatalf("mkdir qnap state: %v", err)
+ }
+ persistPath := filepath.Join(persistDir, "pulse-agent")
+ u.cfg.StateDir = persistDir
+ qnapPersistentPathFn = func(string, string) string { return persistPath }
+ restartProcessFn = func(string) error { return nil }
+
+ t.Run("WriteError", func(t *testing.T) {
+ readFileFn = func(string) ([]byte, error) { return []byte("new"), nil }
+ writeFileFn = func(string, []byte, os.FileMode) error { return errors.New("write fail") }
+ renameFn = os.Rename
+ if err := u.performUpdateWithExecPath(context.Background(), execPath); err != nil {
+ t.Fatalf("expected update success, got %v", err)
+ }
+ })
+
+ t.Run("RenameError", func(t *testing.T) {
+ readFileFn = func(string) ([]byte, error) { return []byte("new"), nil }
+ writeFileFn = os.WriteFile
+ renameFn = func(oldPath, newPath string) error {
+ if newPath == persistPath {
+ return errors.New("rename fail")
+ }
+ return os.Rename(oldPath, newPath)
+ }
+ if err := u.performUpdateWithExecPath(context.Background(), execPath); err != nil {
+ t.Fatalf("expected update success, got %v", err)
+ }
+ })
+
+ t.Run("Success", func(t *testing.T) {
+ readFileFn = func(string) ([]byte, error) { return []byte("new"), nil }
+ writeFileFn = os.WriteFile
+ renameFn = os.Rename
+ if err := u.performUpdateWithExecPath(context.Background(), execPath); err != nil {
+ t.Fatalf("expected update success, got %v", err)
+ }
+ got, err := os.ReadFile(persistPath)
+ if err != nil {
+ t.Fatalf("read qnap persistent binary: %v", err)
+ }
+ if string(got) != "new" {
+ t.Fatalf("qnap persistent binary = %q, want %q", string(got), "new")
+ }
+ })
+}
+
type errorReader struct {
sent bool
}
diff --git a/internal/agentupdate/update.go b/internal/agentupdate/update.go
index ee6f5fdbcf..9d8f3081e1 100644
--- a/internal/agentupdate/update.go
+++ b/internal/agentupdate/update.go
@@ -73,7 +73,10 @@ var (
runtimeGOARCH = runtime.GOARCH
unameCommand = func() ([]byte, error) { return exec.Command("uname", "-m").Output() }
unraidVersionPath = "/etc/unraid-version"
+ qnapGetcfgPath = "/sbin/getcfg"
+ qnapQpkgConfPath = "/etc/config/qpkg.conf"
unraidPersistentPathFn = unraidPersistentPath
+ qnapPersistentPathFn = qnapPersistentPath
restartProcessFn = restartProcess
osExecutableFn = os.Executable
evalSymlinksFn = filepath.EvalSymlinks
@@ -100,6 +103,9 @@ type Config struct {
// CurrentVersion is the version currently running
CurrentVersion string
+ // StateDir is the persistent state directory used by the runtime installer.
+ StateDir string
+
// CheckInterval is how often to check for updates (default: 1 hour)
CheckInterval time.Duration
@@ -477,6 +483,14 @@ func isUnraid() bool {
return err == nil
}
+func isQNAP() bool {
+ if _, err := os.Stat(qnapGetcfgPath); err == nil {
+ return true
+ }
+ _, err := os.Stat(qnapQpkgConfPath)
+ return err == nil
+}
+
// verifyBinaryMagic checks that the file is a valid executable for the current platform
func verifyBinaryMagic(path string) (retErr error) {
f, err := os.Open(path)
@@ -538,6 +552,18 @@ func unraidPersistentPath(agentName string) string {
return fmt.Sprintf("/boot/config/plugins/%s/%s", agentName, agentName)
}
+func qnapPersistentPath(stateDir, agentName string) string {
+ name, err := normalizeAgentName(agentName)
+ if err != nil {
+ return ""
+ }
+ stateDir = strings.TrimSpace(stateDir)
+ if stateDir == "" {
+ return ""
+ }
+ return filepath.Join(stateDir, name)
+}
+
func normalizeAgentName(agentName string) (string, error) {
name := strings.TrimSpace(agentName)
if name == "" {
@@ -738,26 +764,15 @@ func (u *Updater) performUpdateWithExecPath(ctx context.Context, execPath string
if isUnraid() {
persistPath := unraidPersistentPathFn(agentName)
if _, err := os.Stat(persistPath); err == nil {
- // Persistent path exists, update it
- u.logger.Debug().Str("path", persistPath).Msg("updating unraid persistent binary")
-
- // Read the newly installed binary
- newBinary, err := readFileFn(execPath)
- if err != nil {
- u.logger.Warn().Err(err).Str("path", execPath).Msg("failed to read new binary for unraid persistence")
- } else {
- // Write to persistent storage (atomic via temp file)
- tmpPersist := persistPath + ".tmp"
- if err := writeFileFn(tmpPersist, newBinary, 0644); err != nil {
- u.logger.Warn().Err(err).Str("path", tmpPersist).Msg("failed to write unraid persistent binary")
- } else if err := renameFn(tmpPersist, persistPath); err != nil {
- u.logger.Warn().Err(err).Msg("Failed to rename Unraid persistent binary")
- if removeErr := os.Remove(tmpPersist); removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) {
- u.logger.Warn().Err(removeErr).Str("path", tmpPersist).Msg("Failed to remove temporary Unraid persistent binary")
- }
- } else {
- u.logger.Info().Str("path", persistPath).Msg("updated unraid persistent binary")
- }
+ u.syncPersistentBinaryCopy(execPath, persistPath, "unraid")
+ }
+ }
+
+ if isQNAP() {
+ persistPath := qnapPersistentPathFn(u.cfg.StateDir, agentName)
+ if persistPath != "" {
+ if _, err := os.Stat(filepath.Dir(persistPath)); err == nil {
+ u.syncPersistentBinaryCopy(execPath, persistPath, "qnap")
}
}
}
@@ -766,6 +781,31 @@ func (u *Updater) performUpdateWithExecPath(ctx context.Context, execPath string
return restartProcessFn(execPath)
}
+func (u *Updater) syncPersistentBinaryCopy(execPath, persistPath, platform string) {
+ u.logger.Debug().Str("path", persistPath).Str("platform", platform).Msg("updating persistent binary")
+
+ newBinary, err := readFileFn(execPath)
+ if err != nil {
+ u.logger.Warn().Err(err).Str("path", execPath).Str("platform", platform).Msg("failed to read new binary for persistent update")
+ return
+ }
+
+ tmpPersist := persistPath + ".tmp"
+ if err := writeFileFn(tmpPersist, newBinary, 0644); err != nil {
+ u.logger.Warn().Err(err).Str("path", tmpPersist).Str("platform", platform).Msg("failed to write persistent binary")
+ return
+ }
+ if err := renameFn(tmpPersist, persistPath); err != nil {
+ u.logger.Warn().Err(err).Str("path", persistPath).Str("platform", platform).Msg("failed to replace persistent binary")
+ if removeErr := os.Remove(tmpPersist); removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) {
+ u.logger.Warn().Err(removeErr).Str("path", tmpPersist).Str("platform", platform).Msg("failed to remove temporary persistent binary")
+ }
+ return
+ }
+
+ u.logger.Info().Str("path", persistPath).Str("platform", platform).Msg("updated persistent binary")
+}
+
// GetUpdatedFromVersion checks if the agent was recently updated and returns the previous version.
// Returns empty string if no update info exists. Clears the info file after reading.
func GetUpdatedFromVersion() string {
diff --git a/internal/agentupdate/update_test.go b/internal/agentupdate/update_test.go
index b3391fe811..279fc7a349 100644
--- a/internal/agentupdate/update_test.go
+++ b/internal/agentupdate/update_test.go
@@ -82,6 +82,49 @@ func TestUnraidPersistentPath(t *testing.T) {
}
}
+func TestQnapPersistentPath(t *testing.T) {
+ tests := []struct {
+ name string
+ stateDir string
+ agentName string
+ expected string
+ }{
+ {
+ name: "canonical qnap state dir",
+ stateDir: "/share/CACHEDEV1_DATA/.pulse-agent",
+ agentName: "pulse-agent",
+ expected: "/share/CACHEDEV1_DATA/.pulse-agent/pulse-agent",
+ },
+ {
+ name: "trims state dir whitespace",
+ stateDir: " /share/MD0_DATA/.pulse-agent ",
+ agentName: "custom-agent",
+ expected: "/share/MD0_DATA/.pulse-agent/custom-agent",
+ },
+ {
+ name: "empty state dir",
+ stateDir: "",
+ agentName: "pulse-agent",
+ expected: "",
+ },
+ {
+ name: "invalid agent name",
+ stateDir: "/share/CACHEDEV1_DATA/.pulse-agent",
+ agentName: "../pulse-agent",
+ expected: "",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ result := qnapPersistentPath(tc.stateDir, tc.agentName)
+ if result != tc.expected {
+ t.Errorf("qnapPersistentPath(%q, %q) = %q, want %q", tc.stateDir, tc.agentName, result, tc.expected)
+ }
+ })
+ }
+}
+
func TestVerifyBinaryMagic_ELF(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("ELF verification test only runs on Linux")
diff --git a/scripts/install.sh b/scripts/install.sh
index f1a54a36a9..c2c3a2c364 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
#
# Pulse Unified Agent Installer
-# Supports: Linux (systemd, OpenRC, SysV init), macOS (launchd), FreeBSD (rc.d), Synology DSM (6.x/7+), Unraid
+# Supports: Linux (systemd, OpenRC, SysV init), macOS (launchd), FreeBSD (rc.d), Synology DSM (6.x/7+), Unraid, QNAP QTS/QuTS hero, TrueNAS
#
# Usage:
# curl -fsSL http://pulse/install.sh | bash -s -- --url http://pulse --token <token> [options]
@@ -739,6 +739,150 @@ complete_installation_flow() {
fi
}
+portable_sed_in_place() {
+ local expr="$1"
+ local target="$2"
+
+ sed -i '' "$expr" "$target" 2>/dev/null || sed -i "$expr" "$target" 2>/dev/null || true
+}
+
+detect_qnap_data_volume() {
+ local qnap_vol=""
+ local candidate=""
+
+ if command -v getcfg >/dev/null 2>&1; then
+ qnap_vol=$(getcfg SHARE_DEF defVolMP -f /etc/config/def_share.info 2>/dev/null || echo "")
+ qnap_vol="${qnap_vol%/}"
+ if [[ -n "$qnap_vol" ]] && [[ -d "$qnap_vol" ]] && [[ -w "$qnap_vol" ]]; then
+ printf '%s\n' "$qnap_vol"
+ return 0
+ fi
+ fi
+
+ for candidate in /share/CACHEDEV1_DATA /share/CACHEDEV2_DATA /share/MD0_DATA /share/HDA_DATA; do
+ if [[ -d "$candidate" ]] && [[ -w "$candidate" ]]; then
+ printf '%s\n' "$candidate"
+ return 0
+ fi
+ done
+
+ return 1
+}
+
+find_qnap_state_dir() {
+ local candidate=""
+
+ if [[ -n "$STATE_DIR" ]] && [[ "$STATE_DIR" != "/var/lib/pulse-agent" ]]; then
+ if [[ -d "$STATE_DIR" ]] || [[ -f "$STATE_DIR/connection.env" ]] || [[ -f "$STATE_DIR/agent-id" ]]; then
+ printf '%s\n' "$STATE_DIR"
+ return 0
+ fi
+ fi
+
+ candidate=$(detect_qnap_data_volume || true)
+ if [[ -n "$candidate" ]]; then
+ printf '%s\n' "${candidate}/.pulse-agent"
+ return 0
+ fi
+
+ for candidate in /share/CACHEDEV1_DATA/.pulse-agent /share/CACHEDEV2_DATA/.pulse-agent /share/MD0_DATA/.pulse-agent /share/HDA_DATA/.pulse-agent; do
+ if [[ -d "$candidate" ]] || [[ -f "$candidate/connection.env" ]] || [[ -f "$candidate/agent-id" ]]; then
+ printf '%s\n' "$candidate"
+ return 0
+ fi
+ done
+
+ return 1
+}
+
+remove_qnap_autorun_block() {
+ local autorun_path="$1"
+
+ portable_sed_in_place '/^# Pulse Agent bootstrap begin$/,/^# Pulse Agent bootstrap end$/d' "$autorun_path"
+ portable_sed_in_place '/^# Pulse Agent$/d' "$autorun_path"
+ portable_sed_in_place '/start-pulse-agent\.sh/d' "$autorun_path"
+}
+
+write_qnap_wrapper_script() {
+ local wrapper_script="$1"
+ local runtime_binary="$2"
+ local stored_binary="$3"
+ local export_ssl_cert=""
+
+ if [[ -n "$SSL_CERT_ENV_NAME" ]]; then
+ export_ssl_cert=$'\n'"export ${SSL_CERT_ENV_NAME}=\"${SSL_CERT_ENV_VALUE}\""
+ fi
+
+ cat > "$wrapper_script" <<EOF
+#!/bin/sh
+# Pulse Agent startup script for QNAP
+# Auto-generated by Pulse installer.
+
+wait_for_file() {
+ path="\$1"
+ while [ ! -f "\$path" ]; do
+ sleep 5
+ done
+}
+
+wait_for_file "${stored_binary}"
+
+# Kill any existing pulse-agent processes before refreshing the runtime copy.
+pkill -x "pulse-agent" 2>/dev/null || true
+sleep 2
+
+mkdir -p "$(dirname "$runtime_binary")" 2>/dev/null || true
+cp "${stored_binary}" "${runtime_binary}"
+chmod +x "${runtime_binary}"${export_ssl_cert}
+
+# Watchdog loop: restart agent if it exits.
+RESTART_DELAY=5
+MAX_RESTART_DELAY=60
+
+while true; do
+ echo "\$(date '+%Y-%m-%d %H:%M:%S') [watchdog] Starting pulse-agent..." >> /var/log/${AGENT_NAME}.log
+ ${runtime_binary} ${EXEC_ARGS} >> /var/log/${AGENT_NAME}.log 2>&1
+ EXIT_CODE=\$?
+
+ echo "\$(date '+%Y-%m-%d %H:%M:%S') [watchdog] pulse-agent exited with code \$EXIT_CODE, restarting in \${RESTART_DELAY}s..." >> /var/log/${AGENT_NAME}.log
+ sleep \$RESTART_DELAY
+
+ RESTART_DELAY=\$((RESTART_DELAY * 2))
+ if [ \$RESTART_DELAY -gt \$MAX_RESTART_DELAY ]; then
+ RESTART_DELAY=\$MAX_RESTART_DELAY
+ fi
+done
+EOF
+
+ chmod +x "$wrapper_script"
+}
+
+append_qnap_autorun_block() {
+ local autorun_path="$1"
+ local wrapper_script="$2"
+ local state_dir="$3"
+
+ remove_qnap_autorun_block "$autorun_path"
+ if [[ ! -f "$autorun_path" ]]; then
+ echo "#!/bin/sh" > "$autorun_path"
+ fi
+
+ cat >> "$autorun_path" <<EOF
+
+# Pulse Agent bootstrap begin
+(
+ while [ ! -x "${wrapper_script}" ]; do
+ sleep 5
+ done
+ "${wrapper_script}" >> /var/log/${AGENT_NAME}.log 2>&1 &
+) >> /var/log/${AGENT_NAME}.log 2>&1 &
+# Pulse Agent bootstrap end
+
+EOF
+
+ chmod +x "$autorun_path"
+}
+
# --- Auto-Detection Functions ---
detect_docker() {
# Check if Docker is available and accessible
@@ -980,6 +1124,7 @@ recover_connection_state() {
find_connection_state_file() {
local conn_env=""
+ local qnap_state_dir=""
for conn_env in /var/lib/pulse-agent/connection.env /boot/config/plugins/pulse-agent/connection.env "$TRUENAS_STATE_DIR/connection.env"; do
if [[ -f "$conn_env" ]]; then
@@ -988,6 +1133,12 @@ find_connection_state_file() {
fi
done
+ qnap_state_dir=$(find_qnap_state_dir || true)
+ if [[ -n "$qnap_state_dir" ]] && [[ -f "$qnap_state_dir/connection.env" ]]; then
+ printf '%s\n' "$qnap_state_dir/connection.env"
+ return 0
+ fi
+
return 1
}
@@ -1172,6 +1323,7 @@ fi
# --- Uninstall Logic ---
if [[ "$UNINSTALL" == "true" ]]; then
log_info "Uninstalling ${AGENT_NAME} and cleaning up legacy agents..."
+ local qnap_state_dir=""
# Recover connection details from the canonical installer-owned state artifact
# if command line input is only partial. Read keys explicitly instead of
@@ -1191,8 +1343,15 @@ if [[ "$UNINSTALL" == "true" ]]; then
# Try to recover agent ID if not provided.
# Priority: agent-id file (canonical) > hostname API lookup (fallback)
if [[ -z "$AGENT_ID" ]]; then
+ local aid_path=""
+ local aid_paths=(/var/lib/pulse-agent/agent-id /boot/config/plugins/pulse-agent/agent-id "$TRUENAS_STATE_DIR/agent-id")
+ qnap_state_dir=$(find_qnap_state_dir || true)
+ if [[ -n "$qnap_state_dir" ]]; then
+ aid_paths+=("$qnap_state_dir/agent-id")
+ fi
+
# Primary: canonical agent-id file
- for aid_path in /var/lib/pulse-agent/agent-id /boot/config/plugins/pulse-agent/agent-id "$TRUENAS_STATE_DIR/agent-id"; do
+ for aid_path in "${aid_paths[@]}"; do
if [[ -f "$aid_path" ]]; then
AGENT_ID=$(cat "$aid_path")
log_info "Recovered agent ID from ${aid_path}"
@@ -1309,6 +1468,27 @@ if [[ "$UNINSTALL" == "true" ]]; then
rm -rf /var/log/pulse
fi
+ # QNAP QTS/QuTS hero
+ qnap_state_dir=$(find_qnap_state_dir || true)
+ if [[ -n "$qnap_state_dir" ]] || [[ -f /sbin/getcfg ]] || [[ -f /etc/config/qpkg.conf ]]; then
+ log_info "Removing QNAP installation..."
+ if [[ -x /etc/init.d/init_disk.sh ]]; then
+ if /etc/init.d/init_disk.sh mount_flash_config 2>/dev/null && [[ -d /tmp/nasconfig_tmp ]]; then
+ AUTORUN_PATH="/tmp/nasconfig_tmp/autorun.sh"
+ if [[ -f "$AUTORUN_PATH" ]]; then
+ remove_qnap_autorun_block "$AUTORUN_PATH"
+ fi
+ /etc/init.d/init_disk.sh umount_flash_config 2>/dev/null || true
+ else
+ /etc/init.d/init_disk.sh umount_flash_config 2>/dev/null || true
+ log_warn "Could not mount QNAP flash config to remove autorun.sh entry."
+ fi
+ fi
+ if [[ -n "$qnap_state_dir" ]]; then
+ rm -rf "$qnap_state_dir"
+ fi
+ fi
+
# TrueNAS SCALE/CORE
if [[ -d "$TRUENAS_STATE_DIR" ]] || [[ -f /etc/truenas-version ]] || [[ -f /etc/version ]]; then
if [[ "$(uname -s)" == "Linux" ]]; then
@@ -1888,6 +2068,75 @@ EOF
exit 0
fi
+# 3b. QNAP QTS/QuTS hero (ephemeral boot config; autorun.sh executes before the
+# encrypted data volume is always ready, so boot persistence must wait for the
+# canonical persistent wrapper on the data volume).
+if [[ -f /sbin/getcfg ]] || [[ -f /etc/config/qpkg.conf ]]; then
+ log_info "Detected QNAP QTS/QuTS hero system..."
+
+ QNAP_VOL=$(detect_qnap_data_volume || true)
+ if [[ -z "$QNAP_VOL" ]]; then
+ fail "Could not find a writable QNAP data volume. Is a storage volume configured?"
+ fi
+
+ STATE_DIR="${QNAP_VOL}/.pulse-agent"
+ QNAP_STORED_BINARY="${STATE_DIR}/${BINARY_NAME}"
+ RUNTIME_BINARY="${INSTALL_DIR}/${BINARY_NAME}"
+ WRAPPER_SCRIPT="${STATE_DIR}/start-pulse-agent.sh"
+
+ mkdir -p "$STATE_DIR"
+
+ # Copy binary to persistent storage and keep the runtime copy executable.
+ cp "${RUNTIME_BINARY}" "$QNAP_STORED_BINARY"
+ chmod +x "$QNAP_STORED_BINARY"
+ chmod +x "$RUNTIME_BINARY"
+
+ log_info "Installed binary to ${QNAP_STORED_BINARY} (persistent) and ${RUNTIME_BINARY} (runtime)..."
+
+ build_exec_args
+
+ log_info "Stopping any existing pulse agents..."
+ pkill -x "pulse-agent" 2>/dev/null || true
+ pkill -f "start-pulse-agent.sh" 2>/dev/null || true
+ sleep 2
+
+ write_qnap_wrapper_script "$WRAPPER_SCRIPT" "$RUNTIME_BINARY" "$QNAP_STORED_BINARY"
+
+ AUTORUN_CONFIGURED=false
+ if [[ -x /etc/init.d/init_disk.sh ]]; then
+ if /etc/init.d/init_disk.sh mount_flash_config 2>/dev/null && [[ -d /tmp/nasconfig_tmp ]]; then
+ AUTORUN_PATH="/tmp/nasconfig_tmp/autorun.sh"
+ append_qnap_autorun_block "$AUTORUN_PATH" "$WRAPPER_SCRIPT" "$STATE_DIR"
+ /etc/init.d/init_disk.sh umount_flash_config 2>/dev/null || true
+ AUTORUN_CONFIGURED=true
+ log_info "Configured autorun.sh with a deferred Pulse Agent bootstrap."
+ else
+ /etc/init.d/init_disk.sh umount_flash_config 2>/dev/null || true
+ fi
+ fi
+
+ if [[ "$AUTORUN_CONFIGURED" != true ]]; then
+ log_warn "Could not configure autorun.sh automatically."
+ log_warn "To persist across reboots, add a block to autorun.sh that waits for ${WRAPPER_SCRIPT} and then launches it."
+ log_warn "See: https://wiki.qnap.com/wiki/Running_Your_Own_Application_at_Startup"
+ fi
+
+ log_info "Starting agent with QNAP watchdog..."
+ sh "${WRAPPER_SCRIPT}" >> "/var/log/${AGENT_NAME}.log" 2>&1 &
+ disown 2>/dev/null || true
+
+ complete_installation_flow "$STATE_DIR" "Installation complete! Agent is running." "Upgrade complete! Agent is running." "tail -f /var/log/${AGENT_NAME}.log"
+ log_info "Persistent state: $STATE_DIR"
+ if [[ "$AUTORUN_CONFIGURED" == true ]]; then
+ log_info "The agent will start automatically after the QNAP data volume becomes available."
+ log_info "IMPORTANT: Ensure 'Run user defined startup processes (autorun.sh)' is enabled"
+ log_info " in QNAP Control Panel > Hardware > General."
+ fi
+ log_info "To check status: pgrep -a pulse-agent"
+ log_info "To view logs: tail -f /var/log/${AGENT_NAME}.log"
+ exit 0
+fi
+
# 4. TrueNAS SCALE/CORE (immutable root, uses systemd on SCALE and rc.d on CORE)
# TrueNAS can wipe service registration files on upgrades, so we store the service
# in /data and create an Init/Shutdown task to recreate the symlink on boot.
diff --git a/scripts/installtests/install_sh_test.go b/scripts/installtests/install_sh_test.go
index 983dc66bcb..383354ee8d 100644
--- a/scripts/installtests/install_sh_test.go
+++ b/scripts/installtests/install_sh_test.go
@@ -448,6 +448,51 @@ func TestWriteTrueNASBootstrapScriptUsesCanonicalRenderer(t *testing.T) {
}
}
+func TestInstallSHUsesCanonicalQNAPBootstrapRenderer(t *testing.T) {
+ content, err := os.ReadFile(repoFile("scripts", "install.sh"))
+ if err != nil {
+ t.Fatalf("read install.sh: %v", err)
+ }
+
+ script := string(content)
+ required := []string{
+ `detect_qnap_data_volume() {`,
+ `find_qnap_state_dir() {`,
+ `remove_qnap_autorun_block() {`,
+ `write_qnap_wrapper_script() {`,
+ `append_qnap_autorun_block() {`,
+ `STATE_DIR="${QNAP_VOL}/.pulse-agent"`,
+ `write_qnap_wrapper_script "$WRAPPER_SCRIPT" "$RUNTIME_BINARY" "$QNAP_STORED_BINARY"`,
+ `append_qnap_autorun_block "$AUTORUN_PATH" "$WRAPPER_SCRIPT" "$STATE_DIR"`,
+ `complete_installation_flow "$STATE_DIR" "Installation complete! Agent is running." "Upgrade complete! Agent is running." "tail -f /var/log/${AGENT_NAME}.log"`,
+ }
+ for _, needle := range required {
+ if !strings.Contains(script, needle) {
+ t.Fatalf("install.sh missing canonical QNAP bootstrap ownership: %s", needle)
+ }
+ }
+}
+
+func TestInstallSHUsesQNAPStateForUninstallRecovery(t *testing.T) {
+ content, err := os.ReadFile(repoFile("scripts", "install.sh"))
+ if err != nil {
+ t.Fatalf("read install.sh: %v", err)
+ }
+
+ script := string(content)
+ required := []string{
+ `qnap_state_dir=$(find_qnap_state_dir || true)`,
+ `aid_paths+=("$qnap_state_dir/agent-id")`,
+ `if [[ -n "$qnap_state_dir" ]] && [[ -f "$qnap_state_dir/connection.env" ]]; then`,
+ `remove_qnap_autorun_block "$AUTORUN_PATH"`,
+ }
+ for _, needle := range required {
+ if !strings.Contains(script, needle) {
+ t.Fatalf("install.sh missing QNAP uninstall continuity handling: %s", needle)
+ }
+ }
+}
+
func TestInstallSHUsesSharedServiceRenderers(t *testing.T) {
content, err := os.ReadFile(repoFile("scripts", "install.sh"))
if err != nil {
@@ -487,6 +532,7 @@ func TestInstallSHUsesCanonicalCompletionHelper(t *testing.T) {
`json_event "complete" "installed_unhealthy" "Agent installed but not responding"`,
`complete_installation_flow "/var/lib/pulse-agent" "Installation complete! Agent is running." "Upgrade complete! Agent restarted with new configuration." "tail -f $LOG_FILE"`,
`complete_installation_flow "$UNRAID_STORAGE_DIR" "Installation complete! Agent is running." "Upgrade complete! Agent is running." "tail -f /var/log/${AGENT_NAME}.log"`,
+ `complete_installation_flow "$STATE_DIR" "Installation complete! Agent is running." "Upgrade complete! Agent is running." "tail -f /var/log/${AGENT_NAME}.log"`,
`complete_installation_flow "$TRUENAS_STATE_DIR" "Installation complete! Agent is running." "Upgrade complete! Agent is running." ""`,
`complete_installation_flow "/var/lib/pulse-agent" "Installation complete! Agent is running." "Upgrade complete! Agent restarted with new configuration." "tail -f /var/log/messages"`,
`complete_installation_flow "/var/lib/pulse-agent" "Installation complete! Agent is running." "Upgrade complete! Agent restarted with new configuration." "journalctl -u ${AGENT_NAME} --no-pager -n 20"`,