Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(glue): patch botocore when the job script first imports it, not before (#2427)

mishukdutta-cz51826802e32e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 50a629cc..b491491a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **Glue — a job's own botocore loads from where the script asks** — the Spark boot shim imported `botocore` before the job script ran, so a `--py-files` deps zip that holds botocore gave the zipped copy, and a script that then swapped the zip for its extracted folder failed with `DataNotFoundError: Unable to load data for: endpoints`; the shim now patches `Session.create_client` when the script first imports `botocore.session`, and still adds `endpoint_url` only when the caller sets none.
- **Glue — Spark job scripts get `--JOB_NAME` and `--JOB_RUN_ID`** — a Spark job run passed only the job's `DefaultArguments` and the run's `Arguments`, so a script that reads `JOB_NAME` or `JOB_RUN_ID` with `getResolvedOptions` failed; both now reach the script, as on AWS. They replace a value in `DefaultArguments`, and a value in the run's `Arguments` replaces them. `pythonshell` scripts don't get them, as on AWS. `GetJobRun` still shows only the arguments the caller gave.
- **Step Functions — JSONata fields on an inline `Map`** — `Items`, `ItemSelector`, `MaxConcurrency`, `Output` and `Assign` were ignored or read as JSONPath, so the Map iterated over the whole input, iterations got literal `{% ... %}` text, a `MaxConcurrency` expression failed with `States.Runtime`, and `Assign` variables were never set; all five are now evaluated, as on AWS. `Items` that is not an array fails with `States.QueryEvaluationError`.
- **Step Functions — JSONata `Catch` on `Map` and `Parallel` states** — a catcher's `Output` and `Assign` were ignored, so the caught error passed on unchanged and the catcher's variables were never set; both now apply, as on a `Task` state.
diff --git a/ministack/services/glue.py b/ministack/services/glue.py
index e7443b02..50f2e422 100644
--- a/ministack/services/glue.py
+++ b/ministack/services/glue.py
@@ -1828,25 +1828,59 @@ def _execute_subprocess(run, job, args, resolved):
# Session.create_client covers every botocore vintage; the user script then
# runs unmodified as __main__ with its own argv, so getResolvedOptions and
# __name__ checks behave identically.
+# The patch is applied when the script first imports botocore.session, not
+# before. A deps zip on --py-files can hold its own botocore, and an early
+# import would load botocore from that zip, where it cannot read its data files.
_GLUE_BOOT_SCRIPT = """\
import os
import runpy
import sys
_endpoint = os.environ.get("AWS_ENDPOINT_URL")
-if _endpoint:
- try:
- import botocore.session as _bs
- _orig_create_client = _bs.Session.create_client
+
+
+class _PatchedSessionLoader:
+ def __init__(self, loader):
+ self._loader = loader
+
+ def __getattr__(self, name):
+ return getattr(self._loader, name)
+
+ def exec_module(self, module):
+ self._loader.exec_module(module)
+ _orig_create_client = module.Session.create_client
def _create_client(self, *args, **kwargs):
if not kwargs.get("endpoint_url"):
kwargs["endpoint_url"] = _endpoint
return _orig_create_client(self, *args, **kwargs)
- _bs.Session.create_client = _create_client
- except Exception:
- pass
+ module.Session.create_client = _create_client
+
+
+def _with_patch(spec):
+ if hasattr(spec.loader, "exec_module"):
+ spec.loader = _PatchedSessionLoader(spec.loader)
+ return spec
+
+
+class _BotocoreSessionFinder:
+ # Stays on sys.meta_path, so each load of botocore.session is patched, also after a find_spec probe or a reload.
+ def find_spec(self, name, path=None, target=None):
+ if name != "botocore.session":
+ return None
+ # The other finders resolve it from the sys.path of this import.
+ for finder in sys.meta_path:
+ if finder is self or not hasattr(finder, "find_spec"):
+ continue
+ spec = finder.find_spec(name, path, target)
+ if spec is not None:
+ return _with_patch(spec)
+ return None
+
+
+if _endpoint:
+ sys.meta_path.insert(0, _BotocoreSessionFinder())
_script = {script!r}
sys.argv = [_script] + sys.argv[1:]
diff --git a/tests/test_glue.py b/tests/test_glue.py
index 72963e53..a00cf7bd 100644
--- a/tests/test_glue.py
+++ b/tests/test_glue.py
@@ -2790,6 +2790,92 @@ def test_glue_spark_container_env_points_sdk_at_ministack(tmp_path, monkeypatch)
assert run["JobRunState"] == "SUCCEEDED"
+# A small stand-in for botocore: create_client returns the endpoint_url it gets.
+_FAKE_BOTOCORE_SESSION = (
+ "ORIGIN = {origin!r}\n"
+ "class Session:\n"
+ " def create_client(self, service, endpoint_url=None):\n"
+ " return endpoint_url\n"
+)
+
+
+def _write_fake_botocore(root, origin):
+ (root / "botocore").mkdir(parents=True)
+ (root / "botocore" / "__init__.py").write_text("")
+ (root / "botocore" / "session.py").write_text(_FAKE_BOTOCORE_SESSION.format(origin=origin))
+
+
+def _run_glue_boot(tmp_path, script, pythonpath):
+ """Run the boot shim with the host Python, as spark-submit runs it, and return the job script's stdout."""
+ import subprocess
+ import sys
+
+ from ministack.services.glue import _GLUE_BOOT_SCRIPT
+
+ job = tmp_path / "job.py"
+ job.write_text(script)
+ boot = tmp_path / "_ministack_boot.py"
+ boot.write_text(_GLUE_BOOT_SCRIPT.format(script=str(job)))
+ env = {**os.environ, "AWS_ENDPOINT_URL": "http://ministack:4566", "PYTHONPATH": pythonpath}
+ proc = subprocess.run([sys.executable, str(boot)], capture_output=True, text=True, env=env, timeout=30)
+ assert proc.returncode == 0, proc.stderr
+ return proc.stdout.strip()
+
+
+def test_glue_boot_patches_botocore_that_the_script_loads_after_it_swaps_its_deps_zip(tmp_path):
+ """A job that swaps its --py-files zip for an extracted folder gets botocore from the folder, with the patch."""
+ import zipfile
+
+ _write_fake_botocore(tmp_path / "zipped", "zip")
+ deps_zip = tmp_path / "glue-deps.zip"
+ with zipfile.ZipFile(deps_zip, "w") as zf:
+ for name in ("__init__.py", "session.py"):
+ zf.write(tmp_path / "zipped" / "botocore" / name, f"botocore/{name}")
+ _write_fake_botocore(tmp_path / "extracted", "folder")
+ script = (
+ "import sys\n"
+ f"sys.path.remove({str(deps_zip)!r})\n"
+ f"sys.path.insert(0, {str(tmp_path / 'extracted')!r})\n"
+ "import botocore.session\n"
+ "print(botocore.session.ORIGIN, botocore.session.Session().create_client('s3'))\n"
+ )
+
+ assert _run_glue_boot(tmp_path, script, str(deps_zip)) == "folder http://ministack:4566"
+
+
[email protected]("call,expected", [
+ ("create_client('s3')", "http://ministack:4566"),
+ ("create_client('s3', endpoint_url='http://custom:9000')", "http://custom:9000"),
+], ids=["default-endpoint", "caller-endpoint"])
+def test_glue_boot_sets_the_endpoint_only_when_the_caller_does_not(tmp_path, call, expected):
+ """botocore is not loaded before the script runs, and the patch keeps an endpoint_url that the caller sets."""
+ _write_fake_botocore(tmp_path / "site", "site")
+ script = (
+ "import sys\n"
+ "loaded_early = 'botocore' in sys.modules\n"
+ "import botocore.session\n"
+ f"print(loaded_early, botocore.session.Session().{call})\n"
+ )
+
+ assert _run_glue_boot(tmp_path, script, str(tmp_path / "site")) == f"False {expected}"
+
+
+def test_glue_boot_patches_botocore_after_a_find_spec_probe_and_a_reload(tmp_path):
+ """A find_spec check before the import does not use up the patch, and a reload is patched too."""
+ _write_fake_botocore(tmp_path / "site", "site")
+ script = (
+ "import importlib\n"
+ "import importlib.util\n"
+ "importlib.util.find_spec('botocore.session')\n"
+ "import botocore.session\n"
+ "first = botocore.session.Session().create_client('s3')\n"
+ "importlib.reload(botocore.session)\n"
+ "print(first, botocore.session.Session().create_client('s3'))\n"
+ )
+
+ assert _run_glue_boot(tmp_path, script, str(tmp_path / "site")) == "http://ministack:4566 http://ministack:4566"
+
+
def test_glue_translate_loopback_conf_rewrites_only_gateway_loopbacks():
from ministack.services.glue import _translate_loopback_conf