Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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; \
Expand Down
3 changes: 3 additions & 0 deletions changes/unreleased/Changed-20261130-000000.yaml
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions changes/unreleased/Fixed-20261130-000000.yaml
Original file line number Diff line number Diff line change
@@ -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 <service> version <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
5 changes: 3 additions & 2 deletions e2e/fixture_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}

Expand Down
2 changes: 1 addition & 1 deletion e2e/rag_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
t.Logf("CreateDatabase rejected as expected: %s", err)

t.Log("RAG unsupported version test completed successfully")
Expand Down
4 changes: 2 additions & 2 deletions e2e/service_provisioning_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions server/internal/api/apiv1/post_init_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down
17 changes: 17 additions & 0 deletions server/internal/api/apiv1/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
45 changes: 45 additions & 0 deletions server/internal/api/apiv1/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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)
}
})
}
}
3 changes: 3 additions & 0 deletions server/internal/database/apply_upgrade_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 4 additions & 0 deletions server/internal/database/orchestrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 8 additions & 1 deletion server/internal/database/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
36 changes: 33 additions & 3 deletions server/internal/database/spec_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down Expand Up @@ -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",
Expand Down
6 changes: 6 additions & 0 deletions server/internal/orchestrator/swarm/orchestrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 3 additions & 1 deletion server/internal/orchestrator/systemd/postgrest_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
44 changes: 40 additions & 4 deletions server/internal/orchestrator/systemd/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading