77 lines
2.6 KiB
Go
77 lines
2.6 KiB
Go
package archied
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
|
|
"github.com/samcharles93/archie-core/internal/app/servicekit"
|
|
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
|
"github.com/samcharles93/archie-core/internal/domain/presence"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore"
|
|
)
|
|
|
|
// imagePolicy is the control plane's agent image, reached through the State
|
|
// Store contract. Only the image field changes, preserving concurrent edits
|
|
// to unrelated settings.
|
|
type imagePolicy struct{ configPath string }
|
|
|
|
func (p imagePolicy) Image(ctx context.Context) (string, error) {
|
|
var image string
|
|
err := p.with(ctx, func(_ pb.ControlPlaneServiceClient, _ *pb.QueryResponse, _ map[string]json.RawMessage, current string) error {
|
|
image = current
|
|
return nil
|
|
})
|
|
return image, err
|
|
}
|
|
|
|
func (p imagePolicy) SetImage(ctx context.Context, expected, desired string) error {
|
|
return p.with(ctx, func(rpc pb.ControlPlaneServiceClient, response *pb.QueryResponse, policy map[string]json.RawMessage, current string) error {
|
|
if current == desired {
|
|
return nil
|
|
}
|
|
if current != expected {
|
|
return errors.New("image policy changed during update; refusing to overwrite it")
|
|
}
|
|
var err error
|
|
if policy["image"], err = json.Marshal(desired); err != nil {
|
|
return err
|
|
}
|
|
data, err := json.Marshal(policy)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = rpc.Command(ctx, &pb.CommandRequest{Kind: controlplanestore.ContainerRuntimePoliciesKind, Command: "replace", ValueJson: data, ExpectedVersion: response.Resource.Version, Actor: "self-update", Source: "installer", RequestId: fmt.Sprintf("self-update-%x-%d", sha256.Sum256(data), response.Resource.Version)})
|
|
return err
|
|
})
|
|
}
|
|
|
|
func (p imagePolicy) with(ctx context.Context, use func(pb.ControlPlaneServiceClient, *pb.QueryResponse, map[string]json.RawMessage, string) error) error {
|
|
_, doc, err := servicekit.Resolve(slog.New(slog.DiscardHandler), p.configPath, "")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
client, cleanup, err := servicekit.StateStoreClient(presence.Daemon, doc.Config)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer cleanup()
|
|
rpc := client.ControlPlane()
|
|
response, err := rpc.Query(ctx, &pb.QueryRequest{Kind: controlplanestore.ContainerRuntimePoliciesKind})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var policy map[string]json.RawMessage
|
|
if err := json.Unmarshal(response.Resource.ValueJson, &policy); err != nil {
|
|
return err
|
|
}
|
|
var current string
|
|
if err := json.Unmarshal(policy["image"], ¤t); err != nil {
|
|
return err
|
|
}
|
|
return use(rpc, response, policy, current)
|
|
}
|