diff --git a/Makefile b/Makefile index a62476df..6e2c4beb 100644 --- a/Makefile +++ b/Makefile @@ -235,10 +235,24 @@ lint: .PHONY: licenses licenses: GOOS=linux $(go-licenses) check ./... - GOOS=linux $(go-licenses) report ./... \ - --ignore github.com/pgEdge/control-plane \ - --ignore github.com/eclipse/paho.golang \ - --template=NOTICE.txt.tmpl > NOTICE.txt + # go-licenses looks up the source repository of modules with vanity import + # paths (e.g. go.etcd.io) over the network, and writes "Unknown" for the + # license URL when a lookup fails. Retry so that a transient network error + # doesn't change NOTICE.txt. + @for attempt in 1 2 3; do \ + GOOS=linux $(go-licenses) report ./... \ + --ignore github.com/pgEdge/control-plane \ + --ignore github.com/eclipse/paho.golang \ + --template=NOTICE.txt.tmpl > NOTICE.txt || exit 1; \ + grep -q '(Unknown)' NOTICE.txt || break; \ + echo "NOTICE.txt has unresolved license URLs (attempt $$attempt of 3)"; \ + [ $$attempt -lt 3 ] && sleep 10; \ + done; \ + if grep -q '(Unknown)' NOTICE.txt; then \ + echo "failed to resolve the license URLs of:"; \ + grep -B3 '(Unknown)' NOTICE.txt | grep '^\* Name:' | sort -u; \ + exit 1; \ + fi # go-licenses duplicates the package subpath before "LICENSE" for # opentelemetry-go's per-submodule tags (e.g. .../blob/metric/v1.44.0/metric/LICENSE), # but the LICENSE file only exists once at the repo root, so those links 404. @@ -252,7 +266,7 @@ licenses: licenses-ci: licenses @sort NOTICE.txt > ./licenses-ci-local.txt @git show HEAD:NOTICE.txt | sort > ./licenses-ci-upstream.txt - @if ! diff ./licenses-ci-local.txt ./licenses-ci-upstream.txt > /dev/null; then \ + @if ! diff ./licenses-ci-upstream.txt ./licenses-ci-local.txt; then \ echo "Please commit the updated NOTICE.txt file via 'make licenses'."; \ rm ./licenses-ci-local.txt ./licenses-ci-upstream.txt; \ exit 1; \ diff --git a/changes/unreleased/Changed-20261130-000000.yaml b/changes/unreleased/Changed-20261130-000000.yaml new file mode 100644 index 00000000..0c996e47 --- /dev/null +++ b/changes/unreleased/Changed-20261130-000000.yaml @@ -0,0 +1,3 @@ +kind: Changed +body: Creating or updating a database that uses an unreachable host now fails right away with an error that names the host, instead of after a 5 minute timeout. +time: 2026-11-30T00:00:00.000000+00:00 diff --git a/changes/unreleased/Fixed-20261130-000000.yaml b/changes/unreleased/Fixed-20261130-000000.yaml new file mode 100644 index 00000000..c3fac5d2 --- /dev/null +++ b/changes/unreleased/Fixed-20261130-000000.yaml @@ -0,0 +1,3 @@ +kind: Fixed +body: On hosts that use the systemd orchestrator, creating or updating a database now checks each host's installed service packages at request time and reports every service that can't run, with the package to install. Previously, only the first problem was reported, as `does not support version `, and a package installed or removed in the last 15 seconds could give the wrong result or leave the database in a failed state. +time: 2026-11-30T00:00:00.000000+00:00 diff --git a/e2e/fixture_test.go b/e2e/fixture_test.go index 9c63efea..58812178 100644 --- a/e2e/fixture_test.go +++ b/e2e/fixture_test.go @@ -83,8 +83,9 @@ type TestConfig struct { Hosts map[string]TestConfigHost `yaml:"hosts"` S3 TestConfigS3 `yaml:"s3"` // ServicePackagesNotInstalled is true when the fixture's hosts don't have - // the PostgREST and MCP server packages installed, such as systemd hosts - // that only have the community Postgres packages. + // the PostgREST, MCP server, and RAG server packages installed, such as + // systemd hosts that only have the community Postgres packages. Fixtures + // that set it to false must install all three packages. ServicePackagesNotInstalled bool `yaml:"service_packages_not_installed"` } diff --git a/e2e/rag_service_test.go b/e2e/rag_service_test.go index c0c684d5..5b756074 100644 --- a/e2e/rag_service_test.go +++ b/e2e/rag_service_test.go @@ -664,7 +664,7 @@ func TestProvisionRAGServiceUnsupportedVersion(t *testing.T) { require.Error(t, err, "CreateDatabase should reject an unsupported service version") assert.ErrorIs(t, err, client.ErrInvalidInput, "Error should be invalid input") assert.Nil(t, createResp, "CreateDatabase should not return a response") - assert.Contains(t, err.Error(), "does not support rag version 99.99.99", "Error should name the unsupported version") + assert.Contains(t, err.Error(), "version 99.99.99", "Error should name the unsupported version") t.Logf("CreateDatabase rejected as expected: %s", err) t.Log("RAG unsupported version test completed successfully") diff --git a/e2e/service_provisioning_test.go b/e2e/service_provisioning_test.go index a293c4e9..8e34c4a1 100644 --- a/e2e/service_provisioning_test.go +++ b/e2e/service_provisioning_test.go @@ -440,7 +440,7 @@ func TestProvisionMCPServiceUnsupportedVersion(t *testing.T) { require.Error(t, err, "CreateDatabase should reject an unsupported service version") assert.ErrorIs(t, err, client.ErrInvalidInput, "Error should be invalid input") assert.Nil(t, createResp, "CreateDatabase should not return a response") - assert.Contains(t, err.Error(), "does not support mcp version 99.99.99", "Error should name the unsupported version") + assert.Contains(t, err.Error(), "version 99.99.99", "Error should name the unsupported version") t.Logf("CreateDatabase rejected as expected: %s", err) @@ -556,7 +556,7 @@ func TestProvisionMCPServiceRecovery(t *testing.T) { }) require.Error(t, err, "UpdateDatabase should reject an unsupported service version") assert.ErrorIs(t, err, client.ErrInvalidInput, "Error should be invalid input") - assert.Contains(t, err.Error(), "does not support mcp version 99.99.99", "Error should name the unsupported version") + assert.Contains(t, err.Error(), "version 99.99.99", "Error should name the unsupported version") t.Logf("UpdateDatabase rejected as expected: %s", err) // The rejected update must not have been applied diff --git a/server/internal/api/apiv1/post_init_handlers.go b/server/internal/api/apiv1/post_init_handlers.go index f2f97a62..ee094d9c 100644 --- a/server/internal/api/apiv1/post_init_handlers.go +++ b/server/internal/api/apiv1/post_init_handlers.go @@ -354,6 +354,10 @@ func (s *PostInitHandlers) CreateDatabase(ctx context.Context, req *api.CreateDa return nil, makeInvalidInputErr(fmt.Errorf("failed to validate database spec: %w", err)) } + if err := s.validateSpecHostsResponding(ctx, spec); err != nil { + return nil, err + } + // Full validation on create (no PreviousSpec, not delta mode). input := &workflows.ValidateSpecInput{ DatabaseID: spec.DatabaseID, @@ -384,6 +388,26 @@ func (s *PostInitHandlers) CreateDatabase(ctx context.Context, req *api.CreateDa }, nil } +// validateSpecHostsResponding fails fast if any host that the spec uses is +// unreachable, rather than waiting for the ValidateSpec workflow to time out. +func (s *PostInitHandlers) validateSpecHostsResponding(ctx context.Context, spec *database.Spec) error { + hostIDs := ds.NewSet[string]() + for _, node := range spec.Nodes { + hostIDs.Add(node.HostIDs...) + } + for _, svc := range spec.Services { + hostIDs.Add(svc.HostIDs...) + } + hosts, err := s.hostSvc.GetHosts(ctx, hostIDs.ToSlice()) + if err != nil { + return apiErr(fmt.Errorf("failed to get hosts: %w", err)) + } + if err := validateHostsResponding(hosts); err != nil { + return makeInvalidInputErr(err) + } + return nil +} + func (s *PostInitHandlers) GetDatabase(ctx context.Context, req *api.GetDatabasePayload) (*api.Database, error) { databaseID, err := dbIdentToString(req.DatabaseID) if err != nil { @@ -454,6 +478,9 @@ func (s *PostInitHandlers) UpdateDatabase(ctx context.Context, req *api.UpdateDa if err != nil { return nil, makeInvalidInputErr(fmt.Errorf("failed to validate database spec: %w", err)) } + if err := s.validateSpecHostsResponding(ctx, spec); err != nil { + return nil, err + } input := &workflows.ValidateSpecInput{ DatabaseID: spec.DatabaseID, diff --git a/server/internal/api/apiv1/validate.go b/server/internal/api/apiv1/validate.go index 02b5529e..c1ff5f68 100644 --- a/server/internal/api/apiv1/validate.go +++ b/server/internal/api/apiv1/validate.go @@ -358,6 +358,23 @@ func validateDatabaseUpdate(old *database.Spec, new *api.DatabaseSpec) error { return errors.Join(errs...) } +// validateHostsResponding rejects a spec that uses an unreachable host. The +// ValidateSpec workflow runs on every host that the spec uses, so it would +// otherwise wait until it times out for a host that isn't running. +func validateHostsResponding(hosts []*host.Host) error { + var unreachable []string + for _, h := range hosts { + if h.Status != nil && h.Status.State == host.HostStateUnreachable { + unreachable = append(unreachable, h.ID) + } + } + if len(unreachable) == 0 { + return nil + } + slices.Sort(unreachable) + return fmt.Errorf("unable to validate the database spec on unreachable hosts: %s. check that the Control Plane server is running on each of them", strings.Join(unreachable, ", ")) +} + // validatePrimaryNotRemoved rejects updates that remove a node's current // primary instance while keeping the node. Patroni does not switch over when // the primary is removed, so the node would be unavailable for writes until a diff --git a/server/internal/api/apiv1/validate_test.go b/server/internal/api/apiv1/validate_test.go index 326b3990..9068701c 100644 --- a/server/internal/api/apiv1/validate_test.go +++ b/server/internal/api/apiv1/validate_test.go @@ -8,6 +8,7 @@ import ( "github.com/pgEdge/control-plane/server/internal/config" "github.com/pgEdge/control-plane/server/internal/database" "github.com/pgEdge/control-plane/server/internal/ds" + "github.com/pgEdge/control-plane/server/internal/host" "github.com/pgEdge/control-plane/server/internal/utils" "github.com/stretchr/testify/assert" ) @@ -2806,3 +2807,47 @@ func TestValidateDatabaseUpdate_NullServiceEntry(t *testing.T) { }) assert.ErrorContains(t, err, "services[0]: service must not be null") } + +func TestValidateHostsResponding(t *testing.T) { + withState := func(id string, state host.HostState) *host.Host { + return &host.Host{ID: id, Status: &host.HostStatus{State: state}} + } + for _, tc := range []struct { + name string + hosts []*host.Host + expectedErr string + }{ + { + name: "all healthy", + hosts: []*host.Host{withState("host-1", host.HostStateHealthy), withState("host-2", host.HostStateHealthy)}, + }, + { + // A degraded host's Control Plane is still running, so it can + // validate the spec. + name: "degraded", + hosts: []*host.Host{withState("host-1", host.HostStateDegraded)}, + }, + { + name: "no status", + hosts: []*host.Host{{ID: "host-1"}}, + }, + { + name: "unreachable", + hosts: []*host.Host{ + withState("host-3", host.HostStateUnreachable), + withState("host-1", host.HostStateHealthy), + withState("host-2", host.HostStateUnreachable), + }, + expectedErr: "unable to validate the database spec on unreachable hosts: host-2, host-3. check that the Control Plane server is running on each of them", + }, + } { + t.Run(tc.name, func(t *testing.T) { + err := validateHostsResponding(tc.hosts) + if tc.expectedErr != "" { + assert.EqualError(t, err, tc.expectedErr) + } else { + assert.NoError(t, err) + } + }) + } +} diff --git a/server/internal/database/apply_upgrade_test.go b/server/internal/database/apply_upgrade_test.go index 077fcdc9..022311c9 100644 --- a/server/internal/database/apply_upgrade_test.go +++ b/server/internal/database/apply_upgrade_test.go @@ -62,6 +62,9 @@ func (s *stubOrchestrator) ExecuteInstanceCommand(context.Context, io.Writer, st func (s *stubOrchestrator) ValidateInstanceSpecs(context.Context, []*database.InstanceSpecChange) ([]*database.ValidationResult, error) { return nil, nil } +func (s *stubOrchestrator) ValidateServiceSpecs(context.Context, []*database.ServiceSpec) (map[string]string, []string) { + return nil, nil +} func (s *stubOrchestrator) StopInstance(context.Context, string) error { return nil } func (s *stubOrchestrator) StartInstance(context.Context, string) error { return nil } func (s *stubOrchestrator) NodeDSN(context.Context, *resource.Context, string, string, string) (*postgres.DSN, error) { diff --git a/server/internal/database/orchestrator.go b/server/internal/database/orchestrator.go index 6c03e6d5..e57cb5ba 100644 --- a/server/internal/database/orchestrator.go +++ b/server/internal/database/orchestrator.go @@ -183,6 +183,10 @@ type Orchestrator interface { CreatePgBackRestBackup(ctx context.Context, w io.Writer, spec *InstanceSpec, options *pgbackrest.BackupOptions) error ExecuteInstanceCommand(ctx context.Context, w io.Writer, databaseID, instanceID string, args ...string) error ValidateInstanceSpecs(ctx context.Context, changes []*InstanceSpecChange) ([]*ValidationResult, error) + // ValidateServiceSpecs checks that the given services can run on this + // host. It returns the version that each valid service will run, keyed by + // service ID, and one error message per service that can't run. + ValidateServiceSpecs(ctx context.Context, services []*ServiceSpec) (map[string]string, []string) StopInstance(ctx context.Context, instanceID string) error StartInstance(ctx context.Context, instanceID string) error NodeDSN(ctx context.Context, rc *resource.Context, nodeName string, fromInstanceID string, dbName string) (*postgres.DSN, error) diff --git a/server/internal/database/service.go b/server/internal/database/service.go index a7d24176..79190408 100644 --- a/server/internal/database/service.go +++ b/server/internal/database/service.go @@ -685,7 +685,14 @@ func validateServiceHosts(services []*ServiceSpec, hostsByID map[string]*host.Ho // validate against it. continue } - if h.Orchestrator != config.OrchestratorSystemD && svc.swarmImageOverride() != "" { + if h.Orchestrator == config.OrchestratorSystemD { + // This host record can be up to a host monitor interval old, + // so the ValidateSpec workflow checks the installed services + // on the host itself, including that the hosts agree on the + // version that "latest" resolves to. + continue + } + if svc.swarmImageOverride() != "" { // A user-specified image bypasses the version manifest. continue } diff --git a/server/internal/database/spec_internal_test.go b/server/internal/database/spec_internal_test.go index e63e6a8b..9c935977 100644 --- a/server/internal/database/spec_internal_test.go +++ b/server/internal/database/spec_internal_test.go @@ -165,6 +165,18 @@ func TestValidateServiceHosts(t *testing.T) { SupportedServices: map[string][]string{"postgrest": {"14.5"}}, DefaultServiceVersions: map[string]string{"postgrest": "14.5"}, }, + "host-systemd-2": { + ID: "host-systemd-2", + Orchestrator: config.OrchestratorSystemD, + SupportedServices: map[string][]string{"postgrest": {"14.10"}}, + DefaultServiceVersions: map[string]string{"postgrest": "14.10"}, + }, + "host-systemd-3": { + ID: "host-systemd-3", + Orchestrator: config.OrchestratorSystemD, + SupportedServices: map[string][]string{}, + DefaultServiceVersions: map[string]string{}, + }, } postgrest := func(version string, hostIDs ...string) *ServiceSpec { return &ServiceSpec{ @@ -212,14 +224,32 @@ func TestValidateServiceHosts(t *testing.T) { }(), }, { - name: "image override doesn't bypass validation on systemd hosts", + // The ValidateSpec workflow checks the installed version on the + // host itself, since the host record can be out of date. + name: "systemd hosts check the installed version on the host", service: func() *ServiceSpec { svc := postgrest("99.0", "host-systemd") svc.Port = utils.PointerTo(0) - svc.OrchestratorOpts = &OrchestratorOpts{Swarm: &SwarmOpts{Image: "registry.example.com/postgrest:dev"}} return svc }(), - expectedErr: `service "api": host host-systemd does not support postgrest version 99.0`, + }, + { + name: "systemd host without the service checks it on the host", + service: func() *ServiceSpec { + svc := postgrest("latest", "host-systemd", "host-systemd-3") + svc.Port = utils.PointerTo(0) + return svc + }(), + }, + { + // The ValidateSpec workflow compares the installed versions + // across hosts, since these host records can be out of date. + name: "systemd hosts check latest agreement on the hosts", + service: func() *ServiceSpec { + svc := postgrest("latest", "host-systemd", "host-systemd-2") + svc.Port = utils.PointerTo(0) + return svc + }(), }, { name: "host without supported services is not validated", diff --git a/server/internal/orchestrator/swarm/orchestrator.go b/server/internal/orchestrator/swarm/orchestrator.go index 5be2b57d..d178d8da 100644 --- a/server/internal/orchestrator/swarm/orchestrator.go +++ b/server/internal/orchestrator/swarm/orchestrator.go @@ -1131,6 +1131,12 @@ func (o *Orchestrator) ExecuteInstanceCommand(ctx context.Context, w io.Writer, return PostgresContainerExec(ctx, w, o.docker, instanceID, args) } +// ValidateServiceSpecs is a no-op, since the API server validates swarm +// services against the version manifest, which every host shares. +func (o *Orchestrator) ValidateServiceSpecs(context.Context, []*database.ServiceSpec) (map[string]string, []string) { + return nil, nil +} + func (o *Orchestrator) ValidateInstanceSpecs(ctx context.Context, changes []*database.InstanceSpecChange) ([]*database.ValidationResult, error) { results := make([]*database.ValidationResult, 0, len(changes)*3) diff --git a/server/internal/orchestrator/systemd/postgrest_service.go b/server/internal/orchestrator/systemd/postgrest_service.go index 36e70566..441d8e62 100644 --- a/server/internal/orchestrator/systemd/postgrest_service.go +++ b/server/internal/orchestrator/systemd/postgrest_service.go @@ -20,6 +20,8 @@ const ( // postgrestUser is the Linux user that PostgREST units run as. The // pgedge-postgrest package creates it as the shared pgEdge services user. postgrestUser = "pgedge" + // postgrestPackageName is the package that installs PostgREST. + postgrestPackageName = "pgedge-postgrest" // postgrestConfigBaseDir holds one config directory per service instance. postgrestConfigBaseDir = "/etc/postgrest" // postgrestListenHost makes PostgREST listen on all IPv4 and IPv6 @@ -87,7 +89,7 @@ func (o *Orchestrator) generatePostgRESTInstanceResources(spec *database.Service return nil, err } - uid, gid, err := o.lookupServiceUser(postgrestUser, "pgedge-postgrest") + uid, gid, err := o.lookupServiceUser(postgrestUser, postgrestPackageName) if err != nil { return nil, err } diff --git a/server/internal/orchestrator/systemd/service.go b/server/internal/orchestrator/systemd/service.go index 2f75a78d..c5eae252 100644 --- a/server/internal/orchestrator/systemd/service.go +++ b/server/internal/orchestrator/systemd/service.go @@ -243,14 +243,50 @@ func (o *Orchestrator) installedServiceVersion(svc *database.ServiceSpec) (strin ctx, cancel := context.WithTimeout(context.Background(), serviceHealthCheckTimeout) defer cancel() - // A failure to detect another service type doesn't affect this one. installed, err := o.versionsProbe.InstalledServices(ctx) + return checkInstalledServiceVersion(svc, installed, err) +} + +// ValidateServiceSpecs checks the given services against the services that are +// installed on this host right now. It returns the installed version of each +// valid service, keyed by service ID, and one error message per service that +// can't run on this host. +func (o *Orchestrator) ValidateServiceSpecs(ctx context.Context, services []*database.ServiceSpec) (map[string]string, []string) { + ctx, cancel := context.WithTimeout(ctx, serviceHealthCheckTimeout) + defer cancel() + + installed, probeErr := o.versionsProbe.InstalledServices(ctx) + versions := map[string]string{} + var errs []string + for _, svc := range services { + version, err := checkInstalledServiceVersion(svc, installed, probeErr) + if err != nil { + errs = append(errs, fmt.Sprintf("service %q: %v", svc.ServiceID, err)) + continue + } + versions[svc.ServiceID] = version + } + return versions, errs +} + +// servicePackageNames maps each service type to the package that installs it. +var servicePackageNames = map[string]string{ + "postgrest": postgrestPackageName, + "mcp": mcpPackageName, + "rag": ragPackageName, +} + +func checkInstalledServiceVersion(svc *database.ServiceSpec, installed map[string]string, probeErr error) (string, error) { + // A failure to detect another service type doesn't affect this one. version, ok := installed[svc.ServiceType] switch { - case !ok && err != nil: - return "", fmt.Errorf("failed to get installed service versions: %w", err) + case !ok && probeErr != nil: + return "", fmt.Errorf("failed to get installed service versions: %w", probeErr) case !ok: - return "", fmt.Errorf("service type %q is not installed on this host", svc.ServiceType) + if pkg := servicePackageNames[svc.ServiceType]; pkg != "" { + return "", fmt.Errorf("%s is not installed on this host. install the %s package", svc.ServiceType, pkg) + } + return "", fmt.Errorf("%s is not installed on this host", svc.ServiceType) } if svc.Version != host.ServiceVersionLatest && svc.Version != version { return "", fmt.Errorf("%s version %s is installed on this host, but version %s was requested", svc.ServiceType, version, svc.Version) diff --git a/server/internal/orchestrator/systemd/service_test.go b/server/internal/orchestrator/systemd/service_test.go index 00a4b048..9beb1d8b 100644 --- a/server/internal/orchestrator/systemd/service_test.go +++ b/server/internal/orchestrator/systemd/service_test.go @@ -1,6 +1,9 @@ package systemd import ( + "context" + "errors" + "io" "net" "net/http" "net/http/httptest" @@ -8,8 +11,12 @@ import ( "testing" "time" + "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/pgEdge/control-plane/server/internal/config" + "github.com/pgEdge/control-plane/server/internal/database" ) func TestServiceServing(t *testing.T) { @@ -94,3 +101,92 @@ func TestServiceHealthCheckTimeouts(t *testing.T) { assert.Greater(t, serviceInstanceStatusTimeout, check.timeout, serviceType) } } + +func TestCheckInstalledServiceVersion(t *testing.T) { + installed := map[string]string{"postgrest": "14.18"} + for _, tc := range []struct { + name string + svc *database.ServiceSpec + probeErr error + expectedVersion string + expectedErr string + }{ + { + name: "latest", + svc: &database.ServiceSpec{ServiceType: "postgrest", Version: "latest"}, + expectedVersion: "14.18", + }, + { + name: "matching version", + svc: &database.ServiceSpec{ServiceType: "postgrest", Version: "14.18"}, + expectedVersion: "14.18", + }, + { + name: "different version", + svc: &database.ServiceSpec{ServiceType: "postgrest", Version: "14.5"}, + expectedErr: "postgrest version 14.18 is installed on this host, but version 14.5 was requested", + }, + { + name: "not installed", + svc: &database.ServiceSpec{ServiceType: "mcp", Version: "latest"}, + expectedErr: "mcp is not installed on this host. install the pgedge-postgres-mcp package", + }, + { + name: "not installed without a known package", + svc: &database.ServiceSpec{ServiceType: "other", Version: "latest"}, + expectedErr: "other is not installed on this host", + }, + { + name: "probe failure", + svc: &database.ServiceSpec{ServiceType: "rag", Version: "latest"}, + probeErr: errors.New("boom"), + expectedErr: "failed to get installed service versions: boom", + }, + { + name: "probe failure for another service", + svc: &database.ServiceSpec{ServiceType: "postgrest", Version: "latest"}, + probeErr: errors.New("boom"), + expectedVersion: "14.18", + }, + } { + t.Run(tc.name, func(t *testing.T) { + version, err := checkInstalledServiceVersion(tc.svc, installed, tc.probeErr) + if tc.expectedErr != "" { + assert.EqualError(t, err, tc.expectedErr) + return + } + require.NoError(t, err) + assert.Equal(t, tc.expectedVersion, version) + }) + } +} + +func TestValidateServiceSpecs(t *testing.T) { + const postgrestPath = "/usr/bin/postgrest" + + fsys := afero.NewMemMapFs() + require.NoError(t, afero.WriteFile(fsys, postgrestPath, nil, 0o755)) + probe, err := NewInstalledVersionsProbe( + func(_ context.Context, stdout, _ io.Writer, _ string, _ ...string) error { + _, err := stdout.Write([]byte("PostgREST 14.18\n")) + return err + }, + fsys, + config.SystemD{OSFamily: config.OSFamilyRedHat, PostgRESTPath: postgrestPath}, + ) + require.NoError(t, err) + o := &Orchestrator{versionsProbe: probe} + + versions, errs := o.ValidateServiceSpecs(t.Context(), []*database.ServiceSpec{ + {ServiceID: "api", ServiceType: "postgrest", Version: "latest"}, + {ServiceID: "old-api", ServiceType: "postgrest", Version: "14.5"}, + {ServiceID: "mcp-server", ServiceType: "mcp", Version: "latest"}, + {ServiceID: "rag", ServiceType: "rag", Version: "latest"}, + }) + assert.Equal(t, []string{ + `service "old-api": postgrest version 14.18 is installed on this host, but version 14.5 was requested`, + `service "mcp-server": mcp is not installed on this host. install the pgedge-postgres-mcp package`, + `service "rag": rag is not installed on this host. install the pgedge-rag-server2 package`, + }, errs) + assert.Equal(t, map[string]string{"api": "14.18"}, versions) +} diff --git a/server/internal/workflows/activities/validate_instance_specs.go b/server/internal/workflows/activities/validate_instance_specs.go index 21185e86..80b4bdc9 100644 --- a/server/internal/workflows/activities/validate_instance_specs.go +++ b/server/internal/workflows/activities/validate_instance_specs.go @@ -15,10 +15,15 @@ type ValidateInstanceSpecsInput struct { DatabaseID string `json:"database_id"` Specs []*database.InstanceSpec `json:"spec"` PreviousSpecs []*database.InstanceSpec `json:"previous_spec"` + Services []*database.ServiceSpec `json:"services,omitempty"` } type ValidateInstanceSpecsOutput struct { Results []*database.ValidationResult `json:"results"` + // ServiceVersions maps each valid service's ID to the version that it will + // run on this host. It's only set by orchestrators that check services on + // the host. + ServiceVersions map[string]string `json:"service_versions,omitempty"` } func (a *Activities) ExecuteValidateInstanceSpecs( @@ -75,9 +80,21 @@ func (a *Activities) ValidateInstanceSpecs(ctx context.Context, input *ValidateI if err != nil { return nil, fmt.Errorf("instance spec validation failed: %w", err) } + var serviceVersions map[string]string + if len(input.Services) > 0 { + var errs []string + serviceVersions, errs = a.Orchestrator.ValidateServiceSpecs(ctx, input.Services) + if len(errs) > 0 { + results = append(results, &database.ValidationResult{ + HostID: a.Config.HostID, + Errors: errs, + }) + } + } logger.Info("instance spec validation completed") return &ValidateInstanceSpecsOutput{ - Results: results, + Results: results, + ServiceVersions: serviceVersions, }, nil } diff --git a/server/internal/workflows/validate_spec.go b/server/internal/workflows/validate_spec.go index 85a18202..b8491234 100644 --- a/server/internal/workflows/validate_spec.go +++ b/server/internal/workflows/validate_spec.go @@ -3,10 +3,14 @@ package workflows import ( "errors" "fmt" + "maps" + "slices" + "strings" "github.com/cschleiden/go-workflows/workflow" "github.com/pgEdge/control-plane/server/internal/database" + "github.com/pgEdge/control-plane/server/internal/host" "github.com/pgEdge/control-plane/server/internal/workflows/activities" ) @@ -29,6 +33,9 @@ func (o *ValidateSpecOutput) merge(results []*database.ValidationResult) { o.Valid = false for _, err := range r.Errors { msg := fmt.Sprintf("validation error for node %s, host %s: %s", r.NodeName, r.HostID, err) + if r.NodeName == "" { + msg = fmt.Sprintf("validation error for host %s: %s", r.HostID, err) + } o.Errors = append(o.Errors, msg) } } @@ -47,30 +54,42 @@ func (w *Workflows) ValidateSpec(ctx workflow.Context, input *ValidateSpecInput) } var futures []workflow.Future[*activities.ValidateInstanceSpecsOutput] - for hostID, grp := range instancesByHost { - if len(grp.Current) == 0 { + var futureHostIDs []string + // Sorted so that errors are reported in a consistent order. + for _, hostID := range slices.Sorted(maps.Keys(instancesByHost)) { + grp := instancesByHost[hostID] + if len(grp.Current) == 0 && len(grp.Services) == 0 { continue } input := &activities.ValidateInstanceSpecsInput{ DatabaseID: databaseID, Specs: grp.Current, PreviousSpecs: grp.Previous, + Services: grp.Services, } future := w.Activities.ExecuteValidateInstanceSpecs(ctx, hostID, input) futures = append(futures, future) + futureHostIDs = append(futureHostIDs, hostID) } overallResult := &ValidateSpecOutput{Valid: true} var allErrors []error - for _, instanceFuture := range futures { + var serviceVersions []hostServiceVersions + for i, instanceFuture := range futures { output, err := instanceFuture.Get(ctx) if err != nil { allErrors = append(allErrors, err) continue } overallResult.merge(output.Results) + if len(output.ServiceVersions) > 0 { + serviceVersions = append(serviceVersions, hostServiceVersions{ + hostID: futureHostIDs[i], + versions: output.ServiceVersions, + }) + } } if err := errors.Join(allErrors...); err != nil { @@ -78,13 +97,52 @@ func (w *Workflows) ValidateSpec(ctx workflow.Context, input *ValidateSpecInput) return nil, fmt.Errorf("failed to validate instances: %w", err) } + if errs := latestServiceVersionErrors(input.Spec.Services, serviceVersions); len(errs) > 0 { + overallResult.Valid = false + overallResult.Errors = append(overallResult.Errors, errs...) + } + logger.Info("instance validation succeeded") return overallResult, nil } +type hostServiceVersions struct { + hostID string + versions map[string]string +} + +// latestServiceVersionErrors returns an error for each service that uses +// "latest" and would run different versions on different hosts. Each host +// resolves "latest" to the version that's installed on it, so the hosts must +// agree for every instance to run the same version. +func latestServiceVersionErrors(services []*database.ServiceSpec, hosts []hostServiceVersions) []string { + var errs []string + for _, svc := range services { + if svc.Version != host.ServiceVersionLatest { + continue + } + var found []string + distinct := map[string]bool{} + for _, h := range hosts { + if version, ok := h.versions[svc.ServiceID]; ok { + found = append(found, fmt.Sprintf("%s has %s", h.hostID, version)) + distinct[version] = true + } + } + if len(distinct) > 1 { + errs = append(errs, fmt.Sprintf( + "service %q: hosts have different versions of %s installed (%s). install the same version on every host or request a specific version", + svc.ServiceID, svc.ServiceType, strings.Join(found, ", "), + )) + } + } + return errs +} + type hostGroup struct { Current []*database.InstanceSpec Previous []*database.InstanceSpec + Services []*database.ServiceSpec } func (w *Workflows) getInstancesByHost( @@ -117,6 +175,15 @@ func (w *Workflows) getInstancesByHost( Previous: prevByHost[hostID], } } + // Services can run on hosts that don't run any database instances, so + // those hosts need to validate their services too. + for _, svc := range spec.Services { + for _, hostID := range svc.HostIDs { + grp := res[hostID] + grp.Services = append(grp.Services, svc) + res[hostID] = grp + } + } return res, nil } diff --git a/server/internal/workflows/validate_spec_test.go b/server/internal/workflows/validate_spec_test.go new file mode 100644 index 00000000..7dc6ade4 --- /dev/null +++ b/server/internal/workflows/validate_spec_test.go @@ -0,0 +1,90 @@ +package workflows + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/pgEdge/control-plane/server/internal/database" +) + +func TestGetInstancesByHostIncludesServiceHosts(t *testing.T) { + api := &database.ServiceSpec{ServiceID: "api", ServiceType: "postgrest", HostIDs: []string{"host-1", "host-3"}} + spec := &database.Spec{ + DatabaseID: "db", + DatabaseName: "db", + PostgresVersion: "18.7", + SpockVersion: "5", + Nodes: []*database.Node{ + {Name: "n1", HostIDs: []string{"host-1"}}, + {Name: "n2", HostIDs: []string{"host-2"}}, + }, + Services: []*database.ServiceSpec{api}, + } + + groups, err := (&Workflows{}).getInstancesByHost(nil, spec, nil) + require.NoError(t, err) + + require.Len(t, groups, 3) + assert.Len(t, groups["host-1"].Current, 1) + assert.Equal(t, []*database.ServiceSpec{api}, groups["host-1"].Services) + assert.Len(t, groups["host-2"].Current, 1) + assert.Empty(t, groups["host-2"].Services) + // host-3 only runs the service, so it has no instances to validate. + assert.Empty(t, groups["host-3"].Current) + assert.Equal(t, []*database.ServiceSpec{api}, groups["host-3"].Services) +} + +func TestLatestServiceVersionErrors(t *testing.T) { + services := []*database.ServiceSpec{ + {ServiceID: "api", ServiceType: "postgrest", Version: "latest"}, + {ServiceID: "pinned-api", ServiceType: "postgrest", Version: "14.5"}, + {ServiceID: "mcp-server", ServiceType: "mcp", Version: "latest"}, + } + + for _, tc := range []struct { + name string + hosts []hostServiceVersions + expected []string + }{ + { + name: "hosts agree", + hosts: []hostServiceVersions{ + {hostID: "host-1", versions: map[string]string{"api": "14.18", "mcp-server": "1.1.0"}}, + {hostID: "host-2", versions: map[string]string{"api": "14.18", "mcp-server": "1.1.0"}}, + }, + }, + { + name: "hosts disagree on a latest service", + hosts: []hostServiceVersions{ + {hostID: "host-1", versions: map[string]string{"api": "14.5", "mcp-server": "1.1.0"}}, + {hostID: "host-2", versions: map[string]string{"api": "14.10", "mcp-server": "1.1.0"}}, + {hostID: "host-3", versions: map[string]string{"api": "14.10"}}, + }, + expected: []string{ + `service "api": hosts have different versions of postgrest installed (host-1 has 14.5, host-2 has 14.10, host-3 has 14.10). install the same version on every host or request a specific version`, + }, + }, + { + name: "pinned versions are checked on each host instead", + hosts: []hostServiceVersions{ + {hostID: "host-1", versions: map[string]string{"pinned-api": "14.5"}}, + {hostID: "host-2", versions: map[string]string{"pinned-api": "14.6"}}, + }, + }, + { + name: "a single host", + hosts: []hostServiceVersions{ + {hostID: "host-1", versions: map[string]string{"api": "14.5"}}, + }, + }, + { + name: "no service versions, such as on swarm", + }, + } { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.expected, latestServiceVersionErrors(services, tc.hosts)) + }) + } +}