diff --git a/README.md b/README.md index 8c2f602..b85a950 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ The right to manage `Organization` objects is bound by the installation: it bind In the namespace the operator keeps, from the first reconcile on: - the network policies `networkPolicy.names`, copied from `platformNamespace`; -- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`); +- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`). Every reconcile resets its `spec.url`, `spec.interval` and `spec.ref` to `agentChart.*` (other fields and labels stay). A move of `spec.ref` to a higher major (`2.x` to `3.x`) waits per organization until agent-manager's migrate sets `agent-platform.giantswarm.io/agent-chart-ready-major` to the new major on the report ConfigMap (`agentChart.migrationReport`), with `agent-platform.giantswarm.io/agent-chart-ready-releases` naming every HelmRelease on the source and `agent-platform.giantswarm.io/agent-chart-ready-release-versions` recording each one's UID and `metadata.generation` as the run left it. A release recreated under the same name or whose spec changed after the run (or a mark without the versions) holds the move, naming the release, until migrate runs again; an organization with no HelmRelease on the source moves at once. While it waits the organization is not Ready (`ChartSourceHeld`) and is rechecked every `agentChart.migrationPoll`. A range of no release major (a pre-release alone) or of several (`>=2.6.0`) creates and moves no source: `ChartRangeInvalid`. Organizations do not pin their own chart version; - the Helm ServiceAccount `helmReleaseServiceAccount`, which the organization's HelmReleases run as, with a RoleBinding to the ClusterRole `agent-platform-tenant-flux`; - the RoleBinding `organization-admins`, which binds the ClusterRole `agent-platform:admin` to the Users and Groups of the organization's `spec.admins`, in their order. It follows the list while the Agent Platform is on, and an edit of it is reverted. With no admins the operator empties its binding and deletes it (emptied first, so a finalizer that holds the binding keeps no access), the organization has no such binding, and that is no error: the platform team manages the organization. A RoleBinding `organization-admins` that the operator did not write is left as it is, and the organization is `AgentPlatformReady=False NameTaken` while it has admins. The operator writes no binding in other namespaces from the list (no `cluster-admin`); - the ResourceQuota `agent-platform-organization-objects` on object counts (`objectQuota`), so one organization cannot flood the API server with objects; diff --git a/go.mod b/go.mod index e7322c8..134d599 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/giantswarm/agent-platform-operator go 1.26.0 require ( + github.com/Masterminds/semver/v3 v3.4.0 github.com/aws/aws-sdk-go-v2 v1.48.2 github.com/aws/aws-sdk-go-v2/config v1.33.23 github.com/aws/aws-sdk-go-v2/service/s3 v1.117.0 diff --git a/helm/agent-platform-operator/README.md b/helm/agent-platform-operator/README.md index df01e12..8eaef8b 100644 --- a/helm/agent-platform-operator/README.md +++ b/helm/agent-platform-operator/README.md @@ -18,11 +18,13 @@ Reconciles each Organization (security.giantswarm.io) with the Agent Platform en | platformNamespace | string | `"kagent"` | The platform namespace (kagent's) the network policies are copied from. | | networkPolicy.flavor | string | `""` | Kind of the network policies copied into every organization namespace: `kubernetes` (NetworkPolicy) or `cilium` (CiliumNetworkPolicy). Empty copies none. | | networkPolicy.names | list | `[]` | Names of the network policies in `platformNamespace` copied into every organization namespace (the platform's worker policy, `substrate-workers` with Cilium, `substrate-workers-ingress` with Kubernetes network policies). | -| agentChart.ociUrl | string | `"oci://gsoci.azurecr.io/charts/giantswarm/agent"` | OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. Empty keeps none. | +| agentChart.ociUrl | string | `"oci://gsoci.azurecr.io/charts/giantswarm/agent"` | OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. Every reconcile resets its url, interval and ref to these values. Empty keeps none. | | agentChart.semver | string | `"2.x"` | Semver range the OCIRepository tracks. | | agentChart.semverFilter | string | `""` | Regular expression the chart's tags must match before the range is evaluated (the OCIRepository's `ref.semverFilter`); empty filters nothing. | | agentChart.interval | string | `"30m"` | OCIRepository.spec.interval. | | agentChart.ociRepositoryApiVersion | string | `"source.toolkit.fluxcd.io/v1"` | source.toolkit.fluxcd.io API version of the OCIRepository. | +| agentChart.migrationReport | string | `"agent-manager-migrate-report"` | agent-manager migrate's report ConfigMap in an organization namespace. A move to a higher major (`2.x` to `3.x`) waits until migrate annotates it `agent-platform.giantswarm.io/agent-chart-ready-major` with the new major (organization not Ready, `ChartSourceHeld`, meanwhile). The operator reads this one ConfigMap name only. | +| agentChart.migrationPoll | string | `"1m"` | How often a waiting organization looks for migrate's annotation again. | | helmReleaseServiceAccount | string | `"kagent-flux"` | The ServiceAccount the organization's HelmReleases run as (`spec.serviceAccountName`, which helm-controller impersonates), kept in every organization namespace and bound there to the ClusterRole `agent-platform-tenant-flux`. The same name as agent-manager's `flux.helmReleaseServiceAccount`. Empty keeps none. | | serviceAccountBindings | list | `[]` | ClusterRoles bound to a ServiceAccount of another namespace in every organization namespace, such as Substrate's credential providers' Secret readers, which read the Secret an actor's credential names there. Each ClusterRole is bound by a RoleBinding named after it (listed once, not the Helm or Flux binding's name), and the operator gets `bind` on it; a ClusterRole removed from the list loses its bindings. The agent-platform chart's admission policy holds which ServiceAccounts the operator binds there. | | snapshots.bucket | string | `""` | Bucket of the organizations' worker snapshots: an organization's `status.capabilities.agentPlatform.snapshotPrefix` is `s3:///`. Empty leaves it empty. | diff --git a/helm/agent-platform-operator/templates/deployment.yaml b/helm/agent-platform-operator/templates/deployment.yaml index 8ce38cc..201e827 100644 --- a/helm/agent-platform-operator/templates/deployment.yaml +++ b/helm/agent-platform-operator/templates/deployment.yaml @@ -35,6 +35,8 @@ spec: {{- end }} - --ocirepository-interval={{ .Values.agentChart.interval }} - --flux-ocirepository-api-version={{ .Values.agentChart.ociRepositoryApiVersion }} + - --agent-chart-migration-report={{ .Values.agentChart.migrationReport }} + - --agent-chart-migration-poll={{ .Values.agentChart.migrationPoll }} - --helmrelease-service-account={{ .Values.helmReleaseServiceAccount }} {{- with .Values.serviceAccountBindings }} - {{ printf "--service-account-bindings=%s" (include "serviceAccountBindings" $) | quote }} diff --git a/helm/agent-platform-operator/templates/rbac.yaml b/helm/agent-platform-operator/templates/rbac.yaml index b13c8ee..8148b13 100644 --- a/helm/agent-platform-operator/templates/rbac.yaml +++ b/helm/agent-platform-operator/templates/rbac.yaml @@ -3,7 +3,8 @@ The operator's own permissions. RBAC cannot select namespaces by label, so the ClusterRole lets the ServiceAccount create namespaces and write RoleBindings, ServiceAccounts, -OCIRepositories, network policies and ResourceQuotas in every namespace, and +OCIRepositories (updates only of the agent chart's name), network policies +and ResourceQuotas in every namespace, and with curated.enabled write and delete Agents, AgentTemplates, Harnesses, RemoteMCPServers and WorkerPools in every namespace, the platform namespace's curated sources included. The erasure of a deleted organization deletes @@ -87,9 +88,26 @@ rules: resources: ["serviceaccounts"] verbs: ["update"] {{- end }} + {{- with .Values.agentChart.ociUrl }} + # The agent chart's OCIRepository: created, and brought back to + # agentChart.* on every reconcile. RBAC cannot name the object of a create; + # an update is held to the chart's name (the last segment of + # agentChart.ociUrl), so without the platform chart's scope policy a leaked + # token still cannot repoint another Flux source. - apiGroups: ["source.toolkit.fluxcd.io"] resources: ["ocirepositories"] verbs: ["get", "create"] + - apiGroups: ["source.toolkit.fluxcd.io"] + resources: ["ocirepositories"] + resourceNames: [{{ base . | quote }}] + verbs: ["update"] + # agent-manager migrate's report, read before the source moves to a higher + # agent chart major (agentChart.migrationReport); no other ConfigMap. + - apiGroups: [""] + resources: ["configmaps"] + resourceNames: [{{ $.Values.agentChart.migrationReport | quote }}] + verbs: ["get"] + {{- end }} # The organization's Flux Kustomization: kept in commit mode, deleted by # the erasure; with the installation's set, the one that applied each # organization is read for the AgentPlatformOrphaned condition, in any @@ -109,6 +127,8 @@ rules: - "create" - "update" {{- end }} + # The HelmReleases are listed too before a move of the chart source to a + # higher major: one with no release on it moves without migrate's mark. - apiGroups: ["helm.toolkit.fluxcd.io"] resources: ["helmreleases"] verbs: ["list", "delete"] diff --git a/helm/agent-platform-operator/values.schema.json b/helm/agent-platform-operator/values.schema.json index 04a7b15..ced6690 100644 --- a/helm/agent-platform-operator/values.schema.json +++ b/helm/agent-platform-operator/values.schema.json @@ -11,13 +11,21 @@ "type": "string", "description": "OCIRepository.spec.interval." }, + "migrationPoll": { + "type": "string", + "description": "How often a waiting organization looks for migrate's annotation again." + }, + "migrationReport": { + "type": "string", + "description": "agent-manager migrate's report ConfigMap in an organization namespace. A move to a higher major (`2.x` to `3.x`) waits until migrate annotates it `agent-platform.giantswarm.io/agent-chart-ready-major` with the new major (organization not Ready, `ChartSourceHeld`, meanwhile). The operator reads this one ConfigMap name only." + }, "ociRepositoryApiVersion": { "type": "string", "description": "source.toolkit.fluxcd.io API version of the OCIRepository." }, "ociUrl": { "type": "string", - "description": "OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. Empty keeps none." + "description": "OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. Every reconcile resets its url, interval and ref to these values. Empty keeps none." }, "semver": { "type": "string", diff --git a/helm/agent-platform-operator/values.yaml b/helm/agent-platform-operator/values.yaml index 340c58e..7d80441 100644 --- a/helm/agent-platform-operator/values.yaml +++ b/helm/agent-platform-operator/values.yaml @@ -31,7 +31,8 @@ networkPolicy: agentChart: # -- OCI URL of the agent chart. The OCIRepository kept in every # organization namespace is named after its last segment (`agent`); the - # organization's HelmReleases reference it by that name. Empty keeps none. + # organization's HelmReleases reference it by that name. Every reconcile + # resets its url, interval and ref to these values. Empty keeps none. ociUrl: oci://gsoci.azurecr.io/charts/giantswarm/agent # -- Semver range the OCIRepository tracks. semver: "2.x" @@ -42,6 +43,14 @@ agentChart: interval: 30m # -- source.toolkit.fluxcd.io API version of the OCIRepository. ociRepositoryApiVersion: source.toolkit.fluxcd.io/v1 + # -- agent-manager migrate's report ConfigMap in an organization namespace. + # A move to a higher major (`2.x` to `3.x`) waits until migrate annotates it + # `agent-platform.giantswarm.io/agent-chart-ready-major` with the new major + # (organization not Ready, `ChartSourceHeld`, meanwhile). The operator reads + # this one ConfigMap name only. + migrationReport: agent-manager-migrate-report + # -- How often a waiting organization looks for migrate's annotation again. + migrationPoll: 1m # -- The ServiceAccount the organization's HelmReleases run as # (`spec.serviceAccountName`, which helm-controller impersonates), kept in diff --git a/internal/controller/chartmajor.go b/internal/controller/chartmajor.go new file mode 100644 index 0000000..6de1e92 --- /dev/null +++ b/internal/controller/chartmajor.go @@ -0,0 +1,356 @@ +package controller + +import ( + "context" + "encoding/json" + "fmt" + "regexp" + "slices" + "strconv" + "strings" + "time" + + "github.com/Masterminds/semver/v3" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// MigrationReadyAnnotation is what agent-manager's migrate sets on its report +// ConfigMap in an organization namespace (ChartSource.MigrationReport) to the +// agent chart major every release there is on the values of (agent-manager's +// migrate.OrganizationReadyAnnotation: the two constants are one contract). +// The operator moves the namespace's chart source across a major only while +// it names the new major. +const MigrationReadyAnnotation = "agent-platform.giantswarm.io/agent-chart-ready-major" + +// DefaultMigrationReport is agent-manager migrate's report ConfigMap. +const DefaultMigrationReport = "agent-manager-migrate-report" + +// MigrationReadyReleasesAnnotation is set beside MigrationReadyAnnotation to +// the comma-separated names of the HelmReleases the run found on target +// values (agent-manager's migrate.OrganizationReadyReleasesAnnotation). A +// release on the source that it does not name was created after the run read +// the namespace: the mark does not cover it, and migrate must run again. +const MigrationReadyReleasesAnnotation = "agent-platform.giantswarm.io/agent-chart-ready-releases" + +// MigrationReadyVersionsAnnotation is set beside MigrationReadyReleasesAnnotation +// to a JSON object of each release the run found on target values, by name, +// to the UID and metadata.generation the run left it at +// ({"hand":{"uid":"…","generation":4}}; agent-manager's +// migrate.OrganizationReadyVersionsAnnotation). The mark covers a HelmRelease +// on the source only while both match: a release recreated under the same +// name (another UID) or whose spec changed after the run (another +// generation) holds the move until migrate runs again. A mark without it (an +// older agent-manager) covers no release. +const MigrationReadyVersionsAnnotation = "agent-platform.giantswarm.io/agent-chart-ready-release-versions" + +// releaseVersion is one entry of MigrationReadyVersionsAnnotation. +type releaseVersion struct { + UID string `json:"uid"` + Generation int64 `json:"generation"` +} + +// DefaultMigrationPoll is how often an organization whose chart source is +// held at its major looks for migrate's mark again. +const DefaultMigrationPoll = time.Minute + +const ( + reasonChartSourceHeld = "ChartSourceHeld" + reasonChartRangeInvalid = "ChartRangeInvalid" +) + +// targetMajor is the one release major the configured range admits; a range +// of none (only pre-releases, or not a range) or of several (an open range +// such as >=2.6.0) is refused: the operator could not tell which major's +// values the organization's releases need, and migrate marks one major only. +func (c ChartSource) targetMajor(ns string) (uint64, *notReadyError) { + to := rangeMajors(c.Semver) + if len(to) <= 1 && beyondProbes(c.Semver) { + return 0, ¬ReadyError{reason: reasonChartRangeInvalid, message: fmt.Sprintf( + "the agent chart range %q admits a chart major of %d or more, which the operator does not read, so the chart source in %s is neither created nor moved: configure a range of one major below %d (agentChart.semver, e.g. \">=3.0.0 <4.0.0\")", c.Semver, maxProbedMajor+1, ns, maxProbedMajor+1)} + } + switch len(to) { + case 1: + return to[0], nil + case 0: + return 0, ¬ReadyError{reason: reasonChartRangeInvalid, message: fmt.Sprintf( + "the agent chart range %q admits no release version, so the chart source in %s is neither created nor moved: configure a range of one major (agentChart.semver, e.g. \">=3.0.0 <4.0.0\")", c.Semver, ns)} + default: + return 0, ¬ReadyError{reason: reasonChartRangeInvalid, message: fmt.Sprintf( + "the agent chart range %q admits majors %v, so the chart source in %s is neither created nor moved: agent-manager's migrate readies an organization for one major; bound the range below the next major (agentChart.semver, e.g. \">=3.0.0 <4.0.0\")", c.Semver, to, ns)} + } +} + +// crossesMajor reports whether a source on ref moving to target crosses into +// a higher major: every major ref's range admits is below target. A range +// that admits no release version, or none (a tag or digest the operator never +// writes), is read as below any major, so the move waits too. +func crossesMajor(ref map[string]any, target uint64) bool { + from, _ := ref[fieldSemver].(string) + have := rangeMajors(from) + return len(have) == 0 || have[len(have)-1] < target || (len(have) == 1 && beyondProbes(from)) +} + +// chartSourceHeld is the cause of Ready=False while a chart source waits at +// its major (or, missing, waits to be created); it reconciles the +// organization again after poll. +func chartSourceHeld(ns, name string, major uint64, why string, poll time.Duration) *notReadyError { + return ¬ReadyError{reason: reasonChartSourceHeld, requeueAfter: poll, message: fmt.Sprintf( + "the agent chart source %s/%s is not moved to chart %d.x until agent-manager's migrate marks the namespace ready for it (%s): %s; run migrate again once its report's releases are fixed (kubectl create job --from=cronjob/-agent-manager-migrate)", ns, name, major, MigrationReadyAnnotation, why)} +} + +// releasesOn are the HelmReleases of ns whose chart is the OCIRepository +// name; served is false when the cluster serves no HelmRelease (or none is +// configured). +func (r *OrganizationReconciler) releasesOn(ctx context.Context, reader client.Reader, ns, name string) (rels []unstructured.Unstructured, served bool, err error) { + gvk := r.Config.Erasure.HelmRelease + if gvk.Empty() { + return nil, false, nil + } + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(gvk.GroupVersion().WithKind(gvk.Kind + "List")) + if err := reader.List(ctx, list, client.InNamespace(ns)); err != nil { + if meta.IsNoMatchError(err) || apierrors.IsNotFound(err) { + return nil, false, nil + } + return nil, false, fmt.Errorf("list the HelmReleases of %s: %w", ns, err) + } + for i := range list.Items { + ref, _, _ := unstructured.NestedStringMap(list.Items[i].Object, "spec", "chartRef") + if ref["kind"] == "OCIRepository" && ref[fieldName] == name && (ref[fieldNamespace] == "" || ref[fieldNamespace] == ns) { + rels = append(rels, list.Items[i]) + } + } + return rels, true, nil +} + +// deployedMajor is the chart major a HelmRelease last deployed +// (status.history[0].chartVersion); ok is false when it never deployed one. +func deployedMajor(hr unstructured.Unstructured) (uint64, bool) { + history, _, _ := unstructured.NestedSlice(hr.Object, "status", "history") + if len(history) == 0 { + return 0, false + } + entry, _ := history[0].(map[string]any) + version, _ := entry["chartVersion"].(string) + v, err := semver.NewVersion(version) + if err != nil { + return 0, false + } + return v.Major(), true +} + +// migrationReady reports whether the chart source name in ns may move to (or, +// missing, be created on) major: no HelmRelease of the namespace renders from +// the source, or migrate's report there carries MigrationReadyAnnotation with +// that major and records every such release at its current UID and generation +// in MigrationReadyVersionsAnnotation. +// For a missing source (recreated) only releases whose deployed chart is of a +// lower major count: within a major nothing waits. why says what holds it. +func (r *OrganizationReconciler) migrationReady(ctx context.Context, ns, name string, major uint64, creating bool) (ready bool, why string, err error) { + reader := r.APIReader + if reader == nil { + reader = r.Client + } + rels, served, err := r.releasesOn(ctx, reader, ns, name) + if err != nil { + return false, "", err + } + var using []string + for _, hr := range rels { + if m, ok := deployedMajor(hr); creating && (!ok || m >= major) { + continue + } + using = append(using, hr.GetName()) + } + slices.Sort(using) + if served && len(using) == 0 { + return true, "", nil + } + if creating && !served { + return true, "", nil // nothing to tell a recreated source's releases by + } + report := r.Config.Chart.MigrationReport + if report == "" { + report = DefaultMigrationReport + } + cm := &corev1.ConfigMap{} + switch err := reader.Get(ctx, client.ObjectKey{Namespace: ns, Name: report}, cm); { + case err == nil: + got := cm.Annotations[MigrationReadyAnnotation] + switch { + case got == strconv.FormatUint(major, 10): + versions := map[string]releaseVersion{} + if raw, ok := cm.Annotations[MigrationReadyVersionsAnnotation]; ok { + if err := json.Unmarshal([]byte(raw), &versions); err != nil { + versions = nil + } + } else { + versions = nil + } + if versions == nil { + why = fmt.Sprintf("its report %s marks it ready without the release versions (%s) the move is bound to", report, MigrationReadyVersionsAnnotation) + break + } + var after, changed []string + for _, hr := range rels { + if !slices.Contains(using, hr.GetName()) { + continue + } + v, ok := versions[hr.GetName()] + switch { + case !ok: + after = append(after, hr.GetName()) + case v.UID != string(hr.GetUID()) || v.Generation != hr.GetGeneration(): + changed = append(changed, hr.GetName()) + } + } + slices.Sort(after) + slices.Sort(changed) + if len(after) == 0 && len(changed) == 0 { + return true, "", nil + } + var parts []string + if len(after) > 0 { + parts = append(parts, fmt.Sprintf("HelmReleases %v on the source were created after that run", after)) + } + if len(changed) > 0 { + parts = append(parts, fmt.Sprintf("HelmReleases %v were recreated or changed since that run", changed)) + } + why = fmt.Sprintf("its report %s marks it ready, but %s", report, strings.Join(parts, "; ")) + case got != "": + why = fmt.Sprintf("its report %s marks it ready for %s.x only", report, got) + default: + why = fmt.Sprintf("its report %s names releases not on %d.x values yet", report, major) + } + case apierrors.IsNotFound(err): + why = fmt.Sprintf("no migrate run has written its report %s there yet", report) + default: + return false, "", fmt.Errorf("get the migrate report %s/%s: %w", ns, report, err) + } + if len(using) > 0 { + why = fmt.Sprintf("%s; HelmReleases on it: %v", why, using) + } + return false, why, nil +} + +// versionLiteral is a version a range names (2, 2.6, 2.6.1, v3.0.0-rc.1). +var versionLiteral = regexp.MustCompile(`v?([0-9]+)(?:\.([0-9]+))?(?:\.([0-9]+))?`) + +// maxProbedMajor is the last major rangeMajors probes. +const maxProbedMajor = 99 + +// beyondProbes reports a range that admits a version of a major above +// maxProbedMajor (one it names, or any of major 100): rangeMajors would read its majors short, so +// it is refused as unsupported (as agent-manager's migrate and the +// agent-platform chart refuse it). +func beyondProbes(rng string) bool { + c, err := semver.NewConstraint(rng) + if err != nil { + return false + } + for _, lit := range versionLiteral.FindAllStringSubmatch(rng, -1) { + maj, err := strconv.ParseUint(lit[1], 10, 64) + if err != nil { + return true + } + if maj <= maxProbedMajor { + continue + } + minor, err2 := strconv.ParseUint("0"+lit[2], 10, 64) + patch, err3 := strconv.ParseUint("0"+lit[3], 10, 64) + if err2 != nil || err3 != nil { + return true + } + for _, v := range []*semver.Version{semver.New(maj, minor, patch, "", ""), semver.New(maj, minor, patch+1, "", ""), semver.New(maj, minor+1, 0, "", "")} { + if c.Check(v) { + return true + } + } + } + const late = 999999 + m := uint64(maxProbedMajor + 1) + if c.Check(semver.New(m, late, late, "", "")) { + return true + } + for n := range uint64(200) { + if c.Check(semver.New(m, n, 0, "", "")) || c.Check(semver.New(m, n, late, "", "")) { + return true + } + } + return false +} + +// rangeMajors are the release majors a semver range admits, sorted; none when +// it does not parse. Read as agent-manager's migrate reads a target range +// (internal/migrate majorsOf) and the agent-platform chart's guard +// (agent-platform.agentChart.majors): every version the range names, with the +// next patch and minor, and per major 0-99 the first and a late version of +// every minor below 200 and a late minor, each counting only when the range +// admits it, so every alternative of a `||` range counts. +// +// Supported grammar, the same in all three: a Masterminds semver range as +// Flux reads it (x-ranges, carets, tildes, comparisons, hyphen ranges, `||` +// alternatives) over release majors 0-99. A range that admits a version of +// major 100 or more is unsupported (beyondProbes) and refused by +// targetMajor. These are finite probes, not a general semver intersection. +func rangeMajors(rng string) []uint64 { + c, err := semver.NewConstraint(rng) + if err != nil { + return nil + } + var majors []uint64 + add := func(m uint64) { + if !slices.Contains(majors, m) { + majors = append(majors, m) + } + } + for _, lit := range versionLiteral.FindAllStringSubmatch(rng, -1) { + parts := make([]uint64, 3) + ok := true + for i, s := range lit[1:] { + if s == "" { + continue + } + n, err := strconv.ParseUint(s, 10, 64) + if err != nil { + ok = false + break + } + parts[i] = n + } + if !ok { + continue + } + for _, v := range []*semver.Version{ + semver.New(parts[0], parts[1], parts[2], "", ""), + semver.New(parts[0], parts[1], parts[2]+1, "", ""), + semver.New(parts[0], parts[1]+1, 0, "", ""), + } { + if c.Check(v) { + add(parts[0]) + } + } + } + const late = 999999 + for m := range uint64(maxProbedMajor + 1) { + if slices.Contains(majors, m) { + continue + } + if c.Check(semver.New(m, late, late, "", "")) { + add(m) + continue + } + for n := range uint64(200) { + if c.Check(semver.New(m, n, 0, "", "")) || c.Check(semver.New(m, n, late, "", "")) { + add(m) + break + } + } + } + slices.Sort(majors) + return majors +} diff --git a/internal/controller/chartsource_test.go b/internal/controller/chartsource_test.go new file mode 100644 index 0000000..8b920ed --- /dev/null +++ b/internal/controller/chartsource_test.go @@ -0,0 +1,483 @@ +package controller + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +const ( + noReport = "no migrate run has written its report" + v2Line = "2.x" + chartNS = "agents-payments-abcde" + chartRange = "2.7.x" + chartInterval = "30m" + fieldProvider = "provider" + fieldTimeout = "timeout" + providerValue = "generic" +) + +// chart is the operator's configured agent chart source: what the platform +// release moved it to. +var chart = ChartSource{ + URL: "oci://registry.example.com/charts/giantswarm/agent", + Semver: chartRange, + SemverFilter: "", + Interval: chartInterval, + APIVersion: "source.toolkit.fluxcd.io/v1", +} + +// chartCopy is an OCIRepository named after the chart in chartNS with labels +// and spec. +func chartCopy(labels map[string]string, spec map[string]any) *unstructured.Unstructured { + u := &unstructured.Unstructured{Object: map[string]any{"spec": spec}} + u.SetGroupVersionKind(schema.FromAPIVersionAndKind(chart.APIVersion, "OCIRepository")) + u.SetNamespace(chartNS) + u.SetName(chart.Name()) + u.SetLabels(labels) + return u +} + +// chartSpec is the spec chart derives, with the fields of other. +func chartSpec(other map[string]any) map[string]any { + spec := map[string]any{fieldInterval: chartInterval, fieldURL: chart.URL, fieldRef: map[string]any{fieldSemver: chartRange}} + for k, v := range other { + spec[k] = v + } + return spec +} + +// oldSpec is the spec an older operator release wrote: another registry, +// range and filter, plus fields the operator does not derive (another +// writer's, or the API server's defaults). +func oldSpec() map[string]any { + return map[string]any{ + fieldInterval: "10m", + fieldURL: "oci://gsoci.azurecr.io/charts/giantswarm/agent", + fieldRef: map[string]any{fieldSemver: "2.6.x", "semverFilter": "-dev", "tag": "2.6.0"}, + "insecure": true, + fieldProvider: providerValue, + } +} + +// The chart source of an organization follows the operator's configuration +// on every reconcile: the fields it derives (url, interval, ref) are written, +// every other field and label stays, an unchanged copy is not written again, +// and an object of that name the operator did not write is left alone. +func TestEnsureChartSource(t *testing.T) { + own := ownLabels(ScopeNamespace) + defaulted := map[string]any{fieldProvider: providerValue, fieldTimeout: "60s"} + withNote := map[string]string{ObjectLabel: ScopeNamespace, managedByLabel: managedByValue, "example.com/note": "kept"} + tests := []struct { + name string + existing *unstructured.Unstructured + // want is the spec after the reconcile; wantLabels its labels. + want map[string]any + wantLabels map[string]string + // writes is how many creates and updates the reconcile makes. + writes int + }{ + { + name: "a missing source is created", + want: chartSpec(nil), + wantLabels: own, + writes: 1, + }, + { + name: "an older source moves to the configured url, range and interval, keeping the fields and labels it does not derive", + existing: chartCopy(withNote, oldSpec()), + want: chartSpec(map[string]any{"insecure": true, fieldProvider: providerValue}), + wantLabels: withNote, + writes: 1, + }, + { + name: "a source at the configured spec, with defaulted fields, is not written", + existing: chartCopy(own, chartSpec(defaulted)), + want: chartSpec(defaulted), + // Unchanged: no write, no hot loop. + wantLabels: own, + writes: 0, + }, + { + name: "an interval that alone differs is written", + existing: chartCopy(own, chartSpec(map[string]any{fieldInterval: "5m"})), + want: chartSpec(nil), + wantLabels: own, + writes: 1, + }, + { + name: "a missing own label alone is written, the other labels kept", + existing: chartCopy(map[string]string{ObjectLabel: ScopeNamespace, "example.com/note": "kept"}, chartSpec(nil)), + want: chartSpec(nil), + wantLabels: withNote, + writes: 1, + }, + { + name: "a source of that name the operator did not write is left alone", + existing: chartCopy(map[string]string{"app.kubernetes.io/managed-by": "someone-else"}, oldSpec()), + want: oldSpec(), + wantLabels: map[string]string{"app.kubernetes.io/managed-by": "someone-else"}, + writes: 0, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + b := fake.NewClientBuilder().WithScheme(runtime.NewScheme()) + if tc.existing != nil { + b = b.WithObjects(tc.existing) + } + writes := 0 + c := b.WithInterceptorFuncs(interceptor.Funcs{ + Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + writes++ + return c.Create(ctx, obj, opts...) + }, + Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + writes++ + return c.Update(ctx, obj, opts...) + }, + }).Build() + r := &OrganizationReconciler{Client: c, Config: Config{Chart: chart}} + + require.NoError(t, r.ensureChartSource(t.Context(), chartNS)) + assert.Equal(t, tc.writes, writes) + + got := chartCopy(nil, nil) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + assert.Equal(t, tc.want, got.Object["spec"]) + assert.Equal(t, tc.wantLabels, got.GetLabels()) + + // A second reconcile of what the first left writes nothing. + writes = 0 + require.NoError(t, r.ensureChartSource(t.Context(), chartNS)) + assert.Zero(t, writes, "the second reconcile wrote the source again") + }) + } +} + +// A configured semverFilter is written into ref, and dropped again once the +// configuration has none. +func TestEnsureChartSourceSemverFilter(t *testing.T) { + c := fake.NewClientBuilder().WithScheme(runtime.NewScheme()).WithObjects(chartCopy(ownLabels(ScopeNamespace), oldSpec())).Build() + filtered := chart + filtered.SemverFilter = ".*-rc.*" + r := &OrganizationReconciler{Client: c, Config: Config{Chart: filtered}} + require.NoError(t, r.ensureChartSource(t.Context(), chartNS)) + + got := chartCopy(nil, nil) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + ref, _, _ := unstructured.NestedMap(got.Object, "spec", fieldRef) + assert.Equal(t, map[string]any{fieldSemver: chartRange, "semverFilter": ".*-rc.*"}, ref) + + r.Config.Chart = chart + require.NoError(t, r.ensureChartSource(t.Context(), chartNS)) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + ref, _, _ = unstructured.NestedMap(got.Object, "spec", fieldRef) + assert.Equal(t, map[string]any{fieldSemver: chartRange}, ref) +} + +// triageRelease is the HelmRelease the chart-source tests put on the source. +const triageRelease = "triage" + +var testHelmReleaseGVK = schema.GroupVersionKind{Group: "helm.toolkit.fluxcd.io", Version: "v2", Kind: "HelmRelease"} + +// chartRelease is a HelmRelease in chartNS whose chart is the OCIRepository +// source. +func chartRelease(name, source string) *unstructured.Unstructured { + u := &unstructured.Unstructured{Object: map[string]any{"spec": map[string]any{ + "chartRef": map[string]any{"kind": "OCIRepository", fieldName: source}, + }}} + u.SetGroupVersionKind(testHelmReleaseGVK) + u.SetNamespace(chartNS) + u.SetName(name) + u.SetUID(types.UID("uid-" + name)) + u.SetGeneration(1) + return u +} + +// deployed is a release that last deployed chart version. +func deployed(hr *unstructured.Unstructured, version string) *unstructured.Unstructured { + _ = unstructured.SetNestedSlice(hr.Object, []any{map[string]any{"chartVersion": version, "status": "deployed"}}, "status", "history") + return hr +} + +// deployedHistory is a release whose Helm history lists versions newest +// first, as Flux writes it (status.history[0] is the last deployed). +func deployedHistory(hr *unstructured.Unstructured, versions ...string) *unstructured.Unstructured { + var history []any + for _, v := range versions { + history = append(history, map[string]any{"chartVersion": v, "status": "deployed"}) + } + _ = unstructured.SetNestedSlice(hr.Object, history, "status", "history") + return hr +} + +// migrateReport is agent-manager migrate's report in chartNS, marked ready +// for major, naming releases at the UID and generation chartRelease gives +// them, when major is not empty. +func migrateReport(major string, releases ...string) *corev1.ConfigMap { + versions := map[string]releaseVersion{} + for _, name := range releases { + versions[name] = releaseVersion{UID: "uid-" + name, Generation: 1} + } + return migrateReportWith(major, releases, versions) +} + +// migrateReportWith is migrateReport with the versions it records; nil +// versions leave the annotation out (an older agent-manager's mark). +func migrateReportWith(major string, releases []string, versions map[string]releaseVersion) *corev1.ConfigMap { + cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: chartNS, Name: DefaultMigrationReport}} + if major != "" { + cm.Annotations = map[string]string{MigrationReadyAnnotation: major, MigrationReadyReleasesAnnotation: strings.Join(releases, ",")} + if versions != nil { + raw, _ := json.Marshal(versions) + cm.Annotations[MigrationReadyVersionsAnnotation] = string(raw) + } + } + return cm +} + +// gateScheme knows ConfigMaps and the HelmRelease as unstructured. +func gateScheme(t *testing.T) *runtime.Scheme { + t.Helper() + scheme := runtime.NewScheme() + require.NoError(t, corev1.AddToScheme(scheme)) + scheme.AddKnownTypeWithName(testHelmReleaseGVK, &unstructured.Unstructured{}) + scheme.AddKnownTypeWithName(testHelmReleaseGVK.GroupVersion().WithKind("HelmReleaseList"), &unstructured.UnstructuredList{}) + return scheme +} + +// A move of an organization's chart source to a higher major waits for +// agent-manager migrate's mark on its report in the namespace, unless no +// HelmRelease there uses the source (D-GO-03). Held, the source keeps its +// ref while url and interval still follow, and the organization is not Ready +// (ChartSourceHeld) with a requeue after MigrationPoll. +func TestEnsureChartSourceWaitsForMigrateAcrossAMajor(t *testing.T) { + const v3 = ">=3.0.0 <4.0.0" + v2Ref := map[string]any{fieldSemver: v2Line} + tests := []struct { + name string + semver string + from map[string]any + objects []client.Object + moved bool + mentions string + }{ + {name: "a release on the source and no report: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, mentions: noReport}, + {name: "a report without the mark: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), migrateReport("")}, mentions: "names releases not on 3.x values yet"}, + {name: "a report marked for the old major: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), migrateReport("2")}, mentions: "ready for 2.x only"}, + {name: "a report marked for the new major: moved", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), migrateReport("3", triageRelease)}, moved: true}, + {name: "a release created after migrate's run: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), chartRelease("late", chart.Name()), migrateReport("3", triageRelease)}, + mentions: "HelmReleases [late] on the source were created after that run"}, + {name: "a release recreated under the same name after migrate's run: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), + migrateReportWith("3", []string{triageRelease}, map[string]releaseVersion{triageRelease: {UID: "uid-before", Generation: 1}})}, + mentions: "HelmReleases [triage] were recreated or changed since that run"}, + {name: "a release whose spec changed after migrate's run: held", semver: v3, from: v2Ref, + objects: []client.Object{func() client.Object { + hr := chartRelease(triageRelease, chart.Name()) + hr.SetGeneration(2) + return hr + }(), migrateReport("3", triageRelease)}, + mentions: "HelmReleases [triage] were recreated or changed since that run"}, + {name: "a mark without release versions: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), migrateReportWith("3", []string{triageRelease}, nil)}, + mentions: "without the release versions"}, + {name: "a source on a tag names no major: held", semver: v3, from: map[string]any{"tag": "latest"}, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, mentions: noReport}, + {name: "a source on a digest names no major: held", semver: v3, from: map[string]any{"digest": "sha256:0000000000000000000000000000000000000000000000000000000000000000"}, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, mentions: noReport}, + {name: "a release of another kind with the source's name does not count", semver: v3, from: v2Ref, + objects: []client.Object{func() client.Object { + hr := chartRelease("chart", chart.Name()) + _ = unstructured.SetNestedField(hr.Object, "HelmChart", "spec", "chartRef", "kind") + return hr + }()}, moved: true}, + {name: "no release on the source: moved without a report", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease("dashboards", "dashboards")}, moved: true}, + {name: "a move within a major never waits", semver: chartRange, from: map[string]any{fieldSemver: "2.6.x"}, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, moved: true}, + {name: "a move back down never waits", semver: v2Line, from: map[string]any{fieldSemver: v3}, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, moved: true}, + {name: "an alternative of the old range on the new major: no move across", semver: v3, from: map[string]any{fieldSemver: "2.6.0 || 3.0.1"}, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, moved: true}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + scheme := gateScheme(t) + spec := chartSpec(map[string]any{fieldURL: "oci://old.example.com/charts/giantswarm/agent", fieldRef: tc.from}) + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(append(tc.objects, chartCopy(ownLabels(ScopeNamespace), spec))...).Build() + cfg := chart + cfg.Semver = tc.semver + cfg.MigrationPoll = 7 * time.Second + r := &OrganizationReconciler{Client: c, Config: Config{Chart: cfg, Erasure: ErasureConfig{HelmRelease: testHelmReleaseGVK}}} + + err := r.ensureChartSource(t.Context(), chartNS) + got := chartCopy(nil, nil) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + url, _, _ := unstructured.NestedString(got.Object, "spec", fieldURL) + assert.Equal(t, chart.URL, url, "the url follows either way") + ref, _, _ := unstructured.NestedMap(got.Object, "spec", fieldRef) + if tc.moved { + require.NoError(t, err) + assert.Equal(t, map[string]any{fieldSemver: tc.semver}, ref) + return + } + assert.Equal(t, tc.from, ref, "the ref stays on the old major") + var nr *notReadyError + require.ErrorAs(t, err, &nr) + assert.Equal(t, reasonChartSourceHeld, nr.reason) + assert.Contains(t, nr.message, tc.mentions) + assert.Contains(t, nr.message, MigrationReadyAnnotation) + assert.Equal(t, 7*time.Second, requeueAfter(errors.Join(errors.New("another failure"), err))) + ready, retry := readyCondition(err, 1) + assert.NoError(t, retry, "a held source is no failure to retry") + assert.Equal(t, reasonChartSourceHeld, ready.Reason) + + // A second reconcile writes nothing more. + rv := got.GetResourceVersion() + require.Error(t, r.ensureChartSource(t.Context(), chartNS)) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + assert.Equal(t, rv, got.GetResourceVersion()) + }) + } +} + +// The majors a range admits, read as agent-manager's migrate and the +// agent-platform chart read them (D-GO-08). +func TestRangeMajors(t *testing.T) { + for rng, want := range map[string][]uint64{ + "2.x": {2}, + ">=3.0.0 <4.0.0": {3}, + "3.0.1 || 2.6.0": {2, 3}, + ">=2.6.1 <2.6.9": {2}, + "= 2.6.1": {2}, + "~2.250": {2}, + "3.0.0-rc.6": nil, + "not a range": nil, + ">=2.6.0 <=3.0.0-rc.1": {2}, + "2.6.0 || >=3.0.1 <3.0.5": {2, 3}, + } { + assert.Equal(t, want, rangeMajors(rng), rng) + } +} + +// QB-07: a range past the probed majors is refused as unsupported, as +// agent-manager's migrate and the agent-platform chart refuse it, never read +// as the majors below 100 it shows. +func TestTargetMajorRefusesRangesPastMajor99(t *testing.T) { + for _, rng := range []string{">=100.0.0 <102.0.0", "100.x", ">=99.5.0", "^2.0.0 || 150.0.0"} { + _, nr := ChartSource{Semver: rng}.targetMajor("org-a") + require.NotNil(t, nr, rng) + assert.Equal(t, reasonChartRangeInvalid, nr.reason, rng) + } + for _, rng := range []string{">=100.0.0 <102.0.0", ">=99.5.0"} { + _, nr := ChartSource{Semver: rng}.targetMajor("org-a") + assert.Contains(t, nr.message, "chart major of 100 or more", rng) + } + got, nr := ChartSource{Semver: ">=99.0.0 <100.0.0"}.targetMajor("org-a") + require.Nil(t, nr) + assert.Equal(t, uint64(99), got) +} + +// requeueAfter is the shortest a cause of Ready=False asks for; a failure or +// a cause without one asks for none. +func TestRequeueAfter(t *testing.T) { + assert.Zero(t, requeueAfter(nil)) + assert.Zero(t, requeueAfter(errors.Join(errors.New("failed"), ¬ReadyError{reason: reasonNameTaken}))) + assert.Equal(t, time.Second, requeueAfter(errors.Join(¬ReadyError{requeueAfter: time.Minute}, ¬ReadyError{requeueAfter: time.Second}))) +} + +// A configured range of no release major or of several creates and moves +// nothing and says so (ChartRangeInvalid), never waiting silently for a mark +// migrate cannot write (D-GO-29). +func TestEnsureChartSourceRefusesARangeOfNoneOrSeveralMajors(t *testing.T) { + for rng, mentions := range map[string]string{ + "3.0.0-rc.1": "admits no release version", + "not a range": "admits no release version", + ">=2.6.0": "admits majors [2 3 4", + "2.6.0 || 3.0.1": "admits majors [2 3]", + } { + t.Run(rng, func(t *testing.T) { + from := map[string]any{fieldSemver: v2Line} + c := fake.NewClientBuilder().WithScheme(gateScheme(t)).WithObjects(chartCopy(ownLabels(ScopeNamespace), chartSpec(map[string]any{fieldRef: from}))).Build() + cfg := chart + cfg.Semver = rng + r := &OrganizationReconciler{Client: c, Config: Config{Chart: cfg, Erasure: ErasureConfig{HelmRelease: testHelmReleaseGVK}}} + err := r.ensureChartSource(t.Context(), chartNS) + var nr *notReadyError + require.ErrorAs(t, err, &nr) + assert.Equal(t, reasonChartRangeInvalid, nr.reason) + assert.Contains(t, nr.message, mentions) + got := chartCopy(nil, nil) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + ref, _, _ := unstructured.NestedMap(got.Object, "spec", fieldRef) + assert.Equal(t, from, ref, "the ref stays") + + // Missing, it is not created on such a range. + c = fake.NewClientBuilder().WithScheme(gateScheme(t)).Build() + r.Client = c + require.ErrorAs(t, r.ensureChartSource(t.Context(), chartNS), &nr) + assert.Equal(t, reasonChartRangeInvalid, nr.reason) + assert.Error(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), chartCopy(nil, nil))) + }) + } +} + +// A recreated source (missing while releases use it) waits for migrate's +// mark when a release there last deployed a lower major (D-GO-29). +func TestEnsureChartSourceRecreatedWaitsForMigrate(t *testing.T) { + const v3 = ">=3.0.0 <4.0.0" + for name, tc := range map[string]struct { + semver string + objects []client.Object + created bool + }{ + "a release on 2.x, no mark: not created": {v3, []client.Object{deployed(chartRelease(triageRelease, chart.Name()), "2.6.1")}, false}, + "a release on 2.x, marked: created": {v3, []client.Object{deployed(chartRelease(triageRelease, chart.Name()), "2.6.1"), migrateReport("3", triageRelease)}, true}, + "a release already on 3.x: created": {v3, []client.Object{deployed(chartRelease(triageRelease, chart.Name()), "3.0.0")}, true}, + "a release never deployed: created": {v3, []client.Object{chartRelease(triageRelease, chart.Name())}, true}, + "a release deployed 2.x once, now on 3.x (newest history first): created": {v3, []client.Object{deployedHistory(chartRelease(triageRelease, chart.Name()), "3.0.0", "2.6.1")}, true}, + "a release now on 2.x after 3.x (newest history first): not created": {v3, []client.Object{deployedHistory(chartRelease(triageRelease, chart.Name()), "2.6.1", "3.0.0")}, false}, + "within a major nothing waits": {chartRange, []client.Object{deployed(chartRelease(triageRelease, chart.Name()), "2.6.1")}, true}, + } { + t.Run(name, func(t *testing.T) { + c := fake.NewClientBuilder().WithScheme(gateScheme(t)).WithObjects(tc.objects...).Build() + cfg := chart + cfg.Semver = tc.semver + r := &OrganizationReconciler{Client: c, Config: Config{Chart: cfg, Erasure: ErasureConfig{HelmRelease: testHelmReleaseGVK}}} + err := r.ensureChartSource(t.Context(), chartNS) + getErr := c.Get(t.Context(), client.ObjectKeyFromObject(chartCopy(nil, nil)), chartCopy(nil, nil)) + if tc.created { + require.NoError(t, err) + require.NoError(t, getErr) + return + } + var nr *notReadyError + require.ErrorAs(t, err, &nr) + assert.Equal(t, reasonChartSourceHeld, nr.reason) + assert.Contains(t, nr.message, "HelmReleases on it: [triage]") + assert.Error(t, getErr, "not created") + }) + } +} diff --git a/internal/controller/envtest_test.go b/internal/controller/envtest_test.go index 1b00f80..4cc40b4 100644 --- a/internal/controller/envtest_test.go +++ b/internal/controller/envtest_test.go @@ -30,6 +30,7 @@ import ( "k8s.io/client-go/rest" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + ctrlconfig "sigs.k8s.io/controller-runtime/pkg/config" "sigs.k8s.io/controller-runtime/pkg/envtest" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" @@ -128,6 +129,8 @@ type cluster struct { rest *rest.Config // config is the reconciler's Config. config controller.Config + // operator is the operator's user, as the chart's RBAC binds it. + operator string // log records, in order, what the erasure did through the fakes of // kagent's session API, Substrate's actors and the snapshot bucket, and // what the erasure observers saw it delete. @@ -145,7 +148,7 @@ type cluster struct { // commit mode, as the chart's ServiceAccount. Skipped without envtest binaries: run via // `make test-envtest`, which resolves KUBEBUILDER_ASSETS with setup-envtest // (and needs helm). -func startEnvtest(t *testing.T) *cluster { +func startEnvtest(t *testing.T, options ...func(*controller.Config)) *cluster { t.Helper() if os.Getenv("KUBEBUILDER_ASSETS") == "" { t.Skip("KUBEBUILDER_ASSETS not set; run via `make test-envtest`") @@ -235,13 +238,14 @@ func startEnvtest(t *testing.T) *cluster { sessions := &fakeSessions{log: log, byID: map[string]*fakeSession{}, pkg: pkgV1alpha1} actors := &fakeActors{log: log, sessions: sessions, linger: map[string]int{}} bucket := &fakeBucket{log: log, objects: map[string]int{}, fail: map[string]error{}} - c := &cluster{admin: admin, rest: cfg, log: log, sessions: sessions, actors: actors, bucket: bucket, config: controller.Config{ + c := &cluster{admin: admin, rest: cfg, operator: operator, log: log, sessions: sessions, actors: actors, bucket: bucket, config: controller.Config{ PlatformNamespace: platformNS, NetworkPolicies: []string{workerPolicy}, NetworkPolicyGVK: npGVK, Chart: controller.ChartSource{ URL: "oci://gsoci.azurecr.io/charts/giantswarm/agent", Semver: "2.x", - Interval: "30m", APIVersion: ociGVK.GroupVersion().String(), + Interval: chartInterval, APIVersion: ociGVK.GroupVersion().String(), + MigrationPoll: 200 * time.Millisecond, }, HelmServiceAccount: helmSA, HelmClusterRole: helmClusterRole, @@ -266,10 +270,18 @@ func startEnvtest(t *testing.T) *cluster { }, }} + for _, option := range options { + option(&c.config) + } + asOperator := rest.CopyConfig(cfg) asOperator.Impersonate = rest.ImpersonationConfig{UserName: operator} + // Every test starts its own manager in this process, and controller names + // are unique per process unless the validation is skipped. + skipNameValidation := true mgr, err := ctrl.NewManager(asOperator, ctrl.Options{ Scheme: scheme, + Controller: ctrlconfig.Controller{SkipNameValidation: &skipNameValidation}, Cache: controller.CacheOptions(c.config, time.Hour), Metrics: metricsserver.Options{BindAddress: "0"}, HealthProbeBindAddress: "0", @@ -321,7 +333,7 @@ func curatedSources() []*unstructured.Unstructured { obj(agentGVK, curatedAgent, curatedLabels, agentSpec(agentPrompt, map[string]any{"modelConfig": nameRef(platformModel), toolsField: tools})), obj(agentGVK, platformAgent, nil, agentSpec("Platform only.", nil)), obj(templateGVK, curatedTemplate, curatedLabels, templateSpec("Triage.", map[string]any{"modelConfig": nameRef(platformModel), toolsField: tools})), - obj(serverGVK, musterServer, curatedWith(map[string]string{discoveryLabel: "disabled", "app.kubernetes.io/name": "agent"}), map[string]any{"url": "https://muster.example.com/mcp", descriptionField: "muster"}), + obj(serverGVK, musterServer, curatedWith(map[string]string{discoveryLabel: "disabled", "app.kubernetes.io/name": "agent"}), map[string]any{urlField: "https://muster.example.com/mcp", descriptionField: "muster"}), } } @@ -375,6 +387,9 @@ func nameRef(name string) map[string]any { return map[string]any{nameField: name // an agent template. const ( kindField = "kind" + urlField = "url" + semverField = "semver" + chartInterval = "30m" nameField = "name" intervalField = "interval" harnessRefField = "harnessRef" diff --git a/internal/controller/objects.go b/internal/controller/objects.go index cc90637..080b980 100644 --- a/internal/controller/objects.go +++ b/internal/controller/objects.go @@ -7,6 +7,7 @@ import ( "path" "reflect" "strings" + "time" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" @@ -28,13 +29,28 @@ type ChartSource struct { SemverFilter string Interval string APIVersion string + // MigrationReport is agent-manager migrate's report ConfigMap in an + // organization namespace (DefaultMigrationReport when empty): an + // existing source moves across a major only while it carries + // MigrationReadyAnnotation with the new major. MigrationPoll is how often + // a held organization looks again (DefaultMigrationPoll when zero). + MigrationReport string + MigrationPoll time.Duration } +// The OCIRepository fields ChartSource derives. +const ( + fieldURL = "url" + fieldInterval = "interval" + fieldRef = "ref" + fieldSemver = "semver" +) + // Name is the OCIRepository's name: the chart's. func (c ChartSource) Name() string { return path.Base(c.URL) } func (c ChartSource) object(ns string) *unstructured.Unstructured { - ref := map[string]any{"semver": c.Semver} + ref := map[string]any{fieldSemver: c.Semver} if c.SemverFilter != "" { ref["semverFilter"] = c.SemverFilter } @@ -43,9 +59,9 @@ func (c ChartSource) object(ns string) *unstructured.Unstructured { fieldKind: "OCIRepository", "metadata": map[string]any{fieldName: c.Name(), fieldNamespace: ns}, "spec": map[string]any{ - "interval": c.Interval, - "url": c.URL, - "ref": ref, + fieldInterval: c.Interval, + fieldURL: c.URL, + fieldRef: ref, }, }} } @@ -178,19 +194,115 @@ func (r *OrganizationReconciler) ensureScoped(ctx context.Context, ns, scope str return nil } -// ensureExists creates obj when nothing of its name exists and never changes -// it after: the agent chart's source moves to another range only through a -// migration, as in agent-manager. -func (r *OrganizationReconciler) ensureExists(ctx context.Context, ns string, obj *unstructured.Unstructured) error { - stamp(obj, ns, ScopeNamespace, "") - err := r.Client.Get(ctx, client.ObjectKeyFromObject(obj), object(obj.GroupVersionKind())) - if err == nil { +// ensureChartSource keeps the agent chart's OCIRepository in ns at +// Config.Chart. It creates it, and on every reconcile brings the fields the +// operator derives (spec.url, spec.interval and the whole spec.ref) back to +// the configured ones, so a platform release that moves the chart (another +// registry, range or filter) reaches every organization, not only new ones. +// Every other spec field, label and annotation stays as it is, and a source +// at the configured spec is not written. An object of that name the operator +// did not write is left alone. No organization pins its own chart: the +// AgentPlatformOrganization has no such field, and only the operator writes +// the source. +// +// A move of spec.ref to a higher major waits, per organization, for +// agent-manager's migrate (migrationReady): until its report in the +// namespace marks every release there as on the new major's values, the +// source keeps its ref (url and interval still follow), the organization is +// not Ready (reason ChartSourceHeld) and looks again after MigrationPoll. A +// release still on the old major's values would otherwise fail every upgrade +// on the new chart (agent chart 3.0 refuses muster.requireApproval) and stay +// on its old revision until edited by hand. A missing source whose +// namespace has releases deployed from a lower major is not created until +// the same mark. A configured range of no or several majors creates and +// moves nothing (reason ChartRangeInvalid). +func (r *OrganizationReconciler) ensureChartSource(ctx context.Context, ns string) error { + want := r.Config.Chart.object(ns) + wantLabels := stamp(want, ns, ScopeNamespace, "") + kind := want.GetKind() + poll := r.Config.Chart.MigrationPoll + if poll <= 0 { + poll = DefaultMigrationPoll + } + target, invalid := r.Config.Chart.targetMajor(ns) + existing := object(want.GroupVersionKind()) + err := r.Client.Get(ctx, client.ObjectKeyFromObject(want), existing) + switch { + case apierrors.IsNotFound(err): + if invalid != nil { + return invalid + } + // A recreated source: releases deployed from a lower major still + // wait for migrate's mark, as a move of the source would. + ready, why, err := r.migrationReady(ctx, ns, want.GetName(), target, true) + if err != nil { + return err + } + if !ready { + return chartSourceHeld(ns, want.GetName(), target, why, poll) + } + return r.create(ctx, want, kind) + case err != nil: + return fmt.Errorf("get %s %s/%s: %w", kind, ns, want.GetName(), err) + } + if existing.GetLabels()[ObjectLabel] != ScopeNamespace { + logf.FromContext(ctx).V(1).Info("leaving an object the reconciler did not write", "namespace", ns, "kind", kind, "name", want.GetName()) return nil } - if !apierrors.IsNotFound(err) { - return fmt.Errorf("get %s %s/%s: %w", obj.GetKind(), ns, obj.GetName(), err) + spec, _ := existing.Object["spec"].(map[string]any) + if spec == nil { + spec = map[string]any{} + } + wantSpec, _ := want.Object["spec"].(map[string]any) + var held error + if invalid != nil { + // An invalid range is reported also when the source already carries + // it: Flux would move it to a major migrate never marked (D-GO-37). + held = invalid + } + if !reflect.DeepEqual(spec[fieldRef], wantSpec[fieldRef]) { + have, _ := spec[fieldRef].(map[string]any) + switch { + case invalid != nil: + case crossesMajor(have, target): + ready, why, err := r.migrationReady(ctx, ns, want.GetName(), target, false) + if err != nil { + return err + } + if !ready { + held = chartSourceHeld(ns, want.GetName(), target, why, poll) + } + } + if held != nil { + wantSpec = maps.Clone(wantSpec) + wantSpec[fieldRef] = spec[fieldRef] + } + } + labels := copiedLabels(existing.GetLabels(), wantLabels, false) + same := maps.Equal(labels, existing.GetLabels()) + for k, v := range wantSpec { + same = same && reflect.DeepEqual(spec[k], v) + } + if same { + return held + } + from := map[string]any{fieldURL: spec[fieldURL], fieldRef: spec[fieldRef], fieldInterval: spec[fieldInterval]} + maps.Copy(spec, wantSpec) + existing.Object["spec"] = spec + existing.SetLabels(labels) + before := existing.GetResourceVersion() + if err := r.Client.Update(ctx, existing, client.FieldOwner(fieldManager)); err != nil { + return fmt.Errorf("update %s %s/%s: %w", kind, ns, want.GetName(), err) + } + if existing.GetResourceVersion() == before { + // The API server stored nothing: a field its CRD prunes or a value + // it normalises differs from what the operator derives. Not a change. + logf.FromContext(ctx).V(1).Info("organization chart source written, nothing stored", "namespace", ns, "kind", kind, "name", want.GetName()) + return held } - return r.create(ctx, obj, obj.GetKind()) + logf.FromContext(ctx).Info("organization chart source updated", "namespace", ns, "kind", kind, "name", want.GetName(), + "from", from, "to", wantSpec) + return held } // contains reports whether every field of want is in have with the same diff --git a/internal/controller/organization.go b/internal/controller/organization.go index 3cdb844..6dab01d 100644 --- a/internal/controller/organization.go +++ b/internal/controller/organization.go @@ -17,7 +17,8 @@ // In the namespace the reconciler keeps, from the first reconcile on: // // - the network policies copied from the platform namespace; -// - the agent chart's OCIRepository; +// - the agent chart's OCIRepository, whose url, interval and ref follow +// Config.Chart (ensureChartSource); // - the Helm ServiceAccount the organization's HelmReleases run as, with its // RoleBinding to the ClusterRole Config.HelmClusterRole // (agent-platform-tenant-flux by default); @@ -417,12 +418,26 @@ func (r *OrganizationReconciler) Reconcile(ctx context.Context, req reconcile.Re // First: the worker replica rule reads it. orphanedErr := r.setOrphaned(ctx, org, status) - ready, err := readyCondition(errors.Join(orphanedErr, r.reconcile(ctx, org, status)), org.Generation) + reconcileErr := errors.Join(orphanedErr, r.reconcile(ctx, org, status)) + ready, err := readyCondition(reconcileErr, org.Generation) meta.SetStatusCondition(&status.Conditions, ready) if uerr := r.writeStatus(ctx, org, status); uerr != nil { return reconcile.Result{}, errors.Join(err, uerr) } - return reconcile.Result{}, err + return reconcile.Result{RequeueAfter: requeueAfter(reconcileErr)}, err +} + +// requeueAfter is the shortest requeueAfter of the causes of Ready=False in +// err; zero when none asks for one. +func requeueAfter(err error) time.Duration { + _, notReady := split(err) + var after time.Duration + for _, nr := range notReady { + if nr.requeueAfter > 0 && (after == 0 || nr.requeueAfter < after) { + after = nr.requeueAfter + } + } + return after } // reportSwitchOff reports an organization whose Agent Platform was turned @@ -553,7 +568,7 @@ func (r *OrganizationReconciler) reconcile(ctx context.Context, org *orgv1.Organ } var errs []error if r.Config.Chart.URL != "" { - errs = append(errs, r.ensureExists(ctx, ns.Name, r.Config.Chart.object(ns.Name))) + errs = append(errs, r.ensureChartSource(ctx, ns.Name)) } if sa := r.Config.HelmServiceAccount; sa != "" { errs = append(errs, r.ensureServiceAccount(ctx, ns.Name, sa, ScopeNamespace), r.ensureHelmRoleBinding(ctx, ns.Name)) @@ -577,8 +592,13 @@ func (r *OrganizationReconciler) reconcile(ctx context.Context, org *orgv1.Organ } // notReadyError is a cause of AgentPlatformReady=False that a retry does not -// change: the reconcile has done what it can. -type notReadyError struct{ reason, message string } +// change: the reconcile has done what it can. With requeueAfter the +// organization is reconciled again after that long, for a cause no watched +// event ends (the chart source held for migrate, chartSourceHeld). +type notReadyError struct { + reason, message string + requeueAfter time.Duration +} func (e *notReadyError) Error() string { return e.message } diff --git a/internal/controller/organization_envtest_test.go b/internal/controller/organization_envtest_test.go index 56e6c4a..5b73287 100644 --- a/internal/controller/organization_envtest_test.go +++ b/internal/controller/organization_envtest_test.go @@ -25,6 +25,8 @@ import ( ) const ( + // oldLine is an agent chart range of an older major than the operator's. + oldLine = "1.x" timeout = 30 * time.Second tick = 100 * time.Millisecond kindClusterRole = "ClusterRole" @@ -70,6 +72,161 @@ func TestOrganizationEnvtest(t *testing.T) { assert.Equal(t, []rbacv1.Subject{{Kind: rbacv1.ServiceAccountKind, Name: helmSA, Namespace: ns.Name}}, rb.Subjects) }) + t.Run("the chart source follows the operator's configuration", func(t *testing.T) { + org := c.organization(t, "chart") + ns := c.readyNamespace(t, org) + + // The copy an older operator release wrote: another registry and + // range, plus a field and a label the operator does not derive. + oci := c.read(t, ociGVK, ns.Name, agentChart) + require.NoError(t, unstructured.SetNestedField(oci.Object, "oci://old.example.com/charts/agent", "spec", "url")) + require.NoError(t, unstructured.SetNestedMap(oci.Object, map[string]any{semverField: oldLine, "semverFilter": "-dev"}, "spec", "ref")) + require.NoError(t, unstructured.SetNestedField(oci.Object, "5m", "spec", "interval")) + require.NoError(t, unstructured.SetNestedField(oci.Object, true, "spec", "insecure")) + labels := oci.GetLabels() + labels["example.com/note"] = "kept" + oci.SetLabels(labels) + require.NoError(t, c.admin.Update(t.Context(), oci)) + + c.poke(t, org) + oci = c.eventually(t, ociGVK, ns.Name, agentChart, func(ct *assert.CollectT, u *unstructured.Unstructured) { + url, _, _ := unstructured.NestedString(u.Object, "spec", "url") + ref, _, _ := unstructured.NestedMap(u.Object, "spec", "ref") + interval, _, _ := unstructured.NestedString(u.Object, "spec", "interval") + assert.Equal(ct, c.config.Chart.URL, url) + assert.Equal(ct, map[string]any{semverField: c.config.Chart.Semver}, ref) + assert.Equal(ct, c.config.Chart.Interval, interval) + }) + insecure, _, _ := unstructured.NestedBool(oci.Object, "spec", "insecure") + assert.True(t, insecure, "a field the operator does not derive was dropped") + assert.Equal(t, "kept", oci.GetLabels()["example.com/note"]) + + // A reconcile of a source at the configured spec writes nothing. + c.poke(t, org) + rv := oci.GetResourceVersion() + require.Never(t, func() bool { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(ociGVK) + if err := c.admin.Get(t.Context(), client.ObjectKey{Namespace: ns.Name, Name: agentChart}, u); err != nil { + return true + } + return u.GetResourceVersion() != rv + }, 2*time.Second, tick, "the chart source was written again with nothing to change") + }) + + t.Run("a move of the chart source to a higher major waits for migrate's mark", func(t *testing.T) { + org := c.organization(t, "major") + ns := c.readyNamespace(t, org) + oci := c.read(t, ociGVK, ns.Name, agentChart) + require.NoError(t, unstructured.SetNestedMap(oci.Object, map[string]any{semverField: oldLine}, "spec", "ref")) + require.NoError(t, c.admin.Update(t.Context(), oci)) + hr := newObject(helmReleaseGVK, ns.Name, "triage", nil, helmReleaseSpec) + require.NoError(t, c.admin.Create(t.Context(), hr)) + + c.poke(t, org) + require.EventuallyWithT(t, func(ct *assert.CollectT) { + ready := meta.FindStatusCondition(c.get(ct, org).Status.Conditions, orgv1.AgentPlatformReady) + if assert.NotNil(ct, ready) { + assert.Equal(ct, metav1.ConditionFalse, ready.Status) + assert.Equal(ct, "ChartSourceHeld", ready.Reason) + assert.Contains(ct, ready.Message, controller.MigrationReadyAnnotation) + } + }, timeout, tick) + ref, _, _ := unstructured.NestedMap(c.read(t, ociGVK, ns.Name, agentChart).Object, "spec", "ref") + assert.Equal(t, map[string]any{semverField: oldLine}, ref, "the source stays on its major") + + // migrate's mark for the new major, recording the release as it is: + // the held organization looks again on its own (MigrationPoll) and + // moves. + require.NoError(t, c.admin.Create(t.Context(), migrateMark(t, ns.Name, c.read(t, helmReleaseGVK, ns.Name, "triage")))) + c.eventually(t, ociGVK, ns.Name, agentChart, func(ct *assert.CollectT, u *unstructured.Unstructured) { + ref, _, _ := unstructured.NestedMap(u.Object, "spec", "ref") + assert.Equal(ct, map[string]any{semverField: c.config.Chart.Semver}, ref) + }) + c.readyAt(t, org, org.Generation) + }) + + // The mark covers the releases as migrate's run left them: one recreated + // under the same name, or whose spec changed after the run, holds the + // move with a condition naming it until migrate runs again. + for _, tc := range []struct { + name string + change func(t *testing.T, ns string) + }{ + {name: "recreated", change: func(t *testing.T, ns string) { + require.NoError(t, c.admin.Delete(t.Context(), c.read(t, helmReleaseGVK, ns, "triage"))) + require.Eventually(t, func() bool { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(helmReleaseGVK) + return apierrors.IsNotFound(c.admin.Get(t.Context(), client.ObjectKey{Namespace: ns, Name: "triage"}, u)) + }, timeout, tick) + require.NoError(t, c.admin.Create(t.Context(), newObject(helmReleaseGVK, ns, "triage", nil, helmReleaseSpec))) + }}, + {name: "edited", change: func(t *testing.T, ns string) { + hr := c.read(t, helmReleaseGVK, ns, "triage") + require.NoError(t, unstructured.SetNestedField(hr.Object, "45m", "spec", intervalField)) + require.NoError(t, c.admin.Update(t.Context(), hr)) + }}, + } { + t.Run("a release "+tc.name+" after migrate's run holds the move until migrate runs again", func(t *testing.T) { + org := c.organization(t, "major-"+tc.name) + ns := c.readyNamespace(t, org) + oci := c.read(t, ociGVK, ns.Name, agentChart) + require.NoError(t, unstructured.SetNestedMap(oci.Object, map[string]any{semverField: oldLine}, "spec", "ref")) + require.NoError(t, c.admin.Update(t.Context(), oci)) + require.NoError(t, c.admin.Create(t.Context(), newObject(helmReleaseGVK, ns.Name, "triage", nil, helmReleaseSpec))) + // What migrate's run recorded, then the change after it. + mark := migrateMark(t, ns.Name, c.read(t, helmReleaseGVK, ns.Name, "triage")) + tc.change(t, ns.Name) + require.NoError(t, c.admin.Create(t.Context(), mark)) + + c.poke(t, org) + require.EventuallyWithT(t, func(ct *assert.CollectT) { + ready := meta.FindStatusCondition(c.get(ct, org).Status.Conditions, orgv1.AgentPlatformReady) + if assert.NotNil(ct, ready) { + assert.Equal(ct, metav1.ConditionFalse, ready.Status) + assert.Equal(ct, "ChartSourceHeld", ready.Reason) + assert.Contains(ct, ready.Message, "HelmReleases [triage] were recreated or changed since that run") + } + }, timeout, tick) + require.Never(t, func() bool { + ref, _, _ := unstructured.NestedMap(c.read(t, ociGVK, ns.Name, agentChart).Object, "spec", "ref") + return ref[semverField] != oldLine + }, 2*time.Second, tick, "the source stays on its major") + + // migrate runs again and records the release as it is now. + again := migrateMark(t, ns.Name, c.read(t, helmReleaseGVK, ns.Name, "triage")) + cm := &corev1.ConfigMap{} + require.NoError(t, c.admin.Get(t.Context(), client.ObjectKeyFromObject(again), cm)) + cm.Annotations = again.Annotations + require.NoError(t, c.admin.Update(t.Context(), cm)) + c.eventually(t, ociGVK, ns.Name, agentChart, func(ct *assert.CollectT, u *unstructured.Unstructured) { + ref, _, _ := unstructured.NestedMap(u.Object, "spec", "ref") + assert.Equal(ct, map[string]any{semverField: c.config.Chart.Semver}, ref) + }) + c.readyAt(t, org, org.Generation) + }) + } + + t.Run("the operator updates no OCIRepository but the chart's and reads no ConfigMap but migrate's report", func(t *testing.T) { + org := c.organization(t, "rbac") + ns := c.readyNamespace(t, org) + other := newObject(ociGVK, ns.Name, "dashboards", nil, map[string]any{intervalField: chartInterval, urlField: "oci://example.com/charts/dashboards"}) + require.NoError(t, c.admin.Create(t.Context(), other)) + other = c.read(t, ociGVK, ns.Name, "dashboards") + require.NoError(t, unstructured.SetNestedField(other.Object, "oci://attacker.example.com/charts/dashboards", "spec", urlField)) + operator := c.as(t, c.operator) + err := operator.Update(t.Context(), other) + require.True(t, apierrors.IsForbidden(err), "update of another source: %v", err) + + own := c.read(t, ociGVK, ns.Name, agentChart) + require.NoError(t, operator.Update(t.Context(), own), "the chart's own source stays writable") + + require.NoError(t, c.admin.Create(t.Context(), &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: ns.Name, Name: "settings"}})) + err = operator.Get(t.Context(), client.ObjectKey{Namespace: ns.Name, Name: "settings"}, &corev1.ConfigMap{}) + require.True(t, apierrors.IsForbidden(err), "get of another ConfigMap: %v", err) + }) + t.Run("another writer's annotation on the Helm RoleBinding stays", func(t *testing.T) { org := c.organization(t, "notes") ns := c.readyNamespace(t, org) @@ -390,3 +547,73 @@ func (c *cluster) namespacesOf(t *testing.T, org *orgv1.Organization) []corev1.N require.NoError(t, c.admin.List(t.Context(), list, client.MatchingLabels{v1alpha1.OrganizationUIDLabel: string(org.UID)})) return list.Items } + +// A configured range of several majors is reported (ChartRangeInvalid) also +// when the chart source already carries it: Flux would otherwise move the +// source to a major migrate never marked, with Ready staying true (D-GO-37). +func TestChartRangeInvalidEnvtest(t *testing.T) { + const open = ">=2.6.0" + c := startEnvtest(t, func(cfg *controller.Config) { cfg.Chart.Semver = open }) + + invalid := func(ct *assert.CollectT, org *orgv1.Organization) { + ready := meta.FindStatusCondition(c.get(ct, org).Status.Conditions, orgv1.AgentPlatformReady) + if assert.NotNil(ct, ready) { + assert.Equal(ct, metav1.ConditionFalse, ready.Status) + assert.Equal(ct, "ChartRangeInvalid", ready.Reason) + assert.Contains(ct, ready.Message, open) + } + } + + t.Run("a missing source is not created", func(t *testing.T) { + org := c.organization(t, "open-missing") + require.EventuallyWithT(t, func(ct *assert.CollectT) { invalid(ct, org) }, timeout, tick) + c.absent(t, ociGVK, agentsNamespace(c.get(t, org)), agentChart) + }) + + t.Run("a source that carries the range already stays not Ready", func(t *testing.T) { + org := c.organization(t, "open-carried") + var ns string + require.EventuallyWithT(t, func(ct *assert.CollectT) { + ns = agentsNamespace(c.get(ct, org)) + assert.NotEmpty(ct, ns) + }, timeout, tick) + require.EventuallyWithT(t, func(ct *assert.CollectT) { invalid(ct, org) }, timeout, tick) + + // The copy an older operator wrote: the open range, the operator's + // own labels, the operator's url and interval. + src := newObject(ociGVK, ns, agentChart, map[string]string{controller.ObjectLabel: controller.ScopeNamespace}, + map[string]any{urlField: c.config.Chart.URL, intervalField: c.config.Chart.Interval, "ref": map[string]any{semverField: open}}) + require.NoError(t, c.admin.Create(t.Context(), src)) + + c.poke(t, org) + require.Never(t, func() bool { + ready := meta.FindStatusCondition(c.get(t, org).Status.Conditions, orgv1.AgentPlatformReady) + return ready == nil || ready.Status == metav1.ConditionTrue + }, 3*time.Second, tick, "an organization whose source carries an invalid range is Ready") + require.EventuallyWithT(t, func(ct *assert.CollectT) { invalid(ct, org) }, timeout, tick) + ref, _, _ := unstructured.NestedMap(c.read(t, ociGVK, ns, agentChart).Object, "spec", "ref") + assert.Equal(t, map[string]any{semverField: open}, ref, "the operator leaves the ref as it is") + }) +} + +// migrateMark is agent-manager migrate's report in ns marked ready for the +// configured major ("2"), recording each release at its UID and generation. +func migrateMark(t *testing.T, ns string, releases ...*unstructured.Unstructured) *corev1.ConfigMap { + t.Helper() + names := make([]string, 0, len(releases)) + versions := map[string]map[string]any{} + for _, hr := range releases { + names = append(names, hr.GetName()) + versions[hr.GetName()] = map[string]any{"uid": string(hr.GetUID()), "generation": hr.GetGeneration()} + } + raw, err := json.Marshal(versions) + require.NoError(t, err) + return &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{ + Namespace: ns, Name: controller.DefaultMigrationReport, + Annotations: map[string]string{ + controller.MigrationReadyAnnotation: "2", + controller.MigrationReadyReleasesAnnotation: strings.Join(names, ","), + controller.MigrationReadyVersionsAnnotation: string(raw), + }, + }} +} diff --git a/internal/controller/references_envtest_test.go b/internal/controller/references_envtest_test.go index 197fc09..a8c3ce7 100644 --- a/internal/controller/references_envtest_test.go +++ b/internal/controller/references_envtest_test.go @@ -84,7 +84,7 @@ func referenceCases(t *testing.T, c *cluster) { { desc: "the RemoteMCPServer of a tool", agent: agentSpec("With a server.", map[string]any{toolsField: []any{map[string]any{"mcp": map[string]any{"server": server}}}}), - gvk: serverGVK, ref: "ref-server", spec: map[string]any{"url": "https://tools.example.com/mcp", descriptionField: "tools"}, + gvk: serverGVK, ref: "ref-server", spec: map[string]any{urlField: "https://tools.example.com/mcp", descriptionField: "tools"}, }, } { t.Run(tc.desc, func(t *testing.T) { diff --git a/main.go b/main.go index bb0962f..6ca4048 100644 --- a/main.go +++ b/main.go @@ -74,6 +74,8 @@ func run() error { flag.StringVar(&cfg.Chart.SemverFilter, "agent-chart-semver-filter", "", "Regular expression the agent chart's tags must match before the range is evaluated, as the OCIRepository's ref.semverFilter; empty filters nothing") flag.StringVar(&cfg.Chart.Interval, "ocirepository-interval", "30m", "OCIRepository.spec.interval of the agent chart's source") flag.StringVar(&cfg.Chart.APIVersion, "flux-ocirepository-api-version", "source.toolkit.fluxcd.io/v1", "source.toolkit.fluxcd.io API version of the OCIRepository") + flag.StringVar(&cfg.Chart.MigrationReport, "agent-chart-migration-report", controller.DefaultMigrationReport, "agent-manager migrate's report ConfigMap in an organization namespace: an existing OCIRepository moves to a higher agent chart major only while it carries "+controller.MigrationReadyAnnotation+" with that major, or no HelmRelease there uses it") + flag.DurationVar(&cfg.Chart.MigrationPoll, "agent-chart-migration-poll", controller.DefaultMigrationPoll, "How often an organization whose chart source waits at its major looks for migrate's annotation again") flag.StringVar(&cfg.HelmServiceAccount, "helmrelease-service-account", "kagent-flux", "The ServiceAccount the organization's HelmReleases run as, kept in every organization namespace; empty keeps none") flag.StringVar(&cfg.HelmClusterRole, "helm-cluster-role", "agent-platform-tenant-flux", "ClusterRole bound to --helmrelease-service-account in every organization namespace") flag.StringVar(&serviceAccountBindings, "service-account-bindings", "", `JSON list of {"clusterRole": ..., "serviceAccount": {"namespace": ..., "name": ...}}: each ClusterRole is bound to that ServiceAccount of another namespace in every organization namespace, by a RoleBinding named after the ClusterRole, so it holds the ClusterRole there and nowhere it is not bound (Substrate's credential providers); a ClusterRole removed from the list loses its bindings; empty binds none`)