From 76b16a8abb80bafdc7d6b7dd3efd7704dbf88894 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 24 Oct 2026 10:51:18 +0200 Subject: [PATCH] perf(library): create a whole directory list in one module call Directory loops over ansible.builtin.file cost one SSH round trip per path: the openresty config tree (20 paths) took up to 12.9 s, the webserver core directories (16) up to 13.2 s, every app's compose directories (5) 2.5-5 s per app, the shared CDN roots 5.8 s and the OpenLDAP LDIF dirs 2.2 s on echoserver. directory_batch takes entries (path plus its own mode, owner, group) or paths with one shared set, and handles each path like file with state: directory: symlinks are followed, missing parents get the same attributes, an attribute left out stays as found, and it never recurses. It reports changed_paths, supports check and diff mode, and fails on a relative path, an existing non-directory or a failed mkdir. It replaces the five loops and the earlier install -d of the CDN role directories, which now report changed honestly. Co-Authored-By: Claude Opus 5.5 (1M context) --- library/directory_batch.py | 150 ++++++++++ roles/svc-db-openldap/tasks/00_core.yml | 6 +- roles/svc-prx-openresty/tasks/00_core.yml | 21 +- roles/sys-svc-cdn/tasks/main.yml | 12 +- .../tasks/02_stack_host_prep.yml | 6 +- .../tasks/03_directories.yml | 9 +- .../python/library/test_directory_batch.py | 266 ++++++++++++++++++ 7 files changed, 435 insertions(+), 35 deletions(-) create mode 100644 library/directory_batch.py create mode 100644 tests/unit/python/library/test_directory_batch.py diff --git a/library/directory_batch.py b/library/directory_batch.py new file mode 100644 index 0000000000..115026cabd --- /dev/null +++ b/library/directory_batch.py @@ -0,0 +1,150 @@ +"""Ensure many directories exist in one module call. + +Args: + entries: list of ``{path, mode, owner, group}``, each path with its own + attributes; mutually exclusive with ``paths``. + paths: list of paths that all receive ``mode``, ``owner`` and ``group``. + mode: mode of every path in ``paths``. + owner: owner of every path in ``paths``. + group: group of every path in ``paths``. + + Every path is handled like ``ansible.builtin.file`` with + ``state: directory``: a symlink is followed, a missing path is created + together with its missing parents, which receive the same attributes, an + existing directory gets every given attribute that differs, and an + attribute left out stays as found. + +Returns: + changed_paths: the paths that were created or whose attributes changed. + diff: one ``before``/``after`` record per changed path, in diff mode. +""" + +import os +from pathlib import Path + +from ansible.module_utils.basic import AnsibleModule + +ATTRIBUTES = ("mode", "owner", "group") + +ATTRIBUTE_SPEC = { + "mode": {"type": "raw"}, + "owner": {"type": "str"}, + "group": {"type": "str"}, +} + +ARGUMENT_SPEC = { + "entries": { + "type": "list", + "elements": "dict", + "options": {"path": {"type": "path", "required": True}, **ATTRIBUTE_SPEC}, + }, + "paths": {"type": "list", "elements": "path"}, + **ATTRIBUTE_SPEC, +} + +MUTUALLY_EXCLUSIVE = [["entries", name] for name in ("paths", *ATTRIBUTES)] + +REQUIRED_ONE_OF = [["entries", "paths"]] + + +class DirectoryError(Exception): + pass + + +def requested_entries(params): + if params["entries"] is not None: + return params["entries"] + return [ + {"path": path, **{name: params[name] for name in ATTRIBUTES}} + for path in params["paths"] + ] + + +def path_state(path): + target = Path(path) + if target.is_symlink(): + return "link" + if target.is_dir(): + return "directory" + if target.exists(): + return "file" + return "absent" + + +def apply_attributes(module, path, entry, changed, diff): + file_args = module.load_file_common_arguments( + {"path": path, **{name: entry[name] for name in ATTRIBUTES}} + ) + return module.set_fs_attributes_if_different(file_args, changed, diff, expand=False) + + +def create(module, path, entry, diff): + changed = False + current = "" + for part in path.strip("/").split("/"): + current = f"{current}/{part}" + candidate = Path(current) + if candidate.exists(): + continue + try: + candidate.mkdir() + changed = True + except FileExistsError: + if not candidate.is_dir(): + raise + changed = apply_attributes(module, current, entry, changed, diff) + return changed + + +def ensure(module, entry): + path = entry["path"] + if not Path(path).is_absolute(): + raise DirectoryError(f"{path!r} is not an absolute path") + if Path(path).is_symlink(): + path = os.path.realpath(path) + state = path_state(path) + diff = {"before": {"path": path}, "after": {"path": path}} + if state == "directory": + return apply_attributes(module, path, entry, False, diff), diff + if state != "absent": + raise DirectoryError(f"{path} already exists as a {state}") + diff["before"]["state"] = state + diff["after"]["state"] = "directory" + if module.check_mode: + return True, diff + try: + return create(module, path, entry, diff), diff + except OSError as error: + raise DirectoryError(f"Could not create {path}: {error}") from error + + +def main(): + module = AnsibleModule( + argument_spec=ARGUMENT_SPEC, + mutually_exclusive=MUTUALLY_EXCLUSIVE, + required_one_of=REQUIRED_ONE_OF, + supports_check_mode=True, + ) + changed_paths = [] + diffs = [] + for entry in requested_entries(module.params): + try: + changed, diff = ensure(module, entry) + except DirectoryError as error: + module.fail_json( + msg=str(error), + path=entry["path"], + changed=bool(changed_paths), + changed_paths=changed_paths, + ) + if changed: + changed_paths.append(entry["path"]) + diffs.append(diff) + result = {"changed": bool(changed_paths), "changed_paths": changed_paths} + if module._diff: + result["diff"] = diffs + module.exit_json(**result) + + +if __name__ == "__main__": + main() diff --git a/roles/svc-db-openldap/tasks/00_core.yml b/roles/svc-db-openldap/tasks/00_core.yml index dacc174613..7db1a514df 100644 --- a/roles/svc-db-openldap/tasks/00_core.yml +++ b/roles/svc-db-openldap/tasks/00_core.yml @@ -2,11 +2,9 @@ - include_tasks: utils/once/flag.yml - name: "📁 Create LDIF dirs {{ OPENLDAP_LDIF_PATH_HOST }} before swarm bind-mount" - file: - path: "{{ OPENLDAP_LDIF_PATH_HOST }}{{ item }}" - state: directory + directory_batch: + paths: "{{ [OPENLDAP_LDIF_PATH_HOST] | product(OPENLDAP_LDIF_TYPES) | map('join') | list }}" mode: "0755" - loop: "{{ OPENLDAP_LDIF_TYPES }}" - name: 🎬 Initialize docker include_tasks: 01_docker.yml diff --git a/roles/svc-prx-openresty/tasks/00_core.yml b/roles/svc-prx-openresty/tasks/00_core.yml index ab217ef9eb..074a3e9cf0 100644 --- a/roles/svc-prx-openresty/tasks/00_core.yml +++ b/roles/svc-prx-openresty/tasks/00_core.yml @@ -15,19 +15,14 @@ when: _openresty_docker_sock.stat.exists | default(false) - name: "✅ Ensure the full openresty config tree exists before any http-include writer" - ansible.builtin.file: - path: "{{ item.path }}" - state: directory - mode: "{{ item.mode }}" - loop: >- - {{ lookup('nginx','directories.ensure') + [ - {'path': lookup('nginx','directories.data.well_known'), 'mode': '0755'}, - {'path': LETSENCRYPT_WEBROOT_PATH, 'mode': '0755'}, - {'path': LETSENCRYPT_BASE_PATH, 'mode': '0755'}, - {'path': TLS_SELFSIGNED_BASE_PATH, 'mode': '0755'}, - ] }} - loop_control: - label: "{{ item.path }}" + directory_batch: + entries: >- + {{ lookup('nginx','directories.ensure') + [ + {'path': lookup('nginx','directories.data.well_known'), 'mode': '0755'}, + {'path': LETSENCRYPT_WEBROOT_PATH, 'mode': '0755'}, + {'path': LETSENCRYPT_BASE_PATH, 'mode': '0755'}, + {'path': TLS_SELFSIGNED_BASE_PATH, 'mode': '0755'}, + ] }} - name: 🔎 Stat the nginx.conf path ansible.builtin.stat: diff --git a/roles/sys-svc-cdn/tasks/main.yml b/roles/sys-svc-cdn/tasks/main.yml index b4a6d5116c..214eb1cb8b 100644 --- a/roles/sys-svc-cdn/tasks/main.yml +++ b/roles/sys-svc-cdn/tasks/main.yml @@ -1,11 +1,9 @@ --- - block: - name: ✅ Ensure shared root and vendor exist (run once) - ansible.builtin.file: - path: "{{ item }}" - state: directory + directory_batch: + paths: "{{ CDN_GLOBAL_DIRS }}" mode: "0755" - loop: "{{ CDN_GLOBAL_DIRS }}" - include_tasks: utils/once/flag.yml when: - run_once_sys_svc_cdn is not defined @@ -22,9 +20,9 @@ handler_role_name: "{{ handler_role }}" - name: ✅ Ensure CDN directories exist - ansible.builtin.command: - argv: "{{ ['install', '-d', '-m', '0755'] + CDN_ROLE_DIRS }}" - changed_when: false + directory_batch: + paths: "{{ CDN_ROLE_DIRS }}" + mode: "0755" when: CDN_ROLE_DIRS | length > 0 - name: ✅ Ensure 'latest' symlink points to current release diff --git a/roles/sys-svc-compose/tasks/02_stack_host_prep.yml b/roles/sys-svc-compose/tasks/02_stack_host_prep.yml index 37631527a3..628b87a212 100644 --- a/roles/sys-svc-compose/tasks/02_stack_host_prep.yml +++ b/roles/sys-svc-compose/tasks/02_stack_host_prep.yml @@ -1,10 +1,8 @@ --- - name: "📁 Create sys-svc-compose dirs (with parents) for '{{ application_id }}'" - file: - path: "{{ item.value }}" - state: directory + directory_batch: + paths: "{{ lookup('container', application_id, 'directories').values() | list }}" mode: "0755" - with_dict: "{{ lookup('container', application_id, 'directories') }}" - name: "🛡️ Ensure PHP hardening assets are installed" ansible.builtin.include_role: diff --git a/roles/sys-svc-webserver-core/tasks/03_directories.yml b/roles/sys-svc-webserver-core/tasks/03_directories.yml index 33fdc2eb47..36fe063e6a 100644 --- a/roles/sys-svc-webserver-core/tasks/03_directories.yml +++ b/roles/sys-svc-webserver-core/tasks/03_directories.yml @@ -1,10 +1,5 @@ --- - name: ✅ Ensure all required NGINX host directories exist (single task) become: true - ansible.builtin.file: - path: "{{ item.path }}" - state: directory - mode: "{{ item.mode }}" - loop: "{{ lookup('nginx','directories.ensure') }}" - loop_control: - label: "{{ item.path }}" + directory_batch: + entries: "{{ lookup('nginx','directories.ensure') }}" diff --git a/tests/unit/python/library/test_directory_batch.py b/tests/unit/python/library/test_directory_batch.py new file mode 100644 index 0000000000..8898324867 --- /dev/null +++ b/tests/unit/python/library/test_directory_batch.py @@ -0,0 +1,266 @@ +from __future__ import annotations + +import contextlib +import importlib.util +import io +import json +import os +import stat +import sys +import tempfile +import unittest +from pathlib import Path +from typing import TYPE_CHECKING + +from ansible.module_utils.testing import patch_module_args + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from types import ModuleType + +sys.path.insert(0, str(PROJECT_ROOT)) + +MODULE_PATH = PROJECT_ROOT / "library" / "directory_batch.py" + + +def _load_directory_batch() -> ModuleType: + spec = importlib.util.spec_from_file_location( + "library_directory_batch", str(MODULE_PATH) + ) + if spec is None or spec.loader is None: + raise ImportError(f"Could not load: {MODULE_PATH}") + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) # type: ignore[attr-defined] + return mod + + +_MOD = _load_directory_batch() + + +class DirectoryBatchTests(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.root = Path(self._tmp.name) + + def tearDown(self): + for path in self.root.rglob("*"): + if path.is_dir() and not path.is_symlink(): + path.chmod(0o700) + self._tmp.cleanup() + + def _run(self, args, *, check_mode=False, diff=False): + buffer = io.StringIO() + module_args = {**args, "_ansible_check_mode": check_mode, "_ansible_diff": diff} + with ( + patch_module_args(module_args), + contextlib.redirect_stdout(buffer), + self.assertRaises(SystemExit), + ): + _MOD.main() + return json.loads(buffer.getvalue()) + + def _path(self, *parts): + return str(self.root.joinpath(*parts)) + + def _mode(self, path): + return stat.S_IMODE(Path(path).stat().st_mode) + + def _mkdir(self, path, mode): + Path(path).mkdir() + Path(path).chmod(mode) + + def test_creates_missing_directory_with_its_mode(self): + target = self._path("cache") + result = self._run({"entries": [{"path": target, "mode": "0700"}]}) + self.assertTrue(result["changed"]) + self.assertEqual(result["changed_paths"], [target]) + self.assertEqual(self._mode(target), 0o700) + + def test_missing_parents_receive_the_same_mode(self): + target = self._path("a", "b", "c") + self._run({"entries": [{"path": target, "mode": "0750"}]}) + self.assertEqual(self._mode(self._path("a")), 0o750) + self.assertEqual(self._mode(self._path("a", "b")), 0o750) + self.assertEqual(self._mode(target), 0o750) + + def test_existing_parent_keeps_its_mode(self): + self._mkdir(self._path("a"), 0o701) + self._run({"entries": [{"path": self._path("a", "b"), "mode": "0755"}]}) + self.assertEqual(self._mode(self._path("a")), 0o701) + + def test_existing_directory_with_same_mode_is_unchanged(self): + target = self._path("conf.d") + self._run({"entries": [{"path": target, "mode": "0755"}]}) + result = self._run({"entries": [{"path": target, "mode": "0755"}]}) + self.assertFalse(result["changed"]) + self.assertEqual(result["changed_paths"], []) + + def test_mode_drift_is_repaired_and_reported(self): + target = self._path("conf.d") + self._run({"entries": [{"path": target, "mode": "0755"}]}) + Path(target).chmod(0o700) + result = self._run({"entries": [{"path": target, "mode": "0755"}]}) + self.assertEqual(result["changed_paths"], [target]) + self.assertEqual(self._mode(target), 0o755) + + def test_entry_without_mode_keeps_the_existing_mode(self): + target = self._path("kept") + self._mkdir(target, 0o701) + result = self._run({"entries": [{"path": target}]}) + self.assertFalse(result["changed"]) + self.assertEqual(self._mode(target), 0o701) + + def test_only_the_drifted_entry_is_reported(self): + same = self._path("same") + drifted = self._path("drifted") + entries = [{"path": same, "mode": "0755"}, {"path": drifted, "mode": "0755"}] + self._run({"entries": entries}) + Path(drifted).chmod(0o700) + self.assertEqual(self._run({"entries": entries})["changed_paths"], [drifted]) + + def test_paths_share_the_top_level_mode(self): + first = self._path("instance") + second = self._path("instance", "volumes") + result = self._run({"paths": [first, second], "mode": "0755"}) + self.assertEqual(result["changed_paths"], [first, second]) + self.assertEqual(self._mode(first), 0o755) + self.assertEqual(self._mode(second), 0o755) + + def test_trailing_slash_path_is_created(self): + target = self._path("servers") + "/" + result = self._run({"paths": [target], "mode": "0755"}) + self.assertEqual(result["changed_paths"], [target]) + self.assertTrue(Path(target).is_dir()) + + def test_empty_paths_change_nothing(self): + result = self._run({"paths": [], "mode": "0755"}) + self.assertFalse(result["changed"]) + + def test_check_mode_reports_missing_path_without_creating_it(self): + target = self._path("new", "child") + result = self._run({"paths": [target], "mode": "0755"}, check_mode=True) + self.assertEqual(result["changed_paths"], [target]) + self.assertFalse(Path(self._path("new")).exists()) + + def test_check_mode_reports_mode_drift_without_chmod(self): + target = self._path("conf.d") + self._mkdir(target, 0o700) + result = self._run({"paths": [target], "mode": "0755"}, check_mode=True) + self.assertEqual(result["changed_paths"], [target]) + self.assertEqual(self._mode(target), 0o700) + + def test_check_mode_reports_owner_drift_without_chown(self): + target = self._path("owned") + Path(target).mkdir() + foreign_uid = str(Path(target).stat().st_uid + 1) + result = self._run({"paths": [target], "owner": foreign_uid}, check_mode=True) + self.assertEqual(result["changed_paths"], [target]) + self.assertEqual(Path(target).stat().st_uid, os.getuid()) + + def test_current_owner_and_group_are_unchanged(self): + target = self._path("owned") + Path(target).mkdir() + info = Path(target).stat() + result = self._run( + { + "entries": [ + { + "path": target, + "owner": str(info.st_uid), + "group": str(info.st_gid), + } + ] + } + ) + self.assertFalse(result["changed"]) + + def test_unknown_owner_fails_loudly(self): + target = self._path("owned") + Path(target).mkdir() + result = self._run({"paths": [target], "owner": "no-such-user-dirbatch"}) + self.assertTrue(result["failed"]) + self.assertIn("no-such-user-dirbatch", result["msg"]) + + def test_symlink_to_directory_is_followed(self): + real = self._path("real") + link = self._path("link") + self._mkdir(real, 0o700) + Path(link).symlink_to(real) + result = self._run({"paths": [link], "mode": "0755"}) + self.assertEqual(result["changed_paths"], [link]) + self.assertEqual(self._mode(real), 0o755) + self.assertTrue(Path(link).is_symlink()) + + def test_existing_file_fails_loudly(self): + target = self._path("nginx.conf") + Path(target).write_text("events {}\n", encoding="utf-8") + result = self._run({"paths": [target], "mode": "0755"}) + self.assertTrue(result["failed"]) + self.assertIn("already exists as a file", result["msg"]) + + def test_relative_path_fails_loudly(self): + result = self._run({"paths": ["relative/dir"], "mode": "0755"}) + self.assertTrue(result["failed"]) + self.assertIn("not an absolute path", result["msg"]) + + @unittest.skipIf(os.geteuid() == 0, "root ignores directory permissions") + def test_unwritable_parent_fails_loudly(self): + parent = self._path("locked") + self._mkdir(parent, 0o500) + result = self._run({"paths": [self._path("locked", "child")], "mode": "0755"}) + self.assertTrue(result["failed"]) + self.assertIn("Could not create", result["msg"]) + + def test_failure_reports_the_paths_changed_before_it(self): + created = self._path("created") + blocker = self._path("blocker") + Path(blocker).write_text("", encoding="utf-8") + result = self._run({"paths": [created, blocker], "mode": "0755"}) + self.assertTrue(result["failed"]) + self.assertTrue(result["changed"]) + self.assertEqual(result["changed_paths"], [created]) + + def test_entries_and_paths_are_mutually_exclusive(self): + result = self._run( + {"entries": [{"path": self._path("a")}], "paths": [self._path("b")]} + ) + self.assertTrue(result["failed"]) + self.assertIn("mutually exclusive", result["msg"]) + + def test_entries_and_top_level_mode_are_mutually_exclusive(self): + result = self._run({"entries": [{"path": self._path("a")}], "mode": "0755"}) + self.assertTrue(result["failed"]) + self.assertIn("mutually exclusive", result["msg"]) + + def test_entries_or_paths_is_required(self): + result = self._run({"mode": "0755"}) + self.assertTrue(result["failed"]) + self.assertIn("one of the following is required", result["msg"]) + + def test_unknown_entry_key_is_rejected(self): + result = self._run({"entries": [{"path": self._path("a"), "recurse": True}]}) + self.assertTrue(result["failed"]) + self.assertIn("recurse", result["msg"]) + + def test_diff_mode_lists_each_changed_path(self): + target = self._path("conf.d") + result = self._run({"paths": [target], "mode": "0755"}, diff=True) + self.assertEqual(len(result["diff"]), 1) + self.assertEqual(result["diff"][0]["before"]["state"], "absent") + self.assertEqual(result["diff"][0]["after"]["state"], "directory") + + def test_diff_mode_records_the_mode_change(self): + target = self._path("conf.d") + self._mkdir(target, 0o700) + result = self._run({"paths": [target], "mode": "0755"}, diff=True) + self.assertEqual(result["diff"][0]["before"]["mode"], "0700") + self.assertEqual(result["diff"][0]["after"]["mode"], "0755") + + def test_no_diff_outside_diff_mode(self): + result = self._run({"paths": [self._path("conf.d")], "mode": "0755"}) + self.assertNotIn("diff", result) + + +if __name__ == "__main__": + unittest.main()