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
75 changes: 75 additions & 0 deletions acceptance/bin/capture_tfstate.py
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:
Comment thread
janniklasrose marked this conversation as resolved.
Resolved
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()
171 changes: 171 additions & 0 deletions acceptance/bin/replay_tfstate.py
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()
9 changes: 2 additions & 7 deletions acceptance/bundle/migrate/auto/apply-failure/output.txt
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@

=== Initial deploy on terraform
>>> DATABRICKS_BUNDLE_ENGINE=terraform [CLI] bundle deploy
Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/files...
Created jobs.test_job
Files: 1 uploaded, 0 deleted
Resources: 1 created, 0 changed, 0 deleted, 0 unchanged
=== Replay a prior terraform deployment
>>> replay_tfstate.py terraform-requests.json terraform.tfstate

>>> update_file.py databricks.yml Test Auto-Migrate Apply Failure Test Auto-Migrate Apply Failure (updated)

Expand Down Expand Up @@ -36,7 +32,6 @@ direct_migrated_via_env true
>>> MSYS_NO_PATHCONV=1 [CLI] workspace list /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/state
ID Type Language Path
[NUMID] FILE /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/state/deployment.json
[NUMID] FILE /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/state/metadata.json
[NUMID] FILE /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/state/resources.json
[NUMID] FILE /Workspace/Users/[USERNAME]/.bundle/test-bundle/default/state/terraform.tfstate.backup

Expand Down
4 changes: 2 additions & 2 deletions acceptance/bundle/migrate/auto/apply-failure/script
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export DATABRICKS_BUNDLE_ENGINE=

title "Initial deploy on terraform"
trace DATABRICKS_BUNDLE_ENGINE=terraform $CLI bundle deploy
title "Replay a prior terraform deployment"
trace replay_tfstate.py terraform-requests.json terraform.tfstate
rm -f "$OUT_REQUESTS"

# Change the job so the migrating deploy must update it (jobs/reset), giving us a resource apply
Expand Down
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
}
}
}
]
Loading
Loading