Repository navigation
Remove terraform dependency in migrate tests #6866
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
042a6e9
acceptance: seed migrate tests from a terraform-state fixture
denik 5507c4f
acceptance: record/replay proof for migrate/command/permissions
denik cd5ee43
acceptance: capture_tfstate.py + record/replay for migrate/auto/default
denik 439082e
acceptance: broaden replay_tfstate.py id fields for UC/dashboard/expe…
denik 7f4a560
acceptance: make capture_tfstate.py / replay_tfstate.py executable
denik 5bc14c5
acceptance: record/replay for the UC migrate tests (schema/volume/reg…
denik ba0c001
acceptance: record/replay for the auto fault migrate tests
denik f3f14f0
acceptance: record/replay for migrate/auto simple tests
denik db87a26
acceptance: convert command/ migrate tests to record/replay
denik bdc34cf
acceptance: replay resource requests directly, not via `databricks api`
denik 5616dda
acceptance: replay pushes the remote terraform state too
denik dea390a
acceptance: gofmt/ruff formatting for replay_tfstate.py
denik 7a23ef2
acceptance: keep replay fixtures and out.* files out of the bundle up…
denik e0c837c
acceptance: replay authenticates like the CLI so it works on cloud
denik 9bcea5a
acceptance: make the replay-based migrate tests local-only
denik File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| #!/usr/bin/env python3 | ||
| """ | ||
| Capture a terraform deployment's artifacts as migrate-test fixtures. Run ONCE, right after a | ||
| `DATABRICKS_BUNDLE_ENGINE=terraform bundle deploy`, while the terraform engine is still present. | ||
|
|
||
| Writes into the test's SOURCE dir ($TESTDIR): | ||
| - terraform.tfstate the real terraform state | ||
| - terraform-requests.json the resource-mutating requests (with bodies) terraform issued | ||
|
|
||
| replay_tfstate.py later replays the requests to reconstruct a real terraform-shaped backend and | ||
| drops in the (id-remapped) tfstate, so the migrate test starts from a real terraform deployment | ||
| without running the (removed) terraform engine. The capture-time host is normalized to | ||
| [DATABRICKS_URL] so the fixtures do not embed a per-run port. | ||
|
|
||
| Usage: capture_tfstate.py [TARGET] (TARGET defaults to "default") | ||
| """ | ||
|
|
||
| import json | ||
| import os | ||
| import re | ||
| import sys | ||
|
|
||
| TESTDIR = os.environ["TESTDIR"] | ||
| HOST = os.environ.get("DATABRICKS_HOST", "").rstrip("/") | ||
| # Per-run values baked into the captured state/requests are normalized to placeholders so the | ||
| # fixtures are frozen; replay_tfstate.py substitutes the current run's values back in. | ||
| UNIQUE_NAME = os.environ.get("UNIQUE_NAME", "") | ||
|
|
||
| # Requests that build backend resource state; everything else (file sync, state push, lock, | ||
| # telemetry, scim, mkdirs, deletes) is deploy plumbing the migrate test does not need reconstructed. | ||
| SKIP = re.compile(r"/api/2\.0/workspace(/|-files)|/telemetry|/scim|/\.well-known|/state/|/mkdirs") | ||
|
|
||
|
|
||
| def read_json_many(s): | ||
| dec = json.JSONDecoder() | ||
| out = [] | ||
| pos, n = 0, len(s) | ||
| while pos < n: | ||
| while pos < n and s[pos] in " \t\r\n": | ||
| pos += 1 | ||
| if pos >= n: | ||
| break | ||
| obj, pos = dec.raw_decode(s, pos) | ||
| out.append(obj) | ||
| return out | ||
|
|
||
|
|
||
| def norm(text): | ||
| if HOST: | ||
| text = text.replace(HOST, "[DATABRICKS_URL]") | ||
| # UNIQUE_NAME is a long random per-run token, so a plain replace is safe. | ||
| if len(UNIQUE_NAME) >= 8: | ||
| text = text.replace(UNIQUE_NAME, "[UNIQUE_NAME]") | ||
| return text | ||
|
|
||
|
|
||
| def main(): | ||
| target = sys.argv[1] if len(sys.argv) > 1 else "default" | ||
| tfstate_raw = open(f".databricks/bundle/{target}/terraform/terraform.tfstate").read() | ||
| requests = read_json_many(open(os.environ["OUT_REQUESTS"]).read()) | ||
|
|
||
| kept = [ | ||
| {"method": r["method"], "path": r["path"], "body": r.get("body")} | ||
| for r in requests | ||
| if r.get("method") in ("POST", "PUT", "PATCH") and not SKIP.search(r.get("path", "")) | ||
| ] | ||
|
|
||
| with open(os.path.join(TESTDIR, "terraform.tfstate"), "w") as f: | ||
| f.write(norm(tfstate_raw)) | ||
| with open(os.path.join(TESTDIR, "terraform-requests.json"), "w") as f: | ||
| f.write(norm(json.dumps(kept, indent=2)) + "\n") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| #!/usr/bin/env python3 | ||
| """ | ||
| Reconstruct a terraform deployment for the migrate tests without the (removed) terraform engine. | ||
|
|
||
| Given a checked-in terraform.tfstate and the resource-mutating requests the terraform deploy made | ||
| (both captured once from a real terraform run), replay the requests against the backend so it ends | ||
| up in the exact terraform-shaped state, then write the tfstate locally with each recorded resource | ||
| id rewritten to the one the backend just minted. The migrate step then reads a real terraform state | ||
| backed by real (terraform-shaped) resources. | ||
|
|
||
| The requests carry the recorded ids; the backend mints fresh ones on replay. We learn each mapping | ||
| from the create responses (matching a create to its tfstate resource by an identifying name) and | ||
| rewrite it into every later request and into the tfstate, so cross-resource references stay consistent. | ||
|
|
||
| Usage: replay_tfstate.py REQUESTS.json TFSTATE.json [-t TARGET] | ||
| """ | ||
|
|
||
| import argparse | ||
| import json | ||
| import os | ||
| import re | ||
| import subprocess | ||
| import sys | ||
| import urllib.error | ||
| import urllib.request | ||
|
|
||
| import print_state | ||
|
|
||
| CLI = os.environ["CLI"] | ||
| HOST = os.environ.get("DATABRICKS_HOST", "").rstrip("/") | ||
| UNIQUE_NAME = os.environ.get("UNIQUE_NAME", "") | ||
|
|
||
| # Talk to the workspace directly rather than via `databricks api`: the CLI renders responses through | ||
| # Go's `any`, which decodes JSON numbers as float64 and silently mangles the low digits of a freshly | ||
| # minted id (they exceed 2^53), so the id we'd record would not match the one the backend stored. | ||
| # Python's json keeps ids exact. Bypass any proxy: these tests only hit the workspace directly. | ||
| _opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) | ||
|
|
||
|
|
||
| # The fake server routes by the PAT in DATABRICKS_TOKEN. These fixtures are captured against it, so | ||
| # the migrate tests that replay them are local-only (see their test.toml) - there is no cloud path. | ||
| TOKEN = os.environ.get("DATABRICKS_TOKEN", "") | ||
|
|
||
| # Per resource: which response field carries the new id. Terraform's tfstate stores the same value | ||
| # as the resource's `id`, keyed here by the create path so we can match a create to its tfstate entry. | ||
| ID_FIELDS = ["job_id", "pipeline_id", "dashboard_id", "experiment_id", "full_name", "id", "name"] | ||
|
|
||
| # A create request is matched to its tfstate resource by a human-supplied identifying field; different | ||
| # resource types name it differently (jobs/pipelines use `name`, dashboards use `display_name`, …). | ||
| NAME_FIELDS = ["name", "display_name", "full_name"] | ||
|
|
||
| # A backend-minted value that another resource may reference (e.g. a volume's storage_location, which | ||
| # a pipeline tags). We remap these recorded->minted just like ids: a UUID, an s3-style path (which | ||
| # embeds a UUID), or a long numeric id. Timestamps (13-digit millis) are shorter and excluded. | ||
| BACKEND_VALUE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}") | ||
|
|
||
|
|
||
| def is_backend_value(v): | ||
| s = str(v) | ||
| return bool(BACKEND_VALUE.search(s)) or s.startswith("s3://") or (s.isdigit() and len(s) >= 15) | ||
|
|
||
|
|
||
| def apply_map(text, id_map): | ||
| for old, new in id_map.items(): | ||
| text = text.replace(old, new) | ||
| return text | ||
|
|
||
|
|
||
| def run_cli(*args): | ||
| r = subprocess.run([CLI, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8") | ||
| if r.returncode != 0: | ||
| sys.exit(f"replay_tfstate.py: {' '.join(args)} failed:\n{r.stdout}") | ||
|
|
||
|
|
||
| def api(method, path, body): | ||
| data = json.dumps(body).encode() if body is not None else None | ||
| req = urllib.request.Request(HOST + path, data=data, method=method.upper()) | ||
| req.add_header("Authorization", "Bearer " + TOKEN) | ||
| # Stable UA so tests that record the replayed requests don't pin the Python version. | ||
| req.add_header("User-Agent", "replay_tfstate.py") | ||
| if data is not None: | ||
| req.add_header("Content-Type", "application/json") | ||
| try: | ||
| with _opener.open(req) as resp: | ||
| text = resp.read().decode() | ||
| except urllib.error.HTTPError as e: | ||
| sys.exit(f"replay_tfstate.py: {method} {path} failed: HTTP {e.code}\n{e.read().decode()}") | ||
| return json.loads(text) if text.strip() else {} | ||
|
|
||
|
|
||
| def main(): | ||
| parser = argparse.ArgumentParser() | ||
| parser.add_argument("requests") | ||
| parser.add_argument("tfstate") | ||
| parser.add_argument("-t", "--target", default="default") | ||
| args = parser.parse_args() | ||
|
|
||
| requests_raw = open(args.requests).read() | ||
| tfstate_raw = open(args.tfstate).read() | ||
|
|
||
| # Restore this run's values into the frozen fixtures. UNIQUE_NAME goes into both (resource | ||
| # names must match the current config); the host goes into the requests we issue, but the | ||
| # tfstate keeps [DATABRICKS_URL] so print_state's output matches the goldens. | ||
| if UNIQUE_NAME: | ||
| requests_raw = requests_raw.replace("[UNIQUE_NAME]", UNIQUE_NAME) | ||
| tfstate_raw = tfstate_raw.replace("[UNIQUE_NAME]", UNIQUE_NAME) | ||
| if HOST: | ||
| requests_raw = requests_raw.replace("[DATABRICKS_URL]", HOST) | ||
|
|
||
| requests = json.loads(requests_raw) | ||
| tfstate = json.loads(tfstate_raw) | ||
|
|
||
| # The fixtures stay on disk (a later deploy skips them via the .gitignore script.prepare writes), | ||
| # so replay is non-destructive and a single fixture can be replayed more than once. | ||
|
|
||
| # identifying name -> recorded resource attributes, from the tfstate managed resources. | ||
| name_to_attrs = {} | ||
| for r in tfstate["resources"]: | ||
| if r.get("mode") != "managed": | ||
| continue | ||
| attrs = r["instances"][0]["attributes"] | ||
| if "id" not in attrs: | ||
| continue | ||
| for nf in NAME_FIELDS: | ||
| if attrs.get(nf): | ||
| name_to_attrs[str(attrs[nf])] = attrs | ||
|
|
||
| id_map = {} | ||
| for req in requests: | ||
| path = apply_map(req["path"], id_map) | ||
| body = req.get("body") | ||
| if body is not None: | ||
| body = json.loads(apply_map(json.dumps(body), id_map)) | ||
| resp = api(req["method"], path, body) | ||
|
|
||
| # A create (POST that returns a new id) whose identifying name matches a tfstate resource: | ||
| # map its recorded id to the freshly minted one. | ||
| create_name = None | ||
| if isinstance(body, dict): | ||
| create_name = next((str(body[nf]) for nf in NAME_FIELDS if body.get(nf)), None) | ||
| if req["method"] == "POST" and create_name in name_to_attrs: | ||
| attrs = name_to_attrs[create_name] | ||
| new_id = next((str(resp[f]) for f in ID_FIELDS if f in resp), None) | ||
| if new_id is None: | ||
| sys.exit(f"replay_tfstate.py: no id in response to {req['path']}: {resp}") | ||
| id_map[str(attrs["id"])] = new_id | ||
| # Also remap other backend-minted values a later resource may reference (e.g. a volume's | ||
| # storage_location that a pipeline tags), so those requests and the tfstate stay consistent. | ||
| for k, v in resp.items(): | ||
| old = attrs.get(k) | ||
| if old is not None and str(old) != str(v) and is_backend_value(old): | ||
| id_map[str(old)] = str(v) | ||
|
|
||
| out_dir = os.path.join(".databricks", "bundle", args.target, "terraform") | ||
| os.makedirs(out_dir, exist_ok=True) | ||
| local_path = os.path.join(out_dir, "terraform.tfstate") | ||
| with open(local_path, "w") as f: | ||
| f.write(apply_map(tfstate_raw, id_map)) | ||
|
|
||
| # A real terraform deploy leaves its state both on disk and in the workspace; push the remote | ||
| # copy too so a later migrate has a remote state to back up and tests that inspect the remote | ||
| # state dir see it. workspace import does not create parents, so mkdirs first. | ||
| state_dir = print_state.get_remote_state_path(args.target) | ||
| run_cli("workspace", "mkdirs", state_dir) | ||
| run_cli( | ||
| "workspace", "import", f"{state_dir}/terraform.tfstate", "--file", local_path, "--format", "AUTO", "--overwrite" | ||
| ) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
acceptance/bundle/migrate/auto/apply-failure/terraform-requests.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| [ | ||
| { | ||
| "method": "POST", | ||
| "path": "/api/2.2/jobs/create", | ||
| "body": { | ||
| "deployment": { | ||
| "kind": "BUNDLE", | ||
| "metadata_file_path": "/Workspace/Users/tester@databricks.com/.bundle/test-bundle/default/state/metadata.json" | ||
| }, | ||
| "edit_mode": "UI_LOCKED", | ||
| "format": "MULTI_TASK", | ||
| "max_concurrent_runs": 1, | ||
| "name": "Test Auto-Migrate Apply Failure", | ||
| "queue": { | ||
| "enabled": true | ||
| } | ||
| } | ||
| } | ||
| ] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.