From 7b839fb0c0bdb1e5bf5ca3f918d89440fc5ed454 Mon Sep 17 00:00:00 2001 From: Marko Petzold Date: Sat, 28 Nov 2026 09:35:01 +0100 Subject: [PATCH 1/5] Add Docker engine information retrieval and image name management - Implemented EngineInfo method to retrieve Docker engine platform and version. - Added integration tests for EngineInfo and image name handling. - Enhanced AppStateDatabase to manage present and new image names for requested states. - Introduced new database columns for installed image and version tracking. - Created update scripts for new database schema changes. - Added tests to ensure correct handling of image names in various scenarios. --- src/agent.go | 35 +- src/agent_engine_test.go | 47 ++ src/api/engine_report.go | 265 ++++++++ src/api/engine_report_test.go | 438 ++++++++++++ src/api/external.go | 3 + src/api/firmware_updates.go | 6 +- src/api/request_app_state.go | 25 + src/api/request_app_state_test.go | 38 ++ src/api/update_ironflockos.go | 9 +- src/apps/app_images.go | 548 +++++++++++++++ src/apps/app_images_fallback_test.go | 326 +++++++++ src/apps/app_images_test.go | 636 ++++++++++++++++++ src/apps/app_manager.go | 67 +- src/apps/app_manager_test.go | 111 ++- src/apps/build_app.go | 21 +- src/apps/compose_missing_images_test.go | 55 ++ src/apps/dockerfile_arch_test.go | 82 +++ src/apps/fail_present.go | 32 +- src/apps/image_pins_test.go | 6 +- src/apps/publish_app.go | 61 +- src/apps/pull_app.go | 32 +- src/apps/pushed_digests.go | 206 ++++++ src/apps/pushed_digests_test.go | 146 ++++ src/apps/recovery_lifecycle_test.go | 2 +- src/apps/registry_auth.go | 23 +- src/apps/remove_app.go | 7 +- src/apps/run_app.go | 40 +- src/apps/state_observer.go | 67 +- src/apps/state_observer_test.go | 31 +- src/apps/update_app.go | 32 +- src/apps/update_flow_migration.go | 5 +- src/apps/update_order_test.go | 4 +- src/apps/update_trigger_test.go | 2 +- src/apps/wanted_images.go | 80 +++ src/apps/wanted_images_test.go | 86 +++ src/common/types.go | 48 +- ...ocker_reference_filter_integration_test.go | 42 ++ src/container/engine.go | 157 +++++ src/container/engine_integration_test.go | 26 + src/container/engine_test.go | 263 ++++++++ src/diskguard/diskguard.go | 5 +- src/persistence/database.go | 110 +++ src/persistence/image_names_test.go | 82 +++ src/persistence/statements.go | 13 + .../single-installed_image-col.sql | 1 + .../single-installed_image_version-col.sql | 1 + .../single-new_image_name-col.sql | 1 + .../single-present_image_name-col.sql | 1 + src/store/app_store.go | 30 + src/store/app_store_image_names_test.go | 84 +++ 50 files changed, 4251 insertions(+), 187 deletions(-) create mode 100644 src/agent_engine_test.go create mode 100644 src/api/engine_report.go create mode 100644 src/api/engine_report_test.go create mode 100644 src/apps/app_images.go create mode 100644 src/apps/app_images_fallback_test.go create mode 100644 src/apps/app_images_test.go create mode 100644 src/apps/compose_missing_images_test.go create mode 100644 src/apps/dockerfile_arch_test.go create mode 100644 src/apps/pushed_digests.go create mode 100644 src/apps/pushed_digests_test.go create mode 100644 src/apps/wanted_images.go create mode 100644 src/apps/wanted_images_test.go create mode 100644 src/container/docker_reference_filter_integration_test.go create mode 100644 src/container/engine.go create mode 100644 src/container/engine_integration_test.go create mode 100644 src/container/engine_test.go create mode 100644 src/persistence/image_names_test.go create mode 100644 src/persistence/update-scripts/single-installed_image-col.sql create mode 100644 src/persistence/update-scripts/single-installed_image_version-col.sql create mode 100644 src/persistence/update-scripts/single-new_image_name-col.sql create mode 100644 src/persistence/update-scripts/single-present_image_name-col.sql create mode 100644 src/store/app_store_image_names_test.go diff --git a/src/agent.go b/src/agent.go index 6deedaa..53f136e 100644 --- a/src/agent.go +++ b/src/agent.go @@ -279,9 +279,11 @@ func (agent *Agent) OnConnect(reconnect bool) error { return err } +// updateRemoteDevice sends the connect's device report. It waits for nothing +// but its own call; the Docker engine is read again in the background after +// it (api.External.SendConnectReport). func (agent *Agent) updateRemoteDevice() error { - _, err := agent.Messenger.Call(context.Background(), topics.UpdateDeviceArchitecture, []interface{}{agent.External.DeviceReport()}, nil, nil, nil) - return err + return agent.External.SendConnectReport() } // ensureAppCABundle refreshes the CA bundle app containers verify TLS against. @@ -336,6 +338,11 @@ func NewAgent(generalConfig *config.Config) (agent *Agent) { if err != nil { log.Fatal().Stack().Err(err).Msg("failed to setup docker") } + // The Docker engine's platform and version for the device report, read in + // the background and bounded: an absent or hung daemon holds up nothing, + // and the report then goes without them. + engineReport := api.NewEngineReport(container.EngineInfo) + safe.Go(engineReport.Refresh) filesystem := filesystem.New() tunnelManager, err := tunnel.NewFrpTunnelManager(dummyMessenger, generalConfig) @@ -423,26 +430,14 @@ func NewAgent(generalConfig *config.Config) (agent *Agent) { AppImageRegistry: generalConfig.ReswarmConfig.DockerRegistryURL, // Every image reference the device still needs: present AND newest // version per stage, so a reclaim that races an in-flight update - // cannot delete the version being pulled or the one still running. + // cannot delete the version being pulled or the one still running, + // and the images of the apps' Compose definitions. WantedAppImages: func() (map[string]bool, error) { payloads, err := appStore.GetRequestedStates() if err != nil { return nil, err } - wanted := make(map[string]bool, len(payloads)*4) - for _, p := range payloads { - for _, repo := range []string{p.RegistryImageName.Prod, p.RegistryImageName.Dev} { - if repo == "" { - continue - } - for _, version := range []string{p.PresentVersion, p.NewestVersion, p.Version} { - if version != "" { - wanted[repo+":"+version] = true - } - } - } - } - return wanted, nil + return apps.WantedAppImages(generalConfig.ReswarmConfig, payloads), nil }, // On recovery, reinstate the apps' requested states (which were // stopped/blocked during the emergency), and reconcile every app's @@ -534,6 +529,7 @@ func NewAgent(generalConfig *config.Config) (agent *Agent) { } } + safe.Go(engineReport.Refresh) // compose support was probed (and latched negative) while the // daemon was down container.Compose().RefreshSupport() @@ -624,12 +620,15 @@ func NewAgent(generalConfig *config.Config) (agent *Agent) { // On daemon-availability transitions (event stream lost / daemon back) the // recovery supervisor pokes an immediate status push so the badge flips // right away instead of on the next heartbeat. + // A daemon that comes back may be another engine (Docker Desktop + // restarted with another one): read it again. stateObserver.SetDaemonTransitionFunc(func() { safe.Go(func() { if err := mainSession.UpdateRemoteDeviceStatus(messenger.CONNECTED); err != nil { log.Debug().Err(err).Msg("failed to push device status on a docker daemon transition") } }) + safe.Go(engineReport.Refresh) }) privilege := privilege.NewPrivilege(mainSession, generalConfig) @@ -647,7 +646,9 @@ func NewAgent(generalConfig *config.Config) (agent *Agent) { TerminalManager: &terminalManager, LogManager: &logManager, Config: generalConfig, + Engine: engineReport, } + engineReport.SetResend(external.ResendDeviceReport) agent = &Agent{ Config: generalConfig, diff --git a/src/agent_engine_test.go b/src/agent_engine_test.go new file mode 100644 index 0000000..0fa12aa --- /dev/null +++ b/src/agent_engine_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "context" + "reagent/api" + "reagent/common" + "reagent/container" + "reagent/messenger/topics" + "reagent/safe" + "reagent/testutil/builders" + "reagent/testutil/fakes" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The connect's report goes out at once while the Docker daemon hangs, without +// the engine's keys. +func TestConnectReportDoesNotWaitForDocker(t *testing.T) { + hung := make(chan struct{}) + t.Cleanup(func() { close(hung) }) + reading := make(chan struct{}, 1) + engine := api.NewEngineReport(func(ctx context.Context) (container.EngineInfo, error) { + reading <- struct{}{} + <-hung // longer than any timeout + return container.EngineInfo{}, context.DeadlineExceeded + }) + safe.Go(engine.Refresh) + <-reading + + m := fakes.NewMessenger() + agent := &Agent{Messenger: m, External: &api.External{Config: builders.DefaultTestConfig(), Messenger: m, Engine: engine}} + + start := time.Now() + require.NoError(t, agent.updateRemoteDevice()) + assert.Less(t, time.Since(start), time.Second) + + require.Equal(t, 1, m.GetCallCount()) + call := m.GetCallCalls()[0] + assert.Equal(t, topics.UpdateDeviceArchitecture, call.Topic) + report := call.Args[0].(common.Dict) + assert.Contains(t, report, "architecture") + assert.NotContains(t, report, "engine_platform") + assert.NotContains(t, report, "engine_version") +} diff --git a/src/api/engine_report.go b/src/api/engine_report.go new file mode 100644 index 0000000..aaedbff --- /dev/null +++ b/src/api/engine_report.go @@ -0,0 +1,265 @@ +package api + +import ( + "context" + "fmt" + "reagent/common" + "reagent/container" + "reagent/messenger/topics" + "reagent/safe" + "sync" + "time" + + "github.com/rs/zerolog/log" +) + +// engineReadTimeout bounds one read of the Docker engine's platform and +// version. A var for the tests. +var engineReadTimeout = 10 * time.Second + +// connectReportWait bounds how long a background report waits for a connect +// report in flight. A var for the tests. +var connectReportWait = 30 * time.Second + +// deviceReportCalls lets one background device report at a time reach the +// platform: two at once race for the device's row, and the one that loses is +// dropped. The connect's report never takes it: the connect waits for nothing. +var deviceReportCalls sync.Mutex + +// connectReports counts the connect's device reports in flight, which a +// resend waits for (bounded) so as not to race them. The connect only counts; +// it never waits on it. +var connectReports reportsInFlight + +type reportsInFlight struct { + mu sync.Mutex + n int + idle chan struct{} +} + +func (f *reportsInFlight) start() { + f.mu.Lock() + if f.n == 0 { + f.idle = make(chan struct{}) + } + f.n++ + f.mu.Unlock() +} + +func (f *reportsInFlight) done() { + f.mu.Lock() + f.n-- + if f.n == 0 { + close(f.idle) + } + f.mu.Unlock() +} + +// wait returns once no report is in flight, or after at most d. +func (f *reportsInFlight) wait(d time.Duration) { + f.mu.Lock() + if f.n == 0 { + f.mu.Unlock() + return + } + idle := f.idle + f.mu.Unlock() + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-idle: + case <-timer.C: + } +} + +// EngineReport keeps what the device report says about the Docker engine that +// runs the apps: engine_platform and engine_version. The engine is read in +// the background, never on the way to a connection: a report built before +// the engine answered, or while Docker is absent or hung, simply has no such +// keys, and the platform keeps what it has stored. +// +// It is read when the agent starts, after every connect's report, when a +// Docker daemon that was not there at the start comes up, and when the daemon +// comes back after an outage. When what it knows differs from what the last +// report that went through carried, the report is sent again. A daemon that +// goes away and comes back with the same engine sends nothing; an outage is +// "not known", never a change. +type EngineReport struct { + read func(ctx context.Context) (container.EngineInfo, error) + + mu sync.Mutex + // known is the last engine read, field by field: a read that fails or + // leaves a field out keeps the previous value. + known container.EngineInfo + // sent is what the platform got: the values of reports that went through. + sent container.EngineInfo + // connected is set once a connect's report was sent; before it, the + // connect's report carries what is known and nothing is sent again. + connected bool + // One read (and send) at a time; a Refresh meanwhile makes it read once + // more. + reading bool + again bool + resend func() +} + +// NewEngineReport returns an EngineReport that reads the engine with read. +func NewEngineReport(read func(ctx context.Context) (container.EngineInfo, error)) *EngineReport { + return &EngineReport{read: read} +} + +// SetResend sets what sends the device report again after a change. +func (e *EngineReport) SetResend(resend func()) { + e.mu.Lock() + e.resend = resend + e.mu.Unlock() +} + +// Refresh reads the engine, bounded by engineReadTimeout (but see +// container.Docker.EngineInfo), and sends the report again when the platform +// has not got what it knows. Errors are logged at debug level and change +// nothing. Run it in the background. +func (e *EngineReport) Refresh() { + e.mu.Lock() + if e.reading { + e.again = true + e.mu.Unlock() + return + } + e.reading = true + e.mu.Unlock() + + for { + info, err := e.readOnce() + if err != nil { + log.Debug().Err(err).Msg("could not read the Docker engine's platform and version") + } + + e.mu.Lock() + if err == nil { + if info.Platform != "" { + e.known.Platform = info.Platform + } + if info.Version != "" { + e.known.Version = info.Version + } + } + changed := e.connected && e.known != e.sent + known := e.known + resend := e.resend + e.mu.Unlock() + + // A Refresh asked for while this one reads or sends makes it read + // once more afterwards, also when the send panics. + if changed && resend != nil { + log.Info().Str("engine_platform", known.Platform).Str("engine_version", known.Version).Msg("reporting the Docker engine") + safe.Run(resend) + } + + e.mu.Lock() + again := e.again + e.again = false + if !again { + e.reading = false + } + e.mu.Unlock() + if !again { + return + } + } +} + +// readOnce is one bounded read; a panic in it is an error. +func (e *EngineReport) readOnce() (info container.EngineInfo, err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("reading the Docker engine panicked: %v", r) + } + }() + ctx, cancel := context.WithTimeout(context.Background(), engineReadTimeout) + defer cancel() + return e.read(ctx) +} + +// addTo puts what is known about the engine into a device report. +func (e *EngineReport) addTo(payload common.Dict) { + e.mu.Lock() + defer e.mu.Unlock() + if e.known.Platform != "" { + payload["engine_platform"] = e.known.Platform + } + if e.known.Version != "" { + payload["engine_version"] = e.known.Version + } +} + +// delivered remembers the engine values of a report that went through. +func (e *EngineReport) delivered(payload common.Dict) { + e.mu.Lock() + defer e.mu.Unlock() + if v, ok := payload["engine_platform"].(string); ok { + e.sent.Platform = v + } + if v, ok := payload["engine_version"].(string); ok { + e.sent.Version = v + } +} + +// SendConnectReport sends the device report of a connect. It waits for no +// other report and no Docker read: it only counts itself in flight, and +// afterwards starts a read of the engine in the background, so that an engine +// the start could not read, or one that changed, is reported. +func (ex *External) SendConnectReport() error { + payload, err := ex.callConnectReport() + if ex.Engine != nil { + if err == nil { + ex.Engine.delivered(payload) + } + ex.Engine.mu.Lock() + ex.Engine.connected = true + ex.Engine.mu.Unlock() + safe.Go(ex.Engine.Refresh) + } + return err +} + +// callConnectReport builds and sends the connect's report, counted in flight +// until the call returned. +func (ex *External) callConnectReport() (common.Dict, error) { + connectReports.start() + defer connectReports.done() + payload := ex.DeviceReport() + _, err := ex.Messenger.Call(context.Background(), topics.UpdateDeviceArchitecture, []interface{}{payload}, nil, nil, nil) + return payload, err +} + +// sendBackgroundReport sends a device report with the extra keys, one at a +// time with the other background reports. The payload is built and the +// timeout starts once it is this report's turn. +func (ex *External) sendBackgroundReport(timeout time.Duration, extra common.Dict) error { + deviceReportCalls.Lock() + defer deviceReportCalls.Unlock() + payload := ex.DeviceReport() + for k, v := range extra { + payload[k] = v + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + _, err := ex.Messenger.Call(ctx, topics.UpdateDeviceArchitecture, []interface{}{payload}, nil, nil, nil) + if err == nil && ex.Engine != nil { + ex.Engine.delivered(payload) + } + return err +} + +// ResendDeviceReport sends the device report on its own, for an engine the +// platform has not got. It lets a connect's report in flight finish first +// (bounded by connectReportWait), since the later of two at once can be +// dropped. Errors are logged; the next read after a connect or a daemon +// transition tries again. +func (ex *External) ResendDeviceReport() { + connectReports.wait(connectReportWait) + if err := ex.sendBackgroundReport(osReleaseReportTimeout, nil); err != nil { + log.Warn().Err(err).Msg("failed to report the Docker engine to the backend") + } +} diff --git a/src/api/engine_report_test.go b/src/api/engine_report_test.go new file mode 100644 index 0000000..de18925 --- /dev/null +++ b/src/api/engine_report_test.go @@ -0,0 +1,438 @@ +package api + +import ( + "context" + "errors" + "reagent/common" + "reagent/container" + "reagent/messenger" + "reagent/messenger/topics" + "reagent/release" + "reagent/testutil/fakes" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// fakeEngineRead answers every engine read with the answer set last, and +// counts the reads. +type fakeEngineRead struct { + mu sync.Mutex + answer engineAnswer + reads int +} + +type engineAnswer struct { + info container.EngineInfo + err error + // hang makes the read wait for its context, as a hung daemon does. + hang bool + // wait makes the read wait for the channel to close. + wait chan struct{} + // panics makes the read panic. + panics bool +} + +func (f *fakeEngineRead) set(answer engineAnswer) { + f.mu.Lock() + f.answer = answer + f.mu.Unlock() +} + +func (f *fakeEngineRead) read(ctx context.Context) (container.EngineInfo, error) { + f.mu.Lock() + answer := f.answer + f.reads++ + f.mu.Unlock() + if answer.panics { + panic("boom") + } + if answer.hang { + <-ctx.Done() + return container.EngineInfo{}, ctx.Err() + } + if answer.wait != nil { + <-answer.wait + } + return answer.info, answer.err +} + +func (f *fakeEngineRead) count() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.reads +} + +// reportMessenger records the device reports, can fail them, can hold one +// call until released, and notes whether a call overlapped another and +// whether its context had run out when it was made. +type reportMessenger struct { + *fakes.Messenger + + mu sync.Mutex + err error + block chan struct{} + inFlight int + calls []reportCall +} + +type reportCall struct { + payload common.Dict + overlapped bool + ctxErr error +} + +func (r *reportMessenger) Call(ctx context.Context, topic topics.Topic, args []interface{}, _ common.Dict, _ common.Dict, _ func(messenger.Result)) (messenger.Result, error) { + r.mu.Lock() + block := r.block + r.block = nil + call := reportCall{payload: args[0].(common.Dict), overlapped: r.inFlight > 0, ctxErr: ctx.Err()} + if topic == topics.UpdateDeviceArchitecture { + r.calls = append(r.calls, call) + } + r.inFlight++ + err := r.err + r.mu.Unlock() + + if block != nil { + <-block + } + + r.mu.Lock() + r.inFlight-- + r.mu.Unlock() + if call.ctxErr != nil { + return messenger.Result{}, call.ctxErr + } + return messenger.Result{}, err +} + +func (r *reportMessenger) setErr(err error) { + r.mu.Lock() + r.err = err + r.mu.Unlock() +} + +// holdNext makes the next call wait until the returned func is called. +func (r *reportMessenger) holdNext() (release func()) { + ch := make(chan struct{}) + r.mu.Lock() + r.block = ch + r.mu.Unlock() + var once sync.Once + return func() { once.Do(func() { close(ch) }) } +} + +func (r *reportMessenger) reports() []reportCall { + r.mu.Lock() + defer r.mu.Unlock() + return append([]reportCall(nil), r.calls...) +} + +func (r *reportMessenger) count() int { return len(r.reports()) } + +func engineExternal(t *testing.T, answer engineAnswer) (*External, *reportMessenger, *fakeEngineRead) { + t.Helper() + read := &fakeEngineRead{answer: answer} + engine := NewEngineReport(read.read) + m := &reportMessenger{Messenger: fakes.NewMessenger()} + ex := &External{Config: testConfig(), Messenger: m, Engine: engine} + engine.SetResend(ex.ResendDeviceReport) + return ex, m, read +} + +// settle waits until the engine has been read reads times and no read runs. +func settle(t *testing.T, ex *External, read *fakeEngineRead, reads int) { + t.Helper() + require.Eventually(t, func() bool { + ex.Engine.mu.Lock() + reading := ex.Engine.reading + ex.Engine.mu.Unlock() + return read.count() >= reads && !reading + }, 5*time.Second, time.Millisecond) +} + +var ( + armv7Engine = container.EngineInfo{Platform: "linux/arm/v7", Version: "28.5.2"} + arm64Engine = container.EngineInfo{Platform: "linux/arm64", Version: "29.1.0"} + errDockerDown = errors.New("cannot connect to the Docker daemon") +) + +func TestDeviceReportCarriesTheEngine(t *testing.T) { + ex, m, _ := engineExternal(t, engineAnswer{info: arm64Engine}) + + ex.Engine.Refresh() + report := ex.DeviceReport() + + assert.Equal(t, "linux/arm64", report["engine_platform"]) + assert.Equal(t, "29.1.0", report["engine_version"]) + // Today's value stays the agent's own build, next to the engine's: a + // 32-bit agent build next to an arm64 engine reports both. + sysInfo := release.GetSystemInfo() + assert.Equal(t, sysInfo.Arch+sysInfo.Variant, report["architecture"]) + assert.Zero(t, m.count(), "a read before the connect sends nothing of its own") +} + +func TestDeviceReportLeavesAnUnknownEngineOut(t *testing.T) { + for name, answer := range map[string]engineAnswer{ + "Docker absent": {err: errDockerDown}, + "Docker hangs": {hang: true}, + "version only": {info: container.EngineInfo{Version: "28.5.2"}}, + "nothing read yet, nil": {}, + } { + t.Run(name, func(t *testing.T) { + restore := engineReadTimeout + engineReadTimeout = 50 * time.Millisecond + t.Cleanup(func() { engineReadTimeout = restore }) + ex, m, _ := engineExternal(t, answer) + if name == "nothing read yet, nil" { + ex.Engine = nil + } else { + ex.Engine.Refresh() + } + + report := ex.DeviceReport() + + assert.NotContains(t, report, "engine_platform") + if name == "version only" { + assert.Equal(t, "28.5.2", report["engine_version"]) + } else { + assert.NotContains(t, report, "engine_version") + } + assert.Zero(t, m.count()) + }) + } +} + +// A hung daemon holds up no report: the connect's report goes out at once, +// without the engine, while the read waits out its timeout. +func TestHungDockerHoldsUpNoReport(t *testing.T) { + restore := engineReadTimeout + engineReadTimeout = 300 * time.Millisecond + t.Cleanup(func() { engineReadTimeout = restore }) + ex, m, read := engineExternal(t, engineAnswer{hang: true}) + + done := make(chan struct{}) + go func() { ex.Engine.Refresh(); close(done) }() + require.Eventually(t, func() bool { return read.count() == 1 }, time.Second, time.Millisecond) + + start := time.Now() + require.NoError(t, ex.SendConnectReport()) + assert.Less(t, time.Since(start), 100*time.Millisecond) + require.Equal(t, 1, m.count()) + assert.NotContains(t, m.reports()[0].payload, "engine_platform") + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("the read did not give up after its timeout") + } + settle(t, ex, read, 2) + assert.Equal(t, 1, m.count(), "an engine that never answered changes nothing") +} + +// The start could not read the engine (dockerd still starting), and the fast +// path never reads it again: the read after the connect's report does, and +// the report is sent again. +func TestConnectReadsAnEngineTheStartMissed(t *testing.T) { + ex, m, read := engineExternal(t, engineAnswer{err: errDockerDown}) + ex.Engine.Refresh() + + read.set(engineAnswer{info: armv7Engine}) + require.NoError(t, ex.SendConnectReport()) + settle(t, ex, read, 2) + + require.Eventually(t, func() bool { return m.count() == 2 }, 5*time.Second, time.Millisecond) + reports := m.reports() + assert.NotContains(t, reports[0].payload, "engine_platform", "the connect's report went without it") + assert.Equal(t, "linux/arm/v7", reports[1].payload["engine_platform"]) + assert.Equal(t, "28.5.2", reports[1].payload["engine_version"]) + assert.Contains(t, reports[1].payload, "architecture") + assert.Contains(t, reports[1].payload, "device_key") +} + +// One report per change: a daemon that flaps with the same engine sends +// nothing, another engine is sent once. +func TestEngineChangeSendsTheReportOnce(t *testing.T) { + ex, m, read := engineExternal(t, engineAnswer{info: armv7Engine}) + ex.Engine.Refresh() + require.NoError(t, ex.SendConnectReport()) + settle(t, ex, read, 2) + require.Equal(t, 1, m.count()) + assert.Equal(t, "linux/arm/v7", m.reports()[0].payload["engine_platform"]) + + read.set(engineAnswer{err: errDockerDown}) + ex.Engine.Refresh() + read.set(engineAnswer{info: armv7Engine}) + ex.Engine.Refresh() + assert.Equal(t, 1, m.count(), "an outage and the same engine again send nothing") + assert.Equal(t, "linux/arm/v7", ex.DeviceReport()["engine_platform"], "an outage keeps what is known") + + read.set(engineAnswer{info: arm64Engine}) + ex.Engine.Refresh() + require.Equal(t, 2, m.count()) + assert.Equal(t, "linux/arm64", m.reports()[1].payload["engine_platform"]) + + ex.Engine.Refresh() + assert.Equal(t, 2, m.count()) +} + +// A report that did not go through does not count as sent: the next read +// sends it again, until one goes through. +func TestFailedReportIsSentAgain(t *testing.T) { + ex, m, read := engineExternal(t, engineAnswer{info: armv7Engine}) + ex.Engine.Refresh() + m.setErr(errors.New("dropped")) + require.Error(t, ex.SendConnectReport()) + settle(t, ex, read, 2) // the resend after the connect fails as well + require.Equal(t, 2, m.count()) + + m.setErr(nil) + ex.Engine.Refresh() // e.g. the daemon's next transition, or the next connect + require.Equal(t, 3, m.count()) + assert.Equal(t, "linux/arm/v7", m.reports()[2].payload["engine_platform"]) + + ex.Engine.Refresh() + assert.Equal(t, 3, m.count(), "once it went through, nothing more") +} + +// A resend waits for a connect's report in flight, so that the two do not +// race for the device's row; the connect's report waits for nothing. +func TestResendWaitsForTheConnectReport(t *testing.T) { + ex, m, read := engineExternal(t, engineAnswer{err: errDockerDown}) + ex.Engine.Refresh() + release := m.holdNext() + t.Cleanup(release) + + connected := make(chan error, 1) + go func() { connected <- ex.SendConnectReport() }() + require.Eventually(t, func() bool { return m.count() == 1 }, time.Second, time.Millisecond) + + // The engine becomes known and a reconnect's earlier session counts as + // connected: a read now resends. + ex.Engine.mu.Lock() + ex.Engine.connected = true + ex.Engine.mu.Unlock() + read.set(engineAnswer{info: armv7Engine}) + resent := make(chan struct{}) + go func() { ex.Engine.Refresh(); close(resent) }() + + time.Sleep(100 * time.Millisecond) + assert.Equal(t, 1, m.count(), "the resend waits while the connect's report is in flight") + release() + require.NoError(t, <-connected) + <-resent + + reports := m.reports() + require.GreaterOrEqual(t, len(reports), 2) + for _, r := range reports { + assert.False(t, r.overlapped, "no two reports at once") + } +} + +// The wait for a connect's report is bounded. +func TestResendWaitIsBounded(t *testing.T) { + restore := connectReportWait + connectReportWait = 50 * time.Millisecond + t.Cleanup(func() { connectReportWait = restore }) + ex, m, _ := engineExternal(t, engineAnswer{info: armv7Engine}) + ex.Engine.Refresh() + release := m.holdNext() + t.Cleanup(release) + go func() { _ = ex.SendConnectReport() }() + require.Eventually(t, func() bool { return m.count() == 1 }, time.Second, time.Millisecond) + + start := time.Now() + ex.ResendDeviceReport() + + assert.Less(t, time.Since(start), 2*time.Second) + assert.Equal(t, 2, m.count()) +} + +// The connect's report takes no lock of the background reports. +func TestConnectReportWaitsForNoBackgroundReport(t *testing.T) { + ex, m, _ := engineExternal(t, engineAnswer{err: errDockerDown}) + deviceReportCalls.Lock() + t.Cleanup(deviceReportCalls.Unlock) + + start := time.Now() + require.NoError(t, ex.SendConnectReport()) + + assert.Less(t, time.Since(start), time.Second) + assert.Equal(t, 1, m.count()) +} + +// A background report's timeout starts when it is its turn, and its payload +// is built then: one that waited behind another neither times out for it nor +// sends what was known before it waited. +func TestBackgroundReportWaitsItsTurn(t *testing.T) { + ex, m, read := engineExternal(t, engineAnswer{info: armv7Engine}) + ex.Engine.Refresh() + + deviceReportCalls.Lock() + sent := make(chan error, 1) + go func() { sent <- ex.sendBackgroundReport(50*time.Millisecond, common.Dict{"os_release": common.Dict{}}) }() + time.Sleep(150 * time.Millisecond) // longer than its timeout + read.set(engineAnswer{info: arm64Engine}) + ex.Engine.Refresh() + deviceReportCalls.Unlock() + + require.NoError(t, <-sent) + require.Equal(t, 1, m.count()) + report := m.reports()[0] + assert.NoError(t, report.ctxErr) + assert.Equal(t, "linux/arm64", report.payload["engine_platform"]) + assert.Contains(t, report.payload, "os_release") +} + +// Refreshes during a read do not pile up: they make the read run once more. +func TestRefreshesDuringAReadCoalesce(t *testing.T) { + wait := make(chan struct{}) + ex, _, read := engineExternal(t, engineAnswer{info: armv7Engine, wait: wait}) + + done := make(chan struct{}) + go func() { ex.Engine.Refresh(); close(done) }() + require.Eventually(t, func() bool { return read.count() == 1 }, time.Second, time.Millisecond) + read.set(engineAnswer{info: arm64Engine}) + for range 5 { + ex.Engine.Refresh() + } + close(wait) + <-done + + assert.Equal(t, 2, read.count()) + assert.Equal(t, "linux/arm64", ex.DeviceReport()["engine_platform"], "the read after the others sees the latest engine") +} + +// A read that panics is an error, and the reads after it go on. +func TestRefreshAfterAPanickingRead(t *testing.T) { + ex, _, read := engineExternal(t, engineAnswer{panics: true}) + assert.NotPanics(t, ex.Engine.Refresh) + + read.set(engineAnswer{info: armv7Engine}) + ex.Engine.Refresh() + + assert.Equal(t, "linux/arm/v7", ex.DeviceReport()["engine_platform"]) +} + +// A resend that panics keeps the read that was asked for meanwhile. +func TestRefreshKeepsAPendingReadWhenTheResendPanics(t *testing.T) { + wait := make(chan struct{}) + ex, _, read := engineExternal(t, engineAnswer{info: armv7Engine, wait: wait}) + ex.Engine.connected = true + ex.Engine.SetResend(func() { panic("boom") }) + + done := make(chan struct{}) + go func() { ex.Engine.Refresh(); close(done) }() + require.Eventually(t, func() bool { return read.count() == 1 }, time.Second, time.Millisecond) + ex.Engine.Refresh() + read.set(engineAnswer{info: arm64Engine}) + close(wait) + <-done + + assert.Equal(t, 2, read.count()) + assert.Equal(t, "linux/arm64", ex.DeviceReport()["engine_platform"]) +} diff --git a/src/api/external.go b/src/api/external.go index 8f7ed7f..2c2c268 100644 --- a/src/api/external.go +++ b/src/api/external.go @@ -42,6 +42,9 @@ type External struct { TerminalManager *terminal.TerminalManager LogManager *logging.LogManager Config *config.Config + // Engine is what the device report says about the Docker engine; nil + // leaves it out. + Engine *EngineReport } // RegistrationHandler is the handler that gets executed whenever a registered topic gets called. diff --git a/src/api/firmware_updates.go b/src/api/firmware_updates.go index 87d9533..046b35e 100644 --- a/src/api/firmware_updates.go +++ b/src/api/firmware_updates.go @@ -132,11 +132,7 @@ func (ex *External) reportFirmware() (firmware.Inventory, error) { if err != nil { return firmware.Inventory{}, err } - payload := ex.DeviceReport() - payload["firmware_inventory"] = fitFirmwareReport(firmwareReport(inventory)) - callCtx, cancelCall := context.WithTimeout(context.Background(), firmwareReportCallTimeout) - defer cancelCall() - _, err = ex.Messenger.Call(callCtx, topics.UpdateDeviceArchitecture, []interface{}{payload}, nil, nil, nil) + err = ex.sendBackgroundReport(firmwareReportCallTimeout, common.Dict{"firmware_inventory": fitFirmwareReport(firmwareReport(inventory))}) return inventory, err } diff --git a/src/api/request_app_state.go b/src/api/request_app_state.go index 33a5eb3..1415faa 100644 --- a/src/api/request_app_state.go +++ b/src/api/request_app_state.go @@ -115,6 +115,8 @@ func responseToTransitionPayload(config *config.Config, result messenger.Result) newPrivilegedKw := kwargs["new_privileged"] dockerCredentialsKw := kwargs["docker_credentials"] appCredEpochKw := kwargs["app_cred_epoch"] + presentImageNameKw := kwargs["present_image_name"] + newImageNameKw := kwargs["new_image_name"] var appKey uint64 var releaseKey uint64 @@ -474,6 +476,29 @@ func responseToTransitionPayload(config *config.Config, result messenger.Result) payload.DockerCredentials = dockerCredentials + // The platform's names of the app's image (absent from an older backend + // or appliance). A value that is not a string is left out, never a reason + // to refuse the request: the agent then forms the name as before. + payload.PresentImageName = imageNameOf("present_image_name", presentImageNameKw) + payload.NewImageName = imageNameOf("new_image_name", newImageNameKw) + // The device's architecture as the platform stores it: what a release + // build is for. A value that is not a string is left out. + payload.Architecture, _ = kwargs["architecture"].(string) + // registryToken is added before we transition state and is not part of the response payload return payload, nil } + +// imageNameOf reads an image name of a sync answer: a string, "" for absent, +// null or anything else. +func imageNameOf(key string, value interface{}) string { + if value == nil { + return "" + } + name, ok := value.(string) + if !ok { + log.Warn().Msgf("app-state push with a %s that is not a string (%T); using the agent's own image name", key, value) + return "" + } + return name +} diff --git a/src/api/request_app_state_test.go b/src/api/request_app_state_test.go index ebec13a..52aaba6 100644 --- a/src/api/request_app_state_test.go +++ b/src/api/request_app_state_test.go @@ -630,3 +630,41 @@ func TestResponseToTransitionPayload_Privileged(t *testing.T) { require.Error(t, err) }) } + +// The platform's names of the app's image; a value that is not a string is +// left out and never refuses the request. +func TestResponseToTransitionPayloadImageNames(t *testing.T) { + cfg := testConfig() + + response := createBasicWAMPResponse(42, "my-app", "PROD", "RUNNING") + response.ArgumentsKw["present_image_name"] = "prod_amd64_42_my-app:1.0.0" + response.ArgumentsKw["new_image_name"] = "prod_42_my-app:2.0.0" + payload, err := responseToTransitionPayload(cfg, response) + require.NoError(t, err) + assert.Equal(t, "prod_amd64_42_my-app:1.0.0", payload.PresentImageName) + assert.Equal(t, "prod_42_my-app:2.0.0", payload.NewImageName) + + response = createBasicWAMPResponse(42, "my-app", "PROD", "RUNNING") + response.ArgumentsKw["present_image_name"] = uint64(7) + response.ArgumentsKw["new_image_name"] = nil + payload, err = responseToTransitionPayload(cfg, response) + require.NoError(t, err) + assert.Empty(t, payload.PresentImageName) + assert.Empty(t, payload.NewImageName) + + payload, err = responseToTransitionPayload(cfg, createBasicWAMPResponse(42, "my-app", "PROD", "RUNNING")) + require.NoError(t, err) + assert.Empty(t, payload.PresentImageName, "an older backend names none") + assert.Empty(t, payload.Architecture) + + // the device's architecture as the platform stores it: what a build is for + response = createBasicWAMPResponse(42, "my-app", "DEV", "PUBLISHED") + response.ArgumentsKw["architecture"] = "armv7" + payload, err = responseToTransitionPayload(cfg, response) + require.NoError(t, err) + assert.Equal(t, "armv7", payload.Architecture) + response.ArgumentsKw["architecture"] = 7 + payload, err = responseToTransitionPayload(cfg, response) + require.NoError(t, err) + assert.Empty(t, payload.Architecture) +} diff --git a/src/api/update_ironflockos.go b/src/api/update_ironflockos.go index 03794d7..f1fb99f 100644 --- a/src/api/update_ironflockos.go +++ b/src/api/update_ironflockos.go @@ -128,6 +128,11 @@ func (ex *External) DeviceReport() common.Dict { if imageID, ok := osupdate.ImageIDReport(readRunning()); ok { payload["os_image_id"] = imageID } + // The Docker engine that runs the apps, as far as it is known: read in + // the background, never here. + if ex.Engine != nil { + ex.Engine.addTo(payload) + } return payload } @@ -142,9 +147,7 @@ func (ex *External) ReportOSRelease() { if !ok { return } - payload := ex.DeviceReport() - payload["os_release"] = osRelease - if _, err := ex.Messenger.Call(ctx, topics.UpdateDeviceArchitecture, []interface{}{payload}, nil, nil, nil); err != nil { + if err := ex.sendBackgroundReport(osReleaseReportTimeout, common.Dict{"os_release": osRelease}); err != nil { log.Error().Err(err).Msg("failed to report the OS release to the backend") } } diff --git a/src/apps/app_images.go b/src/apps/app_images.go new file mode 100644 index 0000000..5935f45 --- /dev/null +++ b/src/apps/app_images.go @@ -0,0 +1,548 @@ +package apps + +import ( + "context" + "fmt" + "reagent/common" + "reagent/config" + "reagent/container" + "reagent/errdefs" + "regexp" + "strings" + "time" + + "github.com/rs/zerolog/log" +) + +// The image of a single-image app (an app without a Compose file), PROD. +// +// The platform names it in the sync answer, for the version the device runs +// (present_image_name, for present_version) and for the one it is to go to +// (new_image_name, for newest_version): : below the +// registry's main repository (platform-db app.f_image_name), e.g. +// +// prod_1953_myapp:1.2.0 a release with one name per version, an +// image index with an image per platform +// prod_amd64_1953_myapp:1.1.0 a release from before: one name per version +// and architecture +// +// The device puts its own registry URL and main repository in front, as it +// always did. Before, the agent formed the name itself, from the architecture +// it was built for (TransitionPayload.RegistryImageName.Prod); it still does +// where the platform names none the agent can use: an older backend or +// appliance, an empty field, a name for another version, a name of a shape +// it does not know (which is logged and otherwise ignored: it never makes the +// agent pull, run or remove anything under it), and every DEV app, whose +// image the device builds itself. A release build always pushes under the +// agent's own name (publishApp), which is what the backend expects. + +// imageTagPattern is a Docker tag. +var imageTagPattern = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$`) + +// imageArchPattern is the architecture part of a name from before: a +// lower-case word that does not start with a digit (amd64, arm64, armv7, +// ...). The second part of a new name is the app key, a number. +var imageArchPattern = regexp.MustCompile(`^[a-z][a-z0-9]*$`) + +// platformImageRepository is the repository and tag of name, a name the +// platform gives for this app's single PROD image at version, when it is one +// the agent understands: prod__ or +// prod___ of exactly this app, with a tag that +// is version (letter case aside: the platform's names are lower case). ok is +// false for anything else. +func platformImageRepository(payload common.TransitionPayload, name string, version string) (repository string, tag string, ok bool) { + if payload.Stage != common.PROD || name == "" || version == "" || payload.AppName == "" { + return "", "", false + } + + colon := strings.LastIndex(name, ":") + if colon == -1 { + return "", "", false + } + repository, tag = name[:colon], name[colon+1:] + if !imageTagPattern.MatchString(tag) || !strings.EqualFold(tag, version) { + return "", "", false + } + + appPart := fmt.Sprintf("%d_%s", payload.AppKey, strings.ToLower(payload.AppName)) + if repository == "prod_"+appPart { + return repository, tag, true + } + arch, found := strings.CutPrefix(repository, "prod_") + if !found { + return "", "", false + } + arch, found = strings.CutSuffix(arch, "_"+appPart) + if !found || !imageArchPattern.MatchString(arch) { + return "", "", false + } + return repository, tag, true +} + +// platformProdImage is the reference of the platform's name for the app's +// single PROD image at version (its registry and main repository in front), +// or "" when name is not one for it (platformImageRepository), and when there +// is no configuration to put in front. Where the name is the one the agent +// forms itself, the reference is exactly the agent's own, the version as the +// sync answer spells it: releases under the old names are pulled and run as +// they always were. +func platformProdImage(rc *config.ReswarmConfig, payload common.TransitionPayload, name string, version string) string { + repository, tag, ok := platformImageRepository(payload, name, version) + if !ok { + return "" + } + if repository == payload.ImageName.Prod && payload.RegistryImageName.Prod != "" { + return payload.RegistryImageName.Prod + ":" + version + } + if rc == nil { + return "" + } + return common.BuildRegistryImageName(rc.DockerRegistryURL, rc.DockerMainRepository, repository) + ":" + tag +} + +// platformImageNames are the names the platform gave for the app's single +// image: the present one where the release the device runs is a single-image +// one, the new one where the release it goes to is. A Compose release's +// platform entry carries a name too, which names no image. +func platformImageNames(payload common.TransitionPayload) []string { + names := make([]string, 0, 2) + if payload.DockerCompose == nil && payload.PresentImageName != "" { + names = append(names, payload.PresentImageName) + } + if payload.NewDockerCompose == nil && payload.NewImageName != "" { + names = append(names, payload.NewImageName) + } + return names +} + +// ownProdImage is the name the agent forms itself for the app's image at +// version (RegistryImageName.Prod:version), "" without either. +func ownProdImage(payload common.TransitionPayload, version string) string { + if payload.RegistryImageName.Prod == "" || version == "" { + return "" + } + return payload.RegistryImageName.Prod + ":" + version +} + +// prodImageFor is the reference of the app's single PROD image at version: +// the platform's name for that version, where the sync answer gives one the +// agent understands, else the name the agent forms itself +// (RegistryImageName.Prod:version), as before. Pulls and updates try it first +// (pullProdImage). +func prodImageFor(rc *config.ReswarmConfig, payload common.TransitionPayload, version string) string { + for _, name := range platformImageNames(payload) { + if ref := platformProdImage(rc, payload, name, version); ref != "" { + return ref + } + } + if payload.RegistryImageName.Prod != "" && version != "" { + logUnusedPlatformImageNames(payload) + } + return payload.RegistryImageName.Prod + ":" + version +} + +// logUnusedPlatformImageNames says, at debug level, that the platform named an +// image the agent does not use. A name for another version is normal (the +// present one while the newest is asked for); one of another shape is not. +func logUnusedPlatformImageNames(payload common.TransitionPayload) { + for _, name := range platformImageNames(payload) { + understood := false + for _, version := range []string{payload.PresentVersion, payload.NewestVersion} { + if _, _, ok := platformImageRepository(payload, name, version); ok { + understood = true + } + } + if !understood { + log.Debug().Str("app", payload.AppName).Str("image", name). + Msg("the platform names an image the agent does not understand; using the agent's own name") + } + } +} + +// ownsImageRef reports whether ref (registry, repository, tag) is a reference +// of this app's single PROD image: under the agent's own name, or in a +// repository of the platform's form for this app. +func ownsImageRef(payload common.TransitionPayload, ref string) bool { + if payload.Stage != common.PROD || ref == "" || strings.Contains(ref, "@") { + return false + } + repository, tag := splitImageTag(ref) + if tag == "" { + return false + } + if repository == payload.RegistryImageName.Prod { + return true + } + last := repository[strings.LastIndex(repository, "/")+1:] + _, _, ok := platformImageRepository(payload, last+":"+tag, tag) + return ok +} + +// installedProdImage is the reference the device really pulled or ran the +// app's version under (TransitionPayload.InstalledImage), "" when none is +// recorded for exactly that version. +func installedProdImage(payload common.TransitionPayload, version string) string { + if version == "" || payload.InstalledImageVersion != version || !ownsImageRef(payload, payload.InstalledImage) { + return "" + } + return payload.InstalledImage +} + +// prodImageCandidates are the references under which the device may hold the +// app's single PROD image at version, in the order they are used: the one it +// really pulled or ran it under (installedProdImage), the platform's name for +// it (prodImageFor), then the agent's own name. An app installed before the +// agent took its names from the platform, or before the platform moved the +// version to a new name, has its image under the agent's own name only, and +// runs with it. +func prodImageCandidates(rc *config.ReswarmConfig, payload common.TransitionPayload, version string) []string { + if version == "" { + return nil + } + refs := []string{} + add := func(ref string) { + if ref == "" || strings.HasSuffix(ref, ":") { + return + } + for _, r := range refs { + if r == ref { + return + } + } + refs = append(refs, ref) + } + add(installedProdImage(payload, version)) + add(prodImageFor(rc, payload, version)) + add(ownProdImage(payload, version)) + return refs +} + +// prodImageRepositories are the repositories of the app's single PROD image: +// the agent's own, those the platform names for it, and the one the device +// really pulled or ran it under. Every tag in them is one of this app's PROD +// images (the names carry its key and name). +func prodImageRepositories(rc *config.ReswarmConfig, payload common.TransitionPayload) []string { + repositories := []string{} + add := func(repository string) { + if repository == "" { + return + } + for _, r := range repositories { + if r == repository { + return + } + } + repositories = append(repositories, repository) + } + + add(payload.RegistryImageName.Prod) + for _, name := range platformImageNames(payload) { + for _, version := range []string{payload.PresentVersion, payload.NewestVersion} { + if ref := platformProdImage(rc, payload, name, version); ref != "" { + add(imageRepository(ref)) + break + } + } + } + if ownsImageRef(payload, payload.InstalledImage) { + add(imageRepository(payload.InstalledImage)) + } + return repositories +} + +// appImageRepositories are the repositories of the app's image in its stage: +// for DEV the one its build tags, for PROD prodImageRepositories. +func appImageRepositories(rc *config.ReswarmConfig, payload common.TransitionPayload) []string { + if payload.Stage == common.DEV { + if payload.RegistryImageName.Dev == "" { + return nil + } + return []string{payload.RegistryImageName.Dev} + } + return prodImageRepositories(rc, payload) +} + +// hasImageInRepositories reports whether one of the images carries a tag in +// one of the repositories. +func hasImageInRepositories(images []container.ImageResult, repositories []string) bool { + for _, image := range images { + for _, tag := range image.RepoTags { + repository := imageRepository(tag) + for _, r := range repositories { + if repository == r { + return true + } + } + } + } + return false +} + +// reswarmConfig is the device's .flock configuration, nil when there is none. +func (sm *StateMachine) reswarmConfig() *config.ReswarmConfig { + cfg := sm.Container.GetConfig() + if cfg == nil { + return nil + } + return cfg.ReswarmConfig +} + +// reswarmConfigFor is the configuration the platform's names of payload are +// resolved with, nil where it names none: then the configuration is not read, +// call for call as before. +func (sm *StateMachine) reswarmConfigFor(payload common.TransitionPayload) *config.ReswarmConfig { + if len(platformImageNames(payload)) == 0 { + return nil + } + return sm.reswarmConfig() +} + +// splitImageTag splits "repo:tag" into its repository and tag ("" without). +func splitImageTag(ref string) (string, string) { + if colon := strings.LastIndex(ref, ":"); colon > strings.LastIndex(ref, "/") { + return ref[:colon], ref[colon+1:] + } + return ref, "" +} + +// withInstalledImage is payload with the image the device recorded as really +// pulled or run (InstalledImage), from the stored requested state: a sync +// answer never carries it. Best effort: payload as it is when it cannot be read. +func (sm *StateMachine) withInstalledImage(payload common.TransitionPayload) common.TransitionPayload { + if payload.Stage != common.PROD || sm.StateObserver == nil || sm.StateObserver.AppStore == nil { + return payload + } + stored, err := sm.StateObserver.AppStore.GetRequestedState(payload.AppKey, payload.Stage) + if err != nil || stored.InstalledImage == "" { + return payload + } + payload.InstalledImage, payload.InstalledImageVersion = stored.InstalledImage, stored.InstalledImageVersion + return payload +} + +// rememberInstalledImage records ref as the reference the device holds the +// app's version under. Best effort: without the record the agent finds the +// image by the other names. +func (sm *StateMachine) rememberInstalledImage(payload common.TransitionPayload, version string, ref string) { + if payload.Stage != common.PROD || version == "" || !ownsImageRef(payload, ref) || + sm.StateObserver == nil || sm.StateObserver.AppStore == nil { + return + } + if err := sm.StateObserver.AppStore.SetInstalledImage(payload.AppKey, payload.Stage, version, ref); err != nil { + log.Debug().Err(err).Str("image", ref).Msg("could not record the image the app was installed under") + } +} + +// localProdImage is the reference the app's single PROD image at version is +// on the device under: the first of prodImageCandidates that is there +// (recorded as the one it runs with, when it is not yet). found is false when +// none is. When Docker cannot say (err), ref is the one the device recorded +// for the version, else the agent's own name, as before: never a platform's +// name that nothing confirmed. +func (sm *StateMachine) localProdImage(payload common.TransitionPayload, version string) (ref string, found bool, err error) { + payload = sm.withInstalledImage(payload) + candidates := prodImageCandidates(sm.reswarmConfigFor(payload), payload, version) + fallback := installedProdImage(payload, version) + if fallback == "" { + fallback = payload.RegistryImageName.Prod + ":" + version + } + if len(candidates) == 0 { + // no version: looked for as before + candidates = []string{fallback} + } + for _, candidate := range candidates { + repository, tag := splitImageTag(candidate) + ctx, cancel := context.WithTimeout(context.Background(), time.Second*30) + _, getErr := sm.Container.GetImage(ctx, repository, tag) + cancel() + if getErr == nil { + if candidate != installedProdImage(payload, version) { + sm.rememberInstalledImage(payload, version, candidate) + } + return candidate, true, nil + } + if !errdefs.IsImageNotFound(getErr) { + return fallback, false, getErr + } + } + return candidates[0], false, nil +} + +// pullProdImage pulls the app's single PROD image at version, by tag: under +// the platform's name first (prodImageFor), and, should that pull fail for +// any reason, once more under the agent's own name where that is another +// reference. Until the platform matches a device by its Docker engine, a +// version's image index is sure to hold the agent's platform only, and an +// engine of another platform finds no image of its own in it; the agent's +// per-architecture name, which the registry keeps during the transition, is +// what such a device pulled before. The first error is logged; when both +// pulls fail, the second one's error is returned, the one the agent got +// before. A canceled pull is not tried again. started runs once a pull has +// begun (before its stream is read), on every attempt. It answers the +// reference that was pulled. +func (sm *StateMachine) pullProdImage(payload common.TransitionPayload, version string, started func() error) (string, error) { + ref := prodImageFor(sm.reswarmConfigFor(payload), payload, version) + pullErr, otherErr := sm.pullImage(payload, ref, started) + if otherErr != nil { + return ref, otherErr + } + own := ownProdImage(payload, version) + if pullErr == nil || errdefs.IsDockerStreamCanceled(pullErr) || own == "" || own == ref { + return ref, pullErr + } + + log.Warn().Err(pullErr).Str("app", payload.AppName).Str("image", ref).Str("fallback", own). + Msg("the pull under the platform's name failed; pulling the agent's own name") + _ = sm.LogManager.Write(payload.ContainerName.Prod, fmt.Sprintf("Pulling %s instead...", own)) + ownErr, otherErr := sm.pullImage(payload, own, started) + if otherErr != nil { + return own, otherErr + } + return own, ownErr +} + +// pullImage pulls ref and streams its progress into the app's log. pullErr is +// a failure of the pull itself; otherErr one of started. +func (sm *StateMachine) pullImage(payload common.TransitionPayload, ref string, started func() error) (pullErr error, otherErr error) { + topic := payload.ContainerName.Prod + pullOptions := container.PullOptions{ + AuthConfig: sm.authConfigForImage(payload, ref, topic), + PullID: common.BuildDockerPullID(payload.AppKey, payload.AppName), + } + + log.Debug().Msgf("PULLING IMAGE: %s", ref) + reader, err := sm.Container.Pull(context.Background(), ref, pullOptions) + if err != nil { + _ = sm.LogManager.Write(topic, fmt.Sprintf("Error occured while trying to pull the image: %s", err.Error())) + return err, nil + } + if started != nil { + if err := started(); err != nil { + _ = reader.Close() + return nil, err + } + } + return sm.LogManager.StreamBlocking(topic, common.PULL, reader), nil +} + +// wantedByOthers is every image tag another app's or stage's requested state +// still wants (WantedAppImages over all but payload's own); ok is false when +// the requested states cannot be read, and then nothing may be removed. +func (sm *StateMachine) wantedByOthers(payload common.TransitionPayload) (map[string]bool, bool) { + states, err := sm.StateObserver.AppStore.GetRequestedStates() + if err != nil { + log.Warn().Err(err).Str("app", payload.AppName).Msg("could not read the requested states; leaving the app's images") + return nil, false + } + others := make([]common.TransitionPayload, 0, len(states)) + var rc *config.ReswarmConfig + if len(platformImageNames(payload)) > 0 { + rc = sm.reswarmConfig() + } + for _, state := range states { + if state.AppKey == payload.AppKey && state.Stage == payload.Stage { + continue + } + others = append(others, state) + if rc == nil && len(platformImageNames(state)) > 0 { + rc = sm.reswarmConfig() + } + } + return WantedAppImages(rc, others), true +} + +// removeSupersededProdImage removes, after an update, the tags of the version +// the app ran before (PresentVersion, under the name it was recorded under, +// the platform's name and the agent's own), but not keep (the image the +// update installed: a name of the old and the new version can be one) and +// none that another app's or stage's requested state still wants. Only the +// tag is removed, never forced: an image with another tag keeps it, and one a +// container still uses stays. When the other requested states cannot be read, +// nothing is removed. Best effort; the diskguard reclaims what is left. +func (sm *StateMachine) removeSupersededProdImage(payload common.TransitionPayload, keep string) { + payload = sm.withInstalledImage(payload) + superseded := prodImageCandidates(sm.reswarmConfigFor(payload), payload, payload.PresentVersion) + if len(superseded) == 0 { + return + } + + wanted, ok := sm.wantedByOthers(payload) + if !ok { + return + } + + for _, ref := range superseded { + if ref == keep || wanted[ref] { + log.Debug().Str("app", payload.AppName).Str("image", ref).Msg("keeping a superseded tag that is still wanted") + continue + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second*30) + err := sm.Container.RemoveImage(ctx, ref, map[string]interface{}{"force": false, "pruneChildren": true}) + cancel() + if err != nil { + if !errdefs.IsImageNotFound(err) { + log.Debug().Err(err).Str("image", ref).Msg("could not remove the superseded image") + } + continue + } + log.Debug().Str("image", ref).Msg("removed the superseded image") + } +} + +// removeProdImageRepositories removes, with options, every tag of the app's +// single PROD image (prodImageRepositories) that no other app's or stage's +// requested state still wants: a repository nobody else wants a tag of goes +// whole, as before; in one that holds a wanted tag, the others go tag by tag. +// When the requested states cannot be read, nothing is removed. The first +// error is returned after all repositories were tried. +func (sm *StateMachine) removeProdImageRepositories(payload common.TransitionPayload, options map[string]interface{}) error { + payload = sm.withInstalledImage(payload) + wanted, ok := sm.wantedByOthers(payload) + if !ok { + return nil + } + + var firstErr error + keep := func(err error) { + if err != nil && firstErr == nil { + firstErr = err + } + } + for _, repository := range prodImageRepositories(sm.reswarmConfigFor(payload), payload) { + wantedHere := false + for tag := range wanted { + if imageRepository(tag) == repository { + wantedHere = true + break + } + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*30) + if !wantedHere { + keep(sm.Container.RemoveImagesByName(ctx, repository, options)) + cancel() + continue + } + + images, err := sm.Container.GetImages(ctx, repository) + cancel() + if err != nil { + keep(err) + continue + } + for _, image := range images { + for _, tag := range image.RepoTags { + if imageRepository(tag) != repository || wanted[tag] { + continue + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second*30) + err := sm.Container.RemoveImage(ctx, tag, options) + cancel() + if err != nil && !errdefs.IsImageNotFound(err) { + keep(err) + } + } + } + } + return firstErr +} diff --git a/src/apps/app_images_fallback_test.go b/src/apps/app_images_fallback_test.go new file mode 100644 index 0000000..30c192f --- /dev/null +++ b/src/apps/app_images_fallback_test.go @@ -0,0 +1,326 @@ +package apps + +import ( + "context" + "errors" + "testing" + + dockercontainer "github.com/docker/docker/api/types/container" + + "reagent/common" + "reagent/config" + containerpkg "reagent/container" + "reagent/errdefs" + "reagent/store" + "reagent/testutil/builders" + "reagent/testutil/fakes" + "reagent/testutil/mocks" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// ============================================================================= +// Second round: the pull under the platform's name falls back to the agent's +// own name; the name an image was really pulled under is recorded and used; +// the uninstall keeps what another app wants. Helpers from app_images_test.go. +// ============================================================================= + +// imgStored is the stored requested state of the test app. +func imgStored(t *testing.T, st *store.AppStore) common.TransitionPayload { + t.Helper() + stored, err := st.GetRequestedState(imgAppKey, common.PROD) + require.NoError(t, err) + return stored +} + +// A 64-bit agent next to a 32-bit engine: the version's index holds the +// agent's platform only, and the pull of the index by tag fails ("no matching +// manifest"). The agent pulls its own per-architecture name, as before. +func TestInstallFallsBackToTheAgentsOwnName(t *testing.T) { + newPayload := func(cfg *config.Config) common.TransitionPayload { + p := imgPayload(cfg, "2.0.0", "2.0.0") + p.PresentImageName = "prod_1953_myapp:2.0.0" + p.NewImageName = "prod_1953_myapp:2.0.0" + return p + } + + t.Run("the index has no image for the engine: the stream fails", func(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.REMOVED, "") + payload := newPayload(cfg) + imgStore(t, st, payload) + + mc.EXPECT().HandleRegistryLogins(mock.Anything).Return(nil).Once() + mc.EXPECT().Pull(mock.Anything, imgIndex("2.0.0"), mock.Anything). + Return(fwdErrorStream("no matching manifest for linux/arm/v7 in the manifest list entries"), nil).Once() + mc.EXPECT().Pull(mock.Anything, imgOwn("2.0.0"), mock.Anything).Return(fwdDockerStream(), nil).Once() + fwdAllowLogs(mc) + + require.NoError(t, sm.pullApp(payload, app)) + stored := imgStored(t, st) + assert.Equal(t, imgOwn("2.0.0"), stored.InstalledImage, "the name it really got") + assert.Equal(t, "2.0.0", stored.InstalledImageVersion) + }) + + t.Run("the pull call itself fails", func(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.REMOVED, "") + payload := newPayload(cfg) + imgStore(t, st, payload) + + mc.EXPECT().HandleRegistryLogins(mock.Anything).Return(nil).Once() + mc.EXPECT().Pull(mock.Anything, imgIndex("2.0.0"), mock.Anything).Return(nil, errors.New("manifest unknown")).Once() + mc.EXPECT().Pull(mock.Anything, imgOwn("2.0.0"), mock.Anything).Return(fwdDockerStream(), nil).Once() + fwdAllowLogs(mc) + + require.NoError(t, sm.pullApp(payload, app)) + assert.Equal(t, imgOwn("2.0.0"), imgStored(t, st).InstalledImage) + }) + + t.Run("both fail: the install fails with the second error", func(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.REMOVED, "") + payload := newPayload(cfg) + imgStore(t, st, payload) + + mc.EXPECT().HandleRegistryLogins(mock.Anything).Return(nil).Once() + mc.EXPECT().Pull(mock.Anything, imgIndex("2.0.0"), mock.Anything).Return(nil, errors.New("manifest unknown")).Once() + mc.EXPECT().Pull(mock.Anything, imgOwn("2.0.0"), mock.Anything).Return(nil, errors.New("registry unreachable")).Once() + fwdAllowLogs(mc) + + err := sm.pullApp(payload, app) + require.Error(t, err) + assert.Contains(t, err.Error(), "registry unreachable") + assert.Empty(t, imgStored(t, st).InstalledImage) + }) + + t.Run("a canceled pull is not tried again", func(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.REMOVED, "") + payload := newPayload(cfg) + imgStore(t, st, payload) + + mc.EXPECT().HandleRegistryLogins(mock.Anything).Return(nil).Once() + mc.EXPECT().Pull(mock.Anything, imgIndex("2.0.0"), mock.Anything). + Return(nil, errdefs.DockerStreamCanceled(errors.New("canceled"))).Once() + fwdAllowLogs(mc) + + err := sm.pullApp(payload, app) + assert.True(t, errdefs.IsDockerStreamCanceled(err)) + }) +} + +func TestUpdateFallsBackToTheAgentsOwnName(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.RUNNING, "1.0.0") + payload := imgPayload(cfg, "1.0.0", "2.0.0") + payload.RequestUpdate = true + payload.NewImageName = "prod_1953_myapp:2.0.0" + imgStore(t, st, payload) + + mc.EXPECT().HandleRegistryLogins(mock.Anything).Return(nil).Once() + mc.EXPECT().Pull(mock.Anything, imgIndex("2.0.0"), mock.Anything). + Return(fwdErrorStream("no matching manifest for linux/arm/v7 in the manifest list entries"), nil).Once() + mc.EXPECT().Pull(mock.Anything, imgOwn("2.0.0"), mock.Anything).Return(fwdDockerStream(), nil).Once() + mc.EXPECT().GetContainer(mock.Anything, payload.ContainerName.Prod).Return(dockercontainer.Summary{}, notFoundErr()).Once() + mc.EXPECT().RemoveImage(mock.Anything, imgOwn("1.0.0"), imgRemoveTag).Return(nil).Once() + fwdAllowLogs(mc) + + require.NoError(t, sm.updateApp(payload, app)) + stored := imgStored(t, st) + assert.Equal(t, "2.0.0", stored.PresentVersion) + assert.Equal(t, imgOwn("2.0.0"), stored.InstalledImage) +} + +// The start finds the image under the name it was recorded under, also after +// the platform renamed the version; nothing is pulled (strict mock). +func TestStartWithTheRecordedName(t *testing.T) { + start := func(t *testing.T, stored common.TransitionPayload, recorded string, lookup func(ref string) error) (string, common.TransitionPayload) { + t.Helper() + sm, mc, st, _, app := imgHarness(t, common.PRESENT, stored.PresentVersion) + imgStore(t, st, stored) + if recorded != "" { + require.NoError(t, st.SetInstalledImage(imgAppKey, common.PROD, stored.PresentVersion, recorded)) + } + payload, err := st.GetRequestedState(imgAppKey, common.PROD) + require.NoError(t, err) + + mc.EXPECT().GetImage(mock.Anything, mock.Anything, mock.Anything).RunAndReturn( + func(_ context.Context, repository string, tag string) (containerpkg.ImageResult, error) { + if err := lookup(repository + ":" + tag); err != nil { + return containerpkg.ImageResult{}, err + } + return containerpkg.ImageResult{ID: "sha256:local"}, nil + }).Maybe() + + containerConfig, _, err := sm.computeContainerConfigs(payload, app) + require.NoError(t, err) + return containerConfig.Image, payload + } + onlyLocal := func(want string) func(string) error { + return func(ref string) error { + if ref == want { + return nil + } + return imageNotFound() + } + } + + t.Run("the platform renamed the version", func(t *testing.T) { + cfg := imgTestConfig() + stored := imgPayload(cfg, "2.0.0", "2.0.0") + stored.PresentImageName = "prod_" + imgOtherArch() + "_1953_myapp:2.0.0" + image, _ := start(t, stored, imgIndex("2.0.0"), onlyLocal(imgIndex("2.0.0"))) + assert.Equal(t, imgIndex("2.0.0"), image) + }) + + t.Run("after the fallback: the agent's own name, recorded", func(t *testing.T) { + cfg := imgTestConfig() + stored := imgPayload(cfg, "2.0.0", "2.0.0") + stored.PresentImageName = "prod_1953_myapp:2.0.0" + // the store forms the agent's own name with its configuration + own := common.BuildTransitionPayload(imgAppKey, "MyApp", 0, common.PROD, "", "", 0, 0, builders.DefaultTestConfig()).RegistryImageName.Prod + ":2.0.0" + image, _ := start(t, stored, own, onlyLocal(own)) + assert.Equal(t, own, image) + }) + + t.Run("Docker cannot say: the recorded name, never the platform's unverified one", func(t *testing.T) { + cfg := imgTestConfig() + stored := imgPayload(cfg, "2.0.0", "2.0.0") + stored.PresentImageName = "prod_" + imgOtherArch() + "_1953_myapp:2.0.0" + image, _ := start(t, stored, imgIndex("2.0.0"), func(string) error { return errors.New("daemon busy") }) + assert.Equal(t, imgIndex("2.0.0"), image) + }) + + t.Run("Docker cannot say, nothing recorded: the agent's own name, as before", func(t *testing.T) { + cfg := imgTestConfig() + stored := imgPayload(cfg, "2.0.0", "2.0.0") + stored.PresentImageName = "prod_1953_myapp:2.0.0" + image, read := start(t, stored, "", func(string) error { return errors.New("daemon busy") }) + assert.Equal(t, read.RegistryImageName.Prod+":2.0.0", image) + }) +} + +// The observer, the cleanup and the uninstall know the recorded name. +func TestTheRecordedNameIsTheAppsImage(t *testing.T) { + cfg := imgTestConfig() + + t.Run("observer", func(t *testing.T) { + p := imgPayload(cfg, "2.0.0", "2.0.0") // an older backend names nothing + images := []containerpkg.ImageResult{{ID: "a", RepoTags: []string{imgIndex("2.0.0")}}} + assert.False(t, hasImageInRepositories(images, appImageRepositories(cfg.ReswarmConfig, p))) + p.InstalledImage, p.InstalledImageVersion = imgIndex("2.0.0"), "2.0.0" + assert.True(t, hasImageInRepositories(images, appImageRepositories(cfg.ReswarmConfig, p))) + }) + + t.Run("a recorded reference of another app is not this app's", func(t *testing.T) { + p := imgPayload(cfg, "2.0.0", "2.0.0") + p.InstalledImage, p.InstalledImageVersion = "registry.test/apps/prod_1954_myapp:2.0.0", "2.0.0" + assert.Equal(t, []string{imageRepository(imgOwn("1"))}, prodImageRepositories(cfg.ReswarmConfig, p)) + assert.Empty(t, installedProdImage(p, "2.0.0")) + }) + + t.Run("update cleanup", func(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.RUNNING, "2.0.0") + imgConfig(cfg) + payload := imgPayload(cfg, "2.0.0", "3.0.0") + payload.RequestUpdate = true + imgStore(t, st, payload) + require.NoError(t, st.SetInstalledImage(imgAppKey, common.PROD, "2.0.0", imgIndex("2.0.0"))) + + imgExpectUpdate(mc, payload, payload.RegistryImageName.Prod+":3.0.0") + mc.EXPECT().RemoveImage(mock.Anything, imgIndex("2.0.0"), imgRemoveTag).Return(nil).Once() + mc.EXPECT().RemoveImage(mock.Anything, payload.RegistryImageName.Prod+":2.0.0", imgRemoveTag).Return(imageNotFound()).Once() + + require.NoError(t, sm.updateApp(payload, app)) + }) + + t.Run("uninstall", func(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.PRESENT, "2.0.0") + payload := imgPayload(cfg, "2.0.0", "2.0.0") + payload.RequestedState = common.REMOVED + imgStore(t, st, payload) + require.NoError(t, st.SetInstalledImage(imgAppKey, common.PROD, "2.0.0", imgIndex("2.0.0"))) + + mc.EXPECT().GetContainer(mock.Anything, payload.ContainerName.Prod).Return(dockercontainer.Summary{}, notFoundErr()).Once() + mc.EXPECT().RemoveImagesByName(mock.Anything, payload.RegistryImageName.Prod, map[string]interface{}{"force": true}).Return(nil).Once() + mc.EXPECT().RemoveImagesByName(mock.Anything, imageRepository(imgIndex("1")), map[string]interface{}{"force": true}).Return(nil).Once() + fwdAllowLogs(mc) + + require.NoError(t, sm.removeProdApp(payload, app)) + }) +} + +// Without a configuration a platform's name never becomes a reference: it +// would have no registry. +func TestNoConfigurationNoPlatformReference(t *testing.T) { + cfg := imgTestConfig() + p := imgPayload(cfg, "2.0.0", "2.0.0") + p.NewImageName = "prod_1953_myapp:2.0.0" + assert.Empty(t, platformProdImage(nil, p, p.NewImageName, "2.0.0")) + assert.Equal(t, imgOwn("2.0.0"), prodImageFor(nil, p, "2.0.0")) + + // the agent's own form stays the agent's own reference + p.NewImageName = "prod_" + imgOwnArch() + "_1953_myapp:2.0.0" + assert.Equal(t, imgOwn("2.0.0"), platformProdImage(nil, p, p.NewImageName, "2.0.0")) +} + +// The uninstall keeps every tag another app's requested state wants, also in +// the app's own repositories. +func TestUninstallKeepsWhatAnotherAppWants(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.PRESENT, "1.0.0") + payload := imgPayload(cfg, "1.0.0", "2.0.0") + payload.RequestedState = common.REMOVED + payload.PresentImageName = "prod_1953_myapp:1.0.0" + payload.NewImageName = "prod_1953_myapp:2.0.0" + imgStore(t, st, payload) + + other := common.BuildTransitionPayload(77, "Other", 0, common.PROD, common.PRESENT, common.RUNNING, 0, 0, cfg) + other.DockerCompose = map[string]interface{}{"services": map[string]interface{}{ + "web": map[string]interface{}{"image": imgIndex("1.0.0")}, + }} + imgStore(t, st, other) + + force := map[string]interface{}{"force": true} + mc.EXPECT().GetContainer(mock.Anything, payload.ContainerName.Prod).Return(dockercontainer.Summary{}, notFoundErr()).Once() + mc.EXPECT().RemoveImagesByName(mock.Anything, imageRepository(imgOwn("1")), force).Return(nil).Once() + mc.EXPECT().GetImages(mock.Anything, imageRepository(imgIndex("1"))).Return([]containerpkg.ImageResult{ + {ID: "a", RepoTags: []string{imgIndex("1.0.0")}}, + {ID: "b", RepoTags: []string{imgIndex("2.0.0"), "registry.test/apps/other:1"}}, + }, nil).Once() + mc.EXPECT().RemoveImage(mock.Anything, imgIndex("2.0.0"), force).Return(nil).Once() + fwdAllowLogs(mc) + + require.NoError(t, sm.removeProdApp(payload, app)) +} + +// A store whose requested states cannot be read: nothing is removed. +func TestNothingIsRemovedWhenTheRequestedStatesCannotBeRead(t *testing.T) { + mc := mocks.NewContainer(t) + db := mocks.NewDatabase(t) + db.EXPECT().GetRequestedState(mock.Anything, mock.Anything).Return(common.TransitionPayload{}, errors.New("disk I/O error")).Maybe() + db.EXPECT().GetRequestedStates().Return(nil, errors.New("disk I/O error")).Maybe() + appStore := store.NewAppStore(db, fakes.NewMessenger()) + observer := NewObserver(mc, &appStore, nil) + sm := &StateMachine{Container: mc, StateObserver: &observer} + + cfg := imgTestConfig() + payload := imgPayload(cfg, "1.0.0", "2.0.0") + sm.removeSupersededProdImage(payload, imgOwn("2.0.0")) + require.NoError(t, sm.removeProdImageRepositories(payload, map[string]interface{}{"force": true})) + // the strict mocks fail on any RemoveImage / RemoveImagesByName +} + +// The tag an update installed is never removed as the old version's: with the +// platform's lower-case names, 2.0.0-RC1 and 2.0.0-rc1 are one reference. +func TestUpdateCleanupKeepsTheInstalledTag(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.RUNNING, "2.0.0-RC1") + payload := imgPayload(cfg, "2.0.0-RC1", "2.0.0-rc1") + payload.RequestUpdate = true + payload.PresentImageName = "prod_1953_myapp:2.0.0-rc1" + payload.NewImageName = "prod_1953_myapp:2.0.0-rc1" + imgStore(t, st, payload) + + imgExpectUpdate(mc, payload, imgIndex("2.0.0-rc1")) + mc.EXPECT().RemoveImage(mock.Anything, imgOwn("2.0.0-RC1"), imgRemoveTag).Return(nil).Once() + // no RemoveImage of imgIndex("2.0.0-rc1"): the strict mock fails on it + + require.NoError(t, sm.updateApp(payload, app)) +} diff --git a/src/apps/app_images_test.go b/src/apps/app_images_test.go new file mode 100644 index 0000000..5740ddc --- /dev/null +++ b/src/apps/app_images_test.go @@ -0,0 +1,636 @@ +package apps + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "errors" + "io" + "os" + "path/filepath" + "testing" + + dockercontainer "github.com/docker/docker/api/types/container" + + "reagent/common" + "reagent/config" + containerpkg "reagent/container" + "reagent/errdefs" + "reagent/messenger/topics" + "reagent/release" + "reagent/store" + "reagent/testutil/mocks" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +// ============================================================================= +// The image of a single-image app: the name comes from the platform +// (app_images.go). Helpers are prefixed img*. +// +// The app is 1953 "MyApp" on registry.test/ with the main repository apps/. +// imgOwn is the name this agent forms itself (its build architecture), +// imgIndex the platform's name for a release with one name per version, +// imgOther a name from before for an architecture that is not this agent's. +// ============================================================================= + +const imgAppKey = uint64(1953) + +func imgOwnArch() string { + sysInfo := release.GetSystemInfo() + return sysInfo.Arch + sysInfo.Variant +} + +func imgOtherArch() string { + if imgOwnArch() == "armv6" { + return "amd64" + } + return "armv6" +} + +func imgOwn(version string) string { + return "registry.test/apps/prod_" + imgOwnArch() + "_1953_myapp:" + version +} + +func imgIndex(version string) string { + return "registry.test/apps/prod_1953_myapp:" + version +} + +func imgOther(version string) string { + return "registry.test/apps/prod_" + imgOtherArch() + "_1953_myapp:" + version +} + +// imgConfig puts the test config on registry.test/ with the main repository apps/. +func imgConfig(cfg *config.Config) *config.Config { + cfg.ReswarmConfig.DockerRegistryURL = "registry.test/" + cfg.ReswarmConfig.DockerMainRepository = "apps/" + return cfg +} + +// imgPayload is a sync answer for the app on this device: the version it +// runs and the one it is to go to, without image names (an older backend). +func imgPayload(cfg *config.Config, present, newest string) common.TransitionPayload { + p := common.BuildTransitionPayload(imgAppKey, "MyApp", 0, common.PROD, common.PRESENT, common.RUNNING, 101, 202, cfg) + p.PresentVersion = present + p.NewestVersion = newest + p.Version = present + return p +} + +func imgTestConfig() *config.Config { + cfg := &config.Config{ReswarmConfig: &config.ReswarmConfig{}} + return imgConfig(cfg) +} + +func TestPlatformImageRepository(t *testing.T) { + cfg := imgTestConfig() + p := imgPayload(cfg, "1.0.0", "2.0.0") + + understood := map[string]string{ + "prod_1953_myapp:2.0.0": "prod_1953_myapp", + "prod_amd64_1953_myapp:2.0.0": "prod_amd64_1953_myapp", + "prod_armv7_1953_myapp:2.0.0": "prod_armv7_1953_myapp", + "prod_" + imgOwnArch() + "_1953_myapp:2.0.0": "prod_" + imgOwnArch() + "_1953_myapp", + } + for name, repository := range understood { + got, tag, ok := platformImageRepository(p, name, "2.0.0") + assert.True(t, ok, name) + assert.Equal(t, repository, got, name) + assert.Equal(t, "2.0.0", tag, name) + } + + notUnderstood := []string{ + "", + "prod_1953_myapp", // no tag + "prod_1953_myapp:1.0.0", // another version + "prod_1954_myapp:2.0.0", // another app's key + "prod_19530_myapp:2.0.0", // another app's key + "prod_1953_otherapp:2.0.0", // another app's name + "prod_1953_myapp_1:2.0.0", // a Compose service's image + "prod_amd64_1953_myapp_1:2.0.0", // a Compose service's image from before + "dev_amd64_1953_myapp:2.0.0", // a development build + "prod_64_1953_myapp:2.0.0", // a number where the architecture goes + "prod_amd_64_1953_myapp:2.0.0", // two parts where the architecture goes + "apps/prod_1953_myapp:2.0.0", // with the main repository + "registry.test/apps/prod_1953_myapp:2.0.0", // with registry and main repository + "prod_1953_myapp@sha256:" + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + "prod_1953_myapp:2.0.0 ", + } + for _, name := range notUnderstood { + _, _, ok := platformImageRepository(p, name, "2.0.0") + assert.False(t, ok, "%q must not be understood", name) + } + + t.Run("the tag is the version, letter case aside", func(t *testing.T) { + _, tag, ok := platformImageRepository(p, "prod_1953_myapp:2.0.0-rc1", "2.0.0-RC1") + assert.True(t, ok) + assert.Equal(t, "2.0.0-rc1", tag, "the platform's tag, as the index is tagged") + }) + + t.Run("a DEV app takes no name from the platform", func(t *testing.T) { + dev := p + dev.Stage = common.DEV + _, _, ok := platformImageRepository(dev, "prod_1953_myapp:2.0.0", "2.0.0") + assert.False(t, ok) + }) +} + +func TestProdImageFor(t *testing.T) { + cfg := imgTestConfig() + + t.Run("an older backend names none: the agent's own name, as before", func(t *testing.T) { + p := imgPayload(cfg, "1.0.0", "2.0.0") + assert.Equal(t, imgOwn("2.0.0"), prodImageFor(cfg.ReswarmConfig, p, "2.0.0")) + assert.Equal(t, imgOwn("1.0.0"), prodImageFor(cfg.ReswarmConfig, p, "1.0.0")) + }) + + t.Run("a release with one name per version", func(t *testing.T) { + p := imgPayload(cfg, "1.0.0", "2.0.0") + p.PresentImageName = "prod_" + imgOwnArch() + "_1953_myapp:1.0.0" + p.NewImageName = "prod_1953_myapp:2.0.0" + assert.Equal(t, imgIndex("2.0.0"), prodImageFor(cfg.ReswarmConfig, p, "2.0.0")) + assert.Equal(t, imgOwn("1.0.0"), prodImageFor(cfg.ReswarmConfig, p, "1.0.0")) + }) + + t.Run("a release from before keeps exactly today's reference", func(t *testing.T) { + p := imgPayload(cfg, "1.0.0", "2.0.0-RC1") + p.NewImageName = "prod_" + imgOwnArch() + "_1953_myapp:2.0.0-rc1" + assert.Equal(t, imgOwn("2.0.0-RC1"), prodImageFor(cfg.ReswarmConfig, p, "2.0.0-RC1"), + "the version as the sync answer spells it, as the agent always pulled it") + }) + + t.Run("a release from before of another architecture", func(t *testing.T) { + p := imgPayload(cfg, "1.0.0", "2.0.0") + p.NewImageName = "prod_" + imgOtherArch() + "_1953_myapp:2.0.0" + assert.Equal(t, imgOther("2.0.0"), prodImageFor(cfg.ReswarmConfig, p, "2.0.0")) + }) + + t.Run("a name of another shape is not used", func(t *testing.T) { + for _, name := range []string{"apps/prod_1953_myapp:2.0.0", "prod_1953_other:2.0.0", "nginx:2.0.0", "prod_1953_myapp:2.0.1"} { + p := imgPayload(cfg, "1.0.0", "2.0.0") + p.NewImageName = name + assert.Equal(t, imgOwn("2.0.0"), prodImageFor(cfg.ReswarmConfig, p, "2.0.0"), name) + } + }) + + t.Run("the name of a Compose release names no image", func(t *testing.T) { + p := imgPayload(cfg, "1.0.0", "2.0.0") + p.NewImageName = "prod_1953_myapp:2.0.0" + p.NewDockerCompose = map[string]interface{}{"services": map[string]interface{}{}} + assert.Equal(t, imgOwn("2.0.0"), prodImageFor(cfg.ReswarmConfig, p, "2.0.0")) + }) + + t.Run("a DEV app", func(t *testing.T) { + p := imgPayload(cfg, "1.0.0", "2.0.0") + p.Stage = common.DEV + p.NewImageName = "prod_1953_myapp:2.0.0" + assert.Equal(t, imgOwn("2.0.0"), prodImageFor(cfg.ReswarmConfig, p, "2.0.0")) + }) +} + +func TestProdImageRepositories(t *testing.T) { + cfg := imgTestConfig() + own := imageRepository(imgOwn("1")) + + p := imgPayload(cfg, "1.0.0", "2.0.0") + assert.Equal(t, []string{own}, prodImageRepositories(cfg.ReswarmConfig, p), "an older backend") + + p.PresentImageName = "prod_" + imgOtherArch() + "_1953_myapp:1.0.0" + p.NewImageName = "prod_1953_myapp:2.0.0" + assert.Equal(t, []string{own, imageRepository(imgOther("1")), imageRepository(imgIndex("1"))}, + prodImageRepositories(cfg.ReswarmConfig, p)) + + p.PresentImageName = "library/nginx:1.0.0" + p.NewImageName = "prod_1954_myapp:2.0.0" + assert.Equal(t, []string{own}, prodImageRepositories(cfg.ReswarmConfig, p), "names of another shape add nothing") +} + +func TestWantedAppImagesKeepsThePlatformsNames(t *testing.T) { + cfg := imgTestConfig() + p := imgPayload(cfg, "1.0.0", "2.0.0") + p.PresentImageName = "prod_" + imgOwnArch() + "_1953_myapp:1.0.0" + p.NewImageName = "prod_1953_myapp:2.0.0" + + wanted := WantedAppImages(cfg.ReswarmConfig, []common.TransitionPayload{p}) + for _, ref := range []string{imgOwn("1.0.0"), imgOwn("2.0.0"), imgIndex("2.0.0")} { + assert.True(t, wanted[ref], ref) + } + assert.False(t, wanted[imgIndex("1.0.0")], "the platform names no such image") +} + +// ============================================================================= +// The state machine with the platform's names +// ============================================================================= + +// imgHarness is a state machine on the test registry with the app seeded at +// state and version, and its requested state stored as payload. +func imgHarness(t *testing.T, state common.AppState, version string) (*StateMachine, *mocks.Container, *store.AppStore, *config.Config, *common.App) { + t.Helper() + sm, mc, st, _, cfg := wiredRunBuildSM(t) + imgConfig(cfg) + + seed := imgPayload(cfg, version, version) + seed.CurrentState = state + app, err := st.AddApp(seed) + require.NoError(t, err) + app.StateLock.Lock() + app.Version = version + app.StateLock.Unlock() + return sm, mc, st, cfg, app +} + +func imgStore(t *testing.T, st *store.AppStore, payload common.TransitionPayload) { + t.Helper() + if payload.CurrentState == "" { + payload.CurrentState = common.PRESENT + } + require.NoError(t, st.UpdateLocalRequestedState(payload)) +} + +var imgRemoveTag = map[string]interface{}{"force": false, "pruneChildren": true} + +func imageNotFound() error { + return errdefs.ImageNotFound(errors.New("no such image")) +} + +// imgExpectUpdate wires the container calls of a single-image update that +// pulls ref, with no old container to remove. +func imgExpectUpdate(mc *mocks.Container, payload common.TransitionPayload, ref string) { + mc.EXPECT().HandleRegistryLogins(mock.Anything).Return(nil).Once() + mc.EXPECT().Pull(mock.Anything, ref, mock.Anything).Return(fwdDockerStream(), nil).Once() + mc.EXPECT().GetContainer(mock.Anything, payload.ContainerName.Prod). + Return(dockercontainer.Summary{}, notFoundErr()).Once() + fwdAllowLogs(mc) +} + +func TestInstallUnderTheNewName(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.REMOVED, "") + payload := imgPayload(cfg, "2.0.0", "2.0.0") + payload.PresentImageName = "prod_1953_myapp:2.0.0" + payload.NewImageName = "prod_1953_myapp:2.0.0" + imgStore(t, st, payload) + + mc.EXPECT().HandleRegistryLogins(mock.Anything).Return(nil).Once() + // by tag, no platform named: Docker chooses from the index + mc.EXPECT().Pull(mock.Anything, imgIndex("2.0.0"), mock.Anything).Return(fwdDockerStream(), nil).Once() + fwdAllowLogs(mc) + + require.NoError(t, sm.pullApp(payload, app)) +} + +func TestUpdateFromTheOldNameToTheNewName(t *testing.T) { + newPayload := func(cfg *config.Config) common.TransitionPayload { + p := imgPayload(cfg, "1.0.0", "2.0.0") + p.RequestUpdate = true + // The app was installed before this agent took names from the + // platform: under the agent's own name, which the platform still + // gives for 1.0.0. + p.PresentImageName = "prod_" + imgOwnArch() + "_1953_myapp:1.0.0" + p.NewImageName = "prod_1953_myapp:2.0.0" + return p + } + + t.Run("pulls the new name and removes the old tag", func(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.RUNNING, "1.0.0") + payload := newPayload(cfg) + imgStore(t, st, payload) + + imgExpectUpdate(mc, payload, imgIndex("2.0.0")) + mc.EXPECT().RemoveImage(mock.Anything, imgOwn("1.0.0"), imgRemoveTag).Return(nil).Once() + + require.NoError(t, sm.updateApp(payload, app)) + + stored, err := st.GetRequestedState(imgAppKey, common.PROD) + require.NoError(t, err) + assert.Equal(t, "2.0.0", stored.PresentVersion) + assert.Equal(t, "prod_1953_myapp:2.0.0", stored.PresentImageName, "the installed version's name is stored with it") + }) + + t.Run("keeps the old tag while another installed app uses it", func(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.RUNNING, "1.0.0") + payload := newPayload(cfg) + imgStore(t, st, payload) + + // Another app's Compose file runs this app's image of 1.0.0. + other := common.BuildTransitionPayload(77, "Other", 0, common.PROD, common.PRESENT, common.RUNNING, 0, 0, cfg) + other.DockerCompose = map[string]interface{}{"services": map[string]interface{}{ + "web": map[string]interface{}{"image": imgOwn("1.0.0")}, + }} + imgStore(t, st, other) + + imgExpectUpdate(mc, payload, imgIndex("2.0.0")) + // no RemoveImage: the strict mock fails on one + + require.NoError(t, sm.updateApp(payload, app)) + }) +} + +func TestDowngradeFromTheNewNameToTheOldName(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.RUNNING, "2.0.0") + payload := imgPayload(cfg, "2.0.0", "1.0.0") + payload.RequestUpdate = true + payload.PresentImageName = "prod_1953_myapp:2.0.0" + payload.NewImageName = "prod_" + imgOwnArch() + "_1953_myapp:1.0.0" + imgStore(t, st, payload) + + imgExpectUpdate(mc, payload, imgOwn("1.0.0")) + mc.EXPECT().RemoveImage(mock.Anything, imgIndex("2.0.0"), imgRemoveTag).Return(nil).Once() + mc.EXPECT().RemoveImage(mock.Anything, imgOwn("2.0.0"), imgRemoveTag).Return(imageNotFound()).Once() + + require.NoError(t, sm.updateApp(payload, app)) + + stored, err := st.GetRequestedState(imgAppKey, common.PROD) + require.NoError(t, err) + assert.Equal(t, "prod_"+imgOwnArch()+"_1953_myapp:1.0.0", stored.PresentImageName) +} + +func TestUpdateWithAnOlderBackendIsAsBefore(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.RUNNING, "1.0.0") + payload := imgPayload(cfg, "1.0.0", "2.0.0") + payload.RequestUpdate = true + imgStore(t, st, payload) + + imgExpectUpdate(mc, payload, imgOwn("2.0.0")) + mc.EXPECT().RemoveImage(mock.Anything, imgOwn("1.0.0"), imgRemoveTag).Return(nil).Once() + + require.NoError(t, sm.updateApp(payload, app)) +} + +func TestUpdateWithANameOfAnotherShape(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.RUNNING, "1.0.0") + payload := imgPayload(cfg, "1.0.0", "2.0.0") + payload.RequestUpdate = true + payload.PresentImageName = "library/nginx:1.0.0" + payload.NewImageName = "registry.evil/x:2.0.0" + imgStore(t, st, payload) + + // pulls the agent's own name, and removes only the agent's own tag + imgExpectUpdate(mc, payload, imgOwn("2.0.0")) + mc.EXPECT().RemoveImage(mock.Anything, imgOwn("1.0.0"), imgRemoveTag).Return(nil).Once() + + require.NoError(t, sm.updateApp(payload, app)) +} + +func TestRemoveWithTheNamesOfThePlatform(t *testing.T) { + t.Run("every repository of the app's image", func(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.PRESENT, "1.0.0") + payload := imgPayload(cfg, "1.0.0", "2.0.0") + payload.RequestedState = common.REMOVED + payload.PresentImageName = "prod_" + imgOtherArch() + "_1953_myapp:1.0.0" + payload.NewImageName = "prod_1953_myapp:2.0.0" + imgStore(t, st, payload) + + mc.EXPECT().GetContainer(mock.Anything, payload.ContainerName.Prod).Return(dockercontainer.Summary{}, notFoundErr()).Once() + for _, repository := range []string{imageRepository(imgOwn("1")), imageRepository(imgOther("1")), imageRepository(imgIndex("1"))} { + mc.EXPECT().RemoveImagesByName(mock.Anything, repository, map[string]interface{}{"force": true}).Return(nil).Once() + } + fwdAllowLogs(mc) + + require.NoError(t, sm.removeProdApp(payload, app)) + }) + + t.Run("a name of another shape removes nothing under it", func(t *testing.T) { + sm, mc, st, cfg, app := imgHarness(t, common.PRESENT, "1.0.0") + payload := imgPayload(cfg, "1.0.0", "2.0.0") + payload.RequestedState = common.REMOVED + payload.PresentImageName = "library/nginx:1.0.0" + payload.NewImageName = "prod_1954_otherapp:2.0.0" + imgStore(t, st, payload) + + mc.EXPECT().GetContainer(mock.Anything, payload.ContainerName.Prod).Return(dockercontainer.Summary{}, notFoundErr()).Once() + mc.EXPECT().RemoveImagesByName(mock.Anything, imageRepository(imgOwn("1")), map[string]interface{}{"force": true}).Return(nil).Once() + fwdAllowLogs(mc) + + require.NoError(t, sm.removeProdApp(payload, app)) + }) +} + +// The image an installed app starts with is the one the device has, under +// the name stored with its requested state; nothing is pulled (the strict +// mock fails on a pull). +func TestStartWithTheStoredName(t *testing.T) { + // startImage stores stored, reads it back as a start does (offline too), + // and computes the container's image with the device holding local(read). + startImage := func(t *testing.T, stored common.TransitionPayload, local func(read common.TransitionPayload) string) (image string, want string) { + t.Helper() + sm, mc, st, _, app := imgHarness(t, common.PRESENT, stored.PresentVersion) + imgStore(t, st, stored) + + payload, err := st.GetRequestedState(imgAppKey, common.PROD) + require.NoError(t, err) + want = local(payload) + + mc.EXPECT().GetImage(mock.Anything, mock.Anything, mock.Anything).RunAndReturn( + func(_ context.Context, repository string, tag string) (containerpkg.ImageResult, error) { + if repository+":"+tag == want { + return containerpkg.ImageResult{ID: "sha256:local"}, nil + } + return containerpkg.ImageResult{}, imageNotFound() + }).Maybe() + + containerConfig, _, err := sm.computeContainerConfigs(payload, app) + require.NoError(t, err) + return containerConfig.Image, want + } + + t.Run("a stored name of the new form", func(t *testing.T) { + cfg := imgTestConfig() + stored := imgPayload(cfg, "2.0.0", "2.0.0") + stored.PresentImageName = "prod_1953_myapp:2.0.0" + stored.NewImageName = "prod_1953_myapp:2.0.0" + image, _ := startImage(t, stored, func(common.TransitionPayload) string { return imgIndex("2.0.0") }) + assert.Equal(t, imgIndex("2.0.0"), image) + }) + + t.Run("an app installed before this agent: no stored name", func(t *testing.T) { + cfg := imgTestConfig() + stored := imgPayload(cfg, "1.0.0", "1.0.0") + image, want := startImage(t, stored, func(read common.TransitionPayload) string { + return read.RegistryImageName.Prod + ":1.0.0" + }) + assert.Equal(t, want, image) + }) + + t.Run("a stored new name while the device has the version under the old one", func(t *testing.T) { + // installed before the platform moved the version to its new name + cfg := imgTestConfig() + stored := imgPayload(cfg, "1.0.0", "1.0.0") + stored.PresentImageName = "prod_1953_myapp:1.0.0" + image, want := startImage(t, stored, func(read common.TransitionPayload) string { + return read.RegistryImageName.Prod + ":1.0.0" + }) + assert.Equal(t, want, image, "runs the image it has, offline too") + }) +} + +func TestStoredImageNamesSurviveARestart(t *testing.T) { + _, _, st, cfg, _ := imgHarness(t, common.RUNNING, "1.0.0") + payload := imgPayload(cfg, "1.0.0", "2.0.0") + payload.CurrentState = common.RUNNING + payload.PresentImageName = "prod_1953_myapp:1.0.0" + payload.NewImageName = "prod_1953_myapp:2.0.0" + imgStore(t, st, payload) + + all, err := st.GetRequestedStates() + require.NoError(t, err) + require.Len(t, all, 1) + assert.Equal(t, "prod_1953_myapp:1.0.0", all[0].PresentImageName) + assert.Equal(t, "prod_1953_myapp:2.0.0", all[0].NewImageName) + + // a sync of an older backend names none: the agent's own names again + payload.PresentImageName, payload.NewImageName = "", "" + imgStore(t, st, payload) + one, err := st.GetRequestedState(imgAppKey, common.PROD) + require.NoError(t, err) + assert.Empty(t, one.PresentImageName) + assert.Empty(t, one.NewImageName) +} + +// The observer finds a single-image app's image under the platform's name: +// before, it looked for the agent's own name only, and an app without a +// container whose image has the new name was reported REMOVED. +func TestObserverFindsTheImageUnderThePlatformsName(t *testing.T) { + cfg := imgTestConfig() + p := imgPayload(cfg, "2.0.0", "2.0.0") + p.PresentImageName = "prod_1953_myapp:2.0.0" + + images := []containerpkg.ImageResult{{ID: "sha256:a", RepoTags: []string{"registry.test/apps/prod_19530_myapp:2.0.0", imgIndex("2.0.0")}}} + assert.True(t, hasImageInRepositories(images, appImageRepositories(cfg.ReswarmConfig, p))) + + withoutName := p + withoutName.PresentImageName = "" + assert.False(t, hasImageInRepositories(images, appImageRepositories(cfg.ReswarmConfig, withoutName)), + "negative control: without the platform's name the image is not the app's") + + prefixOnly := []containerpkg.ImageResult{{ID: "sha256:b", RepoTags: []string{imgOwn("2.0.0")[:len(imgOwn("2.0.0"))-len(":2.0.0")] + "x:2.0.0"}}} + assert.False(t, hasImageInRepositories(prefixOnly, appImageRepositories(cfg.ReswarmConfig, withoutName)), + "another app whose name starts like this one's") +} + +// ============================================================================= +// Point 2: the push side of a release build keeps the agent's own name +// ============================================================================= + +// A single-image release build is pushed as +// prod___:, which the +// backend computes from the device's agent_architecture: the platform's names +// for pulling never reach it. The PUBLISHED report names the digest the push +// answered (pushed_digests), where the push stream gave one. +func TestReleaseBuildPushesTheAgentsOwnName(t *testing.T) { + const digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + auxStream := func() io.ReadCloser { + return fwdDockerStream( + `{"status":"The push refers to repository [registry.test/apps/prod_x_1953_myapp]"}`, + `{"status":"3.0.0: digest: `+digest+` size: 528"}`, + `{"progressDetail":{},"aux":{"Tag":"3.0.0","Digest":"`+digest+`","Size":528}}`, + ) + } + + publish := func(t *testing.T, stream io.ReadCloser) (*common.App, common.Dict, string) { + t.Helper() + sm, mc, st, msg, cfg := wiredRunBuildSM(t) + imgConfig(cfg) + + payload := imgPayload(cfg, "1.0.0", "1.0.0") + payload.Stage = common.DEV + payload.Version = "3.0.0" + payload.CurrentState = common.PRESENT + payload.RequestedState = common.PUBLISHED + payload.PresentImageName = "prod_1953_myapp:3.0.0" + payload.NewImageName = "prod_1953_myapp:3.0.0" + devApp, err := st.AddApp(payload) + require.NoError(t, err) + // a digest of an earlier build is never reported for this one + devApp.PushedDigests = map[string]string{"registry.test/apps/old:1": digest} + imgStore(t, st, payload) + + pushed := "registry.test/apps/prod_" + imgOwnArch() + "_1953_myapp:3.0.0" + require.Equal(t, "registry.test/apps/dev_"+imgOwnArch()+"_1953_myapp", payload.RegistryImageName.Dev) + + tarPath := filepath.Join(cfg.CommandLineArguments.AppsBuildDir, payload.AppName+"."+cfg.CommandLineArguments.CompressedBuildExtension) + imgWriteTgz(t, tarPath, map[string]string{"Dockerfile": "FROM scratch\n"}) + + mc.EXPECT().Build(mock.Anything, tarPath, mock.Anything).Return(fwdDockerStream(), nil).Once() + mc.EXPECT().Tag(mock.Anything, payload.RegistryImageName.Dev, pushed).Return(nil).Once() + mc.EXPECT().HandleRegistryLogins(mock.Anything).Return(nil).Once() + mc.EXPECT().Push(mock.Anything, pushed, mock.Anything).Return(stream, nil).Once() + fwdAllowLogs(mc) + + require.NoError(t, sm.publishApp(payload, devApp)) + + var report common.Dict + for _, call := range msg.GetCallCalls() { + if call.Topic != topics.SetActualAppOnDeviceState || len(call.Args) == 0 { + continue + } + if dict, ok := call.Args[0].(common.Dict); ok && dict["state"] == common.PUBLISHED { + report = dict + } + } + require.NotNil(t, report, "the PUBLISHED report") + return devApp, report, pushed + } + + t.Run("the digest the push answered", func(t *testing.T) { + _, report, pushed := publish(t, auxStream()) + assert.Equal(t, map[string]string{pushed: digest}, report["pushed_digests"]) + }) + + t.Run("the containerd image store's status line", func(t *testing.T) { + _, report, pushed := publish(t, fwdDockerStream( + `{"status":"Pushed","progressDetail":{},"id":"5f70bf18a086"}`, + `{"status":"3.0.0: digest: `+digest+` size: 856"}`, + )) + assert.Equal(t, map[string]string{pushed: digest}, report["pushed_digests"]) + }) + + t.Run("a push whose digest is unknown: the key is absent", func(t *testing.T) { + devApp, report, _ := publish(t, fwdDockerStream()) + _, found := report["pushed_digests"] + assert.False(t, found) + assert.Nil(t, devApp.PushedDigests) + }) +} + +// A Compose release build pushes the images under the names of the Compose +// file it is handed; the platform's names do not change them. +func TestComposeReleaseBuildKeepsTheComposeNames(t *testing.T) { + am, mc, _, _, _, cfg := amHarness(t) + imgConfig(cfg) + mc.EXPECT().GetComposePublishedPorts(mock.Anything, mock.Anything).Return(map[string]uint64{}, nil).Maybe() + + payload := imgPayload(cfg, "1.0.0", "1.0.0") + payload.Stage = common.DEV + payload.Version = "3.0.0" + payload.PresentImageName = "prod_1953_myapp:3.0.0" + payload.NewImageName = "prod_1953_myapp:3.0.0" + built := "registry.test/apps/prod_" + imgOwnArch() + "_1953_myapp_1:3.0.0" + payload.DockerCompose = map[string]interface{}{"services": map[string]interface{}{ + "web": map[string]interface{}{"image": built, "build": "."}, + }} + app := &common.App{AppKey: imgAppKey, AppName: "MyApp", Stage: common.DEV} + + path, err := am.StateMachine.SetupComposeFiles(payload, app, false) + require.NoError(t, err) + assert.Equal(t, []string{built}, composePushedImages(path)) +} + +// imgWriteTgz writes an app archive with the given files. +func imgWriteTgz(t *testing.T, path string, files map[string]string) { + t.Helper() + var buf bytes.Buffer + gzw := gzip.NewWriter(&buf) + tw := tar.NewWriter(gzw) + for name, body := range files { + require.NoError(t, tw.WriteHeader(&tar.Header{Name: name, Typeflag: tar.TypeReg, Mode: 0o644, Size: int64(len(body))})) + _, err := tw.Write([]byte(body)) + require.NoError(t, err) + } + require.NoError(t, tw.Close()) + require.NoError(t, gzw.Close()) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600)) +} diff --git a/src/apps/app_manager.go b/src/apps/app_manager.go index cccd8d5..7292059 100644 --- a/src/apps/app_manager.go +++ b/src/apps/app_manager.go @@ -1356,13 +1356,7 @@ func (am *AppManager) CleanupOrphanedAppsFromDatabase(remotePayloads []common.Tr // Remove images if app.Stage == common.DEV { - imageName := common.BuildImageName(app.Stage, "amd64", app.AppKey, app.AppName) // Simplified - should get actual arch - removeImageCtx, cancel := context.WithTimeout(ctx, time.Second*30) - err = am.StateMachine.Container.RemoveImagesByName(removeImageCtx, imageName, map[string]interface{}{"force": true}) - cancel() - if err != nil { - log.Debug().Err(err).Str("image", imageName).Msg("Could not remove image (might not exist)") - } + am.removeOrphanedDevImage(app) } else { // For PROD, try to remove versioned images log.Debug().Str("app", app.AppName).Msg("Skipping image removal for PROD app (versioned images)") @@ -1391,6 +1385,65 @@ func (am *AppManager) CleanupOrphanedAppsFromDatabase(remotePayloads []common.Tr return nil } +// removeOrphanedDevImage removes the image a DEV build made for an app that +// left the device: the repository its build tags +// (TransitionPayload.RegistryImageName.Dev: the registry, the main repository +// and dev___, the architecture the agent was +// built for). Only tags of exactly that repository are removed, and none of +// an image a container uses, running or stopped. Without force: an image that +// carries another tag too (a release published from it) only loses this one. +// Best effort, logged; the app's removal goes on either way. +func (am *AppManager) removeOrphanedDevImage(app *common.App) { + ctr := am.StateMachine.Container + repository := common.BuildTransitionPayload(app.AppKey, app.AppName, 0, common.DEV, "", "", 0, 0, ctr.GetConfig()).RegistryImageName.Dev + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*30) + defer cancel() + + containers, err := ctr.ListContainers(ctx, common.Dict{"all": true}) + if err != nil { + log.Debug().Err(err).Str("image", repository).Msg("Could not list containers; leaving the development image") + return + } + inUse := make(map[string]bool, len(containers)) + for _, c := range containers { + inUse[c.ImageID] = true + } + + images, err := ctr.ListImages(ctx, map[string]interface{}{}) + if err != nil { + log.Debug().Err(err).Str("image", repository).Msg("Could not list images; leaving the development image") + return + } + for _, image := range images { + if inUse[image.ID] { + continue + } + for _, tag := range image.RepoTags { + if imageRepository(tag) != repository { + continue + } + err := ctr.RemoveImage(ctx, tag, map[string]interface{}{"force": false, "pruneChildren": true}) + if err != nil && !errdefs.IsImageNotFound(err) { + log.Debug().Err(err).Str("image", tag).Msg("Could not remove the development image") + continue + } + log.Info().Str("image", tag).Msg("Removed the development image of a removed app") + } + } +} + +// imageRepository is an image reference without its tag and digest. +func imageRepository(ref string) string { + if at := strings.Index(ref, "@"); at != -1 { + ref = ref[:at] + } + if colon := strings.LastIndex(ref, ":"); colon > strings.LastIndex(ref, "/") { + ref = ref[:colon] + } + return ref +} + func (am *AppManager) EnsureLocalRequestedStates() error { log.Debug().Msg("Ensuring local requested states") rStates, err := am.AppStore.GetRequestedStates() diff --git a/src/apps/app_manager_test.go b/src/apps/app_manager_test.go index c82f8cd..ce4293f 100644 --- a/src/apps/app_manager_test.go +++ b/src/apps/app_manager_test.go @@ -2,7 +2,9 @@ package apps import ( "errors" + "fmt" "path/filepath" + "strings" "sync" "testing" "time" @@ -11,8 +13,10 @@ import ( "reagent/common" "reagent/config" + containerpkg "reagent/container" "reagent/logging" "reagent/persistence" + "reagent/release" "reagent/store" "reagent/testutil/builders" "reagent/testutil/fakes" @@ -439,7 +443,9 @@ func TestCleanupOrphanedAppsFromDatabase(t *testing.T) { }) t.Run("removes a stale dev app with a live container and its image", func(t *testing.T) { - am, mc, _, st, _, _ := amHarness(t) + am, mc, _, st, _, cfg := amHarness(t) + cfg.ReswarmConfig.DockerRegistryURL = "registry.test/" + cfg.ReswarmConfig.DockerMainRepository = "apps/" amSeed(t, st, 8, "stale-dev", common.RUNNING, common.DEV) @@ -458,9 +464,13 @@ func TestCleanupOrphanedAppsFromDatabase(t *testing.T) { GetContainer(mock.Anything, common.BuildComposeContainerName(common.DEV, 8, "stale-dev")). Return(container.Summary{}, notFoundErr()). Once() - // DEV apps get their image removed. + // DEV apps get their image removed: the one its build tagged. + devImage := amDevImage(8, "stale-dev") + mc.EXPECT().ListContainers(mock.Anything, common.Dict{"all": true}).Return(nil, nil).Once() + mc.EXPECT().ListImages(mock.Anything, map[string]interface{}{}). + Return([]containerpkg.ImageResult{{ID: "sha256:dev", RepoTags: []string{devImage + ":latest"}}}, nil).Once() mc.EXPECT(). - RemoveImagesByName(mock.Anything, common.BuildImageName(common.DEV, "amd64", 8, "stale-dev"), map[string]interface{}{"force": true}). + RemoveImage(mock.Anything, devImage+":latest", map[string]interface{}{"force": false, "pruneChildren": true}). Return(nil). Once() @@ -472,6 +482,101 @@ func TestCleanupOrphanedAppsFromDatabase(t *testing.T) { }) } +// amDevImage is the repository a DEV build of the app tags on this agent: the +// registry, the main repository, and the architecture the agent was built +// for (registry.test/apps/dev_arm64_8_stale-dev on an arm64 agent). +func amDevImage(key uint64, name string) string { + sysInfo := release.GetSystemInfo() + return fmt.Sprintf("registry.test/apps/dev_%s%s_%d_%s", sysInfo.Arch, sysInfo.Variant, key, name) +} + +// amOrphanedDevApp seeds a DEV app the backend no longer lists, with neither +// of its containers left. +func amOrphanedDevApp(t *testing.T) (*AppManager, *mocks.Container, *store.AppStore) { + t.Helper() + am, mc, _, st, _, cfg := amHarness(t) + cfg.ReswarmConfig.DockerRegistryURL = "registry.test/" + cfg.ReswarmConfig.DockerMainRepository = "apps/" + amSeed(t, st, 8, "stale-dev", common.PRESENT, common.DEV) + mc.EXPECT().GetContainer(mock.Anything, common.BuildContainerName(common.DEV, 8, "stale-dev")). + Return(container.Summary{}, notFoundErr()).Once() + mc.EXPECT().GetContainer(mock.Anything, common.BuildComposeContainerName(common.DEV, 8, "stale-dev")). + Return(container.Summary{}, notFoundErr()).Once() + return am, mc, st +} + +// The cleanup of a DEV app that left the device removes exactly the image its +// build tagged: before, it looked for dev_amd64__ without the +// registry, which no image is called, on any architecture. +func TestCleanupRemovesTheOrphanedDevImage(t *testing.T) { + devImage := amDevImage(8, "stale-dev") + // another agent build: an architecture that is not this one's + sysInfo := release.GetSystemInfo() + otherArch := "armv6" + if sysInfo.Arch+sysInfo.Variant == otherArch { + otherArch = "amd64" + } + others := []string{ + strings.Replace(devImage, "_8_", "_18_", 1), // another app's key + devImage + "-two", // another app's name + strings.Replace(devImage, "/dev_", "/prod_", 1) + ":1.0.0", // the app's release + "registry.test/apps/dev_" + otherArch + "_8_stale-dev:latest", // another agent build + "dev_amd64_8_stale-dev:latest", // the name the old cleanup used + "registry.other/apps/" + devImage[len("registry.test/apps/"):], // another registry + } + + t.Run("removes only its tags", func(t *testing.T) { + am, mc, st := amOrphanedDevApp(t) + mc.EXPECT().ListContainers(mock.Anything, common.Dict{"all": true}). + Return([]containerpkg.ContainerResult{{ImageID: "sha256:other"}}, nil).Once() + images := []containerpkg.ImageResult{ + {ID: "sha256:dev", RepoTags: []string{devImage + ":latest", devImage + ":old"}}, + {ID: "sha256:other", RepoTags: []string{devImage + ":in-use"}}, + } + for i, ref := range others { + images = append(images, containerpkg.ImageResult{ID: fmt.Sprintf("sha256:%d", i), RepoTags: []string{amTagged(ref)}}) + } + mc.EXPECT().ListImages(mock.Anything, map[string]interface{}{}).Return(images, nil).Once() + for _, tag := range []string{devImage + ":latest", devImage + ":old"} { + mc.EXPECT().RemoveImage(mock.Anything, tag, map[string]interface{}{"force": false, "pruneChildren": true}).Return(nil).Once() + } + + require.NoError(t, am.CleanupOrphanedAppsFromDatabase(nil)) + + _, reqErr := st.GetRequestedState(8, common.DEV) + assert.Error(t, reqErr) + }) + + t.Run("leaves every image when the containers cannot be listed", func(t *testing.T) { + am, mc, st := amOrphanedDevApp(t) + mc.EXPECT().ListContainers(mock.Anything, common.Dict{"all": true}).Return(nil, errors.New("daemon gone")).Once() + + require.NoError(t, am.CleanupOrphanedAppsFromDatabase(nil)) + + _, reqErr := st.GetRequestedState(8, common.DEV) + assert.Error(t, reqErr, "the app is removed all the same") + }) + + t.Run("a refused removal is logged", func(t *testing.T) { + am, mc, _ := amOrphanedDevApp(t) + mc.EXPECT().ListContainers(mock.Anything, common.Dict{"all": true}).Return(nil, nil).Once() + mc.EXPECT().ListImages(mock.Anything, map[string]interface{}{}). + Return([]containerpkg.ImageResult{{ID: "sha256:dev", RepoTags: []string{devImage + ":latest"}}}, nil).Once() + mc.EXPECT().RemoveImage(mock.Anything, devImage+":latest", map[string]interface{}{"force": false, "pruneChildren": true}). + Return(errors.New("conflict: unable to remove repository reference")).Once() + + require.NoError(t, am.CleanupOrphanedAppsFromDatabase(nil)) + }) +} + +// amTagged is ref with :latest where it names no tag. +func amTagged(ref string) string { + if strings.LastIndex(ref, ":") > strings.LastIndex(ref, "/") { + return ref + } + return ref + ":latest" +} + // ============================================================================= // IsInvalidOfflineTransition // ============================================================================= diff --git a/src/apps/build_app.go b/src/apps/build_app.go index 89061f2..579af3a 100644 --- a/src/apps/build_app.go +++ b/src/apps/build_app.go @@ -457,8 +457,7 @@ func (sm *StateMachine) runDevBuild(payload common.TransitionPayload, app *commo appFilesTar := buildsDir + "/" + fileName dockerFileName := "Dockerfile" - buildArch := release.GetBuildArch() - archSpecificDockerfile := fmt.Sprintf("Dockerfile.%s", buildArch) + archSpecificDockerfile := fmt.Sprintf("Dockerfile.%s", dockerfileArch(payload)) _, err = filesystem.ReadFileInTgz(appFilesTar, archSpecificDockerfile) if err == nil { dockerFileName = archSpecificDockerfile @@ -519,3 +518,21 @@ func (sm *StateMachine) runDevBuild(payload common.TransitionPayload, app *commo return sm.setState(app, common.BUILT) } + +// dockerfileArch is the architecture whose Dockerfile. a build uses: +// the one the build is for, the device's architecture as the platform stores +// it (TransitionPayload.Architecture, the sync answer's architecture), where it +// is one apps are built for; else, from an older backend or for a value such +// as ARM, the one the agent was built for, as before. A release build is +// pushed and registered for the platform's value, and the registry refuses an +// image of another platform, so the engine that builds it does not decide: +// an armv7 agent on a 64-bit engine still builds Dockerfile.armv7 while the +// platform says armv7. An app without that file builds its Dockerfile. +func dockerfileArch(payload common.TransitionPayload) string { + switch payload.Architecture { + case "amd64", "arm64", "armv7", "armv6", "armv5": + return payload.Architecture + default: + return release.GetBuildArch() + } +} diff --git a/src/apps/compose_missing_images_test.go b/src/apps/compose_missing_images_test.go new file mode 100644 index 0000000..ace4d69 --- /dev/null +++ b/src/apps/compose_missing_images_test.go @@ -0,0 +1,55 @@ +package apps + +import ( + "testing" + + "reagent/config" + containerpkg "reagent/container" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// An appliance's own agent reads its registry on localhost, while the release +// names the appliance's domain: the app's images are on the device under the +// localhost name only (resolveComposeStoreImages). Before, the check looked +// for them only as the release names them, and judged them missing on every +// check: a PRESENT app without containers was reported UNINSTALLED and pulled +// again, a FAILED one never settled offline. +func TestComposeImagesAreFoundUnderTheDevicesRegistry(t *testing.T) { + const digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + compose := map[string]interface{}{"services": map[string]interface{}{ + "web": map[string]interface{}{ + "image": "registry.appliance.example/apps/prod_1953_myapp_1:1.0.0", + "x-image-digest": digest, + }, + "worker": map[string]interface{}{ + "image": "registry.appliance.example/apps/prod_1953_myapp_2:1.0.0", + }, + }} + images := []containerpkg.ImageResult{ + {ID: "a", RepoTags: []string{"localhost:15001/apps/prod_1953_myapp_1:1.0.0"}, RepoDigests: []string{"localhost:15001/apps/prod_1953_myapp_1@" + digest}}, + {ID: "b", RepoTags: []string{"localhost:15001/apps/prod_1953_myapp_2:1.0.0"}}, + } + colocated := &config.ReswarmConfig{DockerRegistryURL: "localhost:15001/", DockerMainRepository: "apps/"} + + missing, err := composeServicesWithMissingImages(colocated, 1953, "MyApp", compose, images) + require.NoError(t, err) + assert.Empty(t, missing) + + // negative control: as the release names them only + missing, err = composeServicesWithMissingImages(nil, 1953, "MyApp", compose, images) + require.NoError(t, err) + assert.Equal(t, []string{"web", "worker"}, missing) + + // the pin still decides: the same name with another digest is missing + other := []containerpkg.ImageResult{{ID: "a", RepoTags: images[0].RepoTags, RepoDigests: []string{"localhost:15001/apps/prod_1953_myapp_1@sha256:" + "1111111111111111111111111111111111111111111111111111111111111111"}}, images[1]} + missing, err = composeServicesWithMissingImages(colocated, 1953, "MyApp", compose, other) + require.NoError(t, err) + assert.Equal(t, []string{"web"}, missing) + + // another app's image is not moved onto the device's registry + missing, err = composeServicesWithMissingImages(colocated, 1954, "Other", compose, images) + require.NoError(t, err) + assert.Equal(t, []string{"web", "worker"}, missing) +} diff --git a/src/apps/dockerfile_arch_test.go b/src/apps/dockerfile_arch_test.go new file mode 100644 index 0000000..a4286e8 --- /dev/null +++ b/src/apps/dockerfile_arch_test.go @@ -0,0 +1,82 @@ +package apps + +import ( + "context" + "path/filepath" + "testing" + + dockerbuild "github.com/docker/docker/api/types/build" + + "reagent/common" + "reagent/release" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +func TestDockerfileArch(t *testing.T) { + for architecture, want := range map[string]string{ + "amd64": "amd64", + "arm64": "arm64", + "armv7": "armv7", + "armv6": "armv6", + "armv5": "armv5", + // from an older backend, or a value apps are not built for: the + // agent's own, as before + "": release.GetBuildArch(), + "ARM": release.GetBuildArch(), + "arm": release.GetBuildArch(), + "ARM64": release.GetBuildArch(), + "riscv": release.GetBuildArch(), + } { + assert.Equal(t, want, dockerfileArch(common.TransitionPayload{Architecture: architecture}), architecture) + } +} + +// The build uses the Dockerfile of the architecture the platform registers it +// for, whatever the agent's own architecture and the engine's. +func TestBuildUsesTheDockerfileOfThePlatformsArchitecture(t *testing.T) { + build := func(t *testing.T, architecture string, files map[string]string) string { + t.Helper() + sm, mc, st, _, cfg := wiredRunBuildSM(t) + + app := seedApp(t, st, "archapp", common.REMOVED, common.DEV) + payload := execPayload("archapp", common.BUILT, common.DEV) + payload.Architecture = architecture + tarPath := filepath.Join(cfg.CommandLineArguments.AppsBuildDir, payload.AppName+"."+cfg.CommandLineArguments.CompressedBuildExtension) + imgWriteTgz(t, tarPath, files) + + var used string + mc.EXPECT().Build(mock.Anything, tarPath, mock.Anything). + Run(func(_ context.Context, _ string, options dockerbuild.ImageBuildOptions) { used = options.Dockerfile }). + Return(fwdDockerStream(), nil).Once() + fwdAllowLogs(mc) + + require.NoError(t, sm.buildApp(payload, app)) + return used + } + all := map[string]string{ + "Dockerfile": "FROM scratch\n", + "Dockerfile.arm64": "FROM scratch\n", + "Dockerfile.armv7": "FROM scratch\n", + "Dockerfile.armv6": "FROM scratch\n", + "Dockerfile.amd64": "FROM scratch\n", + } + + // whatever this agent was built for (the test host): the platform's value decides + assert.Equal(t, "Dockerfile.armv7", build(t, "armv7", all)) + assert.Equal(t, "Dockerfile.armv6", build(t, "armv6", all)) + assert.Equal(t, "Dockerfile.amd64", build(t, "amd64", all)) + assert.Equal(t, "Dockerfile.arm64", build(t, "arm64", all)) + + // an app without the named file builds its Dockerfile, as before + assert.Equal(t, "Dockerfile", build(t, "armv6", map[string]string{"Dockerfile": "FROM scratch\n", "Dockerfile.arm64": "FROM scratch\n"})) + + // no value (older backend): the agent's own architecture, as before + own := "Dockerfile." + release.GetBuildArch() + if _, found := all[own]; !found { + own = "Dockerfile" + } + assert.Equal(t, own, build(t, "", all)) +} diff --git a/src/apps/fail_present.go b/src/apps/fail_present.go index aa853a7..375f9fd 100644 --- a/src/apps/fail_present.go +++ b/src/apps/fail_present.go @@ -27,24 +27,20 @@ func (sm *StateMachine) recoverFailToPresentHandler(payload common.TransitionPay return sm.buildApp(payload, app) } - // Check if the image exists - var fullImageName string - if payload.Stage == common.DEV { - fullImageName = payload.RegistryImageName.Dev - } else if payload.Stage == common.PROD { - fullImageName = payload.RegistryImageName.Prod - } - - getImagesContext, cancel := context.WithTimeout(context.Background(), time.Second*30) - defer cancel() - - images, err := sm.Container.GetImages(getImagesContext, fullImageName) - if err != nil { - return err - } + // Check if the image exists: any tag under the agent's own name or a name + // the platform gave (prodImageRepositories). + withInstalled := sm.withInstalledImage(payload) + for _, fullImageName := range prodImageRepositories(sm.reswarmConfigFor(withInstalled), withInstalled) { + getImagesContext, cancel := context.WithTimeout(context.Background(), time.Second*30) + images, err := sm.Container.GetImages(getImagesContext, fullImageName) + cancel() + if err != nil { + return err + } - if len(images) != 0 { - return sm.setState(app, common.PRESENT) + if len(images) != 0 { + return sm.setState(app, common.PRESENT) + } } return sm.pullApp(payload, app) @@ -64,7 +60,7 @@ func (sm *StateMachine) recoverFailedComposeToPresent(payload common.TransitionP cancel() if err == nil { - missing, missingErr := composeServicesWithMissingImages(payload.DockerCompose, images) + missing, missingErr := composeServicesWithMissingImages(sm.reswarmConfig(), payload.AppKey, payload.AppName, payload.DockerCompose, images) if missingErr == nil && len(missing) == 0 { dockerComposePath, setupErr := sm.SetupComposeFiles(payload, app, false) if setupErr != nil { diff --git a/src/apps/image_pins_test.go b/src/apps/image_pins_test.go index 2ff5016..5b9d3ee 100644 --- a/src/apps/image_pins_test.go +++ b/src/apps/image_pins_test.go @@ -110,7 +110,7 @@ func TestComposeServicesWithMissingImagesHonoursPins(t *testing.T) { t.Run("present: an image holds the pinned digest", func(t *testing.T) { local := []containerpkg.ImageResult{{RepoDigests: []string{"registry.test/apps/x_1@" + pinDigestA}}} - missing, err := composeServicesWithMissingImages(compose, local) + missing, err := composeServicesWithMissingImages(nil, 0, "", compose, local) require.NoError(t, err) assert.Empty(t, missing) }) @@ -120,14 +120,14 @@ func TestComposeServicesWithMissingImagesHonoursPins(t *testing.T) { RepoTags: []string{"registry.test/apps/x_1:1.0.0"}, RepoDigests: []string{"registry.test/apps/x_1@" + pinDigestB}, }} - missing, err := composeServicesWithMissingImages(compose, local) + missing, err := composeServicesWithMissingImages(nil, 0, "", compose, local) require.NoError(t, err) assert.Equal(t, []string{"app"}, missing) }) t.Run("missing: the digest belongs to another repository", func(t *testing.T) { local := []containerpkg.ImageResult{{RepoDigests: []string{"registry.test/apps/x_2@" + pinDigestA}}} - missing, err := composeServicesWithMissingImages(compose, local) + missing, err := composeServicesWithMissingImages(nil, 0, "", compose, local) require.NoError(t, err) assert.Equal(t, []string{"app"}, missing) }) diff --git a/src/apps/publish_app.go b/src/apps/publish_app.go index c401b75..f70c810 100644 --- a/src/apps/publish_app.go +++ b/src/apps/publish_app.go @@ -15,6 +15,9 @@ func (sm *StateMachine) publishApp(payload common.TransitionPayload, app *common return sm.publishComposeApp(payload, app) } + // nothing of an earlier build is reported for this one + setPushedDigests(app, nil) + err := sm.LogManager.Write(payload.PublishContainerName, fmt.Sprintf("Initializing publish process for %s...", app.AppName)) if err != nil { return err @@ -30,6 +33,10 @@ func (sm *StateMachine) publishApp(payload common.TransitionPayload, app *common return err } + // Pushed under the agent's own name, prod___:: the backend computes exactly this from the + // device's agent_architecture. The platform's names (PresentImageName, + // NewImageName) are for pulling and never used here. prodImage := fmt.Sprintf("%s:%s", payload.RegistryImageName.Prod, payload.Version) tagContext, cancel := context.WithTimeout(context.Background(), time.Second*30) defer cancel() @@ -65,6 +72,7 @@ func (sm *StateMachine) publishApp(payload common.TransitionPayload, app *common if err != nil { return err } + reader, pushed := capturePushDigest(reader) streamErr := sm.LogManager.StreamBlocking(payload.PublishContainerName, common.PUSH, reader) if streamErr != nil { @@ -81,6 +89,10 @@ func (sm *StateMachine) publishApp(payload common.TransitionPayload, app *common return streamErr } + if digest, ok := pushedDigestOf(prodImage, pushed); ok { + setPushedDigests(app, map[string]string{prodImage: digest}) + } + err = sm.setState(app, common.PUBLISHED) if err != nil { return err @@ -95,6 +107,9 @@ func (sm *StateMachine) publishApp(payload common.TransitionPayload, app *common } func (sm *StateMachine) publishComposeApp(payload common.TransitionPayload, app *common.App) error { + // nothing of an earlier build is reported for this one + setPushedDigests(app, nil) + err := sm.LogManager.Write(payload.PublishContainerName, fmt.Sprintf("Initializing publish process for %s...", app.AppName)) if err != nil { return err @@ -131,7 +146,7 @@ func (sm *StateMachine) publishComposeApp(payload common.TransitionPayload, app return err } - err = sm.rehostSourceImages(payload) + pushedDigests, err := sm.rehostSourceImages(payload) if err != nil { if errdefs.IsDockerStreamCanceled(err) { // like a canceled push below: no failed state, handled upstream @@ -159,6 +174,15 @@ func (sm *StateMachine) publishComposeApp(payload common.TransitionPayload, app return err } + // The images compose pushed, under the names of the compose file (as it + // pushed them), with the digests their repositories now carry. + for _, ref := range composePushedImages(dockerComposePath) { + if digest, ok := sm.repoDigestOf(ref); ok { + pushedDigests[ref] = digest + } + } + setPushedDigests(app, pushedDigests) + err = sm.setState(app, common.PUBLISHED) if err != nil { return err @@ -181,10 +205,13 @@ func (sm *StateMachine) publishComposeApp(payload common.TransitionPayload, app // the store name and pushed explicitly. After this, installs never touch the // external registry or need the app's credentials. Releases created before // the rewrite carry no x-source-image fields, making this a no-op for them. -func (sm *StateMachine) rehostSourceImages(payload common.TransitionPayload) error { +// It answers the digest each push answered, where its stream named one +// (pushed_digests of the PUBLISHED report). +func (sm *StateMachine) rehostSourceImages(payload common.TransitionPayload) (map[string]string, error) { + pushedDigests := map[string]string{} services, ok := (payload.DockerCompose["services"]).(map[string]interface{}) if !ok { - return errors.New("failed to infer services") + return pushedDigests, errors.New("failed to infer services") } config := sm.Container.GetConfig() @@ -192,7 +219,7 @@ func (sm *StateMachine) rehostSourceImages(payload common.TransitionPayload) err for serviceName, serviceInterface := range services { service, ok := (serviceInterface).(map[string]interface{}) if !ok { - return errors.New("failed to infer service") + return pushedDigests, errors.New("failed to infer service") } sourceImage, _ := service["x-source-image"].(string) @@ -202,12 +229,12 @@ func (sm *StateMachine) rehostSourceImages(payload common.TransitionPayload) err targetImage, _ := service["image"].(string) if targetImage == "" { - return fmt.Errorf("service %s declares x-source-image but no image", serviceName) + return pushedDigests, fmt.Errorf("service %s declares x-source-image but no image", serviceName) } err := sm.LogManager.Write(payload.PublishContainerName, fmt.Sprintf("Re-hosting image %s of service %s as %s...", sourceImage, serviceName, targetImage)) if err != nil { - return err + return pushedDigests, err } sourceHost := registryHostOfImage(sourceImage) @@ -215,7 +242,7 @@ func (sm *StateMachine) rehostSourceImages(payload common.TransitionPayload) err if !credentialFound { err = sm.LogManager.Write(payload.PublishContainerName, registryCredentialMissMessage(sourceHost)) if err != nil { - return err + return pushedDigests, err } } @@ -228,23 +255,23 @@ func (sm *StateMachine) rehostSourceImages(payload common.TransitionPayload) err if err != nil { if isRegistryAuthError(err) { if !credentialFound { - return fmt.Errorf("registry %s rejected the pull of %s: %w — the registry requires credentials and none are stored for it; add them for host %q under App Settings → Docker Registry Credentials, then publish again", sourceHost, sourceImage, err, common.NormalizeRegistryHost(sourceHost)) + return pushedDigests, fmt.Errorf("registry %s rejected the pull of %s: %w — the registry requires credentials and none are stored for it; add them for host %q under App Settings → Docker Registry Credentials, then publish again", sourceHost, sourceImage, err, common.NormalizeRegistryHost(sourceHost)) } - return fmt.Errorf("registry %s rejected the stored credentials while pulling %s: %w — check the username/password under App Settings → Docker Registry Credentials, then publish again", sourceHost, sourceImage, err) + return pushedDigests, fmt.Errorf("registry %s rejected the stored credentials while pulling %s: %w — check the username/password under App Settings → Docker Registry Credentials, then publish again", sourceHost, sourceImage, err) } - return err + return pushedDigests, err } streamErr := sm.LogManager.StreamBlocking(payload.PublishContainerName, common.PULL, pullReader) if streamErr != nil { - return streamErr + return pushedDigests, streamErr } tagContext, cancelTag := context.WithTimeout(context.Background(), time.Second*30) err = sm.Container.Tag(tagContext, sourceImage, targetImage) cancelTag() if err != nil { - return err + return pushedDigests, err } pushOptions := container.PushOptions{ @@ -257,14 +284,18 @@ func (sm *StateMachine) rehostSourceImages(payload common.TransitionPayload) err pushReader, err := sm.Container.Push(context.Background(), targetImage, pushOptions) if err != nil { - return err + return pushedDigests, err } + pushReader, pushed := capturePushDigest(pushReader) streamErr = sm.LogManager.StreamBlocking(payload.PublishContainerName, common.PUSH, pushReader) if streamErr != nil { - return streamErr + return pushedDigests, streamErr + } + if digest, ok := pushedDigestOf(targetImage, pushed); ok { + pushedDigests[targetImage] = digest } } - return nil + return pushedDigests, nil } diff --git a/src/apps/pull_app.go b/src/apps/pull_app.go index 1926df1..3f0e05d 100644 --- a/src/apps/pull_app.go +++ b/src/apps/pull_app.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "reagent/common" - "reagent/container" "reagent/errdefs" ) @@ -153,25 +152,17 @@ func (sm *StateMachine) pullApp(payload common.TransitionPayload, app *common.Ap return err } - fullImageNameWithVersion := fmt.Sprintf("%s:%s", payload.RegistryImageName.Prod, payload.NewestVersion) - pullOptions := container.PullOptions{ - AuthConfig: sm.authConfigForImage(payload, fullImageNameWithVersion, payload.ContainerName.Prod), - PullID: common.BuildDockerPullID(payload.AppKey, payload.AppName), - } - - reader, err := sm.Container.Pull(context.Background(), fullImageNameWithVersion, pullOptions) - if err != nil { - errorMessage := fmt.Sprintf("Error occured while trying to pull the image: %s", err.Error()) - _ = sm.LogManager.Write(payload.ContainerName.Prod, errorMessage) - return err - } - - err = sm.setState(app, common.DOWNLOADING) - if err != nil { - return err - } - - streamErr := sm.LogManager.StreamBlocking(payload.ContainerName.Prod, common.PULL, reader) + // Pulled by tag, with no platform named: where the name is an image + // index, Docker chooses the image of its own platform. DOWNLOADING once + // the first pull has started. + downloading := false + pulled, streamErr := sm.pullProdImage(payload, payload.NewestVersion, func() error { + if downloading { + return nil + } + downloading = true + return sm.setState(app, common.DOWNLOADING) + }) if streamErr != nil { if errdefs.IsDockerStreamCanceled(streamErr) { pullMessage := "The app download was canceled" @@ -185,6 +176,7 @@ func (sm *StateMachine) pullApp(payload common.TransitionPayload, app *common.Ap return streamErr } + sm.rememberInstalledImage(payload, payload.NewestVersion, pulled) pullMessage := fmt.Sprintf("Succesfully installed the app: %s (Version: %s)", payload.AppName, payload.NewestVersion) writeErr := sm.LogManager.Write(payload.ContainerName.Prod, pullMessage) diff --git a/src/apps/pushed_digests.go b/src/apps/pushed_digests.go new file mode 100644 index 0000000..6b0de3b --- /dev/null +++ b/src/apps/pushed_digests.go @@ -0,0 +1,206 @@ +package apps + +import ( + "bytes" + "context" + "encoding/json" + "io" + "os" + "reagent/common" + "regexp" + "strings" + "sync" + "time" + + "github.com/rs/zerolog/log" +) + +// What a release build pushed: pushed_digests of the PUBLISHED report +// (store.UpdateRemoteAppState), {"": +// "sha256:"}. The backend compares it with what the tag holds +// when it publishes the build, so that another device's later push of the +// same tag is not published under this build. A digest the agent cannot tell +// for certain is left out, never guessed. + +// pushDigestCapture reads, as a push's progress stream passes through it, the +// digest the registry answered for the pushed manifest, once per pushed tag: +// the Engine API's aux message {"aux":{"Tag":"","Digest":"sha256:…",…}}, +// and the status line ": digest: sha256:… size: ". The classic image +// store sends both; the containerd image store (Docker 29) sends only the +// status line. Either is the digest of the manifest this push wrote under the +// tag, as the registry accepted it. +type pushDigestCapture struct { + mu sync.Mutex + pending []byte + digests map[string]map[string]bool // tag -> digests seen +} + +func (c *pushDigestCapture) Write(p []byte) (int, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.pending = append(c.pending, p...) + for { + newline := bytes.IndexByte(c.pending, '\n') + if newline == -1 { + break + } + c.readLine(c.pending[:newline]) + c.pending = c.pending[newline+1:] + } + return len(p), nil +} + +func (c *pushDigestCapture) readLine(line []byte) { + var message struct { + Status string `json:"status"` + Aux *struct { + Tag string `json:"Tag"` + Digest string `json:"Digest"` + } `json:"aux"` + } + if json.Unmarshal(bytes.TrimSpace(line), &message) != nil { + return + } + if message.Aux != nil { + c.add(message.Aux.Tag, message.Aux.Digest) + } + if match := pushStatusDigestPattern.FindStringSubmatch(strings.TrimSpace(message.Status)); match != nil { + c.add(match[1], match[2]) + } +} + +// pushStatusDigestPattern is the status line a push ends a tag with. +var pushStatusDigestPattern = regexp.MustCompile(`^(\S+): digest: (\S+) size: [0-9]+$`) + +func (c *pushDigestCapture) add(tag, digest string) { + if c.digests == nil { + c.digests = map[string]map[string]bool{} + } + if c.digests[tag] == nil { + c.digests[tag] = map[string]bool{} + } + c.digests[tag][digest] = true +} + +// digest is the digest the push answered for tag: exactly one, a sha256 +// digest; ok is false otherwise. +func (c *pushDigestCapture) digest(tag string) (string, bool) { + c.mu.Lock() + defer c.mu.Unlock() + if len(c.pending) > 0 { + // a last line without a newline + c.readLine(c.pending) + c.pending = nil + } + return onlyDigest(c.digests[tag]) +} + +// onlyDigest is the one sha256 digest of a set, ok false for none or several. +func onlyDigest(digests map[string]bool) (string, bool) { + if len(digests) != 1 { + return "", false + } + for digest := range digests { + if imageDigestPattern.MatchString(digest) { + return digest, true + } + } + return "", false +} + +// capturingReadCloser passes a push stream on and lets capture read it. +type capturingReadCloser struct { + io.Reader + closer io.Closer +} + +func (r capturingReadCloser) Close() error { return r.closer.Close() } + +// capturePushDigest wraps a push's progress stream so that the pushed +// digest can be read from capture once the stream was read to its end. +func capturePushDigest(reader io.ReadCloser) (io.ReadCloser, *pushDigestCapture) { + capture := &pushDigestCapture{} + if reader == nil { + return nil, capture + } + return capturingReadCloser{Reader: io.TeeReader(reader, capture), closer: reader}, capture +} + +// pushedDigestOf is the digest the push of ref (repository:tag) answered, +// read from its stream (capture). ok is false where it cannot be told. +func pushedDigestOf(ref string, capture *pushDigestCapture) (string, bool) { + if capture == nil { + return "", false + } + _, tag := splitImageTag(ref) + if tag == "" { + return "", false + } + return capture.digest(tag) +} + +// repoDigestOf is the digest under which the local image ref names is in its +// repository, after `docker compose push` pushed it (the CLI's output gives no +// dependable digest): the image's RepoDigests entry for exactly that +// repository. A push records the digest the registry answered there (both +// image stores). Only one entry counts: where the image also carries the +// digest of an earlier push or pull of that repository, which of them this +// push wrote cannot be told, and ok is false. +func (sm *StateMachine) repoDigestOf(ref string) (string, bool) { + repository, tag := splitImageTag(ref) + if tag == "" || strings.Contains(ref, "@") { + return "", false + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + image, err := sm.Container.GetImage(ctx, repository, tag) + if err != nil { + log.Debug().Err(err).Str("image", ref).Msg("could not read the pushed image's digest") + return "", false + } + digests := map[string]bool{} + for _, repoDigest := range image.RepoDigests { + if digest, found := strings.CutPrefix(repoDigest, repository+"@"); found { + digests[digest] = true + } + } + return onlyDigest(digests) +} + +// composePushedImages are the images `docker compose push` pushes from the +// compose file at path: every service that is built and names an image, as +// the file names it. +func composePushedImages(path string) []string { + content, err := os.ReadFile(path) //nolint:gosec // G304: the agent's own compose file, written by SetupComposeFiles + if err != nil { + return nil + } + var compose map[string]interface{} + if json.Unmarshal(content, &compose) != nil { + return nil + } + services, _ := compose["services"].(map[string]interface{}) + refs := []string{} + for _, serviceInterface := range services { + service, ok := serviceInterface.(map[string]interface{}) + if !ok || service["build"] == nil { + continue + } + if ref, _ := service["image"].(string); ref != "" { + refs = append(refs, ref) + } + } + return refs +} + +// setPushedDigests keeps what a release build pushed for its PUBLISHED +// report; nil or empty: nothing is known. +func setPushedDigests(app *common.App, digests map[string]string) { + app.StateLock.Lock() + defer app.StateLock.Unlock() + if len(digests) == 0 { + app.PushedDigests = nil + return + } + app.PushedDigests = digests +} diff --git a/src/apps/pushed_digests_test.go b/src/apps/pushed_digests_test.go new file mode 100644 index 0000000..2218884 --- /dev/null +++ b/src/apps/pushed_digests_test.go @@ -0,0 +1,146 @@ +package apps + +import ( + "context" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "reagent/common" + containerpkg "reagent/container" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +const ( + pdDigestA = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + pdDigestB = "sha256:fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210" +) + +func TestPushDigestCapture(t *testing.T) { + read := func(t *testing.T, stream string) *pushDigestCapture { + t.Helper() + reader, capture := capturePushDigest(io.NopCloser(strings.NewReader(stream))) + passed, err := io.ReadAll(reader) + require.NoError(t, err) + assert.Equal(t, stream, string(passed), "the stream passes on unchanged") + require.NoError(t, reader.Close()) + return capture + } + + t.Run("the aux message of the tag", func(t *testing.T) { + capture := read(t, `{"status":"Pushed"}`+"\n"+`{"aux":{"Tag":"1.0.0","Digest":"`+pdDigestA+`","Size":1}}`) + digest, ok := pushedDigestOf("registry.test/apps/x:1.0.0", capture) + assert.True(t, ok) + assert.Equal(t, pdDigestA, digest) + _, ok = pushedDigestOf("registry.test/apps/x:2.0.0", capture) + assert.False(t, ok, "another tag") + }) + + t.Run("the status line alone (containerd image store)", func(t *testing.T) { + capture := read(t, `{"status":"Pushed","id":"abc"}`+"\n"+`{"status":"1.0.0: digest: `+pdDigestA+` size: 856"}`+"\n") + digest, ok := pushedDigestOf("registry.test/apps/x:1.0.0", capture) + assert.True(t, ok) + assert.Equal(t, pdDigestA, digest) + _, ok = pushedDigestOf("registry.test/apps/x:2.0.0", capture) + assert.False(t, ok, "another tag") + }) + + t.Run("the status line and the aux message agree", func(t *testing.T) { + capture := read(t, `{"status":"1.0.0: digest: `+pdDigestA+` size: 856"}`+"\n"+`{"aux":{"Tag":"1.0.0","Digest":"`+pdDigestA+`","Size":856}}`+"\n") + digest, ok := pushedDigestOf("registry.test/apps/x:1.0.0", capture) + assert.True(t, ok) + assert.Equal(t, pdDigestA, digest) + }) + + t.Run("none, two different, or not a digest: unknown", func(t *testing.T) { + for _, stream := range []string{ + `{"status":"Pushed"}` + "\n", + `{"aux":{"Tag":"1.0.0","Digest":"` + pdDigestA + `"}}` + "\n" + `{"aux":{"Tag":"1.0.0","Digest":"` + pdDigestB + `"}}` + "\n", + `{"aux":{"Tag":"1.0.0","Digest":"md5:abc"}}` + "\n", + `{"aux":{"Tag":"1.0.0","Digest":""}}` + "\n", + `not json` + "\n", + `{"status":"1.0.0: digest: ` + pdDigestA + ` size: 1"}` + "\n" + `{"aux":{"Tag":"1.0.0","Digest":"` + pdDigestB + `"}}` + "\n", + `{"status":"1.0.0: digest: sha256:abc size: 1"}` + "\n", + `{"status":"1.0.0: digest: ` + pdDigestA + `"}` + "\n", + } { + _, ok := pushedDigestOf("registry.test/apps/x:1.0.0", read(t, stream)) + assert.False(t, ok, stream) + } + }) +} + +// After `docker compose push` the digest is read from the image's +// RepoDigests entry of exactly that repository; where it carries two, which +// one this push wrote cannot be told. +func TestRepoDigestOf(t *testing.T) { + sm, mc, _, _, _ := wiredRunBuildSM(t) + ref := "registry.test/apps/prod_arm64_12_demo_1:1.0.0" + + mc.EXPECT().GetImage(mock.Anything, "registry.test/apps/prod_arm64_12_demo_1", "1.0.0"). + Return(containerpkg.ImageResult{RepoDigests: []string{ + "registry.test/apps/prod_arm64_12_demo_1@" + pdDigestA, + "registry.test/apps/prod_arm64_12_demo_10@" + pdDigestB, // another repository + }}, nil).Once() + digest, ok := sm.repoDigestOf(ref) + assert.True(t, ok) + assert.Equal(t, pdDigestA, digest) + + mc.EXPECT().GetImage(mock.Anything, "registry.test/apps/prod_arm64_12_demo_1", "1.0.0"). + Return(containerpkg.ImageResult{RepoDigests: []string{ + "registry.test/apps/prod_arm64_12_demo_1@" + pdDigestA, + "registry.test/apps/prod_arm64_12_demo_1@" + pdDigestB, + }}, nil).Once() + _, ok = sm.repoDigestOf(ref) + assert.False(t, ok, "two digests of the repository") + + mc.EXPECT().GetImage(mock.Anything, "registry.test/apps/prod_arm64_12_demo_1", "1.0.0"). + Return(containerpkg.ImageResult{}, imageNotFound()).Once() + _, ok = sm.repoDigestOf(ref) + assert.False(t, ok, "no image") +} + +func TestComposePushedImages(t *testing.T) { + path := filepath.Join(t.TempDir(), DockerFileName) + require.NoError(t, os.WriteFile(path, []byte(`{"services":{ + "web":{"build":".","image":"registry.test/apps/prod_arm64_12_demo_1:1.0.0"}, + "db":{"image":"registry.test/apps/prod_arm64_12_demo_2:1.0.0","x-source-image":"postgres:16"}, + "tool":{"build":"."} + }}`), 0o600)) + assert.Equal(t, []string{"registry.test/apps/prod_arm64_12_demo_1:1.0.0"}, composePushedImages(path)) + assert.Empty(t, composePushedImages(filepath.Join(t.TempDir(), "missing.json"))) +} + +// The image-only services of a Compose release build are pushed one by one; +// each push's digest comes from its stream. +func TestRehostSourceImagesAnswersThePushedDigests(t *testing.T) { + sm, mc, _, _, _ := wiredRunBuildSM(t) + payload := execPayload("demo", common.PUBLISHED, common.DEV) + known := "registry.test/apps/prod_arm64_1_demo_1:1.0.0" + unknown := "registry.test/apps/prod_arm64_1_demo_2:1.0.0" + payload.DockerCompose = map[string]interface{}{"services": map[string]interface{}{ + "db": map[string]interface{}{"image": known, "x-source-image": "postgres:16"}, + "cache": map[string]interface{}{"image": unknown, "x-source-image": "redis:7"}, + "web": map[string]interface{}{"image": "registry.test/apps/prod_arm64_1_demo_3:1.0.0", "build": "."}, + }} + + mc.EXPECT().Pull(mock.Anything, mock.Anything, mock.Anything).RunAndReturn( + func(_ context.Context, _ string, _ containerpkg.PullOptions) (io.ReadCloser, error) { + return fwdDockerStream(), nil + }).Twice() + mc.EXPECT().Tag(mock.Anything, "postgres:16", known).Return(nil).Once() + mc.EXPECT().Tag(mock.Anything, "redis:7", unknown).Return(nil).Once() + mc.EXPECT().Push(mock.Anything, known, mock.Anything).Return(fwdDockerStream( + `{"status":"1.0.0: digest: `+pdDigestA+` size: 1"}`, + `{"aux":{"Tag":"1.0.0","Digest":"`+pdDigestA+`","Size":1}}`), nil).Once() + mc.EXPECT().Push(mock.Anything, unknown, mock.Anything).Return(fwdDockerStream(), nil).Once() + fwdAllowLogs(mc) + + digests, err := sm.rehostSourceImages(payload) + require.NoError(t, err) + assert.Equal(t, map[string]string{known: pdDigestA}, digests) +} diff --git a/src/apps/recovery_lifecycle_test.go b/src/apps/recovery_lifecycle_test.go index f0f7e31..1b058be 100644 --- a/src/apps/recovery_lifecycle_test.go +++ b/src/apps/recovery_lifecycle_test.go @@ -480,7 +480,7 @@ func TestUpdateApp(t *testing.T) { Once() // Old image cleanup (best-effort; return is ignored by the handler). mc.EXPECT(). - RemoveImageByName(mock.Anything, payload.RegistryImageName.Prod, "1.0.0", mock.Anything). + RemoveImage(mock.Anything, payload.RegistryImageName.Prod+":1.0.0", map[string]interface{}{"force": false, "pruneChildren": true}). Return(nil). Once() diff --git a/src/apps/registry_auth.go b/src/apps/registry_auth.go index 65a8a38..cec3cc3 100644 --- a/src/apps/registry_auth.go +++ b/src/apps/registry_auth.go @@ -157,8 +157,10 @@ func composeReferencesRegistryHost(compose map[string]interface{}, host string) // isOwnStoreImageRepository reports whether a repository path names one of THIS // app's store images. app.f_create_release mints one per compose service as // -// prod____: +// prod___: // +// (the version's image index, one image per platform; releases from before it +// carry prod____, which a release build still pushes), // lowercased, for every service of a release — image-only services included, // whose authored reference is preserved beside it in x-source-image. The // "prod" is a literal there, not the stage. Matching on the app's own key and @@ -231,12 +233,7 @@ func resolveComposeStoreImages(reswarmConfig *config.ReswarmConfig, appKey uint6 continue } - _, repository := splitRegistryHost(imageRef) - if !isOwnStoreImageRepository(reswarmConfig.DockerMainRepository, appKey, appName, repository) { - continue - } - - resolvedRef := registryBase + "/" + repository + resolvedRef := resolveStoreImageRef(reswarmConfig.DockerMainRepository, registryBase, appKey, appName, imageRef) if resolvedRef == imageRef { continue } @@ -248,6 +245,18 @@ func resolveComposeStoreImages(reswarmConfig *config.ReswarmConfig, appKey uint6 return resolved } +// resolveStoreImageRef is one image reference as resolveComposeStoreImages +// resolves it: one of this app's own store images on registryBase (the +// device's registry URL without its trailing slash), any other reference as +// it is. +func resolveStoreImageRef(mainRepository string, registryBase string, appKey uint64, appName string, imageRef string) string { + _, repository := splitRegistryHost(imageRef) + if registryBase == "" || !isOwnStoreImageRepository(mainRepository, appKey, appName, repository) { + return imageRef + } + return registryBase + "/" + repository +} + // authConfigForImage picks pull credentials by the image's registry host: the // platform's own registry gets the device's store token, any other host the // app's docker_credentials entry. A miss on an external host degrades to an diff --git a/src/apps/remove_app.go b/src/apps/remove_app.go index 89fdadf..6040220 100644 --- a/src/apps/remove_app.go +++ b/src/apps/remove_app.go @@ -245,10 +245,9 @@ func (sm *StateMachine) removeProdApp(payload common.TransitionPayload, app *com } } - removeImagesByNameContext, cancel := context.WithTimeout(context.Background(), time.Second*30) - defer cancel() - - err = sm.Container.RemoveImagesByName(removeImagesByNameContext, payload.RegistryImageName.Prod, options) + // Every tag of the app's image: under the agent's own name and under the + // names the platform gave (prodImageRepositories). + err = sm.removeProdImageRepositories(payload, options) if err != nil { return err } diff --git a/src/apps/run_app.go b/src/apps/run_app.go index 2c18518..5ebc115 100644 --- a/src/apps/run_app.go +++ b/src/apps/run_app.go @@ -429,7 +429,7 @@ func (sm *StateMachine) runProdComposeApp(payload common.TransitionPayload, app if imagesErr != nil { log.Warn().Err(imagesErr).Msgf("failed to list local images for %s; deferring the download to compose up", payload.AppName) } else { - missingImageServices, err = composeServicesWithMissingImages(payload.DockerCompose, localImages) + missingImageServices, err = composeServicesWithMissingImages(sm.reswarmConfig(), payload.AppKey, payload.AppName, payload.DockerCompose, localImages) if err != nil { log.Warn().Err(err).Msgf("failed to check compose images for %s; deferring the download to compose up", payload.AppName) missingImageServices = nil @@ -1000,18 +1000,32 @@ func (sm *StateMachine) computeContainerConfigs(payload common.TransitionPayload } } else { - fullImageNameWithTag := fmt.Sprintf("%s:%s", payload.RegistryImageName.Prod, app.Version) - getImageContext, cancel := context.WithTimeout(context.Background(), time.Second*30) - defer cancel() - - _, err := sm.Container.GetImage(getImageContext, payload.RegistryImageName.Prod, payload.PresentVersion) - if err != nil { - if errdefs.IsImageNotFound(err) { - log.Error().Msgf("Image %s:%s was not found, pulling......", payload.RegistryImageName.Prod, payload.PresentVersion) - pullErr := sm.pullApp(payload, app) - if pullErr != nil { - return nil, nil, pullErr - } + // The image the installed version is on the device under: the name + // the platform gave for it, stored with the requested state, or the + // agent's own where the device has it only under that (an app + // installed before the platform named its images). Read from the + // device, never re-derived, so that an app starts offline with the + // image it has. + version := app.Version + if version == "" { + version = payload.PresentVersion + } + fullImageNameWithTag, imageFound, err := sm.localProdImage(payload, version) + switch { + case err != nil: + // as before: Docker could not say, and the start goes on with + // the name recorded for the version, else the agent's own + log.Debug().Err(err).Msgf("could not look for the image %s", fullImageNameWithTag) + case !imageFound: + log.Error().Msgf("Image %s was not found, pulling......", fullImageNameWithTag) + pullErr := sm.pullApp(payload, app) + if pullErr != nil { + return nil, nil, pullErr + } + // the name the pull got the version under (pullProdImage can + // fall back to the agent's own) + if pulled := installedProdImage(sm.withInstalledImage(payload), version); pulled != "" { + fullImageNameWithTag = pulled } } diff --git a/src/apps/state_observer.go b/src/apps/state_observer.go index 1f00606..8bb90f8 100644 --- a/src/apps/state_observer.go +++ b/src/apps/state_observer.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "reagent/common" + "reagent/config" "reagent/container" "reagent/errdefs" "reagent/logging" @@ -253,8 +254,8 @@ func (so *StateObserver) addObserver(stage common.Stage, appKey uint64, appName } // composeServicesWithMissingImages returns the (sorted) names of the compose -// services whose image does not exist locally, matching loosely against the -// RepoTags of the given image list. A service its release pins to a digest +// services whose image does not exist locally, matching each reference +// exactly against the RepoTags of the given image list. A service its release pins to a digest // (x-image-digest) is present only when an image holds that very digest // (pinnedImagePresent): a tag of the same name proves nothing about the // content. Services without an image field are @@ -262,7 +263,14 @@ func (so *StateObserver) addObserver(stage common.Stage, appKey uint64, appName // the install path (runProdComposeApp) uses the result both to decide whether // a real DOWNLOADING phase is needed and to pull only what is actually missing, // so the two stay consistent. -func composeServicesWithMissingImages(dockerCompose map[string]interface{}, images []container.ImageResult) ([]string, error) { +// +// An image of the app's own is looked for also under the name the agent pulls +// it by (resolveStoreImageRef, on this device's registry; reswarmConfig nil: +// only as the release names it): where the release names another host for +// the device's registry (an appliance's own agent reads it on localhost), the +// image is on the device under that name only, and was otherwise judged +// missing on every check. +func composeServicesWithMissingImages(reswarmConfig *config.ReswarmConfig, appKey uint64, appName string, dockerCompose map[string]interface{}, images []container.ImageResult) ([]string, error) { services, ok := (dockerCompose["services"]).(map[string]interface{}) if !ok { return nil, errors.New("failed to infer services") @@ -280,9 +288,23 @@ func composeServicesWithMissingImages(dockerCompose map[string]interface{}, imag } imageName := fmt.Sprint(service["image"]) + imageNames := []string{imageName} + if reswarmConfig != nil { + registryBase := strings.TrimSuffix(strings.TrimSpace(reswarmConfig.DockerRegistryURL), "/") + if resolved := resolveStoreImageRef(reswarmConfig.DockerMainRepository, registryBase, appKey, appName, imageName); resolved != imageName { + imageNames = append(imageNames, resolved) + } + } if digest, pinned := service[composeImageDigestField].(string); pinned { - if !pinnedImagePresent(imageName, digest, images) { + foundPinned := false + for _, name := range imageNames { + if pinnedImagePresent(name, digest, images) { + foundPinned = true + break + } + } + if !foundPinned { missing = append(missing, serviceName) } continue @@ -291,8 +313,15 @@ func composeServicesWithMissingImages(dockerCompose map[string]interface{}, imag foundImage := false for _, image := range images { for _, repoTag := range image.RepoTags { - if strings.Contains(repoTag, imageName) { - foundImage = true + for _, name := range imageNames { + // exactly the reference, as Docker lists it: :latest + // where it names no tag (x:1.0 is not x:1.0.1) + if tagged := imageTag(name); tagged != "" && repoTag == tagged { + foundImage = true + break + } + } + if foundImage { break } } @@ -339,7 +368,11 @@ func (so *StateObserver) CorrectComposeAppState(requestedState common.Transition currentAppState := app.CurrentState app.StateLock.Unlock() - missingImageServices, err := composeServicesWithMissingImages(requestedState.DockerCompose, images) + var reswarmConfig *config.ReswarmConfig + if cfg := so.Container.GetConfig(); cfg != nil { + reswarmConfig = cfg.ReswarmConfig + } + missingImageServices, err := composeServicesWithMissingImages(reswarmConfig, requestedState.AppKey, requestedState.AppName, requestedState.DockerCompose, images) if err != nil { return err } @@ -480,21 +513,13 @@ func (so *StateObserver) CorrectAppStates(updateRemote bool) error { // Since the error is a container not found error (which is expected), we set the err to nil again err = nil - // we should check if the image exists, if it does not, we should set the state to 'REMOVED', else to 'STOPPED' - var fullImageName string - if rState.Stage == common.DEV { - fullImageName = rState.RegistryImageName.Dev - } else if rState.Stage == common.PROD { - fullImageName = rState.RegistryImageName.Prod - } - - foundImage := false - for _, image := range allImages { - if len(image.RepoTags) > 0 && strings.Contains(image.RepoTags[0], fullImageName) { - foundImage = true - break - } + // we should check if the image exists, if it does not, we should set the state to 'REMOVED', else to 'STOPPED': + // a tag of the app's image under the agent's own name or a name the platform gave + var reswarmConfig *config.ReswarmConfig + if cfg := so.Container.GetConfig(); cfg != nil { + reswarmConfig = cfg.ReswarmConfig } + foundImage := hasImageInRepositories(allImages, appImageRepositories(reswarmConfig, rState)) app.StateLock.Lock() currentAppState := app.CurrentState diff --git a/src/apps/state_observer_test.go b/src/apps/state_observer_test.go index a34d401..8b77c88 100644 --- a/src/apps/state_observer_test.go +++ b/src/apps/state_observer_test.go @@ -405,45 +405,60 @@ func TestComposeServicesWithMissingImages(t *testing.T) { } t.Run("all images present", func(t *testing.T) { - missing, err := composeServicesWithMissingImages(compose("registry.example.com/apps/prod_amd64_12_myapp:1.0.0", "eclipse-mosquitto:2"), local) + missing, err := composeServicesWithMissingImages(nil, 0, "", compose("registry.example.com/apps/prod_amd64_12_myapp:1.0.0", "eclipse-mosquitto:2"), local) require.NoError(t, err) assert.Empty(t, missing) }) t.Run("only the services with missing images are returned", func(t *testing.T) { - missing, err := composeServicesWithMissingImages(compose("eclipse-mosquitto:2", "dperson/samba:latest"), local) + missing, err := composeServicesWithMissingImages(nil, 0, "", compose("eclipse-mosquitto:2", "dperson/samba:latest"), local) require.NoError(t, err) assert.Equal(t, []string{"b"}, missing) }) - t.Run("untagged reference matches tagged local image", func(t *testing.T) { - missing, err := composeServicesWithMissingImages(compose("eclipse-mosquitto"), local) + // A reference is matched exactly, as Docker lists it. An untagged one is + // :latest, which compose would pull: eclipse-mosquitto:2 is not it (this + // counted as present before, by substring). + t.Run("untagged reference matches only :latest", func(t *testing.T) { + missing, err := composeServicesWithMissingImages(nil, 0, "", compose("eclipse-mosquitto"), local) + require.NoError(t, err) + assert.Equal(t, []string{"a"}, missing) + + latest := append([]containerpkg.ImageResult{{RepoTags: []string{"eclipse-mosquitto:latest"}}}, local...) + missing, err = composeServicesWithMissingImages(nil, 0, "", compose("eclipse-mosquitto"), latest) require.NoError(t, err) assert.Empty(t, missing) }) + t.Run("a tag that only starts like the reference's is another image", func(t *testing.T) { + withLonger := []containerpkg.ImageResult{{RepoTags: []string{"registry.example.com/apps/prod_12_myapp_1:1.0.1"}}} + missing, err := composeServicesWithMissingImages(nil, 0, "", compose("registry.example.com/apps/prod_12_myapp_1:1.0"), withLonger) + require.NoError(t, err) + assert.Equal(t, []string{"a"}, missing) + }) + t.Run("service without image field is skipped", func(t *testing.T) { dockerCompose := map[string]interface{}{ "services": map[string]interface{}{ "built": map[string]interface{}{"build": "."}, }, } - missing, err := composeServicesWithMissingImages(dockerCompose, local) + missing, err := composeServicesWithMissingImages(nil, 0, "", dockerCompose, local) require.NoError(t, err) assert.Empty(t, missing) }) t.Run("no local images at all returns every image service sorted", func(t *testing.T) { - missing, err := composeServicesWithMissingImages(compose("eclipse-mosquitto:2", "dperson/samba:latest"), nil) + missing, err := composeServicesWithMissingImages(nil, 0, "", compose("eclipse-mosquitto:2", "dperson/samba:latest"), nil) require.NoError(t, err) assert.Equal(t, []string{"a", "b"}, missing) }) t.Run("malformed compose errors", func(t *testing.T) { - _, err := composeServicesWithMissingImages(map[string]interface{}{"services": "garbage"}, local) + _, err := composeServicesWithMissingImages(nil, 0, "", map[string]interface{}{"services": "garbage"}, local) assert.Error(t, err) - _, err = composeServicesWithMissingImages(map[string]interface{}{"services": map[string]interface{}{"a": "garbage"}}, local) + _, err = composeServicesWithMissingImages(nil, 0, "", map[string]interface{}{"services": map[string]interface{}{"a": "garbage"}}, local) assert.Error(t, err) }) } diff --git a/src/apps/update_app.go b/src/apps/update_app.go index 7fbe97f..b1da2bf 100644 --- a/src/apps/update_app.go +++ b/src/apps/update_app.go @@ -4,12 +4,9 @@ import ( "context" "fmt" "reagent/common" - "reagent/container" "reagent/errdefs" - "time" "github.com/pkg/errors" - "github.com/rs/zerolog/log" ) func (sm *StateMachine) getUpdateTransition(payload common.TransitionPayload, app *common.App) TransitionFunc { @@ -91,21 +88,10 @@ func (sm *StateMachine) updateLegacyApp(payload common.TransitionPayload, app *c return err } - fullImageNameWithVersion := fmt.Sprintf("%s:%s", payload.RegistryImageName.Prod, payload.NewestVersion) - pullOptions := container.PullOptions{ - AuthConfig: sm.authConfigForImage(payload, fullImageNameWithVersion, payload.ContainerName.Prod), - PullID: common.BuildDockerPullID(payload.AppKey, payload.AppName), - } - - log.Debug().Msgf("PULLING IMAGE: %s", fullImageNameWithVersion) - reader, err := sm.Container.Pull(context.Background(), fullImageNameWithVersion, pullOptions) - if err != nil { - errorMessage := fmt.Sprintf("Error occured while trying to pull the image: %s", err.Error()) - _ = sm.LogManager.Write(payload.ContainerName.Prod, errorMessage) - return err - } - - streamErr := sm.LogManager.StreamBlocking(payload.ContainerName.Prod, common.PULL, reader) + // The new version's name can differ from the present one's: an app + // installed under a name with the architecture updates to a version under + // the name without, and back on a downgrade (pullProdImage). + fullImageNameWithVersion, streamErr := sm.pullProdImage(payload, payload.NewestVersion, nil) if streamErr != nil { if errdefs.IsDockerStreamCanceled(streamErr) { pullMessage := "The update was canceled" @@ -163,12 +149,9 @@ func (sm *StateMachine) updateLegacyApp(payload common.TransitionPayload, app *c // image under this name, and tearDownComposeInstall already reclaimed its // service images. if payload.DockerCompose == nil { - removeImageByNameContext, cancel := context.WithTimeout(context.Background(), time.Second*30) - defer cancel() - - log.Debug().Msgf("Removing Old Image %s:%s", payload.RegistryImageName.Prod, payload.PresentVersion) - _ = sm.Container.RemoveImageByName(removeImageByNameContext, payload.RegistryImageName.Prod, payload.PresentVersion, map[string]interface{}{"force": true}) + sm.removeSupersededProdImage(payload, fullImageNameWithVersion) } + sm.rememberInstalledImage(payload, payload.NewestVersion, fullImageNameWithVersion) // The state validation will ensure it will reach it's requestedState again return sm.persistPostUpdateRequestedState(payload, app) @@ -192,6 +175,9 @@ func (sm *StateMachine) persistPostUpdateRequestedState(payload common.Transitio payload.NewestVersion = app.Version payload.PresentVersion = app.Version payload.Version = app.Version + // The installed version's image name goes with it: the app starts with it, + // also offline, until the next sync names it again. + payload.PresentImageName = payload.NewImageName // Promote the installed release's definition to the active one. This is the // flow marker every later transition routes on (run/stop/remove, and the diff --git a/src/apps/update_flow_migration.go b/src/apps/update_flow_migration.go index 8d4406d..0492e0c 100644 --- a/src/apps/update_flow_migration.go +++ b/src/apps/update_flow_migration.go @@ -158,10 +158,7 @@ func (sm *StateMachine) removeLegacyProdInstall(payload common.TransitionPayload return err } - removeImagesByNameContext, cancel := context.WithTimeout(context.Background(), time.Second*30) - defer cancel() - - err = sm.Container.RemoveImagesByName(removeImagesByNameContext, payload.RegistryImageName.Prod, map[string]interface{}{"force": true}) + err = sm.removeProdImageRepositories(payload, map[string]interface{}{"force": true}) if err != nil && !errdefs.IsImageNotFound(err) { log.Warn().Err(err).Str("app", payload.AppName).Str("image", payload.RegistryImageName.Prod).Msg("Could not remove the superseded legacy image; leaving it for a later prune") } diff --git a/src/apps/update_order_test.go b/src/apps/update_order_test.go index 1b6c785..7be5e4a 100644 --- a/src/apps/update_order_test.go +++ b/src/apps/update_order_test.go @@ -76,8 +76,8 @@ func TestUpdateAppPullsBeforeTeardown(t *testing.T) { mc.EXPECT().PollContainerState(mock.Anything, "old-ctr", mock.Anything). Return(stateC, pollErrC).Once() - mc.EXPECT().RemoveImageByName(mock.Anything, payload.RegistryImageName.Prod, "1.0.0", mock.Anything). - Run(func(context.Context, string, string, map[string]interface{}) { seq = append(seq, "remove-old-image") }). + mc.EXPECT().RemoveImage(mock.Anything, payload.RegistryImageName.Prod+":1.0.0", map[string]interface{}{"force": false, "pruneChildren": true}). + Run(func(context.Context, string, map[string]interface{}) { seq = append(seq, "remove-old-image") }). Return(nil).Once() fwdAllowLogs(mc) diff --git a/src/apps/update_trigger_test.go b/src/apps/update_trigger_test.go index 1b53354..0e378a8 100644 --- a/src/apps/update_trigger_test.go +++ b/src/apps/update_trigger_test.go @@ -79,7 +79,7 @@ func updExpectPull(mc *mocks.Container, payload common.TransitionPayload, supers Return(fwdDockerStream(), nil). Once() mc.EXPECT(). - RemoveImageByName(mock.Anything, payload.RegistryImageName.Prod, supersededVersion, mock.Anything). + RemoveImage(mock.Anything, payload.RegistryImageName.Prod+":"+supersededVersion, map[string]interface{}{"force": false, "pruneChildren": true}). Return(nil). Once() diff --git a/src/apps/wanted_images.go b/src/apps/wanted_images.go new file mode 100644 index 0000000..0bcaeaf --- /dev/null +++ b/src/apps/wanted_images.go @@ -0,0 +1,80 @@ +package apps + +import ( + "reagent/common" + "reagent/config" + "strings" +) + +// WantedAppImages is every image tag (repo:tag) the apps on the device still +// need, which the disk guard never reclaims: for each app its single image in +// both stages at its present and newest version, under the agent's own name +// and under the name the platform gave for that version, and every service image of +// its Compose definitions, the one it runs and the one an update brings. A +// Compose image is named the way the agent pulls it (resolveComposeStoreImages +// moves the app's own store images onto this device's registry) and as it +// is tagged after a pinned pull (tagPinnedImages), and also as the release +// names it. More names only ever keep more. +func WantedAppImages(reswarmConfig *config.ReswarmConfig, payloads []common.TransitionPayload) map[string]bool { + wanted := make(map[string]bool, len(payloads)*4) + for _, p := range payloads { + for _, repo := range []string{p.RegistryImageName.Prod, p.RegistryImageName.Dev} { + if repo == "" { + continue + } + for _, version := range []string{p.PresentVersion, p.NewestVersion, p.Version} { + if version != "" { + wanted[repo+":"+version] = true + } + } + } + // and under the names the platform gave for them (prodImageFor), and + // the one the device recorded pulling or running it under + for _, version := range []string{p.PresentVersion, p.NewestVersion, p.Version} { + for _, ref := range prodImageCandidates(reswarmConfig, p, version) { + wanted[ref] = true + } + } + if ownsImageRef(p, p.InstalledImage) { + wanted[p.InstalledImage] = true + } + + for _, compose := range []map[string]interface{}{p.DockerCompose, p.NewDockerCompose} { + for _, ref := range composeImageRefs(compose) { + if tag := imageTag(ref); tag != "" { + wanted[tag] = true + } + if reswarmConfig == nil { + continue + } + registryBase := strings.TrimSuffix(strings.TrimSpace(reswarmConfig.DockerRegistryURL), "/") + resolved := resolveStoreImageRef(reswarmConfig.DockerMainRepository, registryBase, p.AppKey, p.AppName, ref) + if tag := imageTag(resolved); tag != "" { + wanted[tag] = true + } + } + } + } + return wanted +} + +// imageTag is the tag Docker lists for an image pulled by ref: ref without a +// digest, with :latest where it names no tag. "" for a reference by digest +// only, which leaves the image without a tag. +func imageTag(ref string) string { + ref = strings.TrimSpace(ref) + digest := false + if at := strings.Index(ref, "@"); at != -1 { + ref, digest = ref[:at], true + } + if ref == "" { + return "" + } + if strings.LastIndex(ref, ":") > strings.LastIndex(ref, "/") { + return ref + } + if digest { + return "" + } + return ref + ":latest" +} diff --git a/src/apps/wanted_images_test.go b/src/apps/wanted_images_test.go new file mode 100644 index 0000000..9d89a53 --- /dev/null +++ b/src/apps/wanted_images_test.go @@ -0,0 +1,86 @@ +package apps + +import ( + "reagent/common" + "reagent/config" + "testing" + + "github.com/stretchr/testify/assert" +) + +const testDigest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + +func TestWantedAppImages(t *testing.T) { + reswarmConfig := &config.ReswarmConfig{DockerRegistryURL: "localhost:15001/", DockerMainRepository: "apps/"} + single := common.TransitionPayload{ + AppKey: 3, AppName: "meter", Stage: common.PROD, + RegistryImageName: common.StageBasedResult{ + Prod: "localhost:15001/apps/prod_arm64_3_meter", + Dev: "localhost:15001/apps/dev_arm64_3_meter", + }, + PresentVersion: "1.0.0", NewestVersion: "1.1.0", + } + compose := common.TransitionPayload{ + AppKey: 7, AppName: "Plant", Stage: common.PROD, + RegistryImageName: common.StageBasedResult{Prod: "localhost:15001/apps/prod_arm64_7_plant"}, + PresentVersion: "1.2.0", NewestVersion: "1.3.0", + DockerCompose: map[string]interface{}{"services": map[string]interface{}{ + // minted with the platform's registry name, pulled from this + // device's registry, pinned to a digest + "web": map[string]interface{}{"image": "registry.example.com/apps/prod_arm64_7_plant_1:1.2.0", composeImageDigestField: testDigest}, + "db": map[string]interface{}{"image": "localhost:15001/apps/prod_arm64_7_plant_2:1.2.0"}, + // pinned in its own reference + "cache": map[string]interface{}{"image": "localhost:15001/library/redis:7@" + testDigest}, + // by digest only: Docker keeps no tag to keep + "proxy": map[string]interface{}{"image": "localhost:15001/library/caddy@" + testDigest}, + "bus": map[string]interface{}{"image": "localhost:15001/library/mosquitto"}, + }}, + NewDockerCompose: map[string]interface{}{"services": map[string]interface{}{ + "web": map[string]interface{}{"image": "localhost:15001/apps/prod_arm64_7_plant_1:1.3.0"}, + }}, + } + + wanted := WantedAppImages(reswarmConfig, []common.TransitionPayload{single, compose}) + + for _, tag := range []string{ + // the single images, as before + "localhost:15001/apps/prod_arm64_3_meter:1.0.0", + "localhost:15001/apps/prod_arm64_3_meter:1.1.0", + "localhost:15001/apps/dev_arm64_3_meter:1.0.0", + "localhost:15001/apps/prod_arm64_7_plant:1.2.0", + // the Compose images: as pulled, as released, and the update's + "localhost:15001/apps/prod_arm64_7_plant_1:1.2.0", + "registry.example.com/apps/prod_arm64_7_plant_1:1.2.0", + "localhost:15001/apps/prod_arm64_7_plant_2:1.2.0", + "localhost:15001/library/redis:7", + "localhost:15001/library/mosquitto:latest", + "localhost:15001/apps/prod_arm64_7_plant_1:1.3.0", + } { + assert.True(t, wanted[tag], "keeps %s", tag) + } + assert.False(t, wanted["localhost:15001/library/caddy:latest"]) + assert.False(t, wanted["localhost:15001/apps/prod_arm64_7_plant_1:1.1.0"], "an older version is not kept") +} + +func TestWantedAppImagesWithoutCompose(t *testing.T) { + wanted := WantedAppImages(nil, []common.TransitionPayload{{ + RegistryImageName: common.StageBasedResult{Prod: "localhost:15001/apps/prod_amd64_3_meter"}, + Version: "2.0.0", + DockerCompose: map[string]interface{}{"services": "not a map"}, + }}) + + assert.Equal(t, map[string]bool{"localhost:15001/apps/prod_amd64_3_meter:2.0.0": true}, wanted) +} + +func TestImageTag(t *testing.T) { + for ref, want := range map[string]string{ + "localhost:15001/apps/x:1.0": "localhost:15001/apps/x:1.0", + "localhost:15001/apps/x": "localhost:15001/apps/x:latest", + "localhost:15001/apps/x:1.0@" + testDigest: "localhost:15001/apps/x:1.0", + "localhost:15001/apps/x@" + testDigest: "", + "redis": "redis:latest", + "": "", + } { + assert.Equal(t, want, imageTag(ref), "imageTag(%q)", ref) + } +} diff --git a/src/common/types.go b/src/common/types.go index c0a23b0..becd97e 100644 --- a/src/common/types.go +++ b/src/common/types.go @@ -43,9 +43,14 @@ type App struct { RequestUpdate bool ReleaseBuild bool Version string - LastUpdated Timestamp - TransitionLock *semaphore.Weighted - StateLock sync.Mutex + // PushedDigests is what the last release build pushed: the image + // reference as pushed and the manifest digest the registry answered for + // it. Sent with the PUBLISHED report (pushed_digests); nil when nothing is + // known. Kept in memory only. + PushedDigests map[string]string + LastUpdated Timestamp + TransitionLock *semaphore.Weighted + StateLock sync.Mutex } func (app *App) SecureTransition() bool { @@ -127,11 +132,38 @@ type TransitionPayload struct { // this epoch and the backend verifies against it; bumping it server-side // rotates the credential. 0 == absent == epoch 1, so an un-migrated // backend needs no special handling. - AppCredEpoch uint64 - CallerAuthID int - AppName string - ImageName StageBasedResult - PresentImageName string + AppCredEpoch uint64 + CallerAuthID int + AppName string + ImageName StageBasedResult + // PresentImageName / NewImageName are the platform's names of the image + // of a single-image app for PresentVersion / NewestVersion + // (present_image_name / new_image_name of the sync answer, + // app.f_image_name): : below the registry's main + // repository, prod__: for a release with one + // image per platform, prod___: for + // one from before. Empty where the platform names none (an older backend + // or appliance). Stored with the requested state, so that an app starts + // with them offline. apps.prodImageFor decides which name is used. + PresentImageName string + NewImageName string + // InstalledImage is the reference (registry, repository, tag) the device + // really pulled or ran InstalledImageVersion under: the platform's name, + // or the agent's own where the pull under the platform's name failed. + // Written by the agent only, stored with the requested state and never + // replaced by a sync, so that a start (offline too), the observer, the + // cleanup and the uninstall find the image after the platform renamed + // the version. Empty: not known (an app installed before this agent). + InstalledImage string + InstalledImageVersion string + // Architecture is the device's architecture as the platform stores it + // (architecture of the sync answer): what a release build is registered + // and pushed for. Empty from an older backend or a stored state. + Architecture string + // RegistryImageName is the name the agent forms itself, from the + // architecture it was built for: what a release build pushes (the + // backend expects exactly that), and for an app's image where the + // platform names none. RegistryImageName StageBasedResult ContainerName StageBasedResult DockerCredentials map[string]DockerCredential diff --git a/src/container/docker_reference_filter_integration_test.go b/src/container/docker_reference_filter_integration_test.go new file mode 100644 index 0000000..736406d --- /dev/null +++ b/src/container/docker_reference_filter_integration_test.go @@ -0,0 +1,42 @@ +//go:build integration + +package container + +import ( + "context" + "fmt" + "os" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestRemoveImagesByNameNeedsTheWholeName guards the contract the removal of +// an app relies on (removeDevApp, removeProdApp, the update-flow migration +// pass RegistryImageName): RemoveImagesByName matches a repository by its +// whole name, registry host and path included. A name without them matches +// nothing, which is why the orphan cleanup of DEV apps, which passed +// dev_amd64__, removed nothing on any architecture. +func TestRemoveImagesByNameNeedsTheWholeName(t *testing.T) { + docker := newIntegrationDocker(t) + pullImage(t, docker, busyboxImage) + + shortName := fmt.Sprintf("dev_amd64_%d_refilter", os.Getpid()) + fullName := "registry.example.test/apps/" + shortName + ref := fullName + ":latest" + t.Cleanup(func() { forceRemoveImage(docker, fullName) }) + + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + require.NoError(t, docker.Tag(ctx, busyboxImage, ref)) + + require.NoError(t, docker.RemoveImagesByName(ctx, shortName, map[string]interface{}{"force": true})) + _, err := docker.GetImage(ctx, fullName, "latest") + assert.NoError(t, err, "the name without registry and repository matches nothing") + + require.NoError(t, docker.RemoveImagesByName(ctx, fullName, map[string]interface{}{"force": true})) + _, err = docker.GetImage(ctx, fullName, "latest") + assert.Error(t, err, "the whole name matches the image") +} diff --git a/src/container/engine.go b/src/container/engine.go new file mode 100644 index 0000000..9531803 --- /dev/null +++ b/src/container/engine.go @@ -0,0 +1,157 @@ +package container + +import ( + "bufio" + "bytes" + "context" + "errors" + "os" + "runtime" + "strings" +) + +// EngineInfo is what the device reports about the Docker engine that runs its +// apps. An empty field is not known. +type EngineInfo struct { + // Platform is the engine's default platform as an OCI platform string: + // linux/amd64, linux/arm64, linux/arm/v7, linux/arm/v6, linux/arm/v8 (a + // 32-bit engine on an ARMv8 CPU), or linux/arm when the variant cannot be + // told. What an app image must match is this, not the architecture the + // agent was built for. + Platform string + // Version is the engine's version, e.g. 27.0.3. + Version string +} + +// readCPUInfo reads the CPU description the engine reads for its variant: +// /proc/cpuinfo of the kernel the agent shares with a Linux engine. A seam +// for the tests. +var readCPUInfo = func() ([]byte, error) { + if runtime.GOOS != "linux" { + return nil, errors.New("no /proc/cpuinfo on " + runtime.GOOS) + } + return os.ReadFile("/proc/cpuinfo") +} + +// EngineInfo asks the engine for its platform and version. On Windows and +// macOS the engine runs in a VM, and what it answers is what counts, never +// the host's architecture. The caller treats an error as "not known yet". +// +// Its own requests end with ctx. It is not strictly bounded by ctx, though: +// the Docker client negotiates its API version once, under a lock it holds +// while it pings with the context of the call that negotiates. While another +// call without a deadline is stuck in that ping (a daemon whose /_ping +// stalls), EngineInfo waits for that lock beyond its own timeout. Callers run +// it in the background, where that costs one waiting goroutine. +func (docker *Docker) EngineInfo(ctx context.Context) (EngineInfo, error) { + version, err := docker.client.ServerVersion(ctx) + if err != nil { + return EngineInfo{}, err + } + + var machine string + var cpuinfo []byte + if strings.EqualFold(version.Arch, "arm") { + // The Engine API names no ARM variant. The engine takes it from the + // CPU (/proc/cpuinfo), and from its kernel's machine name (/info) + // where that says nothing. This machine's CPU is the engine's only + // when the engine runs here (a unix socket); for an engine elsewhere + // (DOCKER_HOST=tcp://, ssh://) only its own answer counts. + if engineIsLocal(docker.client.DaemonHost()) { + cpuinfo, _ = readCPUInfo() + } + if info, err := docker.client.Info(ctx); err == nil { + machine = info.Architecture + } + } + + return EngineInfo{ + Platform: enginePlatform(version.Os, version.Arch, machine, cpuinfo), + Version: strings.TrimSpace(version.Version), + }, nil +} + +// engineIsLocal reports whether the engine at host (DOCKER_HOST's form) runs +// on this machine: a unix socket or a Windows named pipe. +func engineIsLocal(host string) bool { + return strings.HasPrefix(host, "unix://") || strings.HasPrefix(host, "npipe://") +} + +// enginePlatform is the engine's default platform from its OS and GOARCH +// (/version), and for 32-bit ARM the variant the way the engine derives it +// for itself (containerd's platforms package, getCPUVariant): the "CPU +// architecture" of /proc/cpuinfo, with the Raspberry Pi ARMv6 that reports 7, +// else the machine name (/info Architecture: armv7l, armv6l, aarch64). An +// unknown variant is left out rather than guessed; a 32-bit engine on an +// ARMv8 CPU stays v8, which the platform maps. +func enginePlatform(osName, arch, machine string, cpuinfo []byte) string { + osName = strings.ToLower(strings.TrimSpace(osName)) + arch = strings.ToLower(strings.TrimSpace(arch)) + if osName == "" || arch == "" { + return "" + } + if arch != "arm" { + return osName + "/" + arch + } + if variant := armVariant(machine, cpuinfo); variant != "" { + return osName + "/arm/" + variant + } + return osName + "/arm" +} + +// armVariant is the ARM variant (v3 to v8) of a 32-bit engine, or "". +func armVariant(machine string, cpuinfo []byte) string { + variant, found := cpuInfoField(cpuinfo, "CPU architecture") + if found { + // A Raspberry Pi ARMv6 reports 7 (a kernel quirk). + if variant == "7" { + if model, ok := cpuInfoField(cpuinfo, "model name"); ok && strings.HasPrefix(strings.ToLower(model), "armv6-compatible") { + variant = "6" + } + } + } else { + variant = machineVariant(machine) + } + + switch strings.ToLower(variant) { + case "8", "aarch64": + return "v8" + case "7", "7m", "?(12)", "?(13)", "?(14)", "?(15)", "?(16)", "?(17)": + return "v7" + case "6", "6tej": + return "v6" + case "5", "5t", "5te", "5tej": + return "v5" + case "4", "4t": + return "v4" + case "3": + return "v3" + default: + return "" + } +} + +// machineVariant is the variant a kernel's machine name (uname -m) says. +func machineVariant(machine string) string { + machine = strings.ToLower(strings.TrimSpace(machine)) + if machine == "aarch64" || machine == "arm64" { + return "8" + } + if strings.HasPrefix(machine, "armv") && len(machine) >= 5 { + return machine[4:5] + } + return "" +} + +// cpuInfoField is the value of the first line of /proc/cpuinfo that names +// field (case-insensitive), as the engine reads it: the first core is enough. +func cpuInfoField(cpuinfo []byte, field string) (string, bool) { + scanner := bufio.NewScanner(bytes.NewReader(cpuinfo)) + for scanner.Scan() { + key, value, ok := strings.Cut(scanner.Text(), ":") + if ok && strings.EqualFold(strings.TrimSpace(key), field) { + return strings.TrimSpace(value), true + } + } + return "", false +} diff --git a/src/container/engine_integration_test.go b/src/container/engine_integration_test.go new file mode 100644 index 0000000..a17a3c3 --- /dev/null +++ b/src/container/engine_integration_test.go @@ -0,0 +1,26 @@ +//go:build integration + +package container + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The engine on this host answers its platform and version. +func TestIntegrationEngineInfo(t *testing.T) { + docker := newIntegrationDocker(t) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + info, err := docker.EngineInfo(ctx) + + require.NoError(t, err) + assert.Regexp(t, `^linux/(amd64|arm64|arm(/v[5-8])?)$`, info.Platform) + assert.NotEmpty(t, info.Version) + t.Logf("engine: %s, Docker %s", info.Platform, info.Version) +} diff --git a/src/container/engine_test.go b/src/container/engine_test.go new file mode 100644 index 0000000..a9e56eb --- /dev/null +++ b/src/container/engine_test.go @@ -0,0 +1,263 @@ +package container + +import ( + "context" + "errors" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/docker/docker/client" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// /proc/cpuinfo of the boards the platform meets, shortened to what counts. +const ( + // Raspberry Pi 3 or 4 with a 32-bit kernel. + cpuinfoPi32 = "processor\t: 0\nmodel name\t: ARMv7 Processor rev 4 (v7l)\nBogoMIPS\t: 38.40\nCPU architecture: 7\nCPU variant\t: 0x0\n" + // Raspberry Pi Zero or 1: an ARMv6 that reports 7 (the kernel quirk). + cpuinfoPiZero = "processor\t: 0\nmodel name\t: ARMv6-compatible processor rev 7 (v6l)\nBogoMIPS\t: 697.95\nCPU architecture: 7\n" + // Raspberry Pi 3 or 4 with a 64-bit kernel. + cpuinfoPi64 = "processor\t: 0\nBogoMIPS\t: 108.00\nFeatures\t: fp asimd evtstrm crc32 cpuid\nCPU implementer\t: 0x41\nCPU architecture: 8\n" +) + +func TestEnginePlatform(t *testing.T) { + for name, tc := range map[string]struct { + os, arch, machine, cpuinfo string + want string + }{ + "amd64": {os: "linux", arch: "amd64", machine: "x86_64", want: "linux/amd64"}, + "arm64": {os: "linux", arch: "arm64", machine: "aarch64", cpuinfo: cpuinfoPi64, want: "linux/arm64"}, + "32-bit engine, 32-bit kernel, v7": {os: "linux", arch: "arm", machine: "armv7l", cpuinfo: cpuinfoPi32, want: "linux/arm/v7"}, + "32-bit engine, 32-bit kernel, v6": {os: "linux", arch: "arm", machine: "armv6l", cpuinfo: cpuinfoPiZero, want: "linux/arm/v6"}, + "32-bit engine, 64-bit kernel": {os: "linux", arch: "arm", machine: "aarch64", cpuinfo: cpuinfoPi64, want: "linux/arm/v8"}, + "32-bit engine, no cpuinfo, armv7l": {os: "linux", arch: "arm", machine: "armv7l", want: "linux/arm/v7"}, + "32-bit engine, no cpuinfo, armv6l": {os: "linux", arch: "arm", machine: "armv6l", want: "linux/arm/v6"}, + "32-bit engine, no cpuinfo, armv8l": {os: "linux", arch: "arm", machine: "armv8l", want: "linux/arm/v8"}, + "32-bit engine, no cpuinfo, aarch64": {os: "linux", arch: "arm", machine: "aarch64", want: "linux/arm/v8"}, + "32-bit engine, cpuinfo wins": {os: "linux", arch: "arm", machine: "armv7l", cpuinfo: cpuinfoPiZero, want: "linux/arm/v6"}, + "32-bit engine, variant unknown": {os: "linux", arch: "arm", want: "linux/arm"}, + "32-bit engine, cpuinfo says nothing": {os: "linux", arch: "arm", machine: "x86_64", cpuinfo: "processor\t: 0\n", want: "linux/arm"}, + "Windows containers": {os: "windows", arch: "amd64", want: "windows/amd64"}, + "no architecture": {os: "linux", want: ""}, + "no OS": {arch: "amd64", want: ""}, + } { + t.Run(name, func(t *testing.T) { + assert.Equal(t, tc.want, enginePlatform(tc.os, tc.arch, tc.machine, []byte(tc.cpuinfo))) + }) + } +} + +// fakeEngine is a stand-in Docker engine on this machine (a unix socket) +// that answers /_ping, /version and /info with what a real engine of the +// given kind answers. +func fakeEngine(t *testing.T, version, info string, handle func(w http.ResponseWriter, r *http.Request) bool) *Docker { + t.Helper() + dir, err := os.MkdirTemp("", "eng") + require.NoError(t, err) + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + socket := filepath.Join(dir, "docker.sock") + listener, err := net.Listen("unix", socket) + require.NoError(t, err) + engine := fakeEngineServer(version, info, handle) + engine.Listener = listener + engine.Start() + t.Cleanup(engine.Close) + return dockerAt(t, "unix://"+socket) +} + +// remoteFakeEngine is fakeEngine on another machine, as DOCKER_HOST=tcp:// +// names it. +func remoteFakeEngine(t *testing.T, version, info string) *Docker { + t.Helper() + engine := fakeEngineServer(version, info, nil) + engine.Start() + t.Cleanup(engine.Close) + return dockerAt(t, "tcp://"+strings.TrimPrefix(engine.URL, "http://")) +} + +func fakeEngineServer(version, info string, handle func(w http.ResponseWriter, r *http.Request) bool) *httptest.Server { + return httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if handle != nil && handle(w, r) { + return + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Api-Version", "1.47") + switch { + case strings.HasSuffix(r.URL.Path, "/_ping"): + _, _ = w.Write([]byte("OK")) + case strings.HasSuffix(r.URL.Path, "/version"): + _, _ = w.Write([]byte(version)) + case strings.HasSuffix(r.URL.Path, "/info"): + _, _ = w.Write([]byte(info)) + default: + http.NotFound(w, r) + } + })) +} + +// dockerAt is a Docker whose client negotiates its API version, as the +// agent's does, with the engine at host. +func dockerAt(t *testing.T, host string) *Docker { + t.Helper() + cli, err := client.NewClientWithOpts(client.WithHost(host), client.WithAPIVersionNegotiation()) + require.NoError(t, err) + t.Cleanup(func() { _ = cli.Close() }) + return &Docker{client: cli} +} + +// withCPUInfo makes the engine's CPU read cpuinfo (an error when ""). +func withCPUInfo(t *testing.T, cpuinfo string) { + t.Helper() + restore := readCPUInfo + readCPUInfo = func() ([]byte, error) { + if cpuinfo == "" { + return nil, errors.New("no /proc/cpuinfo") + } + return []byte(cpuinfo), nil + } + t.Cleanup(func() { readCPUInfo = restore }) +} + +func TestEngineInfo(t *testing.T) { + for name, tc := range map[string]struct { + version, info, cpuinfo string + want EngineInfo + }{ + "amd64": { + version: `{"Version":"27.0.3","Os":"linux","Arch":"amd64"}`, + info: `{"Architecture":"x86_64"}`, + want: EngineInfo{Platform: "linux/amd64", Version: "27.0.3"}, + }, + "arm64": { + version: `{"Version":"29.1.0","Os":"linux","Arch":"arm64"}`, + info: `{"Architecture":"aarch64"}`, + cpuinfo: cpuinfoPi64, + want: EngineInfo{Platform: "linux/arm64", Version: "29.1.0"}, + }, + "32-bit engine on a 32-bit kernel, v7": { + version: `{"Version":"28.5.2","Os":"linux","Arch":"arm"}`, + info: `{"Architecture":"armv7l"}`, + cpuinfo: cpuinfoPi32, + want: EngineInfo{Platform: "linux/arm/v7", Version: "28.5.2"}, + }, + "32-bit engine on a 32-bit kernel, v6": { + version: `{"Version":"20.10.24","Os":"linux","Arch":"arm"}`, + info: `{"Architecture":"armv6l"}`, + cpuinfo: cpuinfoPiZero, + want: EngineInfo{Platform: "linux/arm/v6", Version: "20.10.24"}, + }, + "32-bit engine on a 64-bit kernel": { + version: `{"Version":"28.5.2","Os":"linux","Arch":"arm"}`, + info: `{"Architecture":"aarch64"}`, + cpuinfo: cpuinfoPi64, + want: EngineInfo{Platform: "linux/arm/v8", Version: "28.5.2"}, + }, + "32-bit engine, no cpuinfo, /info tells": { + version: `{"Version":"28.5.2","Os":"linux","Arch":"arm"}`, + info: `{"Architecture":"armv7l"}`, + want: EngineInfo{Platform: "linux/arm/v7", Version: "28.5.2"}, + }, + "32-bit engine, nothing tells the variant": { + version: `{"Version":"28.5.2","Os":"linux","Arch":"arm"}`, + info: `{}`, + want: EngineInfo{Platform: "linux/arm", Version: "28.5.2"}, + }, + // Docker Desktop on an Intel Mac or Windows PC: the engine's VM counts, + // whatever the agent was built for. + "Docker Desktop": { + version: `{"Version":"28.5.1","Os":"linux","Arch":"amd64"}`, + info: `{"Architecture":"x86_64","OperatingSystem":"Docker Desktop"}`, + want: EngineInfo{Platform: "linux/amd64", Version: "28.5.1"}, + }, + } { + t.Run(name, func(t *testing.T) { + withCPUInfo(t, tc.cpuinfo) + docker := fakeEngine(t, tc.version, tc.info, nil) + + got, err := docker.EngineInfo(context.Background()) + + require.NoError(t, err) + assert.Equal(t, tc.want, got) + }) + } +} + +// A failing /info leaves only the variant out. +func TestEngineInfoWithoutInfo(t *testing.T) { + withCPUInfo(t, "") + docker := fakeEngine(t, `{"Version":"28.5.2","Os":"linux","Arch":"arm"}`, "", func(w http.ResponseWriter, r *http.Request) bool { + if strings.HasSuffix(r.URL.Path, "/info") { + http.Error(w, `{"message":"boom"}`, http.StatusInternalServerError) + return true + } + return false + }) + + got, err := docker.EngineInfo(context.Background()) + + require.NoError(t, err) + assert.Equal(t, EngineInfo{Platform: "linux/arm", Version: "28.5.2"}, got) +} + +func TestEngineInfoDockerAbsent(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + host := "tcp://" + listener.Addr().String() + require.NoError(t, listener.Close()) + + _, err = dockerAt(t, host).EngineInfo(context.Background()) + + assert.Error(t, err) +} + +// A hung daemon costs the caller no more than its timeout. +func TestEngineInfoDockerHangs(t *testing.T) { + release := make(chan struct{}) + docker := fakeEngine(t, "", "", func(w http.ResponseWriter, r *http.Request) bool { + select { + case <-release: + case <-r.Context().Done(): + } + return true + }) + t.Cleanup(func() { close(release) }) + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + start := time.Now() + _, err := docker.EngineInfo(ctx) + + assert.Error(t, err) + assert.Less(t, time.Since(start), 5*time.Second) +} + +// An engine on another machine: this machine's CPU says nothing about it, +// only the engine's own /info does. +func TestEngineInfoRemoteEngine(t *testing.T) { + withCPUInfo(t, cpuinfoPiZero) + docker := remoteFakeEngine(t, `{"Version":"28.5.2","Os":"linux","Arch":"arm"}`, `{"Architecture":"armv7l"}`) + + got, err := docker.EngineInfo(context.Background()) + + require.NoError(t, err) + assert.Equal(t, EngineInfo{Platform: "linux/arm/v7", Version: "28.5.2"}, got) +} + +func TestEngineIsLocal(t *testing.T) { + for host, want := range map[string]bool{ + "unix:///var/run/docker.sock": true, + "npipe:////./pipe/docker_engine": true, + "tcp://192.168.1.20:2375": false, + "ssh://pi@192.168.1.20": false, + "http://localhost:2375": false, + } { + assert.Equal(t, want, engineIsLocal(host), host) + } +} diff --git a/src/diskguard/diskguard.go b/src/diskguard/diskguard.go index c7514e7..3cf0aa3 100644 --- a/src/diskguard/diskguard.go +++ b/src/diskguard/diskguard.go @@ -184,8 +184,9 @@ type Config struct { AppImageRegistry string // WantedAppImages returns every image reference (repo:tag) the device still // needs: for each locally known app, its present and newest version in both - // stages. Anything else under AppImageRegistry is a superseded leftover. An - // error means the wanted set is unknown — no app image is then touched. + // stages, and the images of its Compose definitions. Anything else under + // AppImageRegistry is a superseded leftover. An error means the wanted set + // is unknown — no app image is then touched. WantedAppImages func() (map[string]bool, error) // OnRecover is called once when the device leaves EMERGENCY (every // filesystem apps can fill back at its warn floor), to reinstate the diff --git a/src/persistence/database.go b/src/persistence/database.go index 8d56647..e8f0588 100644 --- a/src/persistence/database.go +++ b/src/persistence/database.go @@ -450,6 +450,18 @@ func (ast *AppStateDatabase) GetRequestedStates() ([]common.TransitionPayload, e payloads = append(payloads, payload) } + // done with the rows before the next query: one connection + _ = rows.Close() + + names := ast.requestedImageNames() + installed := ast.installedImages() + for i := range payloads { + key := imageNamesKey{payloads[i].AppKey, payloads[i].Stage} + payloads[i].PresentImageName = names[key][0] + payloads[i].NewImageName = names[key][1] + payloads[i].InstalledImage = installed[key][0] + payloads[i].InstalledImageVersion = installed[key][1] + } return payloads, nil } @@ -569,6 +581,12 @@ func (ast *AppStateDatabase) GetRequestedState(aKey uint64, aStage common.Stage) return common.TransitionPayload{}, err } + key := imageNamesKey{payload.AppKey, payload.Stage} + names := ast.requestedImageNames()[key] + payload.PresentImageName, payload.NewImageName = names[0], names[1] + installed := ast.installedImages()[key] + payload.InstalledImage, payload.InstalledImageVersion = installed[0], installed[1] + return payload, nil } @@ -634,6 +652,8 @@ func (ast *AppStateDatabase) BulkUpsertRequestedStateChanges(payloads []common.T _ = tx.Rollback() return err } + + writeImageNames(tx, payload) } return tx.Commit() @@ -702,6 +722,8 @@ func (ast *AppStateDatabase) UpsertRequestedStateChange(payload common.Transitio return err } + writeImageNames(ast.db, payload) + return nil } @@ -961,3 +983,91 @@ func (ast *AppStateDatabase) execute(fileName string) error { return nil } + +// stringOrEmpty is a nullable TEXT column's value, "" for NULL. +func stringOrEmpty(value *string) string { + if value == nil { + return "" + } + return *value +} + +// nullIfEmpty stores "" as NULL. +func nullIfEmpty(value string) interface{} { + if value == "" { + return nil + } + return value +} + +// imageNamesKey identifies a requested state (app_key and stage are unique +// together in practice; the row's name is part of its key only for the +// upsert). +type imageNamesKey struct { + appKey uint64 + stage common.Stage +} + +// requestedImageNames reads the platform's image names of every requested +// state (present_image_name, new_image_name). Best effort: where they cannot +// be read (their columns are missing because the single- script failed, e.g. +// on a full disk), none is known, and the agent forms the names itself, as +// before. Read on their own so that the requested states never fail on them. +func (ast *AppStateDatabase) requestedImageNames() map[imageNamesKey][2]string { + return ast.readImageColumns(QuerySelectRequestedStateImageNames) +} + +// installedImages reads, best effort as requestedImageNames, the image each +// requested state's version was really pulled or run under, and its version. +func (ast *AppStateDatabase) installedImages() map[imageNamesKey][2]string { + return ast.readImageColumns(QuerySelectRequestedStateInstalledImages) +} + +// readImageColumns reads app_key, stage and two nullable text columns of the +// requested states; nothing where they cannot be read. +func (ast *AppStateDatabase) readImageColumns(query string) map[imageNamesKey][2]string { + names := map[imageNamesKey][2]string{} + rows, err := ast.db.Query(query) + if err != nil { + log.Debug().Err(err).Msg("could not read the stored image names; the agent forms them itself") + return names + } + defer func() { _ = rows.Close() }() + for rows.Next() { + var appKey uint64 + var stage common.Stage + var first, second *string + if err := rows.Scan(&appKey, &stage, &first, &second); err != nil { + log.Debug().Err(err).Msg("could not read the stored image names; the agent forms them itself") + return map[imageNamesKey][2]string{} + } + names[imageNamesKey{appKey, stage}] = [2]string{stringOrEmpty(first), stringOrEmpty(second)} + } + return names +} + +// SetInstalledImage records the reference the device really pulled or ran +// version of the app under. Only the agent writes it; a sync never replaces +// it. An error means it is not recorded, and the agent finds the image by the +// other names, as before. +func (ast *AppStateDatabase) SetInstalledImage(appKey uint64, stage common.Stage, version string, ref string) error { + _, err := ast.db.Exec(QueryUpdateRequestedStateInstalledImage, nullIfEmpty(ref), nullIfEmpty(version), appKey, stage) + return err +} + +// execer is a database or a transaction. +type execer interface { + Exec(query string, args ...any) (sql.Result, error) +} + +// writeImageNames stores the platform's image names of a requested state just +// written. Best effort, as requestedImageNames: a failure leaves the names out +// and the requested state as it was written. +func writeImageNames(db execer, payload common.TransitionPayload) { + _, err := db.Exec(QueryUpdateRequestedStateImageNames, + nullIfEmpty(payload.PresentImageName), nullIfEmpty(payload.NewImageName), + payload.AppName, payload.AppKey, payload.Stage) + if err != nil { + log.Debug().Err(err).Str("app", payload.AppName).Msg("could not store the image names; the agent forms them itself") + } +} diff --git a/src/persistence/image_names_test.go b/src/persistence/image_names_test.go new file mode 100644 index 0000000..30de950 --- /dev/null +++ b/src/persistence/image_names_test.go @@ -0,0 +1,82 @@ +package persistence + +import ( + "reagent/common" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The platform's image names are stored with the requested state, read back +// by a start (offline too), and replaced by the next sync. +func TestRequestedStateImageNames(t *testing.T) { + db := newTestDB(t) + p := newRequestedPayload(t, "MyApp", 1953, common.PROD) + p.PresentImageName = "prod_amd64_1953_myapp:1.0.0" + p.NewImageName = "prod_1953_myapp:2.0.0" + require.NoError(t, db.UpsertRequestedStateChange(p)) + + one, err := db.GetRequestedState(1953, common.PROD) + require.NoError(t, err) + assert.Equal(t, "prod_amd64_1953_myapp:1.0.0", one.PresentImageName) + assert.Equal(t, "prod_1953_myapp:2.0.0", one.NewImageName) + + // a sync of an older backend: none + p.PresentImageName, p.NewImageName = "", "" + require.NoError(t, db.BulkUpsertRequestedStateChanges([]common.TransitionPayload{p})) + all, err := db.GetRequestedStates() + require.NoError(t, err) + require.Len(t, all, 1) + assert.Empty(t, all[0].PresentImageName) + assert.Empty(t, all[0].NewImageName) +} + +// A database whose columns for the names are missing (their single- script +// failed, e.g. on a full disk) reads and writes the requested states as +// before, without names: the apps still start. +func TestRequestedStatesWithoutImageNameColumns(t *testing.T) { + db := newTestDB(t) + for _, column := range []string{"present_image_name", "installed_image"} { + _, err := db.db.Exec(`ALTER TABLE RequestedAppStates DROP COLUMN ` + column) + require.NoError(t, err) + } + assert.Error(t, db.SetInstalledImage(1953, common.PROD, "1.0.0", "x:1.0.0"), "not recorded, nothing else changes") + + p := newRequestedPayload(t, "MyApp", 1953, common.PROD) + p.PresentVersion = "1.0.0" + p.PresentImageName = "prod_1953_myapp:1.0.0" + require.NoError(t, db.UpsertRequestedStateChange(p)) + require.NoError(t, db.BulkUpsertRequestedStateChanges([]common.TransitionPayload{p})) + + all, err := db.GetRequestedStates() + require.NoError(t, err) + require.Len(t, all, 1) + assert.Equal(t, "1.0.0", all[0].PresentVersion) + assert.Empty(t, all[0].PresentImageName) + + one, err := db.GetRequestedState(1953, common.PROD) + require.NoError(t, err) + assert.Equal(t, "1.0.0", one.PresentVersion) +} + +// The image an app's version was really pulled under is written by the agent +// alone: a sync (an upsert) never replaces it. +func TestInstalledImageSurvivesASync(t *testing.T) { + db := newTestDB(t) + p := newRequestedPayload(t, "MyApp", 1953, common.PROD) + require.NoError(t, db.UpsertRequestedStateChange(p)) + require.NoError(t, db.SetInstalledImage(1953, common.PROD, "2.0.0", "registry.test/apps/prod_1953_myapp:2.0.0")) + + p.PresentImageName = "prod_amd64_1953_myapp:2.0.0" + require.NoError(t, db.BulkUpsertRequestedStateChanges([]common.TransitionPayload{p})) + require.NoError(t, db.UpsertRequestedStateChange(p)) + + one, err := db.GetRequestedState(1953, common.PROD) + require.NoError(t, err) + assert.Equal(t, "registry.test/apps/prod_1953_myapp:2.0.0", one.InstalledImage) + assert.Equal(t, "2.0.0", one.InstalledImageVersion) + all, err := db.GetRequestedStates() + require.NoError(t, err) + assert.Equal(t, "registry.test/apps/prod_1953_myapp:2.0.0", all[0].InstalledImage) +} diff --git a/src/persistence/statements.go b/src/persistence/statements.go index e81ddae..b8673fd 100644 --- a/src/persistence/statements.go +++ b/src/persistence/statements.go @@ -44,3 +44,16 @@ request_update=excluded.request_update` const QueryDeleteAppStateByAppKeyAndStage = `DELETE FROM AppStates WHERE app_key = ? AND stage = ?` const QueryDeleteRequestedStateByAppKeyAndStage = `DELETE FROM RequestedAppStates WHERE app_key = ? AND stage = ?` + +// The image names of a requested state (present_image_name, new_image_name), +// read and written on their own, after the row: where the columns are missing +// (their single- script failed, e.g. on a full disk) the row is read and +// written as before and the names are left out. +const QuerySelectRequestedStateImageNames = `SELECT app_key, stage, present_image_name, new_image_name FROM RequestedAppStates` +const QueryUpdateRequestedStateImageNames = `UPDATE RequestedAppStates SET present_image_name = ?, new_image_name = ? WHERE app_name = ? AND app_key = ? AND stage = ?` + +// The image the device really pulled or ran an app's version under +// (installed_image, installed_image_version): written by the agent alone, +// never by a sync. Read and written on their own as the names above. +const QuerySelectRequestedStateInstalledImages = `SELECT app_key, stage, installed_image, installed_image_version FROM RequestedAppStates` +const QueryUpdateRequestedStateInstalledImage = `UPDATE RequestedAppStates SET installed_image = ?, installed_image_version = ? WHERE app_key = ? AND stage = ?` diff --git a/src/persistence/update-scripts/single-installed_image-col.sql b/src/persistence/update-scripts/single-installed_image-col.sql new file mode 100644 index 0000000..ca3a355 --- /dev/null +++ b/src/persistence/update-scripts/single-installed_image-col.sql @@ -0,0 +1 @@ +ALTER TABLE RequestedAppStates ADD COLUMN installed_image TEXT \ No newline at end of file diff --git a/src/persistence/update-scripts/single-installed_image_version-col.sql b/src/persistence/update-scripts/single-installed_image_version-col.sql new file mode 100644 index 0000000..a7da144 --- /dev/null +++ b/src/persistence/update-scripts/single-installed_image_version-col.sql @@ -0,0 +1 @@ +ALTER TABLE RequestedAppStates ADD COLUMN installed_image_version TEXT \ No newline at end of file diff --git a/src/persistence/update-scripts/single-new_image_name-col.sql b/src/persistence/update-scripts/single-new_image_name-col.sql new file mode 100644 index 0000000..ed27ae1 --- /dev/null +++ b/src/persistence/update-scripts/single-new_image_name-col.sql @@ -0,0 +1 @@ +ALTER TABLE RequestedAppStates ADD COLUMN new_image_name TEXT \ No newline at end of file diff --git a/src/persistence/update-scripts/single-present_image_name-col.sql b/src/persistence/update-scripts/single-present_image_name-col.sql new file mode 100644 index 0000000..9c6e6ed --- /dev/null +++ b/src/persistence/update-scripts/single-present_image_name-col.sql @@ -0,0 +1 @@ +ALTER TABLE RequestedAppStates ADD COLUMN present_image_name TEXT \ No newline at end of file diff --git a/src/store/app_store.go b/src/store/app_store.go index ba98a2c..abfba9e 100644 --- a/src/store/app_store.go +++ b/src/store/app_store.go @@ -3,6 +3,7 @@ package store import ( "context" "encoding/json" + "errors" "fmt" "reagent/common" "reagent/errdefs" @@ -151,6 +152,19 @@ func (am *AppStore) UpdateLocalRequestedState(payload common.TransitionPayload) return am.database.UpsertRequestedStateChange(payload) } +// SetInstalledImage records the reference the device really pulled or ran +// version of the app under (TransitionPayload.InstalledImage). Best effort: a +// database that cannot record it leaves the agent with the other names. +func (am *AppStore) SetInstalledImage(appKey uint64, stage common.Stage, version string, ref string) error { + recorder, ok := am.database.(interface { + SetInstalledImage(appKey uint64, stage common.Stage, version string, ref string) error + }) + if !ok { + return errors.New("the database records no installed image") + } + return recorder.SetInstalledImage(appKey, stage, version, ref) +} + func (am *AppStore) GetRegistryToken(callerID uint64) (string, error) { ctx := context.Background() args := []interface{}{common.Dict{"callerID": callerID}} @@ -236,6 +250,19 @@ func (am *AppStore) UpdateRemoteAppState(ctx context.Context, app *common.App, s "release_build": app.ReleaseBuild, "updateStatus": app.UpdateStatus, }} + // A release build's report names what it pushed, where that is known; + // a backend that does not read it ignores the key. + if stateToSet == common.PUBLISHED { + app.StateLock.Lock() + if len(app.PushedDigests) > 0 { + pushed := make(map[string]string, len(app.PushedDigests)) + for ref, digest := range app.PushedDigests { + pushed[ref] = digest + } + payload[0].(common.Dict)["pushed_digests"] = pushed + } + app.StateLock.Unlock() + } _, err := am.Messenger.Call(ctx, topics.SetActualAppOnDeviceState, payload, nil, nil, nil) if err != nil { @@ -302,6 +329,9 @@ func (am *AppStore) FetchRequestedAppStates() ([]common.TransitionPayload, error payload.DeviceOwnerAccountKey = uint64(deviceSyncState.DeviceOwnerAccountKey) payload.RequestUpdate = deviceSyncState.RequestUpdate payload.PresentVersion = deviceSyncState.PresentVersion + payload.Architecture = deviceSyncState.Architecture + payload.PresentImageName = deviceSyncState.PresentImageName + payload.NewImageName = deviceSyncState.NewImageName payload.DockerCompose = deviceSyncState.DockerCompose payload.NewDockerCompose = deviceSyncState.NewDockerCompose payload.Privileged = deviceSyncState.Privileged diff --git a/src/store/app_store_image_names_test.go b/src/store/app_store_image_names_test.go new file mode 100644 index 0000000..19e8ab4 --- /dev/null +++ b/src/store/app_store_image_names_test.go @@ -0,0 +1,84 @@ +package store + +import ( + "testing" + + "reagent/common" + "reagent/messenger" + "reagent/messenger/topics" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The sync answer names the app's image for the present and the newest +// version; a value that is no string is left out, the rest of the answer is +// taken. +func TestFetchRequestedAppStatesTakesTheImageNames(t *testing.T) { + st, msg := newTestStore(t) + + msg.SetCallResponse(string(topics.GetRequestedAppStates), messenger.Result{ + Arguments: []interface{}{[]interface{}{ + map[string]interface{}{ + "app_key": 1953, "app_name": "MyApp", "stage": "PROD", + "current_state": "RUNNING", "target_state": "RUNNING", + "present_version": "1.0.0", "newest_version": "2.0.0", + "present_image_name": "prod_amd64_1953_myapp:1.0.0", + "architecture": "armv7", + "new_image_name": "prod_1953_myapp:2.0.0", + }, + map[string]interface{}{ + "app_key": 1954, "app_name": "Other", "stage": "PROD", + "current_state": "RUNNING", "target_state": "RUNNING", + "present_version": "1.0.0", "newest_version": "1.0.0", + "present_image_name": 17, + }, + }}, + }, nil) + + payloads, err := st.FetchRequestedAppStates() + require.NoError(t, err) + require.Len(t, payloads, 2) + assert.Equal(t, "prod_amd64_1953_myapp:1.0.0", payloads[0].PresentImageName) + assert.Equal(t, "prod_1953_myapp:2.0.0", payloads[0].NewImageName) + assert.Equal(t, "armv7", payloads[0].Architecture) + assert.Empty(t, payloads[1].PresentImageName) + assert.Equal(t, "1.0.0", payloads[1].PresentVersion, "the rest of the answer is taken") +} + +// The PUBLISHED report of a release build names what it pushed +// (pushed_digests), where that is known; no other report does. +func TestUpdateRemoteAppStateReportsThePushedDigests(t *testing.T) { + pushed := map[string]string{ + "registry.example/apps/prod_arm64_12_demo:1.0.0": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + } + report := func(t *testing.T, digests map[string]string, state common.AppState) common.Dict { + t.Helper() + st, msg := newTestStore(t) + app := &common.App{AppKey: 12, AppName: "demo", Stage: common.DEV, ReleaseBuild: true, PushedDigests: digests} + require.NoError(t, st.UpdateRemoteAppState(t.Context(), app, state)) + calls := msg.GetCallCalls() + require.NotEmpty(t, calls) + dict, ok := calls[len(calls)-1].Args[0].(common.Dict) + require.True(t, ok) + return dict + } + + t.Run("published with digests", func(t *testing.T) { + dict := report(t, pushed, common.PUBLISHED) + assert.Equal(t, pushed, dict["pushed_digests"]) + }) + t.Run("published, nothing known: the key is absent", func(t *testing.T) { + dict := report(t, nil, common.PUBLISHED) + _, found := dict["pushed_digests"] + assert.False(t, found) + dict = report(t, map[string]string{}, common.PUBLISHED) + _, found = dict["pushed_digests"] + assert.False(t, found) + }) + t.Run("another state never carries them", func(t *testing.T) { + dict := report(t, pushed, common.PUBLISHING) + _, found := dict["pushed_digests"] + assert.False(t, found) + }) +} From 29cb7bbd52278b8cad4dffece897e33743ec3dc4 Mon Sep 17 00:00:00 2001 From: Marko Petzold Date: Sat, 28 Nov 2026 09:35:16 +0100 Subject: [PATCH 2/5] release device-agent v1.6.21 --- availableVersions.json | 8 ++++---- src/release/version.txt | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/availableVersions.json b/availableVersions.json index 42aa4d9..93a2344 100644 --- a/availableVersions.json +++ b/availableVersions.json @@ -1,6 +1,6 @@ { - "production": "1.6.20", - "test": "1.6.20", - "local": "1.6.20", - "all": "1.6.20" + "production": "1.6.21", + "test": "1.6.21", + "local": "1.6.21", + "all": "1.6.21" } diff --git a/src/release/version.txt b/src/release/version.txt index cfbf4cb..d003414 100644 --- a/src/release/version.txt +++ b/src/release/version.txt @@ -1 +1 @@ -1.6.20 \ No newline at end of file +1.6.21 \ No newline at end of file From 37c9e5ada64d3229bb79a1d806df6ee2a1d56fda Mon Sep 17 00:00:00 2001 From: Marko Petzold Date: Sat, 28 Nov 2026 10:07:01 +0100 Subject: [PATCH 3/5] Implement releaseBuildRepository function and add unit tests for image naming logic --- src/apps/publish_app.go | 40 ++++++++++++++++--- src/apps/release_build_image_test.go | 58 ++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 5 deletions(-) create mode 100644 src/apps/release_build_image_test.go diff --git a/src/apps/publish_app.go b/src/apps/publish_app.go index f70c810..261c6ad 100644 --- a/src/apps/publish_app.go +++ b/src/apps/publish_app.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "reagent/common" + "reagent/config" "reagent/container" "reagent/errdefs" "time" @@ -33,11 +34,11 @@ func (sm *StateMachine) publishApp(payload common.TransitionPayload, app *common return err } - // Pushed under the agent's own name, prod___:: the backend computes exactly this from the - // device's agent_architecture. The platform's names (PresentImageName, - // NewImageName) are for pulling and never used here. - prodImage := fmt.Sprintf("%s:%s", payload.RegistryImageName.Prod, payload.Version) + // Pushed under the per-architecture name of the platform the build is + // for (releaseBuildRepository): the backend expects exactly that name, + // and the registry's token allows no other. The platform's names + // (PresentImageName, NewImageName) are for pulling and never used here. + prodImage := fmt.Sprintf("%s:%s", releaseBuildRepository(sm.reswarmConfig(), payload), payload.Version) tagContext, cancel := context.WithTimeout(context.Background(), time.Second*30) defer cancel() @@ -299,3 +300,32 @@ func (sm *StateMachine) rehostSourceImages(payload common.TransitionPayload) (ma return pushedDigests, nil } + +// releaseBuildRepository is the repository a release build's single image is +// pushed under: prod___ in the device's +// registry and main repository, for the architecture the build is for. That +// is the device's architecture as the platform stores it +// (TransitionPayload.Architecture, the sync answer's architecture: what +// dockerfileArch builds for, and what the platform registers the build as), +// where the platform names one that apps are built for. It is the +// architecture the agent was built for on every device whose apps are +// matched by it, so the name is the agent's own (RegistryImageName.Prod), +// as it always was. It differs where the platform matches the device's apps +// by its Docker engine: an arm64 agent next to a 32-bit engine builds armv7 +// images, and pushed under the agent's own name they would replace the +// arm64 image of the same version under the tag arm64 devices pull, while +// armv7 devices would find none under theirs. From an older backend, a +// stored state or for a value such as ARM (no architecture named), and +// without a configuration to form the name with: the agent's own name. +// (A Compose build pushes the names its Compose file carries, which the +// platform wrote for the same architecture.) +func releaseBuildRepository(rc *config.ReswarmConfig, payload common.TransitionPayload) string { + switch payload.Architecture { + case "amd64", "arm64", "armv7", "armv6", "armv5": + if rc != nil { + return common.BuildRegistryImageName(rc.DockerRegistryURL, rc.DockerMainRepository, + common.BuildImageName(common.PROD, payload.Architecture, payload.AppKey, payload.AppName)) + } + } + return payload.RegistryImageName.Prod +} diff --git a/src/apps/release_build_image_test.go b/src/apps/release_build_image_test.go new file mode 100644 index 0000000..2bf037d --- /dev/null +++ b/src/apps/release_build_image_test.go @@ -0,0 +1,58 @@ +package apps + +import ( + "reagent/common" + "reagent/config" + "testing" + + "github.com/stretchr/testify/assert" +) + +// The repository a release build's single image is pushed under: the name +// per architecture of the platform the build is for, which is the agent's own +// name on every device whose apps are matched by the agent's architecture. +func TestReleaseBuildRepository(t *testing.T) { + rc := &config.ReswarmConfig{DockerRegistryURL: "registry.test/", DockerMainRepository: "apps/"} + // An arm64 agent: the names it forms itself. + own := common.TransitionPayload{ + AppKey: 7, + AppName: "MyApp", + Stage: common.DEV, + RegistryImageName: common.StageBasedResult{ + Dev: "registry.test/apps/dev_arm64_7_myapp", + Prod: "registry.test/apps/prod_arm64_7_myapp", + }, + } + + t.Run("a device whose apps are matched by the agent's architecture pushes under the agent's own name, as always", func(t *testing.T) { + payload := own + payload.Architecture = "arm64" + assert.Equal(t, own.RegistryImageName.Prod, releaseBuildRepository(rc, payload)) + }) + + t.Run("a device whose apps are matched by its Docker engine pushes under the engine's architecture", func(t *testing.T) { + // arm64 agent, 32-bit engine: the platform says armv7, the build is an + // armv7 image, and prod_arm64_... is the arm64 platform's tag. + payload := own + payload.Architecture = "armv7" + got := releaseBuildRepository(rc, payload) + assert.Equal(t, "registry.test/apps/prod_armv7_7_myapp", got) + assert.NotEqual(t, own.RegistryImageName.Prod, got, "negative control: the agent's own name is another") + // the same architecture the build's Dockerfile is chosen for + assert.Equal(t, "armv7", dockerfileArch(payload)) + }) + + t.Run("without an architecture from the platform, or one no app is built for: the agent's own name", func(t *testing.T) { + for _, architecture := range []string{"", "ARM", "arm", "riscv64"} { + payload := own + payload.Architecture = architecture + assert.Equal(t, own.RegistryImageName.Prod, releaseBuildRepository(rc, payload), architecture) + } + }) + + t.Run("without a configuration to form the name with: the agent's own name", func(t *testing.T) { + payload := own + payload.Architecture = "armv7" + assert.Equal(t, own.RegistryImageName.Prod, releaseBuildRepository(nil, payload)) + }) +} From eb6960ea982258c26b9798c74785dc09f916705e Mon Sep 17 00:00:00 2001 From: Marko Petzold Date: Sat, 28 Nov 2026 10:16:38 +0100 Subject: [PATCH 4/5] Refactor tarPath construction to ensure compatibility across platforms --- src/apps/app_images_test.go | 3 ++- src/apps/dockerfile_arch_test.go | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/apps/app_images_test.go b/src/apps/app_images_test.go index 5740ddc..015cd78 100644 --- a/src/apps/app_images_test.go +++ b/src/apps/app_images_test.go @@ -550,7 +550,8 @@ func TestReleaseBuildPushesTheAgentsOwnName(t *testing.T) { pushed := "registry.test/apps/prod_" + imgOwnArch() + "_1953_myapp:3.0.0" require.Equal(t, "registry.test/apps/dev_"+imgOwnArch()+"_1953_myapp", payload.RegistryImageName.Dev) - tarPath := filepath.Join(cfg.CommandLineArguments.AppsBuildDir, payload.AppName+"."+cfg.CommandLineArguments.CompressedBuildExtension) + // the build joins with "/" (build_app.go), on Windows too + tarPath := cfg.CommandLineArguments.AppsBuildDir + "/" + payload.AppName + "." + cfg.CommandLineArguments.CompressedBuildExtension imgWriteTgz(t, tarPath, map[string]string{"Dockerfile": "FROM scratch\n"}) mc.EXPECT().Build(mock.Anything, tarPath, mock.Anything).Return(fwdDockerStream(), nil).Once() diff --git a/src/apps/dockerfile_arch_test.go b/src/apps/dockerfile_arch_test.go index a4286e8..742cce2 100644 --- a/src/apps/dockerfile_arch_test.go +++ b/src/apps/dockerfile_arch_test.go @@ -2,7 +2,6 @@ package apps import ( "context" - "path/filepath" "testing" dockerbuild "github.com/docker/docker/api/types/build" @@ -44,7 +43,8 @@ func TestBuildUsesTheDockerfileOfThePlatformsArchitecture(t *testing.T) { app := seedApp(t, st, "archapp", common.REMOVED, common.DEV) payload := execPayload("archapp", common.BUILT, common.DEV) payload.Architecture = architecture - tarPath := filepath.Join(cfg.CommandLineArguments.AppsBuildDir, payload.AppName+"."+cfg.CommandLineArguments.CompressedBuildExtension) + // the build joins with "/" (build_app.go), on Windows too + tarPath := cfg.CommandLineArguments.AppsBuildDir + "/" + payload.AppName + "." + cfg.CommandLineArguments.CompressedBuildExtension imgWriteTgz(t, tarPath, files) var used string From c32f11c72a1ef781b58c196fe73f5bd4a99dd987 Mon Sep 17 00:00:00 2001 From: Marko Petzold Date: Sat, 28 Nov 2026 10:30:14 +0100 Subject: [PATCH 5/5] Improve unreachableFrps function to select a free loopback port dynamically for tests --- src/tunnel/capability_test.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/tunnel/capability_test.go b/src/tunnel/capability_test.go index f7dfa09..be5ec78 100644 --- a/src/tunnel/capability_test.go +++ b/src/tunnel/capability_test.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "io" + "math/rand/v2" "net" "net/http" "net/http/httptest" @@ -249,12 +250,25 @@ func plainProbe(m *FrpTunnelManager) { // unreachableFrps points the manager at a port nothing is listening on, standing // in for the appliance tunnel profile being switched off. +// +// The port lies below every system's ephemeral range (Linux from 32768, +// macOS and Windows from 49152): a port freed from a ":0" listener goes back +// to that range, where a listener of a test running in parallel (go test +// ./... runs packages at once) can take it and make the probe succeed. func unreachableFrps(t *testing.T, m *FrpTunnelManager) { t.Helper() - ln, err := net.Listen("tcp", "127.0.0.1:0") - require.NoError(t, err) - port := ln.Addr().(*net.TCPAddr).Port - require.NoError(t, ln.Close()) // hand the port back before anyone can use it + port := 0 + for range 50 { + candidate := 20000 + rand.IntN(10000) + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", candidate)) + if err != nil { + continue // in use + } + require.NoError(t, ln.Close()) + port = candidate + break + } + require.NotZero(t, port, "no free loopback port below the ephemeral range") m.configBuilder.yamlConfig.ServerAddr = "127.0.0.1" m.configBuilder.yamlConfig.ServerPort = port