A package is now a set of immutable versions with declared grants and a default version that installations run unless they pin another. Adopting a version is what accepts its grants, replacing the per-extension lifecycle actions with version, pin and update-policy commands.
652 lines
24 KiB
Go
652 lines
24 KiB
Go
package connectors
|
|
|
|
import (
|
|
"cmp"
|
|
"context"
|
|
"encoding/json/jsontext"
|
|
json "encoding/json/v2"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"slices"
|
|
"time"
|
|
|
|
"github.com/danielgtaylor/huma/v2"
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
|
"github.com/samcharles93/archie-core/modules/connectors/internal/catalogue"
|
|
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
|
|
"github.com/samcharles93/archie-core/modules/governance"
|
|
)
|
|
|
|
// grantsOf decodes stored grants; ok is false when none are stored.
|
|
func grantsOf(raw []byte) (g catalogue.Grants, ok bool, err error) {
|
|
if len(raw) == 0 {
|
|
return catalogue.Grants{}, false, nil
|
|
}
|
|
if err := json.Unmarshal(raw, &g); err != nil {
|
|
return catalogue.Grants{}, false, fmt.Errorf("grants: %w", err)
|
|
}
|
|
return g.Normalised(), true, nil
|
|
}
|
|
|
|
// settingsOf decodes the settings a version declared in the catalogue.
|
|
func settingsOf(raw []byte) ([]Setting, error) {
|
|
out := []Setting{}
|
|
if len(raw) == 0 {
|
|
return out, nil
|
|
}
|
|
if err := json.Unmarshal(raw, &out); err != nil {
|
|
return nil, fmt.Errorf("declared settings: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// packageVersions is one package with its versions, as the store holds them.
|
|
type packageVersions struct {
|
|
pkg store.Package
|
|
versions []store.Version
|
|
}
|
|
|
|
// version returns the named version of the package.
|
|
func (p packageVersions) version(name string) (store.Version, bool) {
|
|
i := slices.IndexFunc(p.versions, func(v store.Version) bool { return v.Version == name })
|
|
if i < 0 {
|
|
return store.Version{}, false
|
|
}
|
|
return p.versions[i], true
|
|
}
|
|
|
|
// defaultVersion returns the version installations run unless they pin one.
|
|
func (p packageVersions) defaultVersion() (store.Version, bool) {
|
|
i := slices.IndexFunc(p.versions, func(v store.Version) bool { return v.ID == p.pkg.DefaultVersion.UUID })
|
|
if i < 0 {
|
|
return store.Version{}, false
|
|
}
|
|
return p.versions[i], true
|
|
}
|
|
|
|
// packageNamed reads a package and its versions; a missing package is a 404.
|
|
func (m *Module) packageNamed(ctx context.Context, name string) (packageVersions, error) {
|
|
pkgs, err := m.store.Packages(ctx)
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "list packages", "error", err)
|
|
return packageVersions{}, huma.NewError(http.StatusInternalServerError, "couldn't read the packages")
|
|
}
|
|
i := slices.IndexFunc(pkgs, func(p store.Package) bool { return p.Name == name })
|
|
if i < 0 {
|
|
return packageVersions{}, errNoPackage(name)
|
|
}
|
|
all, err := m.store.Versions(ctx)
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "list package versions", "error", err)
|
|
return packageVersions{}, huma.NewError(http.StatusInternalServerError, "couldn't read the package versions")
|
|
}
|
|
out := packageVersions{pkg: pkgs[i]}
|
|
for _, v := range all {
|
|
if v.PackageID == pkgs[i].ID {
|
|
out.versions = append(out.versions, v)
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// withVersion points a at version v of its package: an installation runs the
|
|
// binary of the version it pins, or of its package's default.
|
|
func withVersion(a store.Installed, v store.Version, pinned bool) store.Installed {
|
|
a.VersionID, a.Version, a.Path, a.SHA256 = v.ID, v.Version, v.Path, v.SHA256
|
|
a.Declared, a.Accepted, a.DeclaredSettings = v.Declared, v.Accepted, v.Settings
|
|
a.Capabilities, a.Effects = v.Capabilities, v.Effects
|
|
a.PinnedVersion = uuid.NullUUID{}
|
|
if pinned {
|
|
a.PinnedVersion = uuid.NullUUID{UUID: v.ID, Valid: true}
|
|
}
|
|
return a
|
|
}
|
|
|
|
// register fetches a version the catalogue offers and records it, not yet
|
|
// accepted.
|
|
func (m *Module) register(ctx context.Context, location string, entry catalogue.Entry, v catalogue.Version) (store.Package, store.Version, error) {
|
|
if !slices.Contains(catalogueContracts, entry.Contract) {
|
|
return store.Package{}, store.Version{}, huma.NewError(http.StatusUnprocessableEntity,
|
|
fmt.Sprintf("%s serves contract %q, which a catalogue doesn't install", entry.Name, entry.Contract))
|
|
}
|
|
ref, err := catalogue.Resolve(location, v.Artifact)
|
|
if err != nil {
|
|
return store.Package{}, store.Version{}, err
|
|
}
|
|
path, err := m.fetcher.Fetch(ctx, entry.Name, ref, v.Digest)
|
|
if err != nil {
|
|
return store.Package{}, store.Version{}, fmt.Errorf("%s %s: %w", entry.Name, v.Version, err)
|
|
}
|
|
declared, err := json.Marshal(v.Grants.Normalised())
|
|
if err != nil {
|
|
return store.Package{}, store.Version{}, err
|
|
}
|
|
settings, err := json.Marshal(v.Settings, json.FormatNilSliceAsNull(false))
|
|
if err != nil {
|
|
return store.Package{}, store.Version{}, err
|
|
}
|
|
pkg, ver, err := m.store.RegisterVersion(ctx,
|
|
store.Package{Name: entry.Name, Contract: entry.Contract, DisplayName: entry.DisplayName, Description: entry.Description, Managed: true},
|
|
store.Version{Version: v.Version, Path: path, SHA256: v.Digest, Declared: declared, Settings: settings},
|
|
governance.CallerID(ctx))
|
|
if err != nil {
|
|
return store.Package{}, store.Version{}, err
|
|
}
|
|
m.log.InfoContext(ctx, "package version registered", "audit", true, "action", "package.register",
|
|
"package", entry.Name, "version", v.Version, "digest", v.Digest)
|
|
return pkg, ver, nil
|
|
}
|
|
|
|
// accept records the grants the instance accepts for a version: the declared
|
|
// grants narrowed to want, where a nil list keeps what was declared.
|
|
func (m *Module) acceptGrants(ctx context.Context, v store.Version, want *grantsRequest) (catalogue.Grants, error) {
|
|
declared, _, err := grantsOf(v.Declared)
|
|
if err != nil {
|
|
return catalogue.Grants{}, err
|
|
}
|
|
grants := declared
|
|
if want != nil {
|
|
if want.Egress != nil {
|
|
grants.Egress = want.Egress
|
|
}
|
|
if want.Env != nil {
|
|
grants.Env = want.Env
|
|
}
|
|
}
|
|
accepted, err := catalogue.Accept(declared, grants)
|
|
if err != nil {
|
|
return catalogue.Grants{}, err
|
|
}
|
|
raw, err := json.Marshal(accepted)
|
|
if err != nil {
|
|
return catalogue.Grants{}, err
|
|
}
|
|
if err := m.store.AcceptVersion(ctx, v.ID, raw, governance.CallerID(ctx)); err != nil {
|
|
return catalogue.Grants{}, err
|
|
}
|
|
m.log.InfoContext(ctx, "package version accepted", "audit", true, "action", "package.accept",
|
|
"version_id", v.ID.String(), "version", v.Version)
|
|
return accepted, nil
|
|
}
|
|
|
|
// relaunchFollowers restarts the installations of a package that run its
|
|
// default version, so they run the version it now names. skip is one already
|
|
// restarted.
|
|
func (m *Module) relaunchFollowers(ctx context.Context, packageID uuid.UUID, skip ...uuid.UUID) {
|
|
installed, err := m.refresh(ctx)
|
|
if err != nil {
|
|
m.log.ErrorContext(ctx, "read installations to restart", "package_id", packageID.String(), "error", err)
|
|
return
|
|
}
|
|
for _, a := range ordered(installed) {
|
|
if a.PackageID == packageID && !a.PinnedVersion.Valid && !slices.Contains(skip, a.ID) {
|
|
_ = m.launch(ctx, a)
|
|
}
|
|
}
|
|
}
|
|
|
|
// instanceRow returns the instance installation of name; ok is false when
|
|
// there is none.
|
|
func (m *Module) instanceRow(ctx context.Context, name string) (a store.Installed, ok bool, err error) {
|
|
installed, err := m.store.List(ctx)
|
|
if err != nil {
|
|
return store.Installed{}, false, err
|
|
}
|
|
i := slices.IndexFunc(installed, func(a store.Installed) bool { return a.Scope == store.ScopeInstance && a.Name == name })
|
|
if i < 0 {
|
|
return store.Installed{}, false, nil
|
|
}
|
|
return installed[i], true, nil
|
|
}
|
|
|
|
// persistInstance stores an instance installation together with the package
|
|
// version it runs, accepted by the caller.
|
|
func (m *Module) persistInstance(ctx context.Context) persistFunc {
|
|
by := governance.CallerID(ctx)
|
|
return func(ctx context.Context, in store.Installed, caps jsontext.Value) (store.Installed, error) {
|
|
return m.store.SaveInstalled(ctx, in, by, caps)
|
|
}
|
|
}
|
|
|
|
// packageError maps what a version change returns to an HTTP status.
|
|
func (m *Module) packageError(ctx context.Context, err error) error {
|
|
var status *huma.ErrorModel
|
|
switch {
|
|
case errors.As(err, &status):
|
|
return err
|
|
case errors.Is(err, catalogue.ErrBeyondDeclared), errors.Is(err, catalogue.ErrDigestMismatch),
|
|
errors.Is(err, store.ErrVersionExists), errors.Is(err, store.ErrContractChanged):
|
|
return huma.NewError(http.StatusUnprocessableEntity, err.Error())
|
|
case errors.Is(err, store.ErrDefaultVersion), errors.Is(err, store.ErrVersionPinned):
|
|
return huma.NewError(http.StatusConflict, err.Error())
|
|
case errors.Is(err, catalogue.ErrInvalidPolicy):
|
|
return huma.NewError(http.StatusBadRequest, err.Error())
|
|
case errors.Is(err, errNoSource), errors.Is(err, catalogue.ErrBadSignature), errors.Is(err, catalogue.ErrStale):
|
|
return catalogueError(err)
|
|
}
|
|
m.log.ErrorContext(ctx, "change package", "error", err)
|
|
return huma.NewError(http.StatusInternalServerError, "couldn't change the package")
|
|
}
|
|
|
|
// grantsRequest is what an operator accepts for a version and gives an
|
|
// installation. A nil Egress or Env keeps what the version declared.
|
|
type grantsRequest struct {
|
|
Egress []string `json:"egress,omitempty" doc:"Every host the extension may reach. Omitted: the hosts the version declares"`
|
|
Env []string `json:"env,omitempty" doc:"Host environment variables the extension may see. Omitted: those the version declares"`
|
|
}
|
|
|
|
// installInput installs an extension from the catalogue in one step: fetch the
|
|
// version, accept its grants, and create and start an installation.
|
|
type installInput struct {
|
|
Name string `path:"name"`
|
|
Body struct {
|
|
Version string `json:"version,omitzero" doc:"The catalogue version to install. Default: the latest"`
|
|
Scope string `json:"scope,omitzero" enum:"instance,org,person" doc:"Who owns the installation. Default: the instance"`
|
|
// Installation is what a binding calls the installation; the
|
|
// default is the package's name.
|
|
Installation string `json:"installation,omitzero"`
|
|
grantsRequest
|
|
Settings map[string]string `json:"settings,omitzero"`
|
|
Credentials map[string]string `json:"credentials,omitzero" doc:"Each credential slot and the credential, by name, that fills it"`
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
}
|
|
|
|
func (m *Module) install(ctx context.Context, in *installInput) (*httpapi.Reply[ExtensionView], error) {
|
|
m.pkgMu.Lock()
|
|
defer m.pkgMu.Unlock()
|
|
req := in.Body
|
|
auth, err := authorityOf(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
owner, err := auth.ownerAt(cmp.Or(req.Scope, store.ScopeInstance))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
installed, err := m.store.List(ctx)
|
|
if err != nil {
|
|
return nil, m.packageError(ctx, err)
|
|
}
|
|
name := cmp.Or(req.Installation, in.Name)
|
|
if !validName.MatchString(name) {
|
|
return nil, huma.NewError(http.StatusBadRequest, "an installation needs a lowercase name")
|
|
}
|
|
if slices.ContainsFunc(installed, func(a store.Installed) bool { return a.Owner() == owner && a.Name == name }) {
|
|
return nil, huma.NewError(http.StatusConflict, fmt.Sprintf("%s already has an installation named %s", owner.Scope, name))
|
|
}
|
|
pkg, ver, accepted, err := m.fetchAccepted(ctx, in.Name, req.Version, &req.grantsRequest)
|
|
if err != nil {
|
|
return nil, m.packageError(ctx, err)
|
|
}
|
|
a := withVersion(store.Installed{
|
|
ID: uuid.New(), PackageID: pkg.ID, Scope: owner.Scope, OrgID: owner.OrgID, PersonID: owner.PersonID, Name: name,
|
|
PackageName: pkg.Name, Contract: pkg.Contract, Managed: true, DisplayName: pkg.DisplayName, Description: pkg.Description,
|
|
}, ver, pkg.DefaultVersion.UUID != ver.ID)
|
|
egress, env := req.Egress, req.Env
|
|
if egress == nil {
|
|
egress = accepted.Egress
|
|
}
|
|
if env == nil {
|
|
env = accepted.Env
|
|
}
|
|
return m.saveInstallation(ctx, auth, a, installationRequest{
|
|
Settings: req.Settings, Egress: egress, Env: env, Credentials: req.Credentials, Enabled: req.Enabled,
|
|
}, installed, false, store.Installed{})
|
|
}
|
|
|
|
// fetchAccepted fetches a catalogue version of name and accepts it with want
|
|
// narrowing what it declared. A version already accepted keeps its grants, so
|
|
// installing it again can't narrow what its other installations were given.
|
|
func (m *Module) fetchAccepted(ctx context.Context, name, version string, want *grantsRequest) (store.Package, store.Version, catalogue.Grants, error) {
|
|
doc, location, err := m.readCatalogue(ctx)
|
|
if err != nil {
|
|
return store.Package{}, store.Version{}, catalogue.Grants{}, err
|
|
}
|
|
entry, ok := doc.Entry(name)
|
|
if !ok {
|
|
return store.Package{}, store.Version{}, catalogue.Grants{}, huma.NewError(http.StatusNotFound, "the catalogue doesn't list "+name)
|
|
}
|
|
cv, ok := entry.Version(version)
|
|
if !ok {
|
|
return store.Package{}, store.Version{}, catalogue.Grants{}, huma.NewError(http.StatusNotFound, fmt.Sprintf("the catalogue doesn't list %s %s", name, version))
|
|
}
|
|
pkg, ver, err := m.register(ctx, location, entry, cv)
|
|
if err != nil {
|
|
return store.Package{}, store.Version{}, catalogue.Grants{}, err
|
|
}
|
|
accepted, ok, err := grantsOf(ver.Accepted)
|
|
if err != nil || ok {
|
|
return pkg, ver, accepted, err
|
|
}
|
|
if accepted, err = m.acceptGrants(ctx, ver, want); err != nil {
|
|
return store.Package{}, store.Version{}, catalogue.Grants{}, err
|
|
}
|
|
ver.Accepted, err = json.Marshal(accepted)
|
|
return pkg, ver, accepted, err
|
|
}
|
|
|
|
type packageNameInput struct {
|
|
Name string `path:"name"`
|
|
}
|
|
|
|
type registerVersionInput struct {
|
|
Name string `path:"name"`
|
|
Body struct {
|
|
Version string `json:"version,omitzero" doc:"The catalogue version to fetch. Default: the latest"`
|
|
}
|
|
}
|
|
|
|
// registerVersion fetches another version of an installed package from the
|
|
// catalogue. A version that asks for no more than the default version was
|
|
// granted is accepted with the same grants; one that asks for more waits for
|
|
// an operator to accept it.
|
|
func (m *Module) registerVersion(ctx context.Context, in *registerVersionInput) (*httpapi.Reply[VersionView], error) {
|
|
m.pkgMu.Lock()
|
|
defer m.pkgMu.Unlock()
|
|
pv, err := m.packageNamed(ctx, in.Name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !pv.pkg.Managed {
|
|
return nil, huma.NewError(http.StatusConflict, in.Name+" is accepted by path, not installed from the catalogue")
|
|
}
|
|
doc, location, err := m.readCatalogue(ctx)
|
|
if err != nil {
|
|
return nil, m.packageError(ctx, err)
|
|
}
|
|
ver, err := m.offer(ctx, doc, location, pv, in.Body.Version)
|
|
if err != nil {
|
|
return nil, m.packageError(ctx, err)
|
|
}
|
|
return httpapi.OK(versionView(ver, pv.pkg, nil)), nil
|
|
}
|
|
|
|
// offer registers a version of pv from the catalogue and accepts it when the
|
|
// default version's grants cover what it declares.
|
|
func (m *Module) offer(ctx context.Context, doc catalogue.Document, location string, pv packageVersions, version string) (store.Version, error) {
|
|
entry, ok := doc.Entry(pv.pkg.Name)
|
|
if !ok {
|
|
return store.Version{}, huma.NewError(http.StatusNotFound, "the catalogue doesn't list "+pv.pkg.Name)
|
|
}
|
|
cv, ok := entry.Version(version)
|
|
if !ok {
|
|
return store.Version{}, huma.NewError(http.StatusNotFound, fmt.Sprintf("the catalogue doesn't list %s %s", pv.pkg.Name, version))
|
|
}
|
|
_, ver, err := m.register(ctx, location, entry, cv)
|
|
if err != nil || len(ver.Accepted) > 0 {
|
|
return ver, err
|
|
}
|
|
def, ok := pv.defaultVersion()
|
|
if !ok {
|
|
return ver, nil
|
|
}
|
|
held, ok, err := grantsOf(def.Accepted)
|
|
if err != nil || !ok || !held.Covers(cv.Grants.Normalised()) {
|
|
return ver, err
|
|
}
|
|
accepted, err := m.acceptGrants(ctx, ver, nil)
|
|
if err != nil {
|
|
return store.Version{}, err
|
|
}
|
|
ver.Accepted, err = json.Marshal(accepted)
|
|
return ver, err
|
|
}
|
|
|
|
type versionInput struct {
|
|
Name string `path:"name"`
|
|
Version string `path:"version"`
|
|
}
|
|
|
|
type acceptVersionInput struct {
|
|
Name string `path:"name"`
|
|
Version string `path:"version"`
|
|
Body *grantsRequest
|
|
}
|
|
|
|
// acceptVersion records the grants the instance accepts for a version. With no
|
|
// body it accepts what the version declared.
|
|
func (m *Module) acceptVersion(ctx context.Context, in *acceptVersionInput) (*httpapi.Reply[VersionView], error) {
|
|
m.pkgMu.Lock()
|
|
defer m.pkgMu.Unlock()
|
|
pv, err := m.packageNamed(ctx, in.Name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ver, ok := pv.version(in.Version)
|
|
if !ok {
|
|
return nil, errNoVersion(in.Name, in.Version)
|
|
}
|
|
accepted, err := m.acceptGrants(ctx, ver, in.Body)
|
|
if err != nil {
|
|
return nil, m.packageError(ctx, err)
|
|
}
|
|
if ver.Accepted, err = json.Marshal(accepted); err != nil {
|
|
return nil, m.packageError(ctx, err)
|
|
}
|
|
if ver.ID == pv.pkg.DefaultVersion.UUID {
|
|
m.relaunchFollowers(context.WithoutCancel(ctx), pv.pkg.ID)
|
|
}
|
|
return httpapi.OK(versionView(ver, pv.pkg, nil)), nil
|
|
}
|
|
|
|
type defaultVersionInput struct {
|
|
Name string `path:"name"`
|
|
Body struct {
|
|
Version string `json:"version" doc:"An accepted version of the package"`
|
|
}
|
|
}
|
|
|
|
// setDefaultVersion moves every installation that follows the package to an
|
|
// accepted version: an update, or a rollback to an earlier one.
|
|
func (m *Module) setDefaultVersion(ctx context.Context, in *defaultVersionInput) (*httpapi.Reply[VersionView], error) {
|
|
m.pkgMu.Lock()
|
|
defer m.pkgMu.Unlock()
|
|
pv, err := m.packageNamed(ctx, in.Name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ver, ok := pv.version(in.Body.Version)
|
|
if !ok {
|
|
return nil, errNoVersion(in.Name, in.Body.Version)
|
|
}
|
|
if len(ver.Accepted) == 0 {
|
|
return nil, huma.NewError(http.StatusConflict, fmt.Sprintf("accept %s %s before running it", in.Name, ver.Version))
|
|
}
|
|
if err := m.store.SetDefaultVersion(ctx, pv.pkg.ID, ver.ID); err != nil {
|
|
return nil, m.packageError(ctx, err)
|
|
}
|
|
m.log.InfoContext(ctx, "package default version set", "audit", true, "action", "package.default",
|
|
"package", in.Name, "version", ver.Version)
|
|
m.relaunchFollowers(context.WithoutCancel(ctx), pv.pkg.ID)
|
|
pv.pkg.DefaultVersion = uuid.NullUUID{UUID: ver.ID, Valid: true}
|
|
return httpapi.OK(versionView(ver, pv.pkg, nil)), nil
|
|
}
|
|
|
|
type updatePolicyInput struct {
|
|
Name string `path:"name"`
|
|
Body struct {
|
|
Policy string `json:"policy" enum:"manual,auto"`
|
|
}
|
|
}
|
|
|
|
func (m *Module) setUpdatePolicy(ctx context.Context, in *updatePolicyInput) (*httpapi.Reply[packageState], error) {
|
|
if err := catalogue.CheckPolicy(in.Body.Policy); err != nil {
|
|
return nil, huma.NewError(http.StatusBadRequest, err.Error())
|
|
}
|
|
pv, err := m.packageNamed(ctx, in.Name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := m.store.SetUpdatePolicy(ctx, pv.pkg.ID, in.Body.Policy); err != nil {
|
|
return nil, m.packageError(ctx, err)
|
|
}
|
|
m.log.InfoContext(ctx, "package update policy set", "audit", true, "action", "package.update_policy",
|
|
"package", in.Name, "policy", in.Body.Policy)
|
|
return httpapi.OK(packageState{Name: in.Name, State: "running"}), nil
|
|
}
|
|
|
|
// removeVersion deletes a version no installation runs.
|
|
func (m *Module) removeVersion(ctx context.Context, in *versionInput) (*httpapi.Reply[packageState], error) {
|
|
m.pkgMu.Lock()
|
|
defer m.pkgMu.Unlock()
|
|
pv, err := m.packageNamed(ctx, in.Name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ver, ok := pv.version(in.Version)
|
|
if !ok {
|
|
return nil, errNoVersion(in.Name, in.Version)
|
|
}
|
|
if err := m.store.DeleteVersion(ctx, ver.ID); err != nil {
|
|
return nil, m.packageError(ctx, err)
|
|
}
|
|
m.log.InfoContext(ctx, "package version removed", "audit", true, "action", "package.remove_version",
|
|
"package", in.Name, "version", ver.Version)
|
|
return httpapi.OK(packageState{Name: in.Name, State: "removed"}), nil
|
|
}
|
|
|
|
func errNoVersion(name, version string) error {
|
|
return huma.NewError(http.StatusNotFound, fmt.Sprintf("%s has no version %s", name, version))
|
|
}
|
|
|
|
// UpdateAuto fetches the newest catalogue version of every package whose
|
|
// policy is auto. One whose grants the default version's cover becomes the
|
|
// default; one that asks for more waits for an operator. One package that
|
|
// fails doesn't stop the rest. It does nothing when no catalogue source is
|
|
// set.
|
|
func (m *Module) UpdateAuto(ctx context.Context) error {
|
|
pkgs, err := m.store.Packages(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var auto []string
|
|
for _, p := range pkgs {
|
|
if p.Managed && p.UpdatePolicy == catalogue.PolicyAuto {
|
|
auto = append(auto, p.Name)
|
|
}
|
|
}
|
|
if len(auto) == 0 {
|
|
return nil
|
|
}
|
|
doc, location, err := m.readCatalogue(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var errs []error
|
|
for _, name := range auto {
|
|
if err := m.updateOne(ctx, doc, location, name); err != nil {
|
|
errs = append(errs, fmt.Errorf("update %s: %w", name, err))
|
|
}
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
func (m *Module) updateOne(ctx context.Context, doc catalogue.Document, location, name string) error {
|
|
m.pkgMu.Lock()
|
|
defer m.pkgMu.Unlock()
|
|
pv, err := m.packageNamed(ctx, name)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
entry, ok := doc.Entry(name)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
latest, ok := entry.Latest()
|
|
def, hasDefault := pv.defaultVersion()
|
|
if !ok || (hasDefault && !catalogue.Newer(latest.Version, def.Version)) {
|
|
return nil
|
|
}
|
|
ver, err := m.offer(ctx, doc, location, pv, latest.Version)
|
|
if err != nil || len(ver.Accepted) == 0 {
|
|
return err
|
|
}
|
|
if err := m.store.SetDefaultVersion(ctx, pv.pkg.ID, ver.ID); err != nil {
|
|
return err
|
|
}
|
|
m.log.InfoContext(ctx, "package updated", "audit", true, "action", "package.default", "package", name, "version", ver.Version)
|
|
m.relaunchFollowers(ctx, pv.pkg.ID)
|
|
return nil
|
|
}
|
|
|
|
// WatchUpdates runs UpdateAuto every interval until ctx ends.
|
|
func (m *Module) WatchUpdates(ctx context.Context, interval time.Duration) {
|
|
ticker := time.NewTicker(interval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
if err := m.UpdateAuto(ctx); err != nil {
|
|
m.log.WarnContext(ctx, "update extensions from the catalogue", "error", err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// VersionView is one version of a package.
|
|
type VersionView struct {
|
|
Version string `json:"version"`
|
|
Digest string `json:"digest"`
|
|
Declared catalogue.Grants `json:"declared"`
|
|
// Accepted is nil until the instance accepts the version.
|
|
Accepted *catalogue.Grants `json:"accepted"`
|
|
Settings []Setting `json:"settings"`
|
|
Default bool `json:"default"`
|
|
// Installations counts the installations that run this version.
|
|
Installations int `json:"installations"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
// versionView shows a version. running counts the installations on each
|
|
// version ID; nil leaves the count at zero.
|
|
func versionView(v store.Version, p store.Package, running map[uuid.UUID]int) VersionView {
|
|
view := VersionView{
|
|
Version: v.Version, Digest: v.SHA256, Default: v.ID == p.DefaultVersion.UUID,
|
|
Installations: running[v.ID], CreatedAt: v.CreatedAt, Settings: []Setting{},
|
|
}
|
|
view.Declared, _, _ = grantsOf(v.Declared)
|
|
view.Declared = view.Declared.Normalised()
|
|
if held, ok, err := grantsOf(v.Accepted); err == nil && ok {
|
|
view.Accepted = &held
|
|
}
|
|
if s, err := settingsOf(v.Settings); err == nil {
|
|
view.Settings = s
|
|
}
|
|
return view
|
|
}
|
|
|
|
func (m *Module) registerPackages(api huma.API) {
|
|
tags := []string{"Packages"}
|
|
write := httpapi.AdminAuthorized(governance.ActionUpdate, governance.KindConnector)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionCreate, governance.KindConnector), huma.Operation{
|
|
OperationID: "register-package-version", Method: http.MethodPost, Path: "/api/packages/{name}/versions",
|
|
Summary: "Fetch another catalogue version of an installed package", Tags: tags,
|
|
}, m.registerVersion)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionApprove, governance.KindConnector), huma.Operation{
|
|
OperationID: "accept-package-version", Method: http.MethodPost, Path: "/api/packages/{name}/versions/{version}/accept",
|
|
Summary: "Accept the grants a package version may use", Tags: tags,
|
|
}, m.acceptVersion)
|
|
httpapi.Register(api, write, huma.Operation{
|
|
OperationID: "put-package-default-version", Method: http.MethodPut, Path: "/api/packages/{name}/default-version",
|
|
Summary: "Run an accepted version in every installation that follows the package", Tags: tags,
|
|
}, m.setDefaultVersion)
|
|
httpapi.Register(api, write, huma.Operation{
|
|
OperationID: "put-package-update-policy", Method: http.MethodPut, Path: "/api/packages/{name}/update-policy",
|
|
Summary: "Set whether a package follows the catalogue on its own", Tags: tags,
|
|
}, m.setUpdatePolicy)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionDelete, governance.KindConnector), huma.Operation{
|
|
OperationID: "remove-package-version", Method: http.MethodDelete, Path: "/api/packages/{name}/versions/{version}",
|
|
Summary: "Remove a version no installation runs", Tags: tags,
|
|
}, m.removeVersion)
|
|
httpapi.Register(api, httpapi.AdminAuthorized(governance.ActionDelete, governance.KindConnector), huma.Operation{
|
|
OperationID: "remove-package", Method: http.MethodDelete, Path: "/api/packages/{name}",
|
|
Summary: "Remove a package, its versions and its instance installations", Tags: tags,
|
|
}, m.removePackage)
|
|
}
|