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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,13 @@ standard manifests a kubectl or GitOps user would apply, returns them on
`kustomization.yaml` and the parent's entry. An update rewrites the
release's file and a delete removes it (and the chart source's when no
other release uses it); a release defined elsewhere in the repository is
refused. A Kustomization that does not prune leaves a removed release in
refused. A delete that removes the last file of `agent-manager/` also adds
`.gitkeep` to the path above it when that path is not the repository's root
and has no `kustomization.yaml` and no `.gitkeep` in git: git keeps no empty
directory, and the Kustomization
would fail on a path that does not exist before it prunes the release; Flux
builds a path with no YAML file as an empty kustomization. A Kustomization
that does not prune leaves a removed release in
place, which the answer's `liveSteps` names. Each pull request has a head
branch of its own, cut from the base: the agent's branch name
(`agent-manager/<verb>-<namespace>-<name>`, verb `create`, `update` or
Expand Down
6 changes: 3 additions & 3 deletions docs/organizations-commit-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,9 @@ Secret. Commits, over MCP and REST, use the configured RFC 8693 manager App gran
have it. Without it, the merge removes `agent-manager/` and with it the content path,
and the organization's Kustomization fails on a path that does not exist before it
prunes the agent's HelmRelease. With it, Flux builds the path as an empty
kustomization and prunes the HelmRelease. This holds whether the agent tools found the
content path themselves or through the organization's own Kustomization, which builds
it. A dry run shows the `.gitkeep` in `commit.files`.
kustomization and prunes the HelmRelease. This holds for every target of the agent
tools, not only a content path (see "Write modes" in the README). A dry run shows the
`.gitkeep` in `commit.files`.
- The admins are not a file of the content path: they are `spec.admins` of the
organization's file, and agent-platform-operator binds them to `agent-platform:admin`
in the organization namespace.
Expand Down
91 changes: 35 additions & 56 deletions internal/agents/commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,18 @@ const KustomizationNamespaceLabel = "kustomize.toolkit.fluxcd.io/namespace"
// layout, the one cluster-manager and model-manager write theirs to).
const CommitDirectory = "agent-manager"

// KeepFile keeps an organization's content path that has no
// kustomization.yaml in git when a write in mode commit removes its last
// KeepFile keeps a path that a Flux Kustomization builds, and that has no
// kustomization.yaml in git, when a write in mode commit removes its last
// file: Flux generates the path's kustomization, git keeps no empty
// directory, and the organization's Kustomization, which builds the path,
// would fail on a path that does not exist and prune nothing. Flux's
// generator lists YAML files only, so the marker changes nothing of what it
// builds. The organization tools and the agent tools write it.
// directory, and the Kustomization would fail on a path that does not exist
// and prune nothing. Flux's generator lists YAML files only, so the marker
// changes nothing of what it builds. The organization tools write it in an
// organization's content path, the agent tools above agent-manager's
// directory of any target.
const KeepFile = ".gitkeep"

// KeepContent is KeepFile's content: why it is there.
const KeepContent = "# Keeps this organization's content path in git when it has no other file: Flux generates its kustomization and prunes what left it.\n"
const KeepContent = "# Keeps this path in git when it has no other file: Flux generates its kustomization and prunes what left it.\n"

// GitHubRemote is what commit mode needs of GitHub: the pull request seams,
// the reads of the base (at a branch, or at one commit its head resolves to)
Expand Down Expand Up @@ -115,11 +116,6 @@ type commitLocation struct {
// ServiceAccount has no right on OCIRepositories), and
// agent-platform-operator keeps the namespace's chart source live.
liveChartSource bool
// content marks the target as an organization's content path, found
// through organizationContent or through the organization's own
// Kustomization, which builds it: a write that empties agent-manager's
// directory there keeps the path (keepContentPath).
content bool
}

func (l commitLocation) directory() layout.Directory {
Expand Down Expand Up @@ -228,37 +224,18 @@ func explicitLocation(w WriteOptions) (commitLocation, error) {
// names after the organization namespace. When the labels name that
// Kustomization and the caller's read of it is refused, the location is the
// organization's content path (organizationContent), which that Kustomization
// builds from: the target of the organization's first agent. A target the
// caller reads through that Kustomization is marked as the content path when
// it is the same repository, branch and directory.
// builds from: the target of the organization's first agent.
func (s *Service) ownerLocation(ctx context.Context, st *site, obj *unstructured.Unstructured) (commitLocation, error) {
ks, err := labelledKustomization(ctx, st.flux, obj)
own := obj.GetLabels()[KustomizationNameLabel] == st.fluxNS
if errors.Is(err, ErrForbidden) && own {
if errors.Is(err, ErrForbidden) && obj.GetLabels()[KustomizationNameLabel] == st.fluxNS {
if loc, ok, orgErr := s.organizationContent(ctx, st); orgErr != nil || ok {
return loc, orgErr
}
}
if err != nil {
return commitLocation{}, err
}
loc, err := kustomizationLocation(ctx, st.flux, ks)
if err != nil || !own {
return loc, err
}
org, ok, err := s.organizationNamespace(ctx, st)
if err != nil {
return commitLocation{}, err
}
loc.content = ok && sameLocation(loc.Location, org.Content)
return loc, nil
}

// sameLocation reports whether a and b are the same directory on the same
// branch of the same repository; GitHub ignores the case of owner and name.
func sameLocation(a, b provenance.Location) bool {
return strings.EqualFold(a.Repository.Owner, b.Repository.Owner) && strings.EqualFold(a.Repository.Name, b.Repository.Name) &&
a.Branch == b.Branch && a.Directory == b.Directory
return kustomizationLocation(ctx, st.flux, ks)
}

// namespaceLocation is where a new agent of the site goes: the caller's target, else
Expand Down Expand Up @@ -374,7 +351,7 @@ func (s *Service) organizationContent(ctx context.Context, st *site) (commitLoca

// contentLocation is the commit target of org's content path.
func contentLocation(org OrganizationNamespace) commitLocation {
return commitLocation{Location: org.Content, liveChartSource: true, content: true}
return commitLocation{Location: org.Content, liveChartSource: true}
}

// releaseLocation is where an existing agent's release of the site lives in
Expand Down Expand Up @@ -508,19 +485,18 @@ func (c *agentCommit) requireReleaseFile(ctx context.Context, hr *unstructured.U
// a pull request of it is open, the write adds its commit to that pull
// request, as when every write of the object shared one head; otherwise the
// write cuts a head branch of its own (Head) from the base, so no file of an
// earlier, closed or merged, pull request of the agent rides along. In an
// organization's content path, a write that empties agent-manager's
// directory keeps the path (keepContentPath).
// earlier, closed or merged, pull request of the agent rides along. A write
// that empties agent-manager's directory keeps the target's path
// (keepTargetPath).
func (c *agentCommit) open(ctx context.Context, write map[string][]byte, remove []string, object, title, body string, dryRun bool) (*CommitResult, error) {
plan, err := layout.Build(ctx, c.remote, c.loc.directory(), write, remove)
if err != nil {
return nil, commitError(c.gh, err)
}
change, files := plan.Change(), plan.Files
if c.loc.content {
if files, err = c.keepContentPath(ctx, &change, files); err != nil {
return nil, err
}
change := plan.Change()
files, err := c.keepTargetPath(ctx, &change, plan.Files)
if err != nil {
return nil, err
}
out := &CommitResult{
Repository: c.loc.Repository.String(), Base: c.loc.Branch, Directory: c.loc.directory().Path(),
Expand Down Expand Up @@ -567,20 +543,23 @@ func (c *agentCommit) open(ctx context.Context, write map[string][]byte, remove
return out, nil
}

// keepContentPath adds KeepFile to change, the plan layout.Build made for
// agent-manager's directory in an organization's content path, and returns
// files, the plan's files, with it. It does so when the plan empties the
// directory (it removes the directory's kustomization.yaml with its last
// file) and the base branch carries neither the content path's
// kustomization.yaml nor KeepFile: Flux generates the content path's
// kustomization, and the merge would otherwise remove the path, so the
// organization's Kustomization would fail before it prunes the agent's
// release. A content path with a kustomization.yaml stays: layout.Build takes
// agent-manager out of its list. The organization tools keep the path the
// same way (organizations' leaveToFlux).
func (c *agentCommit) keepContentPath(ctx context.Context, change *commit.Change, files []layout.File) ([]layout.File, error) {
// keepTargetPath adds KeepFile to change, the plan layout.Build made for
// agent-manager's directory, and returns files, the plan's files, with it.
// It does so when the plan empties the directory (it removes the directory's
// kustomization.yaml with its last file) and the base branch carries neither
// a kustomization.yaml nor KeepFile in the target's path, the directory
// above: Flux generates that path's kustomization, and the merge could
// otherwise remove the path, so the Kustomization that builds it would fail
// before it prunes the agent's release. This holds for every target: an
// organization's content path, the path of the Kustomization that applies
// the agent, and a path the caller names. A path with a kustomization.yaml
// stays: layout.Build takes agent-manager out of its list. So does the
// repository's root, a target with no directory, which no merge removes. The
// organization tools keep a content path the same way (organizations'
// leaveToFlux).
func (c *agentCommit) keepTargetPath(ctx context.Context, change *commit.Change, files []layout.File) ([]layout.File, error) {
own := path.Join(c.loc.directory().Path(), layout.KustomizationFile)
if !slices.ContainsFunc(files, func(f layout.File) bool { return f.Path == own && f.Action == layout.Remove }) {
if c.loc.Directory == "" || !slices.ContainsFunc(files, func(f layout.File) bool { return f.Path == own && f.Action == layout.Remove }) {
return files, nil
}
marker := path.Join(c.loc.Directory, KeepFile)
Expand Down
92 changes: 60 additions & 32 deletions internal/agents/commit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"maps"
"net/http"
"path"
"slices"
"strings"
"testing"
Expand Down Expand Up @@ -355,35 +356,54 @@ func TestCommitInAnOrganizationGoesToItsContentPathWhenItsKustomizationCannotBeR
assert.Contains(t, err.Error(), "get Kustomization flux-giantswarm/agents")
}

// delete_agent of the last agent of an organization's content path without a
// kustomization.yaml, whose kustomization Flux generates, keeps the content
// path with a .gitkeep: git keeps no empty directory, and the organization's
// Kustomization would fail on a path that does not exist before it prunes the
// agent's HelmRelease (giantswarm/agent-manager#502 item 3). The content path
// is the target when the caller may not read the organization's Kustomization,
// and when that Kustomization, which the caller reads, builds it. A content
// path with a kustomization.yaml, a .gitkeep that git carries already, and an
// agent-manager directory that keeps another agent get no new .gitkeep.
func TestCommitDeleteOfAnOrganizationsLastAgentKeepsItsContentPath(t *testing.T) {
const dir = orgContent + "/agent-manager"
const marker = orgContent + "/.gitkeep"
// delete_agent of the last agent in a target path without a kustomization.yaml,
// whose kustomization Flux generates, keeps the path with a .gitkeep: git
// keeps no empty directory, and the Kustomization that builds the path would
// fail on a path that does not exist before it prunes the agent's HelmRelease
// (giantswarm/agent-manager#502 items 3, 4 and 5). Every target keeps its
// path: an organization's content path, found when the caller may not read the
// organization's Kustomization and when that Kustomization, which the caller
// reads, builds it; the path of another Kustomization that applies the agent;
// and a path the caller names. A path with a kustomization.yaml, a .gitkeep
// that git carries already, an agent-manager directory that keeps another
// agent, and the repository's root, which no merge removes, get no new
// .gitkeep.
func TestCommitDeleteOfTheLastAgentKeepsItsTargetPath(t *testing.T) {
const otherPath = "clusters/other"
const contentDir = orgContent + "/agent-manager"
for _, tc := range []struct {
name string
// readable: the caller reads the organization's Kustomization.
readable bool
more map[string][]byte
added bool
// target is how the delete finds its target: "refused", the
// organization's Kustomization, which the caller may not read (its
// content path); "own", that Kustomization, read; "other", another
// Kustomization, read, which builds otherPath; "root", another
// Kustomization, read, which builds the repository's root; "named", the
// content path, which the caller names.
target string
more map[string][]byte
added bool
}{
{"generated by Flux, its Kustomization refused", false, nil, true},
{"generated by Flux, its Kustomization read", true, nil, true},
{"with a kustomization.yaml", false, map[string][]byte{orgContent + "/kustomization.yaml": []byte("resources:\n - agent-manager\n")}, false},
{"generated by Flux, with a .gitkeep", false, map[string][]byte{marker: []byte("\n")}, false},
{"generated by Flux, with another agent", false, map[string][]byte{
dir + "/kustomization.yaml": []byte("resources:\n - first.yaml\n - second.yaml\n"),
dir + "/second.yaml": []byte("kind: HelmRelease\n"),
{"content path, its Kustomization refused", "refused", nil, true},
{"content path, its Kustomization read", "own", nil, true},
{"another Kustomization's path", "other", nil, true},
{"a path the caller names", "named", nil, true},
{"the repository's root, which no merge removes", "root", map[string][]byte{"README.md": []byte("fleet\n")}, false},
{"content path with a kustomization.yaml", "refused", map[string][]byte{orgContent + "/kustomization.yaml": []byte("resources:\n - agent-manager\n")}, false},
{"content path with a .gitkeep", "refused", map[string][]byte{orgContent + "/.gitkeep": []byte("\n")}, false},
{"content path with another agent", "refused", map[string][]byte{
contentDir + "/kustomization.yaml": []byte("resources:\n - first.yaml\n - second.yaml\n"),
contentDir + "/second.yaml": []byte("kind: HelmRelease\n"),
}, false},
} {
t.Run(tc.name, func(t *testing.T) {
target, ks := orgContent, orgNS
switch tc.target {
case "other":
target, ks = otherPath, "other"
case "root":
target, ks = "", "root"
}
dir, marker := path.Join(target, "agent-manager"), path.Join(target, ".gitkeep")
f, fake, ctx := organizationFixture(t)
values := map[string]any{"agent": map[string]any{"name": "first"}, "modelConfig": map[string]any{"name": "own"}, ToolsetValuesKey: []any{"preset:read-only"}}
base := map[string][]byte{
Expand All @@ -393,36 +413,44 @@ func TestCommitDeleteOfAnOrganizationsLastAgentKeepsItsContentPath(t *testing.T)
maps.Copy(base, tc.more)
fake.AddBranch(orgRepo, "main", base)
mustCreate(t, f, ociGVR, ociRepository(orgNS, "2.x"))
mustCreate(t, f, hrGVR, helmRelease(orgNS, "first", values, true, map[string]any{KustomizationNameLabel: orgNS, KustomizationNamespaceLabel: "flux-giantswarm"}))
if tc.readable {
mustCreate(t, f, hrGVR, helmRelease(orgNS, "first", values, true, map[string]any{KustomizationNameLabel: ks, KustomizationNamespaceLabel: "flux-giantswarm"}))
switch tc.target {
case "own", "other", "root":
mustCreate(t, f, gitRepoGVR, &unstructured.Unstructured{Object: map[string]any{
"apiVersion": "source.toolkit.fluxcd.io/v1", "kind": "GitRepository",
"metadata": map[string]any{"name": "mc-config", "namespace": "flux-giantswarm"},
"spec": map[string]any{"url": "https://github.com/giantswarm/mc-config", "ref": map[string]any{"branch": "main"}},
}})
mustCreate(t, f, ksGVR, &unstructured.Unstructured{Object: map[string]any{
"apiVersion": "kustomize.toolkit.fluxcd.io/v1", "kind": "Kustomization",
"metadata": map[string]any{"name": orgNS, "namespace": "flux-giantswarm"},
"spec": map[string]any{"path": "./" + orgContent, "prune": true, "sourceRef": map[string]any{"kind": "GitRepository", "name": "mc-config"}},
"metadata": map[string]any{"name": ks, "namespace": "flux-giantswarm"},
"spec": map[string]any{"path": "./" + target, "prune": true, "sourceRef": map[string]any{"kind": "GitRepository", "name": "mc-config"}},
}})
} else {
default:
refuse(f, "get", ksGVR)
}
w := WriteOptions{Mode: ModeCommit}
if tc.target == "named" {
w.Repository, w.Branch, w.Path = orgRepo.Owner+"/"+orgRepo.Name, "main", orgContent
}

dry, err := f.svc.Delete(ctx, In(orgNS), "first", false, WriteOptions{Mode: ModeCommit, DryRun: true})
dryRun := w
dryRun.DryRun = true
dry, err := f.svc.Delete(ctx, In(orgNS), "first", false, dryRun)
require.NoError(t, err)
assert.Equal(t, tc.readable, dry.Commit.Kustomization != "", "the target is found as the case says")
assert.Equal(t, dir, dry.Commit.Directory, "the target is the case's path")
assert.Equal(t, tc.target != "refused" && tc.target != "named", dry.Commit.Kustomization != "", "the target is found as the case says")
assert.Equal(t, "remove", filesByPath(dry.Commit)[dir+"/first.yaml"].Action)
_, dryMarker := filesByPath(dry.Commit)[marker]
assert.Equal(t, tc.added, dryMarker, "a dry run shows the .gitkeep the pull request adds")

res, err := f.svc.Delete(ctx, In(orgNS), "first", false, WriteOptions{Mode: ModeCommit})
res, err := f.svc.Delete(ctx, In(orgNS), "first", false, w)
require.NoError(t, err)
require.Len(t, fake.PullRequests(), 1)
head := fake.Files(orgRepo, fake.PullRequests()[0].Head)
_, kept := head[dir+"/first.yaml"]
assert.False(t, kept, "the agent's file goes")
assert.True(t, slices.ContainsFunc(slices.Collect(maps.Keys(head)), func(p string) bool { return strings.HasPrefix(p, orgContent+"/") }), "the content path stays in git")
assert.True(t, slices.ContainsFunc(slices.Collect(maps.Keys(head)), func(p string) bool { return target == "" || strings.HasPrefix(p, target+"/") }), "the target's path stays in git")
_, added := filesByPath(res.Commit)[marker]
assert.Equal(t, tc.added, added, "the .gitkeep is added only when the path would go and git lacks it")
if tc.added {
Expand Down
Loading