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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ The changes made to the Runner between two releases wait under Unreleased and go

## Unreleased

### Added

- **A repository's folder:** a repository's own checkout is read from the folder the controller names as its root

## 7.9.0

The RTE Runner of [AnsibleForms 7.9.0](https://github.com/ansibleforms/ansibleforms/releases/tag/7.9.0).
Expand Down
80 changes: 80 additions & 0 deletions internal/ansible/prepare.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,86 @@ func RepoFolder(repoPath, name string) (string, error) {
return filepath.Join(repoPath, name), nil
}

// maxRepoPathLength is the longest folder a repository reads as its root, as the controller keeps it.
const maxRepoPathLength = 250

// NormalizeRepoPath checks the folder a repository reads as its root, as the controller does
// (Repo.normalizeRepoPath in the application): relative to its checkout, each folder a plain name
// (no leading /, no . nor .., no empty folder, no hidden one), its trailing slashes dropped.
//
// Args:
//
// value: the folder given ("" : the whole checkout).
//
// Returns:
//
// The folder, normalised ("" : none).
//
// Errors:
//
// When it is not a folder inside the repository, saying why.
func NormalizeRepoPath(value string) (string, error) {
// step 1 : trimmed, its trailing slashes dropped (prod/ is prod)
text := strings.TrimRight(strings.TrimSpace(value), "/")
if text == "" {
return "", nil
}
// step 2 : relative, each folder a plain name
if strings.HasPrefix(text, "/") {
return "", fmt.Errorf("Invalid repository folder: %s. It is relative to the repository: no leading /.", text)
}
if len(text) > maxRepoPathLength {
return "", fmt.Errorf("Invalid repository folder: it is longer than %d characters.", maxRepoPathLength)
}
for _, part := range strings.Split(text, "/") {
switch {
case part == "":
return "", fmt.Errorf("Invalid repository folder: %s. It has an empty folder (//).", text)
case part == "." || part == "..":
return "", fmt.Errorf("Invalid repository folder: %s. It must stay inside the repository: no . nor .. in it.", text)
case !ValidRepoName(part):
return "", fmt.Errorf("Invalid repository folder: %s. Each folder has letters, digits, dots, dashes and underscores only, not starting with a dot.", text)
}
}
return text, nil
}

// ContentFolder is a repository's root: its checkout under the repositories folder, or the folder
// of it the controller reads as its root. A folder the checkout does not have refuses the job,
// never read as the whole checkout or an empty one.
//
// Args:
//
// repoPath: the repositories folder (REPO_PATH).
// name: the repository.
// sub: the folder it reads as its root ("" : the whole checkout).
//
// Returns:
//
// The folder.
//
// Errors:
//
// When the name or the folder is not valid, or the folder is not in the checkout.
func ContentFolder(repoPath, name, sub string) (string, error) {
checkout, err := RepoFolder(repoPath, name)
if err != nil {
return "", err
}
rel, err := NormalizeRepoPath(sub)
if err != nil {
return "", err
}
if rel == "" {
return checkout, nil
}
folder := filepath.Join(checkout, filepath.FromSlash(rel))
if !isDir(folder) {
return "", fmt.Errorf("Repository '%s' reads its folder '%s', which is not in its checkout on this Runner. Add the folder in git, or change the repository's folder.", name, rel)
}
return folder, nil
}

// exists tells whether a path exists.
//
// Args:
Expand Down
48 changes: 48 additions & 0 deletions internal/ansible/prepare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,54 @@ func TestRepoFolder(t *testing.T) {
}
}

// TestNormalizeRepoPath checks the folder a repository reads as its root, as the controller
// checks it: relative, each folder a plain name, its trailing slashes dropped.
func TestNormalizeRepoPath(t *testing.T) {
for in, want := range map[string]string{"": "", " ": "", "/": "", "dev": "dev", " envs/prod/ ": "envs/prod", "a.b/c_d-1": "a.b/c_d-1"} {
if got, err := NormalizeRepoPath(in); err != nil || got != want {
t.Errorf("%q: %q %v", in, got, err)
}
}
for in, why := range map[string]string{
"/etc": "no leading /",
strings.Repeat("a", 251): "longer than 250",
"a//b": "an empty folder",
"a/../b": "no . nor ..",
"./a": "no . nor ..",
"a/.git": "letters, digits",
"a b": "letters, digits",
"a/b..c": "letters, digits",
} {
if _, err := NormalizeRepoPath(in); err == nil || !strings.Contains(err.Error(), why) {
t.Errorf("%q: %v", in, err)
}
}
}

// TestContentFolder checks a repository's root: its checkout, or its folder in it ; a bad name, a
// bad folder or one the checkout does not have refused.
func TestContentFolder(t *testing.T) {
repos := t.TempDir()
_ = os.MkdirAll(filepath.Join(repos, "r", "envs", "prod"), 0o700)
_ = os.WriteFile(filepath.Join(repos, "r", "file"), nil, 0o600)
if f, err := ContentFolder(repos, "r", ""); err != nil || f != filepath.Join(repos, "r") {
t.Errorf("the checkout %s %v", f, err)
}
if f, err := ContentFolder(repos, "r", "envs/prod/"); err != nil || f != filepath.Join(repos, "r", "envs", "prod") {
t.Errorf("its folder %s %v", f, err)
}
for _, c := range []struct{ name, sub, why string }{
{"../r", "", "Invalid repository name"},
{"r", "../x", "no . nor .."},
{"r", "dev", "reads its folder 'dev', which is not in its checkout"},
{"r", "file", "reads its folder 'file', which is not in its checkout"},
} {
if _, err := ContentFolder(repos, c.name, c.sub); err == nil || !strings.Contains(err.Error(), c.why) {
t.Errorf("%s %s: %v", c.name, c.sub, err)
}
}
}

// TestPlaybookFile checks the playbook's file: as named, else with .yml or .yaml when only that
// one is there.
func TestPlaybookFile(t *testing.T) {
Expand Down
61 changes: 50 additions & 11 deletions internal/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,12 @@ func (r *Runner) run(j *job, h jobstream.Header, paths, given map[string]any, tr
h.Playbook = "playbook"
}
if len(h.Inventories) == 0 {
for i, inv := range inventoryRoots(paths) {
roots, err := inventoryRoots(paths)
if err != nil {
fail("[ERROR]: " + err.Error())
return
}
for i, inv := range roots {
name := fmt.Sprintf("inventory-%d", i)
folders[name] = inv.Dir
h.Inventories = append(h.Inventories, jobstream.Inventory{Repository: inv.Repository, Folder: name})
Expand Down Expand Up @@ -913,14 +918,37 @@ func asList(v any) []any {
return l
}

// repoRoot is a repository's root on this Runner (its own checkout under REPO_PATH): the folder
// of it the controller reads as its root (the run message's paths.folders), its whole checkout
// without one.
//
// Args:
//
// paths: the run message's paths.
// name: the repository.
//
// Returns:
//
// The folder.
//
// Errors:
//
// When the name or its folder is not valid, or the folder is not in its checkout.
func repoRoot(paths map[string]any, name string) (string, error) {
folders, _ := paths["folders"].(map[string]any)
sub, _ := folders[name].(string)
return ansible.ContentFolder(settings.RepoPath(), name, sub)
}

// playbookDir resolves a job's playbook folder, as the controller's own Runner does: the
// playbooks the controller sent when it sent them ; else, with local files, its repository's root
// (playbookRoot), its repository's playbooks folder when it has one, the repository, or
// ANSIBLE_PATH ; the sub folder under it.
// ANSIBLE_PATH ; the sub folder under it. A repository's root is the folder of it the controller
// reads as its root, when it names one.
//
// Args:
//
// paths: the run message's paths ({ playbookRepo, inventoryRepos, playbookRoot }).
// paths: the run message's paths ({ playbookRepo, inventoryRepos, folders, playbookRoot }).
// sent: the folder of the playbooks the controller sent, empty when it sent none.
// transferred: tells the job's files were sent (its repository is then not on this Runner).
//
Expand All @@ -932,13 +960,15 @@ func playbookDir(paths map[string]any, sent string, transferred bool) func(strin
repo, _ := paths["playbookRepo"].(string)
root := sent
if b, _ := paths["playbookRoot"].(bool); b && root == "" {
folder, err := ansible.RepoFolder(settings.RepoPath(), repo)
if transferred || err != nil || !exists(folder) {
checkout, err := ansible.RepoFolder(settings.RepoPath(), repo)
if transferred || err != nil || !exists(checkout) {
return "", fmt.Errorf("playbookRepository '%s' is not a repository used for playbooks", repo)
}
root = folder
if root, err = repoRoot(paths, repo); err != nil {
return "", err
}
} else if root == "" && repo != "" {
folder, err := ansible.RepoFolder(settings.RepoPath(), repo)
folder, err := repoRoot(paths, repo)
if err != nil {
return "", err
}
Expand Down Expand Up @@ -971,7 +1001,8 @@ func exists(p string) bool {
}

// inventoryRoots are the folders a job's inventories are in: the local inventories folder, then
// each repository its paths name for inventories.
// each repository its paths name for inventories, from the folder of it the controller reads as
// its root.
//
// Args:
//
Expand All @@ -980,14 +1011,22 @@ func exists(p string) bool {
// Returns:
//
// The folders.
func inventoryRoots(paths map[string]any) []ansible.Root {
//
// Errors:
//
// When a repository's folder is not valid, or not in its checkout.
func inventoryRoots(paths map[string]any) ([]ansible.Root, error) {
roots := []ansible.Root{{Dir: settings.InventoryPath()}}
for _, v := range asList(paths["inventoryRepos"]) {
if name, ok := v.(string); ok && ansible.ValidRepoName(name) {
roots = append(roots, ansible.Root{Repository: name, Dir: filepath.Join(settings.RepoPath(), name)})
dir, err := repoRoot(paths, name)
if err != nil {
return nil, err
}
roots = append(roots, ansible.Root{Repository: name, Dir: dir})
}
}
return roots
return roots, nil
}

// onCancel stops a job: its playbook's process group signalled at once ; a job not handed over
Expand Down
48 changes: 45 additions & 3 deletions internal/runner/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,14 @@ func TestRunJobContainer(t *testing.T) {
if m := end(56)["message"].(string); !strings.Contains(m, "Invalid repository name") {
t.Errorf("a playbook folder that is not one: %s", m)
}
repos := t.TempDir()
t.Setenv("REPO_PATH", repos)
_ = os.MkdirAll(filepath.Join(repos, "inv"), 0o700)
send(t, conn, socket.Message{"t": "run", "jobId": 57, "contract": socket.SocketContract, "sealed": sealed(t, 57, map[string]any{}),
"paths": map[string]any{"inventoryRepos": []any{"inv"}, "folders": map[string]any{"inv": "prod"}}})
if m := end(57)["message"].(string); !strings.Contains(m, "Repository 'inv' reads its folder 'prod', which is not in its checkout") {
t.Errorf("an inventory repository's folder not in its checkout: %s", m)
}
}

// TestRunJobAckedFirst checks a job whose items were all acked before its run let go: removed
Expand Down Expand Up @@ -980,9 +988,43 @@ func TestPaths(t *testing.T) {
if _, err := playbookDir(map[string]any{"playbookRepo": "plain", "playbookRoot": true}, "", true)(""); err == nil {
t.Error("a repository's root, its files sent without playbooks")
}
roots := inventoryRoots(map[string]any{"inventoryRepos": []any{"a", 1.0, "../b"}})
if len(roots) != 2 || roots[0].Dir != "/inv" || roots[1].Repository != "a" {
t.Errorf("roots %v", roots)
roots, err := inventoryRoots(map[string]any{"inventoryRepos": []any{"a", 1.0, "../b"}})
if err != nil || len(roots) != 2 || roots[0].Dir != "/inv" || roots[1].Repository != "a" || roots[1].Dir != filepath.Join(repos, "a") {
t.Errorf("roots %v %v", roots, err)
}
// a repository's folder read as its root (paths.folders): its playbooks and inventories there
_ = os.MkdirAll(filepath.Join(repos, "sub", "envs", "prod", "playbooks"), 0o700)
_ = os.MkdirAll(filepath.Join(repos, "sub", "dev"), 0o700)
folders := map[string]any{"sub": "envs/prod/", "plain": "", "other": 1.0}
for _, c := range []struct {
paths map[string]any
want string
}{
{map[string]any{"playbookRepo": "sub", "folders": folders}, filepath.Join(repos, "sub", "envs", "prod", "playbooks")},
{map[string]any{"playbookRepo": "sub", "playbookRoot": true, "folders": folders}, filepath.Join(repos, "sub", "envs", "prod")},
{map[string]any{"playbookRepo": "sub", "folders": map[string]any{"sub": "dev"}}, filepath.Join(repos, "sub", "dev")},
{map[string]any{"playbookRepo": "plain", "folders": folders}, filepath.Join(repos, "plain")},
{map[string]any{"playbookRepo": "plain", "folders": "bad"}, filepath.Join(repos, "plain")},
} {
if got, err := playbookDir(c.paths, "", false)(""); err != nil || got != c.want {
t.Errorf("%v: %s %v", c.paths, got, err)
}
}
for _, paths := range []map[string]any{
{"playbookRepo": "sub", "folders": map[string]any{"sub": "gone"}},
{"playbookRepo": "sub", "playbookRoot": true, "folders": map[string]any{"sub": "gone"}},
{"playbookRepo": "sub", "folders": map[string]any{"sub": "../x"}},
} {
if _, err := playbookDir(paths, "", false)(""); err == nil {
t.Errorf("%v: no error", paths)
}
}
roots, err = inventoryRoots(map[string]any{"inventoryRepos": []any{"sub", "plain"}, "folders": map[string]any{"sub": "dev"}})
if err != nil || len(roots) != 3 || roots[1].Dir != filepath.Join(repos, "sub", "dev") || roots[2].Dir != filepath.Join(repos, "plain") {
t.Errorf("roots in a folder %v %v", roots, err)
}
if _, err := inventoryRoots(map[string]any{"inventoryRepos": []any{"sub"}, "folders": map[string]any{"sub": "/abs"}}); err == nil {
t.Error("an inventory repository's folder that is not one")
}
if len(extravarsOf(map[string]any{"b": 2.0})) != 1 || len(extravarsOf(`{"a":1}`)) != 1 || len(extravarsOf("null")) != 0 || len(extravarsOf("bad")) != 0 || len(extravarsOf(nil)) != 0 || asList("x") != nil {
t.Error("readers")
Expand Down