diff --git a/acceptance/bin/dms_resources.py b/acceptance/bin/dms_resources.py new file mode 100644 index 00000000000..25e469c5bad --- /dev/null +++ b/acceptance/bin/dms_resources.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +""" +Read resource ids and state from the deployment metadata service. + +While a bundle records deployment history the service owns the resource set, so the state file is +not where ids and state come from. The service is asked instead, which takes two lookups: the CLI +keeps no deployment id locally, and the id is the object id of the workspace node the service +registers under /resources.deployment.json (see libs/dms/resolve.go). +""" + +import functools +import glob +import json +import os +import posixpath +import subprocess +import sys + +sys.path.insert(0, os.path.dirname(__file__)) +from print_state import get_state_file + +CLI = os.environ.get("CLI", "databricks") + +# Must match dms.DeploymentNodeName. +DEPLOYMENT_NODE_NAME = "resources.deployment.json" + + +def run_json(cmd, allow_failure=False): + """Run cmd and parse its stdout, or return None if it fails and allow_failure is set. stderr is + captured rather than inherited: these lookups are plumbing, and a CLI warning like "no files to + sync" would otherwise land in the test output.""" + result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8") + if result.returncode != 0: + if allow_failure: + return None + raise SystemExit(f"{cmd} failed with code {result.returncode}\n{result.stdout}{result.stderr}".strip()) + return json.loads(result.stdout) + + +def records_deployment_history(): + """Whether this run records deployment history, so the service is what to ask.""" + return os.environ.get("DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY") == "true" + + +def get_remote_state_path(target): + """The bundle's remote state directory. + + Preferred source is the sync snapshot, because it needs no CLI call: re-running the config + load would need whatever --var and flags the test deployed with, which a helper cannot know. + A bundle with no files to sync writes no snapshot, so fall back to asking the CLI - those + bundles are the ones with nothing to parameterize.""" + target_dir = os.path.dirname(get_state_file(target, False)) + snapshots = glob.glob(f"{target_dir}/sync-snapshots/*.json") + if snapshots: + # One snapshot per remote path, so a test that moved its root leaves several: the newest + # is the one the last deploy used. + newest = max(snapshots, key=os.path.getmtime) + remote_path = json.loads(open(newest).read())["remote_path"] + # state and files are siblings under the bundle root. + return posixpath.join(posixpath.dirname(remote_path), "state") + + args = [CLI, "bundle", "validate", "--output", "json"] + if target: + args += ["-t", target] + return run_json(args)["workspace"]["state_path"] + + +@functools.cache +def get_resources(target): + """Map every recorded resource key ("jobs.foo") to its {"id", "state"}. + + Empty when the bundle has no deployment recorded yet. Cached because a lookup costs three + round trips and a script asks for one resource at a time. + """ + state_path = get_remote_state_path(target) + if not state_path: + return {} + + # No node means nothing has been recorded, the conclusion dms.resolveDeploymentID also draws + # from a 404 - the deployment is gone once the bundle is destroyed. + node = run_json([CLI, "workspace", "get-status", f"{state_path}/{DEPLOYMENT_NODE_NAME}"], allow_failure=True) + if not node or not node.get("object_id"): + return {} + deployment_id = node["object_id"] + + result = {} + # The service pages at 50 resources; the local fake returns everything at once. + page_token = None + while True: + url = f"/api/2.0/bundle/deployments/{deployment_id}/resources" + if page_token: + url += f"?page_token={page_token}" + listed = run_json([CLI, "api", "get", url]) + for resource in listed.get("resources") or []: + # The service stores state as the opaque envelope the CLI wrote (dstate.RecordedState), + # so unwrap it to the resource state itself. + envelope = json.loads(resource["state"]) if resource.get("state") else {} + result[resource["resource_key"]] = { + "id": resource.get("resource_id"), + "state": envelope.get("state") or {}, + "depends_on": envelope.get("depends_on") or [], + } + page_token = listed.get("next_page_token") + if not page_token: + return result diff --git a/acceptance/bin/print_state.py b/acceptance/bin/print_state.py index 7e82f7b3d16..2959a76f81b 100755 --- a/acceptance/bin/print_state.py +++ b/acceptance/bin/print_state.py @@ -8,9 +8,14 @@ import argparse import glob +import json import os +def records_deployment_history(): + return os.environ.get("DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY") == "true" + + def print_file(filename): data = open(filename).read() print(data, end="") @@ -53,6 +58,26 @@ def get_state_file(target, backup): return filtered[0] if filtered else result[0] +def print_recorded_state(filename, target): + """Print the state file with its resources filled in from the deployment metadata service. + + While recording, the file itself carries only the header - the service holds the resources - so + printing it raw would show an empty state and differ from the same test's non-recording run. + """ + # Imported here rather than at module level: dms_resources reads get_state_file from this module. + from dms_resources import get_resources + + data = json.loads(open(filename).read()) + state = {} + for key, value in sorted(get_resources(target).items()): + entry = {"__id__": value["id"], "state": value["state"]} + if value["depends_on"]: + entry["depends_on"] = value["depends_on"] + state[f"resources.{key}"] = entry + data["state"] = state + print(json.dumps(data, indent=1)) + + def main(): parser = argparse.ArgumentParser() parser.add_argument("-t", "--target") @@ -60,7 +85,11 @@ def main(): args = parser.parse_args() for filename in get_state_files(args.target, args.backup): - if os.path.exists(filename): + if not os.path.exists(filename): + continue + if filename.endswith("resources.json") and records_deployment_history(): + print_recorded_state(filename, args.target) + else: print_file(filename) diff --git a/acceptance/bin/read_id.py b/acceptance/bin/read_id.py index 87cd2954bdf..06e7b69281e 100755 --- a/acceptance/bin/read_id.py +++ b/acceptance/bin/read_id.py @@ -15,6 +15,7 @@ sys.path.insert(0, str(Path(__file__).parent)) from add_repl import add_repl +from dms_resources import get_resources, records_deployment_history from print_state import get_state_file @@ -34,6 +35,15 @@ def get_id_terraform(filename, name): print(f"Cannot find resource with {name=}. Available: {available}", file=sys.stderr) +def get_id_recorded(target, name): + resources = get_resources(target) + for key, value in resources.items(): + if key.split(".")[1] == name: + return value["id"] + + print(f"Cannot find recorded resource with {name=}. Available: {list(resources)}", file=sys.stderr) + + def get_id_direct(filename, name): raw = open(filename).read() data = json.loads(raw) @@ -53,11 +63,14 @@ def main(): parser.add_argument("name") args = parser.parse_args() - filename = get_state_file(args.target, args.backup) - if filename.endswith(".tfstate"): - id = get_id_terraform(filename, args.name) + if records_deployment_history(): + id = get_id_recorded(args.target, args.name) else: - id = get_id_direct(filename, args.name) + filename = get_state_file(args.target, args.backup) + if filename.endswith(".tfstate"): + id = get_id_terraform(filename, args.name) + else: + id = get_id_direct(filename, args.name) if id: print(id) diff --git a/acceptance/bin/read_state.py b/acceptance/bin/read_state.py index 0166bf9abbb..4d9bf84186e 100755 --- a/acceptance/bin/read_state.py +++ b/acceptance/bin/read_state.py @@ -9,6 +9,9 @@ import os import sys +sys.path.insert(0, os.path.dirname(__file__)) +from dms_resources import get_resources, records_deployment_history + def print_resource_terraform(group, name, *attrs): resource_type = "databricks_" + group[:-1] @@ -50,7 +53,21 @@ def print_resource_direct(group, name, *attrs): print(group, name, " ".join(values)) -if os.environ.get("DATABRICKS_BUNDLE_ENGINE", "").startswith("direct"): +def print_resource_recorded(group, name, *attrs): + result = get_resources(None).get(f"{group}.{name}") + if result is None: + print(f"State not found for {group}.{name}") + return + + state = dict(result["state"]) + state.setdefault("id", result["id"]) + values = [f"{x}={state.get(x)!r}" for x in attrs] + print(group, name, " ".join(values)) + + +if records_deployment_history(): + print_resource_recorded(*sys.argv[1:]) +elif os.environ.get("DATABRICKS_BUNDLE_ENGINE", "").startswith("direct"): print_resource_direct(*sys.argv[1:]) else: print_resource_terraform(*sys.argv[1:]) diff --git a/acceptance/bin/replace_ids.py b/acceptance/bin/replace_ids.py index e0ebf1cd0e6..2f5d8165032 100755 --- a/acceptance/bin/replace_ids.py +++ b/acceptance/bin/replace_ids.py @@ -10,6 +10,7 @@ sys.path.insert(0, str(Path(__file__).parent)) from add_repl import add_repl +from dms_resources import get_resources, records_deployment_history from print_state import get_state_file @@ -26,6 +27,12 @@ def iter_ids_terraform(filename): yield r_name, id +def iter_ids_recorded(target): + for key, value in get_resources(target).items(): + if value["id"]: + yield key.split(".")[1], value["id"] + + def iter_ids_direct(filename): raw = open(filename).read() data = json.loads(raw) @@ -44,11 +51,14 @@ def main(): parser.add_argument("--backup", action="store_true") args = parser.parse_args() - filename = get_state_file(args.target, args.backup) - if filename.endswith(".tfstate"): - it = iter_ids_terraform(filename) + if records_deployment_history(): + it = iter_ids_recorded(args.target) else: - it = iter_ids_direct(filename) + filename = get_state_file(args.target, args.backup) + if filename.endswith(".tfstate"): + it = iter_ids_terraform(filename) + else: + it = iter_ids_direct(filename) for name, id in it: add_repl(id, name.upper() + "_ID") diff --git a/acceptance/bundle/deploy/files/out-of-band-delete/test.toml b/acceptance/bundle/deploy/files/out-of-band-delete/test.toml index 8c3f2408d5c..f8f11b0a174 100644 --- a/acceptance/bundle/deploy/files/out-of-band-delete/test.toml +++ b/acceptance/bundle/deploy/files/out-of-band-delete/test.toml @@ -1,6 +1,8 @@ -# Recording needs a bundle it has seen from the start. This test seeds a state file, -# so recording refuses it. TODO(DMS): drop this once existing state can be -# handed over to the service (see the TODO in dstate.Open). +# The out-of-band delete takes the whole bundle root, including the workspace node the +# service registers the deployment under. The state file survives and is accepted (it records +# record_deployment_history), so the redeploy re-stamps the job with the new deployment's id +# and reports it as changed where the non-recording run reports it unchanged. Both are right, +# but the two variants share one golden. EnvMatrix.DMS = [""] Badness = "After the remote bundle files are deleted out-of-band, the next deploy does not re-upload them until the local sync snapshot is removed." diff --git a/acceptance/bundle/deploy/readplan/test.toml b/acceptance/bundle/deploy/readplan/test.toml index e6ef3fcdcfb..576ff1ab001 100644 --- a/acceptance/bundle/deploy/readplan/test.toml +++ b/acceptance/bundle/deploy/readplan/test.toml @@ -1,3 +1,3 @@ -# Saved plans don't carry the deployment stamp. Applying one plans an update on the next run. -# See dms_no_readplan in acceptance/bundle/test.toml. +# Dumps post-deploy state/plan, which carry the DMS deployment stamp under recording (applied at +# deploy, not saved in the plan). deploy --plan recording is covered by bundle/dms, so opt out here. EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/deploy/wal/header-only-wal/output.txt b/acceptance/bundle/deploy/wal/header-only-wal/output.txt index 807fa926044..da8c1bdc1f3 100644 --- a/acceptance/bundle/deploy/wal/header-only-wal/output.txt +++ b/acceptance/bundle/deploy/wal/header-only-wal/output.txt @@ -28,7 +28,7 @@ Resources: 1 created, 0 changed, 0 deleted, 0 unchanged >>> errcode assert_not_exists.py .databricks/bundle/default/resources.json.wal ->>> errcode cat .databricks/bundle/default/resources.json +>>> errcode print_state.py { "serial": 1, "state_keys": [ diff --git a/acceptance/bundle/deploy/wal/header-only-wal/script b/acceptance/bundle/deploy/wal/header-only-wal/script index 89da7e1a277..557fc7d4f47 100644 --- a/acceptance/bundle/deploy/wal/header-only-wal/script +++ b/acceptance/bundle/deploy/wal/header-only-wal/script @@ -19,4 +19,4 @@ title "Third deploy (must recover and succeed, not blocked by the leftover WAL)" trace errcode $CLI bundle deploy --force-lock trace errcode assert_not_exists.py .databricks/bundle/default/resources.json.wal -trace errcode cat .databricks/bundle/default/resources.json | jq -S '{serial: .serial, state_keys: (.state | keys)}' +trace errcode print_state.py | jq -S '{serial: .serial, state_keys: (.state | keys)}' diff --git a/acceptance/bundle/dms/declined-deploy/databricks.yml.tmpl b/acceptance/bundle/dms/declined-deploy/databricks.yml.tmpl new file mode 100644 index 00000000000..e909afaab5c --- /dev/null +++ b/acceptance/bundle/dms/declined-deploy/databricks.yml.tmpl @@ -0,0 +1,10 @@ +bundle: + name: dms-declined-deploy-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + schemas: + foo: + name: dms_declined_deploy_schema_$UNIQUE_NAME + catalog_name: main diff --git a/acceptance/bundle/dms/declined-deploy/out.requests.txt b/acceptance/bundle/dms/declined-deploy/out.requests.txt new file mode 100644 index 00000000000..eb169f26a0c --- /dev/null +++ b/acceptance/bundle/dms/declined-deploy/out.requests.txt @@ -0,0 +1,7 @@ +{ + "method": "DELETE", + "path": "/api/2.1/unity-catalog/catalogs/dms_other_[UNIQUE_NAME]", + "q": { + "force": "true" + } +} diff --git a/acceptance/bundle/dms/declined-deploy/out.test.toml b/acceptance/bundle/dms/declined-deploy/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/declined-deploy/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/declined-deploy/output.txt b/acceptance/bundle/dms/declined-deploy/output.txt new file mode 100644 index 00000000000..d09e8d18743 --- /dev/null +++ b/acceptance/bundle/dms/declined-deploy/output.txt @@ -0,0 +1,88 @@ + +=== Deploy a schema, so the deployment and its first version exist +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-declined-deploy-[UNIQUE_NAME]/default/files... +Created schemas.foo +Files: 5 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments", + "body": { + "display_name": "dms-declined-deploy-[UNIQUE_NAME]", + "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-declined-deploy-[UNIQUE_NAME]/default/state", + "target_name": "default", + "workspace_info": { + "file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-declined-deploy-[UNIQUE_NAME]/default/files", + "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-declined-deploy-[UNIQUE_NAME]/default" + } + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "1" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "operations": [ + { + "resource_key": "schemas.foo", + "action_type": "OPERATION_ACTION_TYPE_CREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/schemas.foo", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "main.dms_declined_deploy_schema_[UNIQUE_NAME]", + "sequence_id": "0", + "state": "{\"state\":{\"catalog_name\":\"main\",\"name\":\"dms_declined_deploy_schema_[UNIQUE_NAME]\"}}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} + +=== A destructive change without --auto-approve is declined: this console cannot prompt +>>> update_file.py databricks.yml catalog_name: main catalog_name: dms_other_[UNIQUE_NAME] + +>>> musterr [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-declined-deploy-[UNIQUE_NAME]/default/files... + +This action will result in the deletion or recreation of the following UC schemas. Any underlying data may be lost: + recreate resources.schemas.foo +Error: the deployment requires destructive actions, but the current console does not support prompting. +Deleting data assets such as schemas, pipelines, or volumes may cause permanent data loss and should be carefully reviewed. +To proceed, use --auto-approve after reviewing the plan above. + +Files: 4 uploaded, 0 deleted + +=== Nothing was recorded for the declined deploy - no version, so none to abort +>>> print_requests.py --dms //api/2.0/bundle + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.schemas.foo + +This action will result in the deletion of the following UC schemas. Any underlying data may be lost: + delete resources.schemas.foo + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-declined-deploy-[UNIQUE_NAME]/default + +Destroy: 1 deleted diff --git a/acceptance/bundle/dms/declined-deploy/script b/acceptance/bundle/dms/declined-deploy/script new file mode 100644 index 00000000000..e67ff786b19 --- /dev/null +++ b/acceptance/bundle/dms/declined-deploy/script @@ -0,0 +1,22 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy a schema, so the deployment and its first version exist" +trace $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle + +title "A destructive change without --auto-approve is declined: this console cannot prompt" +# Changing the catalog recreates the schema, which needs approval. +# Unity Catalog has no catalog called "other", so make one to move the schema into. +other_catalog="dms_other_${UNIQUE_NAME}" +$CLI catalogs create "$other_catalog" &> LOG.catalog +trap '$CLI catalogs delete "$other_catalog" --force >> LOG.catalog 2>&1' EXIT +trace update_file.py databricks.yml "catalog_name: main" "catalog_name: ${other_catalog}" +trace musterr $CLI bundle deploy + +title "Nothing was recorded for the declined deploy - no version, so none to abort" +# The version number it would have used is left for the next deploy to take, so the +# history has no entry that reads like a deploy which failed or did nothing. +trace print_requests.py --dms //api/2.0/bundle + +trace $CLI bundle destroy --auto-approve +rm -f out.requests.txt diff --git a/acceptance/bundle/dms/depends-on/databricks.yml.tmpl b/acceptance/bundle/dms/depends-on/databricks.yml.tmpl new file mode 100644 index 00000000000..1a60d215ecc --- /dev/null +++ b/acceptance/bundle/dms/depends-on/databricks.yml.tmpl @@ -0,0 +1,12 @@ +bundle: + name: dms-depends-on-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + parent: + name: parent + child: + name: child + description: depends on ${resources.jobs.parent.id} diff --git a/acceptance/bundle/dms/depends-on/out.test.toml b/acceptance/bundle/dms/depends-on/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/depends-on/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/depends-on/output.txt b/acceptance/bundle/dms/depends-on/output.txt new file mode 100644 index 00000000000..4807497d63c --- /dev/null +++ b/acceptance/bundle/dms/depends-on/output.txt @@ -0,0 +1,47 @@ + +=== Deploy a job that references another: depends_on is recorded alongside the config, since the reference is resolved to a literal in the config itself +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-depends-on-[UNIQUE_NAME]/default/files... +Created jobs.child +Created jobs.parent +Files: 5 uploaded, 0 deleted +Resources: 2 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //versions/1/operations +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.parent", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "[NUMID]", + "sequence_id": "0", + "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-depends-on-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":1,\"name\":\"parent\",\"queue\":{\"enabled\":true}}}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.child", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "[NUMID]", + "sequence_id": "0", + "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-depends-on-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"description\":\"depends on [NUMID]\",\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":1,\"name\":\"child\",\"queue\":{\"enabled\":true}},\"depends_on\":[{\"node\":\"resources.jobs.parent\",\"label\":\"${resources.jobs.parent.id}\"}]}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.jobs.child + delete resources.jobs.parent + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-depends-on-[UNIQUE_NAME]/default + +Destroy: 2 deleted diff --git a/acceptance/bundle/dms/depends-on/script b/acceptance/bundle/dms/depends-on/script new file mode 100644 index 00000000000..7f5576ce72b --- /dev/null +++ b/acceptance/bundle/dms/depends-on/script @@ -0,0 +1,8 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy a job that references another: depends_on is recorded alongside the config, since the reference is resolved to a literal in the config itself" +trace $CLI bundle deploy +trace print_requests.py --dms //versions/1/operations + +trace $CLI bundle destroy --auto-approve +rm -f out.requests.txt diff --git a/acceptance/bundle/dms/deployment-metadata-change/databricks.yml.tmpl b/acceptance/bundle/dms/deployment-metadata-change/databricks.yml.tmpl new file mode 100644 index 00000000000..07f434b2e7a --- /dev/null +++ b/acceptance/bundle/dms/deployment-metadata-change/databricks.yml.tmpl @@ -0,0 +1,22 @@ +bundle: + name: dms-metadata-before-$UNIQUE_NAME +experimental: + record_deployment_history: true + +workspace: + # Pinned, so renaming the bundle or switching target below keeps the same deployment: the + # deployment is the workspace node under state_path, and a different path would be a + # different deployment. + state_path: /Workspace/Users/${workspace.current_user.userName}/.bundle/dms-metadata-pinned-$UNIQUE_NAME/state + +resources: + schemas: + foo: + name: dms_metadata_schema_$UNIQUE_NAME + catalog_name: main + +targets: + dev: + default: true + prod: + mode: production diff --git a/acceptance/bundle/dms/deployment-metadata-change/out.test.toml b/acceptance/bundle/dms/deployment-metadata-change/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/deployment-metadata-change/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/deployment-metadata-change/output.txt b/acceptance/bundle/dms/deployment-metadata-change/output.txt new file mode 100644 index 00000000000..0b0798eee7f --- /dev/null +++ b/acceptance/bundle/dms/deployment-metadata-change/output.txt @@ -0,0 +1,144 @@ + +=== Deploy: the deployment is created carrying this bundle's metadata +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-metadata-before-[UNIQUE_NAME]/dev/files... +Created schemas.foo +Files: 5 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments", + "body": { + "display_name": "dms-metadata-before-[UNIQUE_NAME]", + "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-metadata-pinned-[UNIQUE_NAME]/state", + "target_name": "dev", + "workspace_info": { + "file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-metadata-before-[UNIQUE_NAME]/dev/files", + "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-metadata-before-[UNIQUE_NAME]/dev" + } + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "1" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "operations": [ + { + "resource_key": "schemas.foo", + "action_type": "OPERATION_ACTION_TYPE_CREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/schemas.foo", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "main.dms_metadata_schema_[UNIQUE_NAME]", + "sequence_id": "0", + "state": "{\"state\":{\"catalog_name\":\"main\",\"name\":\"dms_metadata_schema_[UNIQUE_NAME]\"}}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} + +=== Rename the bundle and switch target+mode. The state path is pinned, so this is the same deployment, updated in place - the mask carries every field that changed +>>> update_file.py databricks.yml dms-metadata-before dms-metadata-after + +>>> [CLI] bundle deploy -t prod +Recommendation: target with 'mode: production' should set 'workspace.root_path' to make sure only one copy is deployed + +A common practice is to use a username or principal name in this path, i.e. use + + root_path: /Workspace/Users/[USERNAME]/.bundle/${bundle.name}/${bundle.target} + +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-metadata-after-[UNIQUE_NAME]/prod/files... +Files: 5 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 1 unchanged + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]", + "q": { + "update_mask": "display_name,target_name,deployment_mode,workspace_info" + }, + "body": { + "deployment_mode": "DEPLOYMENT_MODE_PRODUCTION", + "display_name": "dms-metadata-after-[UNIQUE_NAME]", + "target_name": "prod", + "workspace_info": { + "file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-metadata-after-[UNIQUE_NAME]/prod/files", + "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-metadata-after-[UNIQUE_NAME]/prod" + } + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "2" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "previous_version_id": "1" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} + +=== Deploy again without touching anything: the record already says this, so no deployment update +>>> [CLI] bundle deploy -t prod +Recommendation: target with 'mode: production' should set 'workspace.root_path' to make sure only one copy is deployed + +A common practice is to use a username or principal name in this path, i.e. use + + root_path: /Workspace/Users/[USERNAME]/.bundle/${bundle.name}/${bundle.target} + +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-metadata-after-[UNIQUE_NAME]/prod/files... +Files: 2 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 1 unchanged + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "3" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "previous_version_id": "2" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/3/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} diff --git a/acceptance/bundle/dms/deployment-metadata-change/script b/acceptance/bundle/dms/deployment-metadata-change/script new file mode 100644 index 00000000000..03f0c593999 --- /dev/null +++ b/acceptance/bundle/dms/deployment-metadata-change/script @@ -0,0 +1,14 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy: the deployment is created carrying this bundle's metadata" +trace $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle + +title "Rename the bundle and switch target+mode. The state path is pinned, so this is the same deployment, updated in place - the mask carries every field that changed" +trace update_file.py databricks.yml dms-metadata-before dms-metadata-after +trace $CLI bundle deploy -t prod +trace print_requests.py --dms //api/2.0/bundle + +title "Deploy again without touching anything: the record already says this, so no deployment update" +trace $CLI bundle deploy -t prod +trace print_requests.py --dms //api/2.0/bundle diff --git a/acceptance/bundle/dms/emptied-resource/databricks.yml.tmpl b/acceptance/bundle/dms/emptied-resource/databricks.yml.tmpl new file mode 100644 index 00000000000..b8c21a3cc96 --- /dev/null +++ b/acceptance/bundle/dms/emptied-resource/databricks.yml.tmpl @@ -0,0 +1,11 @@ +bundle: + name: dms-emptied-resource-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + schemas: + foo: + name: dms_emptied_resource_$UNIQUE_NAME + catalog_name: main + grants: [{principal: deco-test-user@databricks.com, privileges: [USE_SCHEMA]}] diff --git a/acceptance/bundle/dms/emptied-resource/out.test.toml b/acceptance/bundle/dms/emptied-resource/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/emptied-resource/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/emptied-resource/output.txt b/acceptance/bundle/dms/emptied-resource/output.txt new file mode 100644 index 00000000000..d1170a2f40c --- /dev/null +++ b/acceptance/bundle/dms/emptied-resource/output.txt @@ -0,0 +1,97 @@ + +=== Deploy a schema with one grant: the grants node is recorded with its state +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-emptied-resource-[UNIQUE_NAME]/default/files... +Created schemas.foo +Created schemas.foo.grants +Files: 5 uploaded, 0 deleted +Resources: 2 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments", + "body": { + "display_name": "dms-emptied-resource-[UNIQUE_NAME]", + "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-emptied-resource-[UNIQUE_NAME]/default/state", + "target_name": "default", + "workspace_info": { + "file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-emptied-resource-[UNIQUE_NAME]/default/files", + "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-emptied-resource-[UNIQUE_NAME]/default" + } + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "1" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "operations": [ + { + "resource_key": "schemas.foo", + "action_type": "OPERATION_ACTION_TYPE_CREATE" + }, + { + "resource_key": "schemas.foo.grants", + "action_type": "OPERATION_ACTION_TYPE_CREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/schemas.foo", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "main.dms_emptied_resource_[UNIQUE_NAME]", + "sequence_id": "0", + "state": "{\"state\":{\"catalog_name\":\"main\",\"name\":\"dms_emptied_resource_[UNIQUE_NAME]\"}}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/schemas.foo.grants", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "schema/main.dms_emptied_resource_[UNIQUE_NAME]", + "sequence_id": "0", + "state": "{\"state\":{\"securable_type\":\"schema\",\"full_name\":\"main.dms_emptied_resource_[UNIQUE_NAME]\",\"__embed__\":[{\"principal\":\"deco-test-user@databricks.com\",\"privileges\":[\"USE_SCHEMA\"]}]},\"depends_on\":[{\"node\":\"resources.schemas.foo\",\"label\":\"${resources.schemas.foo.id}\"}]}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} + +=== Revoke the grant, so the grants node empties out +>>> update_file.py databricks.yml grants: [{principal: someone@example.com, privileges: [USE_SCHEMA]}] grants: [] +old='grants: [{principal: someone@example.com, privileges: [USE_SCHEMA]}]' not found in filename='databricks.yml' +bundle: + name: dms-emptied-resource-[UNIQUE_NAME] +experimental: + record_deployment_history: true + +resources: + schemas: + foo: + name: dms_emptied_resource_[UNIQUE_NAME] + catalog_name: main + grants: [{principal: deco-test-user@databricks.com, privileges: [USE_SCHEMA]}] + + +Exit code: 1 diff --git a/acceptance/bundle/dms/emptied-resource/script b/acceptance/bundle/dms/emptied-resource/script new file mode 100644 index 00000000000..5573dda9894 --- /dev/null +++ b/acceptance/bundle/dms/emptied-resource/script @@ -0,0 +1,20 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy a schema with one grant: the grants node is recorded with its state" +trace $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle + +title "Revoke the grant, so the grants node empties out" +trace update_file.py databricks.yml 'grants: [{principal: someone@example.com, privileges: [USE_SCHEMA]}]' 'grants: []' +trace $CLI bundle deploy + +# The action type stays update: it is staged from the plan, before apply knows the state +# comes back empty. What drops the resource from the deployment is the update naming state +# with no value. +trace print_requests.py --dms //api/2.0/bundle + +title "Plan again: reading state back from the service works and reports no work" +trace $CLI bundle plan | contains.py "Plan: 0 to add, 0 to change, 0 to delete" "!unexpected end of JSON input" + +trace $CLI bundle destroy --auto-approve +rm -f out.requests.txt diff --git a/acceptance/bundle/dms/existing-state/databricks.yml.tmpl b/acceptance/bundle/dms/existing-state/databricks.yml.tmpl new file mode 100644 index 00000000000..29addd6433e --- /dev/null +++ b/acceptance/bundle/dms/existing-state/databricks.yml.tmpl @@ -0,0 +1,7 @@ +bundle: + name: dms-existing-state-$UNIQUE_NAME + +resources: + jobs: + one: + name: one diff --git a/acceptance/bundle/dms/existing-state/out.test.toml b/acceptance/bundle/dms/existing-state/out.test.toml new file mode 100644 index 00000000000..d73c45e3119 --- /dev/null +++ b/acceptance/bundle/dms/existing-state/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/dms/existing-state/output.txt b/acceptance/bundle/dms/existing-state/output.txt new file mode 100644 index 00000000000..68843cf8624 --- /dev/null +++ b/acceptance/bundle/dms/existing-state/output.txt @@ -0,0 +1,89 @@ + +=== Deploy without recording: the bundle gets ordinary direct-engine state, unknown to DMS +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/files... +Created jobs.one +Files: 6 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle --oneline + +>>> jq {state_version, features} .databricks/bundle/default/resources.json +{ + "state_version": 2, + "features": null +} + +=== Turning recording on afterwards is an error: those resources were never recorded, so treating DMS as authoritative would deploy them a second time +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true [CLI] bundle deploy +Error: cannot record deployment history for a bundle that already has deployed resources tracked in [TEST_TMP_DIR]/.databricks/bundle/default/resources.json: only new deployments can be recorded + +To record this bundle's history, start it over as a new deployment: + 1. remove experimental.record_deployment_history from your bundle configuration + 2. run "databricks bundle destroy" to delete the existing resources + 3. add experimental.record_deployment_history back and deploy again + +To keep the existing resources instead, unset experimental.record_deployment_history + + +=== No deployment was created in DMS +>>> print_requests.py --dms //api/2.0/bundle --oneline + +=== Still an error after wiping the local cache: deploy pulls the state file back from the workspace, so the resources are still tracked +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true [CLI] bundle deploy +Error: cannot record deployment history for a bundle that already has deployed resources tracked in [TEST_TMP_DIR]/.databricks/bundle/default/resources.json: only new deployments can be recorded + +To record this bundle's history, start it over as a new deployment: + 1. remove experimental.record_deployment_history from your bundle configuration + 2. run "databricks bundle destroy" to delete the existing resources + 3. add experimental.record_deployment_history back and deploy again + +To keep the existing resources instead, unset experimental.record_deployment_history + + +>>> print_requests.py --dms //api/2.0/bundle --oneline + +=== Destroy clears the tracked resources, so recording can be enabled afterwards +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.jobs.one + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default + +Destroy: 1 deleted + +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/files... +Created jobs.one +Files: 6 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle --oneline +{"method": "POST", "path": "/api/2.0/bundle/deployments", "body": {"display_name": "dms-existing-state-[UNIQUE_NAME]", "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/state", "target_name": "default", "workspace_info": {"file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/files", "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default"}}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions", "q": {"version_id": "1"}, "body": {"cli_version": "[CLI_VERSION]", "version_type": "VERSION_TYPE_DEPLOY", "operations": [{"resource_key": "jobs.one", "action_type": "OPERATION_ACTION_TYPE_CREATE"}]}} +{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.one", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "", "resource_id": "[NUMID]", "sequence_id": "0", "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":1,\"name\":\"one\",\"queue\":{\"enabled\":true}}}", "status": "OPERATION_STATUS_SUCCEEDED"}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", "body": {"completion_reason": "VERSION_COMPLETE_SUCCESS"}} + +=== Recording moves the state to the feature version and records the feature, which is what says its resources are the ones the service holds +>>> jq {state_version, features} .databricks/bundle/default/resources.json +{ + "state_version": 3, + "features": { + "record_deployment_history": {} + } +} + +=== So it is accepted even with the deployment gone. The file's state is a no-op while recording, so the service having nothing means the job is created again under a fresh deployment +>>> MSYS_NO_PATHCONV=1 [CLI] workspace delete /Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/state/resources.deployment.json + +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/files... +Created jobs.one +Files: 2 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle --oneline +{"method": "POST", "path": "/api/2.0/bundle/deployments", "body": {"display_name": "dms-existing-state-[UNIQUE_NAME]", "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/state", "target_name": "default", "workspace_info": {"file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/files", "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default"}}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions", "q": {"version_id": "1"}, "body": {"cli_version": "[CLI_VERSION]", "version_type": "VERSION_TYPE_DEPLOY", "operations": [{"resource_key": "jobs.one", "action_type": "OPERATION_ACTION_TYPE_CREATE"}]}} +{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.one", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "", "resource_id": "[NUMID]", "sequence_id": "0", "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-existing-state-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":1,\"name\":\"one\",\"queue\":{\"enabled\":true}}}", "status": "OPERATION_STATUS_SUCCEEDED"}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", "body": {"completion_reason": "VERSION_COMPLETE_SUCCESS"}} diff --git a/acceptance/bundle/dms/existing-state/script b/acceptance/bundle/dms/existing-state/script new file mode 100644 index 00000000000..b63bed146cc --- /dev/null +++ b/acceptance/bundle/dms/existing-state/script @@ -0,0 +1,30 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy without recording: the bundle gets ordinary direct-engine state, unknown to DMS" +trace $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle --oneline +trace jq '{state_version, features}' .databricks/bundle/default/resources.json + +title "Turning recording on afterwards is an error: those resources were never recorded, so treating DMS as authoritative would deploy them a second time" +musterr trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true $CLI bundle deploy + +title "No deployment was created in DMS" +trace print_requests.py --dms //api/2.0/bundle --oneline + +title "Still an error after wiping the local cache: deploy pulls the state file back from the workspace, so the resources are still tracked" +rm -rf .databricks +musterr trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle --oneline + +title "Destroy clears the tracked resources, so recording can be enabled afterwards" +trace $CLI bundle destroy --auto-approve +trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle --oneline + +title "Recording moves the state to the feature version and records the feature, which is what says its resources are the ones the service holds" +trace jq '{state_version, features}' .databricks/bundle/default/resources.json + +title "So it is accepted even with the deployment gone. The file's state is a no-op while recording, so the service having nothing means the job is created again under a fresh deployment" +trace MSYS_NO_PATHCONV=1 $CLI workspace delete "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-existing-state-${UNIQUE_NAME}/default/state/resources.deployment.json" +trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle --oneline diff --git a/acceptance/bundle/dms/existing-state/test.toml b/acceptance/bundle/dms/existing-state/test.toml new file mode 100644 index 00000000000..bc95f7e86c4 --- /dev/null +++ b/acceptance/bundle/dms/existing-state/test.toml @@ -0,0 +1,3 @@ +# This test deploys without recording first, then turns it on per-command, so it opts out of +# the parent's DMS=true and drives DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY inline instead. +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/dms/failed-delete/databricks.yml.tmpl b/acceptance/bundle/dms/failed-delete/databricks.yml.tmpl new file mode 100644 index 00000000000..abdb86103ff --- /dev/null +++ b/acceptance/bundle/dms/failed-delete/databricks.yml.tmpl @@ -0,0 +1,9 @@ +bundle: + name: dms-failed-delete-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + stuck: + name: stuck diff --git a/acceptance/bundle/dms/failed-delete/out.test.toml b/acceptance/bundle/dms/failed-delete/out.test.toml new file mode 100644 index 00000000000..9921e91a794 --- /dev/null +++ b/acceptance/bundle/dms/failed-delete/out.test.toml @@ -0,0 +1,3 @@ +Cloud = false +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/failed-delete/output.txt b/acceptance/bundle/dms/failed-delete/output.txt new file mode 100644 index 00000000000..46d6d4a9c2e --- /dev/null +++ b/acceptance/bundle/dms/failed-delete/output.txt @@ -0,0 +1,149 @@ + +=== Deploy: the job is recorded +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-failed-delete-[UNIQUE_NAME]/default/files... +Created jobs.stuck +Files: 6 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments", + "body": { + "display_name": "dms-failed-delete-[UNIQUE_NAME]", + "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-failed-delete-[UNIQUE_NAME]/default/state", + "target_name": "default", + "workspace_info": { + "file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-failed-delete-[UNIQUE_NAME]/default/files", + "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-failed-delete-[UNIQUE_NAME]/default" + } + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "1" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "operations": [ + { + "resource_key": "jobs.stuck", + "action_type": "OPERATION_ACTION_TYPE_CREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.stuck", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "[NUMID]", + "sequence_id": "0", + "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-failed-delete-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":1,\"name\":\"stuck\",\"queue\":{\"enabled\":true}}}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} + +=== A resource that fails to delete is recorded as a failed operation carrying the error, so the history says why rather than showing the resource gone +>>> fault.py POST /api/2.2/jobs/delete 400 0 1 INVALID_PARAMETER_VALUE + +>>> musterr [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.jobs.stuck + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-failed-delete-[UNIQUE_NAME]/default + +Error: cannot delete resources.jobs.stuck: deleting id=[NUMID]: Fault injected by test. (400 INVALID_PARAMETER_VALUE) + +Endpoint: POST [DATABRICKS_URL]/api/2.2/jobs/delete +HTTP Status: 400 Bad Request +API error_code: INVALID_PARAMETER_VALUE +API message: Fault injected by test. + + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "2" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DESTROY", + "previous_version_id": "1", + "operations": [ + { + "resource_key": "jobs.stuck", + "action_type": "OPERATION_ACTION_TYPE_DELETE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/operations/jobs.stuck", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "deleting id=[NUMID]: Fault injected by test. (400 INVALID_PARAMETER_VALUE)", + "resource_id": "[NUMID]", + "sequence_id": "0", + "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-failed-delete-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":1,\"name\":\"stuck\",\"queue\":{\"enabled\":true}}}", + "status": "OPERATION_STATUS_FAILED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_FAILURE" + } +} + +>>> print_state.py +{ + "state_version": 3, + "cli_version": "[CLI_VERSION]", + "lineage": "[UUID]", + "serial": 1, + "features": { + "record_deployment_history": {} + }, + "state": { + "resources.jobs.stuck": { + "__id__": "[NUMID]", + "state": { + "deployment": { + "deployment_id": "[NUMID]", + "kind": "BUNDLE", + "metadata_file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-failed-delete-[UNIQUE_NAME]/default/state/metadata.json", + "version_id": "1" + }, + "edit_mode": "UI_LOCKED", + "format": "MULTI_TASK", + "max_concurrent_runs": 1, + "name": "stuck", + "queue": { + "enabled": true + } + } + } + } +} diff --git a/acceptance/bundle/dms/failed-delete/script b/acceptance/bundle/dms/failed-delete/script new file mode 100644 index 00000000000..fff56460c21 --- /dev/null +++ b/acceptance/bundle/dms/failed-delete/script @@ -0,0 +1,16 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy: the job is recorded" +trace $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle + +title "A resource that fails to delete is recorded as a failed operation carrying the error, so the history says why rather than showing the resource gone" +# The state entry survives too, so the next deploy still knows about the resource. +trace fault.py "POST /api/2.2/jobs/delete" 400 0 1 INVALID_PARAMETER_VALUE +trace musterr $CLI bundle destroy --auto-approve +trace print_requests.py --dms //api/2.0/bundle +trace print_state.py + +# print_state.py asks the service for the resources while recording, so drain those reads instead +# of leaving them behind for the harness to diff. +print_requests.py //api/2.0 > /dev/null diff --git a/acceptance/bundle/dms/failed-delete/test.toml b/acceptance/bundle/dms/failed-delete/test.toml new file mode 100644 index 00000000000..1a22ff04ef4 --- /dev/null +++ b/acceptance/bundle/dms/failed-delete/test.toml @@ -0,0 +1,3 @@ +# Local only: this case needs an injected failure - no job delete that the Jobs API refuses - and fault.py registers +# its rule on the fake, which a cloud run does not have. +Cloud = false diff --git a/acceptance/bundle/dms/failed-recreate/databricks.yml.tmpl b/acceptance/bundle/dms/failed-recreate/databricks.yml.tmpl new file mode 100644 index 00000000000..a2937bf9a41 --- /dev/null +++ b/acceptance/bundle/dms/failed-recreate/databricks.yml.tmpl @@ -0,0 +1,11 @@ +bundle: + name: dms-failed-recreate-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + schemas: + foo: + name: dms_failed_recreate_schema_$UNIQUE_NAME + catalog_name: main + comment: v1 diff --git a/acceptance/bundle/dms/failed-recreate/out.requests.txt b/acceptance/bundle/dms/failed-recreate/out.requests.txt new file mode 100644 index 00000000000..eb169f26a0c --- /dev/null +++ b/acceptance/bundle/dms/failed-recreate/out.requests.txt @@ -0,0 +1,7 @@ +{ + "method": "DELETE", + "path": "/api/2.1/unity-catalog/catalogs/dms_other_[UNIQUE_NAME]", + "q": { + "force": "true" + } +} diff --git a/acceptance/bundle/dms/failed-recreate/out.test.toml b/acceptance/bundle/dms/failed-recreate/out.test.toml new file mode 100644 index 00000000000..9921e91a794 --- /dev/null +++ b/acceptance/bundle/dms/failed-recreate/out.test.toml @@ -0,0 +1,3 @@ +Cloud = false +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/failed-recreate/output.txt b/acceptance/bundle/dms/failed-recreate/output.txt new file mode 100644 index 00000000000..a012fec992f --- /dev/null +++ b/acceptance/bundle/dms/failed-recreate/output.txt @@ -0,0 +1,87 @@ + +=== Deploy the schema, so there is a resource to recreate +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-failed-recreate-[UNIQUE_NAME]/default/files... +Created schemas.foo +Files: 6 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +=== A recreate deletes and then fails to create. The delete went through, so the resource really is gone: the operation records no state, rather than describing the resource as it was before the deploy +>>> update_file.py databricks.yml catalog_name: main catalog_name: dms_other_[UNIQUE_NAME] + +>>> fault.py POST /api/2.1/unity-catalog/schemas 400 0 1 INVALID_PARAMETER_VALUE + +>>> musterr [CLI] bundle deploy --auto-approve +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-failed-recreate-[UNIQUE_NAME]/default/files... + +This action will result in the deletion or recreation of the following UC schemas. Any underlying data may be lost: + recreate resources.schemas.foo +Error: cannot recreate resources.schemas.foo: Fault injected by test. (400 INVALID_PARAMETER_VALUE) + +Endpoint: POST [DATABRICKS_URL]/api/2.1/unity-catalog/schemas +HTTP Status: 400 Bad Request +API error_code: INVALID_PARAMETER_VALUE +API message: Fault injected by test. + +Files: 4 uploaded, 0 deleted + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "2" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "previous_version_id": "1", + "operations": [ + { + "resource_key": "schemas.foo", + "action_type": "OPERATION_ACTION_TYPE_RECREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/operations/schemas.foo", + "q": { + "update_mask": "state,error_message,status" + }, + "body": { + "error_message": "", + "sequence_id": "0", + "status": "OPERATION_STATUS_PENDING" + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/operations/schemas.foo", + "q": { + "update_mask": "error_message,status" + }, + "body": { + "error_message": "Fault injected by test. (400 INVALID_PARAMETER_VALUE)", + "sequence_id": "1", + "status": "OPERATION_STATUS_FAILED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_FAILURE" + } +} + +=== The resource is not listed: state is what projects a resource, and the failed recreate left none +>>> MSYS_NO_PATHCONV=1 [CLI] api get /api/2.0/bundle/deployments/[NUMID]/resources +{} + +=== Planning from DMS state alone creates the schema, which is what has to happen: it no longer exists +>>> [CLI] bundle plan +create schemas.foo + +Plan: 1 to add, 0 to change, 0 to delete, 0 unchanged diff --git a/acceptance/bundle/dms/failed-recreate/script b/acceptance/bundle/dms/failed-recreate/script new file mode 100644 index 00000000000..cb00e0a0d8a --- /dev/null +++ b/acceptance/bundle/dms/failed-recreate/script @@ -0,0 +1,32 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy the schema, so there is a resource to recreate" +trace $CLI bundle deploy +rm -f out.requests.txt + +title "A recreate deletes and then fails to create. The delete went through, so the resource really is gone: the operation records no state, rather than describing the resource as it was before the deploy" +# Unity Catalog has no catalog called "other", so make one to move the schema into. +other_catalog="dms_other_${UNIQUE_NAME}" +$CLI catalogs create "$other_catalog" &> LOG.catalog +trap '$CLI catalogs delete "$other_catalog" --force >> LOG.catalog 2>&1' EXIT +trace update_file.py databricks.yml "catalog_name: main" "catalog_name: ${other_catalog}" +# Fail only the create that follows the delete; the delete itself still goes through. +trace fault.py "POST /api/2.1/unity-catalog/schemas" 400 0 1 INVALID_PARAMETER_VALUE +trace musterr $CLI bundle deploy --auto-approve +# Not sorted: the point of this test is the order the operations are recorded in. +trace print_requests.py --dms //api/2.0/bundle + +title "The resource is not listed: state is what projects a resource, and the failed recreate left none" +# The deployment ID is the workspace node's ID; read it back the way the CLI does. +# Extracted with python, not jq: the ID exceeds 2^53 and jq 1.6 rounds it. +deployment_id=$(MSYS_NO_PATHCONV=1 $CLI workspace get-status "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-failed-recreate-${UNIQUE_NAME}/default/state/resources.deployment.json" -o json | python3 -c 'import sys,json; print(json.load(sys.stdin)["object_id"])') +# MSYS_NO_PATHCONV as above: Git Bash on Windows would rewrite the leading-'/' API +# path into C:/Program Files/Git/api/2.0/... before the CLI saw it. +trace MSYS_NO_PATHCONV=1 $CLI api get "/api/2.0/bundle/deployments/${deployment_id}/resources" + +title "Planning from DMS state alone creates the schema, which is what has to happen: it no longer exists" +rm -rf .databricks +trace $CLI bundle plan +# plan probes the state files concurrently, so the recorded order varies. Only the +# operations above are asserted; drop the rest rather than diff a racy order. +rm -f out.requests.txt diff --git a/acceptance/bundle/dms/failed-recreate/test.toml b/acceptance/bundle/dms/failed-recreate/test.toml new file mode 100644 index 00000000000..8a850ba07c5 --- /dev/null +++ b/acceptance/bundle/dms/failed-recreate/test.toml @@ -0,0 +1,5 @@ +# Local only: the failure is injected, and fault.py registers its rule on the fake, which +# a cloud run does not have. Simulating it for real instead - a catalog or principal that +# does not exist - does not work either: the fake accepts both, so the case would stop +# failing locally. Making it portable needs the fake to model that existence. +Cloud = false diff --git a/acceptance/bundle/dms/failed-update-permissions/databricks.yml.tmpl b/acceptance/bundle/dms/failed-update-permissions/databricks.yml.tmpl new file mode 100644 index 00000000000..622598450cd --- /dev/null +++ b/acceptance/bundle/dms/failed-update-permissions/databricks.yml.tmpl @@ -0,0 +1,12 @@ +bundle: + name: dms-failed-update-permissions-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + foo: + name: foo + permissions: + - level: CAN_VIEW + user_name: viewer@example.com diff --git a/acceptance/bundle/dms/failed-update-permissions/out.test.toml b/acceptance/bundle/dms/failed-update-permissions/out.test.toml new file mode 100644 index 00000000000..9921e91a794 --- /dev/null +++ b/acceptance/bundle/dms/failed-update-permissions/out.test.toml @@ -0,0 +1,3 @@ +Cloud = false +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/failed-update-permissions/output.txt b/acceptance/bundle/dms/failed-update-permissions/output.txt new file mode 100644 index 00000000000..080f4b6c8be --- /dev/null +++ b/acceptance/bundle/dms/failed-update-permissions/output.txt @@ -0,0 +1,29 @@ + +=== Deploy the job and its permissions +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-failed-update-permissions-[UNIQUE_NAME]/default/files... +Created jobs.foo +Created jobs.foo.permissions +Files: 6 uploaded, 0 deleted +Resources: 2 created, 0 changed, 0 deleted, 0 unchanged + +=== A permissions update that fails records the failure with the permissions it still has. The resource ID here is a path rather than a number, and the state is the embedded permission list, so this covers a shape the resource tests do not +>>> update_file.py databricks.yml CAN_VIEW CAN_MANAGE + +>>> fault.py PUT /api/2.0/permissions/jobs/* 403 0 1 PERMISSION_DENIED + +>>> musterr [CLI] bundle deploy --auto-approve +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-failed-update-permissions-[UNIQUE_NAME]/default/files... +Error: cannot update resources.jobs.foo.permissions: updating id=/jobs/[NUMID]: Fault injected by test. (403 PERMISSION_DENIED) + +Endpoint: PUT [DATABRICKS_URL]/api/2.0/permissions/jobs/[NUMID] +HTTP Status: 403 Forbidden +API error_code: PERMISSION_DENIED +API message: Fault injected by test. + +Files: 3 uploaded, 0 deleted + +>>> print_requests.py --dms //api/2.0/bundle --oneline +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions", "q": {"version_id": "2"}, "body": {"cli_version": "[CLI_VERSION]", "version_type": "VERSION_TYPE_DEPLOY", "previous_version_id": "1", "operations": [{"resource_key": "jobs.foo.permissions", "action_type": "OPERATION_ACTION_TYPE_UPDATE"}]}} +{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/operations/jobs.foo.permissions", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "updating id=/jobs/[NUMID]: Fault injected by test. (403 PERMISSION_DENIED)", "resource_id": "/jobs/[NUMID]", "sequence_id": "0", "state": "{\"state\":{\"object_id\":\"/jobs/[NUMID]\",\"__embed__\":[{\"level\":\"CAN_VIEW\",\"user_name\":\"viewer@example.com\"},{\"level\":\"IS_OWNER\",\"user_name\":\"[USERNAME]\"}]},\"depends_on\":[{\"node\":\"resources.jobs.foo\",\"label\":\"${resources.jobs.foo.id}\"}]}", "status": "OPERATION_STATUS_FAILED"}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/complete", "body": {"completion_reason": "VERSION_COMPLETE_FAILURE"}} diff --git a/acceptance/bundle/dms/failed-update-permissions/script b/acceptance/bundle/dms/failed-update-permissions/script new file mode 100644 index 00000000000..56141a30f4c --- /dev/null +++ b/acceptance/bundle/dms/failed-update-permissions/script @@ -0,0 +1,12 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy the job and its permissions" +trace $CLI bundle deploy +rm -f out.requests.txt + +title "A permissions update that fails records the failure with the permissions it still has. The resource ID here is a path rather than a number, and the state is the embedded permission list, so this covers a shape the resource tests do not" +trace update_file.py databricks.yml "CAN_VIEW" "CAN_MANAGE" +# A 403 is what the API returns when the caller cannot change a job's owner. +trace fault.py "PUT /api/2.0/permissions/jobs/*" 403 0 1 PERMISSION_DENIED +trace musterr $CLI bundle deploy --auto-approve +trace print_requests.py --dms //api/2.0/bundle --oneline diff --git a/acceptance/bundle/dms/failed-update-permissions/test.toml b/acceptance/bundle/dms/failed-update-permissions/test.toml new file mode 100644 index 00000000000..8a850ba07c5 --- /dev/null +++ b/acceptance/bundle/dms/failed-update-permissions/test.toml @@ -0,0 +1,5 @@ +# Local only: the failure is injected, and fault.py registers its rule on the fake, which +# a cloud run does not have. Simulating it for real instead - a catalog or principal that +# does not exist - does not work either: the fake accepts both, so the case would stop +# failing locally. Making it portable needs the fake to model that existence. +Cloud = false diff --git a/acceptance/bundle/dms/failed-update/databricks.yml.tmpl b/acceptance/bundle/dms/failed-update/databricks.yml.tmpl new file mode 100644 index 00000000000..87cfcff9f36 --- /dev/null +++ b/acceptance/bundle/dms/failed-update/databricks.yml.tmpl @@ -0,0 +1,11 @@ +bundle: + name: dms-failed-update-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + schemas: + foo: + name: dms_failed_update_schema_$UNIQUE_NAME + catalog_name: main + comment: v1 diff --git a/acceptance/bundle/dms/failed-update/out.test.toml b/acceptance/bundle/dms/failed-update/out.test.toml new file mode 100644 index 00000000000..9921e91a794 --- /dev/null +++ b/acceptance/bundle/dms/failed-update/out.test.toml @@ -0,0 +1,3 @@ +Cloud = false +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/failed-update/output.txt b/acceptance/bundle/dms/failed-update/output.txt new file mode 100644 index 00000000000..125c16608b0 --- /dev/null +++ b/acceptance/bundle/dms/failed-update/output.txt @@ -0,0 +1,86 @@ + +=== Deploy the schema, so there is an existing resource to update +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-failed-update-[UNIQUE_NAME]/default/files... +Created schemas.foo +Files: 6 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +=== An update that fails before writing any state only marks its operation failed. It names no state, so the deployment keeps describing the schema the last successful version recorded - which is right, because nothing touched it +>>> update_file.py databricks.yml comment: v1 comment: v2 + +>>> fault.py PATCH /api/2.1/unity-catalog/schemas/* 400 0 1 INVALID_PARAMETER_VALUE + +>>> musterr [CLI] bundle deploy --auto-approve +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-failed-update-[UNIQUE_NAME]/default/files... +Error: cannot update resources.schemas.foo: updating id=main.dms_failed_update_schema_[UNIQUE_NAME]: Fault injected by test. (400 INVALID_PARAMETER_VALUE) + +Endpoint: PATCH [DATABRICKS_URL]/api/2.1/unity-catalog/schemas/main.dms_failed_update_schema_[UNIQUE_NAME] +HTTP Status: 400 Bad Request +API error_code: INVALID_PARAMETER_VALUE +API message: Fault injected by test. + +Files: 3 uploaded, 0 deleted + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "2" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "previous_version_id": "1", + "operations": [ + { + "resource_key": "schemas.foo", + "action_type": "OPERATION_ACTION_TYPE_UPDATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/operations/schemas.foo", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "updating id=main.dms_failed_update_schema_[UNIQUE_NAME]: Fault injected by test. (400 INVALID_PARAMETER_VALUE)", + "resource_id": "main.dms_failed_update_schema_[UNIQUE_NAME]", + "sequence_id": "0", + "state": "{\"state\":{\"catalog_name\":\"main\",\"comment\":\"v1\",\"name\":\"dms_failed_update_schema_[UNIQUE_NAME]\"}}", + "status": "OPERATION_STATUS_FAILED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_FAILURE" + } +} + +=== The schema is still listed as the previous version left it, so the next plan updates it rather than creating a second one +>>> MSYS_NO_PATHCONV=1 [CLI] api get /api/2.0/bundle/deployments/[NUMID]/resources +{ + "resources": [ + { + "last_action_type": "OPERATION_ACTION_TYPE_UPDATE", + "last_version_id": "2", + "name": "deployments/[NUMID]/resources/schemas.foo", + "resource_id": "main.dms_failed_update_schema_[UNIQUE_NAME]", + "resource_key": "schemas.foo", + "resource_type": "", + "state": "{\"state\":{\"catalog_name\":\"main\",\"comment\":\"v1\",\"name\":\"dms_failed_update_schema_[UNIQUE_NAME]\"}}" + } + ] +} + +=== Planning from DMS state alone updates the schema rather than creating a second one, which is what recording the prior state buys +>>> [CLI] bundle plan +update schemas.foo + +Plan: 0 to add, 1 to change, 0 to delete, 0 unchanged diff --git a/acceptance/bundle/dms/failed-update/script b/acceptance/bundle/dms/failed-update/script new file mode 100644 index 00000000000..91640bd7631 --- /dev/null +++ b/acceptance/bundle/dms/failed-update/script @@ -0,0 +1,28 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy the schema, so there is an existing resource to update" +trace $CLI bundle deploy +rm -f out.requests.txt + +title "An update that fails before writing any state only marks its operation failed. It names no state, so the deployment keeps describing the schema the last successful version recorded - which is right, because nothing touched it" +trace update_file.py databricks.yml "comment: v1" "comment: v2" +# Fail the update call itself, so the deploy never writes state for the schema. +trace fault.py "PATCH /api/2.1/unity-catalog/schemas/*" 400 0 1 INVALID_PARAMETER_VALUE +trace musterr $CLI bundle deploy --auto-approve +# Not sorted: the point of this test is the order the operations are recorded in. +trace print_requests.py --dms //api/2.0/bundle + +title "The schema is still listed as the previous version left it, so the next plan updates it rather than creating a second one" +# The deployment ID is the workspace node's ID; read it back the way the CLI does. +# Extracted with python, not jq: the ID exceeds 2^53 and jq 1.6 rounds it. +deployment_id=$(MSYS_NO_PATHCONV=1 $CLI workspace get-status "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-failed-update-${UNIQUE_NAME}/default/state/resources.deployment.json" -o json | python3 -c 'import sys,json; print(json.load(sys.stdin)["object_id"])') +# MSYS_NO_PATHCONV as above: Git Bash on Windows would rewrite the leading-'/' API +# path into C:/Program Files/Git/api/2.0/... before the CLI saw it. +trace MSYS_NO_PATHCONV=1 $CLI api get "/api/2.0/bundle/deployments/${deployment_id}/resources" + +title "Planning from DMS state alone updates the schema rather than creating a second one, which is what recording the prior state buys" +rm -rf .databricks +trace $CLI bundle plan +# plan probes the state files concurrently, so the recorded order varies. Only the +# operations above are asserted; drop the rest rather than diff a racy order. +rm -f out.requests.txt diff --git a/acceptance/bundle/dms/failed-update/test.toml b/acceptance/bundle/dms/failed-update/test.toml new file mode 100644 index 00000000000..2b4eeb1bb04 --- /dev/null +++ b/acceptance/bundle/dms/failed-update/test.toml @@ -0,0 +1,3 @@ +# Local only: this case needs an injected failure - no schema update that Unity Catalog rejects outright - and fault.py registers +# its rule on the fake, which a cloud run does not have. +Cloud = false diff --git a/acceptance/bundle/dms/multiple-resources/databricks.yml.tmpl b/acceptance/bundle/dms/multiple-resources/databricks.yml.tmpl new file mode 100644 index 00000000000..faa6ef5e63c --- /dev/null +++ b/acceptance/bundle/dms/multiple-resources/databricks.yml.tmpl @@ -0,0 +1,17 @@ +bundle: + name: dms-multiple-resources-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + one: + name: one + two: + name: two + three: + name: three + four: + name: four + five: + name: five diff --git a/acceptance/bundle/dms/multiple-resources/out.test.toml b/acceptance/bundle/dms/multiple-resources/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/multiple-resources/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/multiple-resources/output.txt b/acceptance/bundle/dms/multiple-resources/output.txt new file mode 100644 index 00000000000..ecc2092225a --- /dev/null +++ b/acceptance/bundle/dms/multiple-resources/output.txt @@ -0,0 +1,28 @@ + +=== Deploy several resources: operations are uploaded from background workers, so exactly one is recorded per resource no matter what order the uploads finish in. The serialized state is dropped from the output here; bundle/dms/record covers it. +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-multiple-resources-[UNIQUE_NAME]/default/files... +Created jobs.five +Created jobs.four +Created jobs.one +Created jobs.three +Created jobs.two +Files: 5 uploaded, 0 deleted +Resources: 5 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //versions/1/operations --sort --del-body state --oneline +{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.five", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "", "resource_id": "[NUMID]", "sequence_id": "0", "status": "OPERATION_STATUS_SUCCEEDED"}} +{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.four", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "", "resource_id": "[NUMID]", "sequence_id": "0", "status": "OPERATION_STATUS_SUCCEEDED"}} +{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.one", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "", "resource_id": "[NUMID]", "sequence_id": "0", "status": "OPERATION_STATUS_SUCCEEDED"}} +{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.three", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "", "resource_id": "[NUMID]", "sequence_id": "0", "status": "OPERATION_STATUS_SUCCEEDED"}} +{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.two", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "", "resource_id": "[NUMID]", "sequence_id": "0", "status": "OPERATION_STATUS_SUCCEEDED"}} + +=== Redeploy with no changes: nothing is applied, so no operations are recorded and only the version is opened and completed +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-multiple-resources-[UNIQUE_NAME]/default/files... +Files: 2 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 5 unchanged + +>>> print_requests.py --dms //api/2.0/bundle --sort --oneline +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions", "q": {"version_id": "2"}, "body": {"cli_version": "[CLI_VERSION]", "version_type": "VERSION_TYPE_DEPLOY", "previous_version_id": "1"}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/complete", "body": {"completion_reason": "VERSION_COMPLETE_SUCCESS"}} diff --git a/acceptance/bundle/dms/multiple-resources/script b/acceptance/bundle/dms/multiple-resources/script new file mode 100644 index 00000000000..584423a4d5e --- /dev/null +++ b/acceptance/bundle/dms/multiple-resources/script @@ -0,0 +1,9 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy several resources: operations are uploaded from background workers, so exactly one is recorded per resource no matter what order the uploads finish in. The serialized state is dropped from the output here; bundle/dms/record covers it." +trace $CLI bundle deploy +trace print_requests.py --dms //versions/1/operations --sort --del-body state --oneline + +title "Redeploy with no changes: nothing is applied, so no operations are recorded and only the version is opened and completed" +trace $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle --sort --oneline diff --git a/acceptance/bundle/dms/no-drift/databricks.yml.tmpl b/acceptance/bundle/dms/no-drift/databricks.yml.tmpl new file mode 100644 index 00000000000..e9892fa79a5 --- /dev/null +++ b/acceptance/bundle/dms/no-drift/databricks.yml.tmpl @@ -0,0 +1,20 @@ +bundle: + name: dms-no-drift-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + foo: + name: foo + pipelines: + bar: + # Unique: the Pipelines API refuses a duplicate name, so two overlapping runs on the + # same workspace would collide. Jobs allow duplicates, which is why foo above does not. + name: bar-$UNIQUE_NAME + catalog: main + schema: default + serverless: true + libraries: + - file: + path: ./transform.py diff --git a/acceptance/bundle/dms/no-drift/out.test.toml b/acceptance/bundle/dms/no-drift/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/no-drift/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/no-drift/output.txt b/acceptance/bundle/dms/no-drift/output.txt new file mode 100644 index 00000000000..e15952f27ae --- /dev/null +++ b/acceptance/bundle/dms/no-drift/output.txt @@ -0,0 +1,63 @@ + +=== Deploy, then plan without touching anything: the deployment stamp must not show as drift +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-no-drift-[UNIQUE_NAME]/default/files... +Created jobs.foo +Created pipelines.bar +Files: 6 uploaded, 0 deleted +Resources: 2 created, 0 changed, 0 deleted, 0 unchanged + +>>> [CLI] bundle plan +Plan: 0 to add, 0 to change, 0 to delete, 2 unchanged + +=== A second deploy is a no-op too: no update request for either resource +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-no-drift-[UNIQUE_NAME]/default/files... +Files: 2 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 2 unchanged + +>>> print_requests.py --dms //api/2.2/jobs //api/2.0/pipelines --sort +{ + "method": "POST", + "path": "/api/2.0/pipelines", + "body": { + "catalog": "main", + "channel": "CURRENT", + "deployment": { + "deployment_id": "[NUMID]", + "kind": "BUNDLE", + "metadata_file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-no-drift-[UNIQUE_NAME]/default/state/metadata.json", + "version_id": "1" + }, + "edition": "ADVANCED", + "libraries": [ + { + "file": { + "path": "/Workspace/Users/[USERNAME]/.bundle/dms-no-drift-[UNIQUE_NAME]/default/files/transform.py" + } + } + ], + "name": "bar-[UNIQUE_NAME]", + "schema": "default", + "serverless": true + } +} +{ + "method": "POST", + "path": "/api/2.2/jobs/create", + "body": { + "deployment": { + "deployment_id": "[NUMID]", + "kind": "BUNDLE", + "metadata_file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-no-drift-[UNIQUE_NAME]/default/state/metadata.json", + "version_id": "1" + }, + "edit_mode": "UI_LOCKED", + "format": "MULTI_TASK", + "max_concurrent_runs": 1, + "name": "foo", + "queue": { + "enabled": true + } + } +} diff --git a/acceptance/bundle/dms/no-drift/script b/acceptance/bundle/dms/no-drift/script new file mode 100644 index 00000000000..ffe3976b227 --- /dev/null +++ b/acceptance/bundle/dms/no-drift/script @@ -0,0 +1,12 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy, then plan without touching anything: the deployment stamp must not show as drift" +trace $CLI bundle deploy + +# Only deploy stamps deployment.deployment_id. Plan sees it in state but not in config, +# so it must ignore it or report spurious changes. +trace $CLI bundle plan | contains.py "Plan: 0 to add, 0 to change, 0 to delete, 2 unchanged" + +title "A second deploy is a no-op too: no update request for either resource" +trace $CLI bundle deploy +trace print_requests.py --dms //api/2.2/jobs //api/2.0/pipelines --sort diff --git a/acceptance/bundle/dms/no-drift/transform.py b/acceptance/bundle/dms/no-drift/transform.py new file mode 100644 index 00000000000..c07007592a6 --- /dev/null +++ b/acceptance/bundle/dms/no-drift/transform.py @@ -0,0 +1 @@ +# Minimal source so the pipeline has a library, which the API requires. diff --git a/acceptance/bundle/dms/no-resources/databricks.yml.tmpl b/acceptance/bundle/dms/no-resources/databricks.yml.tmpl new file mode 100644 index 00000000000..973189b1603 --- /dev/null +++ b/acceptance/bundle/dms/no-resources/databricks.yml.tmpl @@ -0,0 +1,4 @@ +bundle: + name: dms-no-resources-$UNIQUE_NAME +experimental: + record_deployment_history: true diff --git a/acceptance/bundle/dms/no-resources/out.test.toml b/acceptance/bundle/dms/no-resources/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/no-resources/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/no-resources/output.txt b/acceptance/bundle/dms/no-resources/output.txt new file mode 100644 index 00000000000..a4f993a04e5 --- /dev/null +++ b/acceptance/bundle/dms/no-resources/output.txt @@ -0,0 +1,80 @@ + +=== First deploy of a bundle with no resources: the deployment is created, and its workspace node identifies it even though no resource state was written +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-no-resources-[UNIQUE_NAME]/default/files... +Files: 5 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle --get +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments", + "body": { + "display_name": "dms-no-resources-[UNIQUE_NAME]", + "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-no-resources-[UNIQUE_NAME]/default/state", + "target_name": "default", + "workspace_info": { + "file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-no-resources-[UNIQUE_NAME]/default/files", + "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-no-resources-[UNIQUE_NAME]/default" + } + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "1" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} + +>>> MSYS_NO_PATHCONV=1 [CLI] workspace get-status /Workspace/Users/[USERNAME]/.bundle/dms-no-resources-[UNIQUE_NAME]/default/state/resources.deployment.json +{ + "object_type": "BUNDLE_DEPLOYMENT", + "path": "/Workspace/Users/[USERNAME]/.bundle/dms-no-resources-[UNIQUE_NAME]/default/state/resources.deployment.json" +} + +=== Redeploy: the deployment is resolved from that node, so no second deployment is created +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-no-resources-[UNIQUE_NAME]/default/files... +Files: 2 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle --get +{ + "method": "GET", + "path": "/api/2.0/bundle/deployments/[NUMID]" +} +{ + "method": "GET", + "path": "/api/2.0/bundle/deployments/[NUMID]/resources" +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "2" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "previous_version_id": "1" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} diff --git a/acceptance/bundle/dms/no-resources/script b/acceptance/bundle/dms/no-resources/script new file mode 100644 index 00000000000..13924f3664f --- /dev/null +++ b/acceptance/bundle/dms/no-resources/script @@ -0,0 +1,10 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "First deploy of a bundle with no resources: the deployment is created, and its workspace node identifies it even though no resource state was written" +trace $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle --get +trace MSYS_NO_PATHCONV=1 $CLI workspace get-status "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-no-resources-${UNIQUE_NAME}/default/state/resources.deployment.json" | jq '{object_type,path}' + +title "Redeploy: the deployment is resolved from that node, so no second deployment is created" +trace $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle --get diff --git a/acceptance/bundle/dms/not-supported/databricks.yml.tmpl b/acceptance/bundle/dms/not-supported/databricks.yml.tmpl new file mode 100644 index 00000000000..9e9352c8506 --- /dev/null +++ b/acceptance/bundle/dms/not-supported/databricks.yml.tmpl @@ -0,0 +1,9 @@ +bundle: + name: dms-not-supported-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + one: + name: one diff --git a/acceptance/bundle/dms/not-supported/out.test.toml b/acceptance/bundle/dms/not-supported/out.test.toml new file mode 100644 index 00000000000..d73c45e3119 --- /dev/null +++ b/acceptance/bundle/dms/not-supported/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/dms/not-supported/output.txt b/acceptance/bundle/dms/not-supported/output.txt new file mode 100644 index 00000000000..59b6ebcf2b1 --- /dev/null +++ b/acceptance/bundle/dms/not-supported/output.txt @@ -0,0 +1,24 @@ + +=== record_deployment_history is rejected: the service side is not ready for users yet +>>> musterr [CLI] bundle validate +Error: experimental.record_deployment_history is not supported yet; remove this setting from your bundle configuration + at experimental.record_deployment_history + in databricks.yml:4:30 + +Name: dms-not-supported-[UNIQUE_NAME] +Target: default +Workspace: + User: [USERNAME] + Path: /Workspace/Users/[USERNAME]/.bundle/dms-not-supported-[UNIQUE_NAME]/default + +Found 1 error + +=== The hidden recording variable permits it +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true [CLI] bundle validate +Name: dms-not-supported-[UNIQUE_NAME] +Target: default +Workspace: + User: [USERNAME] + Path: /Workspace/Users/[USERNAME]/.bundle/dms-not-supported-[UNIQUE_NAME]/default + +Validation OK! diff --git a/acceptance/bundle/dms/not-supported/script b/acceptance/bundle/dms/not-supported/script new file mode 100644 index 00000000000..06a237d3445 --- /dev/null +++ b/acceptance/bundle/dms/not-supported/script @@ -0,0 +1,7 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "record_deployment_history is rejected: the service side is not ready for users yet" +trace musterr $CLI bundle validate + +title "The hidden recording variable permits it" +trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true $CLI bundle validate diff --git a/acceptance/bundle/dms/not-supported/test.toml b/acceptance/bundle/dms/not-supported/test.toml new file mode 100644 index 00000000000..d1c3f78a3ea --- /dev/null +++ b/acceptance/bundle/dms/not-supported/test.toml @@ -0,0 +1,8 @@ +# Unset the force-allow variable inherited from the parent: this test asserts the +# error users see. +# The parent records via DMS=true, which would permit the field; unset it so the rejection +# path is what runs here. +EnvMatrix.DMS = [""] + +# This test only checks validation output; no DMS request is made either way. +RecordRequests = false diff --git a/acceptance/bundle/dms/operation-upload-fails-once/databricks.yml.tmpl b/acceptance/bundle/dms/operation-upload-fails-once/databricks.yml.tmpl new file mode 100644 index 00000000000..c46cfb03d73 --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-fails-once/databricks.yml.tmpl @@ -0,0 +1,11 @@ +bundle: + name: dms-upload-fails-once-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + schemas: + foo: + name: dms_upload_fails_once_schema_$UNIQUE_NAME + catalog_name: main + comment: v1 diff --git a/acceptance/bundle/dms/operation-upload-fails-once/out.requests.txt b/acceptance/bundle/dms/operation-upload-fails-once/out.requests.txt new file mode 100644 index 00000000000..eb169f26a0c --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-fails-once/out.requests.txt @@ -0,0 +1,7 @@ +{ + "method": "DELETE", + "path": "/api/2.1/unity-catalog/catalogs/dms_other_[UNIQUE_NAME]", + "q": { + "force": "true" + } +} diff --git a/acceptance/bundle/dms/operation-upload-fails-once/out.test.toml b/acceptance/bundle/dms/operation-upload-fails-once/out.test.toml new file mode 100644 index 00000000000..9921e91a794 --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-fails-once/out.test.toml @@ -0,0 +1,3 @@ +Cloud = false +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/operation-upload-fails-once/output.txt b/acceptance/bundle/dms/operation-upload-fails-once/output.txt new file mode 100644 index 00000000000..abdeedeb959 --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-fails-once/output.txt @@ -0,0 +1,79 @@ + +=== Deploy so there is a recorded resource to recreate +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-upload-fails-once-[UNIQUE_NAME]/default/files... +Created schemas.foo +Files: 6 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +=== A recreate records twice, and the first one fails: the second must still carry the sequence id staging left, because a rejected update earned no new one +>>> fault.py PATCH /api/2.0/bundle/* 500 0 1 + +>>> update_file.py databricks.yml catalog_name: main catalog_name: dms_other_[UNIQUE_NAME] + +>>> musterr [CLI] bundle deploy --auto-approve +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-upload-fails-once-[UNIQUE_NAME]/default/files... + +This action will result in the deletion or recreation of the following UC schemas. Any underlying data may be lost: + recreate resources.schemas.foo +Error: recording operation for resources.schemas.foo: Fault injected by test. (500 INJECTED) + +Endpoint: PATCH [DATABRICKS_URL]/api/2.0/bundle/deployments/[NUMID]/versions/2/operations/schemas.foo?update_mask=state%2Cerror_message%2Cstatus +HTTP Status: 500 Internal Server Error +API error_code: INJECTED +API message: Fault injected by test. + +Files: 4 uploaded, 0 deleted + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "2" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "previous_version_id": "1", + "operations": [ + { + "resource_key": "schemas.foo", + "action_type": "OPERATION_ACTION_TYPE_RECREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/operations/schemas.foo", + "q": { + "update_mask": "state,error_message,status" + }, + "body": { + "error_message": "", + "sequence_id": "0", + "status": "OPERATION_STATUS_PENDING" + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/operations/schemas.foo", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "dms_other_[UNIQUE_NAME].dms_upload_fails_once_schema_[UNIQUE_NAME]", + "sequence_id": "0", + "state": "{\"state\":{\"catalog_name\":\"dms_other_[UNIQUE_NAME]\",\"comment\":\"v1\",\"name\":\"dms_upload_fails_once_schema_[UNIQUE_NAME]\"}}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_FAILURE" + } +} diff --git a/acceptance/bundle/dms/operation-upload-fails-once/script b/acceptance/bundle/dms/operation-upload-fails-once/script new file mode 100644 index 00000000000..5b609b1b8ee --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-fails-once/script @@ -0,0 +1,15 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy so there is a recorded resource to recreate" +trace $CLI bundle deploy +rm -f out.requests.txt + +title "A recreate records twice, and the first one fails: the second must still carry the sequence id staging left, because a rejected update earned no new one" +trace fault.py "PATCH /api/2.0/bundle/*" 500 0 1 +# Unity Catalog has no catalog called "other", so make one to move the schema into. +other_catalog="dms_other_${UNIQUE_NAME}" +$CLI catalogs create "$other_catalog" &> LOG.catalog +trap '$CLI catalogs delete "$other_catalog" --force >> LOG.catalog 2>&1' EXIT +trace update_file.py databricks.yml "catalog_name: main" "catalog_name: ${other_catalog}" +trace musterr $CLI bundle deploy --auto-approve +trace print_requests.py --dms //api/2.0/bundle diff --git a/acceptance/bundle/dms/operation-upload-fails-once/test.toml b/acceptance/bundle/dms/operation-upload-fails-once/test.toml new file mode 100644 index 00000000000..5baa9c9d923 --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-fails-once/test.toml @@ -0,0 +1,3 @@ +# Local only: this case needs an injected failure - DMS itself must reject the operation upload, once - and fault.py registers +# its rule on the fake, which a cloud run does not have. +Cloud = false diff --git a/acceptance/bundle/dms/operation-upload-fails/databricks.yml.tmpl b/acceptance/bundle/dms/operation-upload-fails/databricks.yml.tmpl new file mode 100644 index 00000000000..b6aa93265df --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-fails/databricks.yml.tmpl @@ -0,0 +1,23 @@ +bundle: + name: dms-operation-upload-fails-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + one: + name: one + two: + name: two + three: + name: three + four: + name: four + five: + name: five + six: + name: six + seven: + name: seven + eight: + name: eight diff --git a/acceptance/bundle/dms/operation-upload-fails/out.test.toml b/acceptance/bundle/dms/operation-upload-fails/out.test.toml new file mode 100644 index 00000000000..9921e91a794 --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-fails/out.test.toml @@ -0,0 +1,3 @@ +Cloud = false +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/operation-upload-fails/output.txt b/acceptance/bundle/dms/operation-upload-fails/output.txt new file mode 100644 index 00000000000..2b273972417 --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-fails/output.txt @@ -0,0 +1,4 @@ + +=== An operation upload failure fails the deploy instead of reporting only at the end +>>> grep -c ^Error: LOG.deploy +deploy reported errors diff --git a/acceptance/bundle/dms/operation-upload-fails/script b/acceptance/bundle/dms/operation-upload-fails/script new file mode 100644 index 00000000000..cc2ead92c6f --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-fails/script @@ -0,0 +1,9 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "An operation upload failure fails the deploy instead of reporting only at the end" +# Which resources get refused depends on how far apply got before a background +# upload failed, so the per-resource errors go to a LOG file rather than the diff. +fault.py "PATCH /api/2.0/bundle/*" 500 0 99 INTERNAL_ERROR +errcode $CLI bundle deploy &> LOG.deploy +contains.py 'recording operation for' '!panic' < LOG.deploy > /dev/null +trace grep -c "^Error:" LOG.deploy > /dev/null && echo "deploy reported errors" diff --git a/acceptance/bundle/dms/operation-upload-fails/test.toml b/acceptance/bundle/dms/operation-upload-fails/test.toml new file mode 100644 index 00000000000..b5502a2516c --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-fails/test.toml @@ -0,0 +1,10 @@ +# Local only: this case needs an injected failure - DMS itself must reject the operation upload - and fault.py registers +# its rule on the fake, which a cloud run does not have. +Cloud = false + +# Which requests are made depends on how far apply got before a background upload +# failed, so recording them would make the output nondeterministic. +RecordRequests = false + +# Completed versions make DMS the source of truth; unrecorded resources get recreated. +# Deploy must stop rather than continue creating. diff --git a/acceptance/bundle/dms/operation-upload-message/databricks.yml.tmpl b/acceptance/bundle/dms/operation-upload-message/databricks.yml.tmpl new file mode 100644 index 00000000000..bc5b4ec97ad --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-message/databricks.yml.tmpl @@ -0,0 +1,9 @@ +bundle: + name: dms-operation-upload-message-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + foo: + name: foo diff --git a/acceptance/bundle/dms/operation-upload-message/out.test.toml b/acceptance/bundle/dms/operation-upload-message/out.test.toml new file mode 100644 index 00000000000..9921e91a794 --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-message/out.test.toml @@ -0,0 +1,3 @@ +Cloud = false +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/operation-upload-message/output.txt b/acceptance/bundle/dms/operation-upload-message/output.txt new file mode 100644 index 00000000000..0791010b1f1 --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-message/output.txt @@ -0,0 +1,16 @@ + +=== What a user sees when an operation cannot be recorded +>>> fault.py PATCH /api/2.0/bundle/* 500 0 1 INTERNAL_ERROR + +>>> errcode [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-operation-upload-message-[UNIQUE_NAME]/default/files... +Error: recording operation for resources.jobs.foo: Fault injected by test. (500 INTERNAL_ERROR) + +Endpoint: PATCH [DATABRICKS_URL]/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.foo?update_mask=state%2Cerror_message%2Cresource_id%2Cstatus +HTTP Status: 500 Internal Server Error +API error_code: INTERNAL_ERROR +API message: Fault injected by test. + +Files: 5 uploaded, 0 deleted + +Exit code: 1 diff --git a/acceptance/bundle/dms/operation-upload-message/script b/acceptance/bundle/dms/operation-upload-message/script new file mode 100644 index 00000000000..c6b796e4149 --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-message/script @@ -0,0 +1,5 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "What a user sees when an operation cannot be recorded" +trace fault.py "PATCH /api/2.0/bundle/*" 500 0 1 INTERNAL_ERROR +trace errcode $CLI bundle deploy diff --git a/acceptance/bundle/dms/operation-upload-message/test.toml b/acceptance/bundle/dms/operation-upload-message/test.toml new file mode 100644 index 00000000000..1dbd55da1f0 --- /dev/null +++ b/acceptance/bundle/dms/operation-upload-message/test.toml @@ -0,0 +1,8 @@ +# Local only: this case needs an injected failure - DMS itself must reject the operation upload - and fault.py registers +# its rule on the fake, which a cloud run does not have. +Cloud = false + +# One resource, so which operation is refused is fixed and the error a user sees can be +# asserted. operation-upload-fails covers a deploy of several resources, where which ones +# were reached before the failure landed is not. +RecordRequests = false diff --git a/acceptance/bundle/dms/provenance/databricks.yml.tmpl b/acceptance/bundle/dms/provenance/databricks.yml.tmpl new file mode 100644 index 00000000000..0a3fa1656ae --- /dev/null +++ b/acceptance/bundle/dms/provenance/databricks.yml.tmpl @@ -0,0 +1,14 @@ +bundle: + name: dms-provenance-$UNIQUE_NAME +experimental: + record_deployment_history: true + +targets: + dev: + default: true + mode: development + +resources: + jobs: + foo: + name: foo diff --git a/acceptance/bundle/dms/provenance/out.test.toml b/acceptance/bundle/dms/provenance/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/provenance/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/provenance/output.txt b/acceptance/bundle/dms/provenance/output.txt new file mode 100644 index 00000000000..2142dabb700 --- /dev/null +++ b/acceptance/bundle/dms/provenance/output.txt @@ -0,0 +1,68 @@ + +=== Deploying from a git repo records where the source came from: the version carries git_info, workspace_info and the target's deployment_mode +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-provenance-[UNIQUE_NAME]/dev/files... +Created jobs.foo +Files: 6 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //versions +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "1" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "git_info": { + "branch": "main", + "commit": "[COMMIT]", + "origin_url": "https://github.com/databricks/bundle-examples.git" + }, + "operations": [ + { + "resource_key": "jobs.foo", + "action_type": "OPERATION_ACTION_TYPE_CREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.foo", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "[NUMID]", + "sequence_id": "0", + "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-provenance-[UNIQUE_NAME]/dev/state/metadata.json\",\"version_id\":\"1\"},\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":4,\"name\":\"[dev [USERNAME]] foo\",\"queue\":{\"enabled\":true},\"tags\":{\"dev\":\"[USERNAME]\"}}}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} + +=== The service denormalizes them onto the deployment, so a reader gets the provenance of the latest version +>>> MSYS_NO_PATHCONV=1 [CLI] api get /api/2.0/bundle/deployments/[NUMID] +{ + "target_name": "dev", + "deployment_mode": "DEPLOYMENT_MODE_DEVELOPMENT", + "git_info": { + "branch": "main", + "commit": "[COMMIT]", + "origin_url": "https://github.com/databricks/bundle-examples.git" + }, + "workspace_info": { + "file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-provenance-[UNIQUE_NAME]/dev/files", + "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-provenance-[UNIQUE_NAME]/dev" + } +} diff --git a/acceptance/bundle/dms/provenance/script b/acceptance/bundle/dms/provenance/script new file mode 100644 index 00000000000..8b15822fa4b --- /dev/null +++ b/acceptance/bundle/dms/provenance/script @@ -0,0 +1,19 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploying from a git repo records where the source came from: the version carries git_info, workspace_info and the target's deployment_mode" +git-repo-init +git remote add origin https://github.com/databricks/bundle-examples.git +trace $CLI bundle deploy +# The commit SHA changes every run, so assert it is a 40-char hex string and drop it. +add_repl.py "$(git rev-parse HEAD)" COMMIT +trace print_requests.py --dms //versions + +title "The service denormalizes them onto the deployment, so a reader gets the provenance of the latest version" +deployment_id=$(MSYS_NO_PATHCONV=1 $CLI workspace get-status "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-provenance-${UNIQUE_NAME}/dev/state/resources.deployment.json" -o json | python3 -c 'import sys,json; print(json.load(sys.stdin)["object_id"])') +# MSYS_NO_PATHCONV as above: Git Bash on Windows would rewrite the leading-'/' API +# path into C:/Program Files/Git/api/2.0/... before the CLI saw it. +trace MSYS_NO_PATHCONV=1 $CLI api get "/api/2.0/bundle/deployments/${deployment_id}" | jq '{target_name, deployment_mode, git_info, workspace_info}' + +# The deploy uploads files in a nondeterministic order; only the requests above are +# asserted. +rm -f out.requests.txt diff --git a/acceptance/bundle/dms/provenance/test.toml b/acceptance/bundle/dms/provenance/test.toml new file mode 100644 index 00000000000..0a47bfb1b91 --- /dev/null +++ b/acceptance/bundle/dms/provenance/test.toml @@ -0,0 +1,4 @@ +# git-repo-init creates a repo in the test directory so the deploy has git provenance. +Ignore = [ + '.git', +] diff --git a/acceptance/bundle/dms/readplan/databricks.yml.tmpl b/acceptance/bundle/dms/readplan/databricks.yml.tmpl new file mode 100644 index 00000000000..d11621ab1e5 --- /dev/null +++ b/acceptance/bundle/dms/readplan/databricks.yml.tmpl @@ -0,0 +1,19 @@ +bundle: + name: dms-readplan-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + foo: + name: foo + pipelines: + bar: + # Unique: the Pipelines API refuses a duplicate name across overlapping runs. + name: bar-$UNIQUE_NAME + catalog: main + schema: default + serverless: true + libraries: + - file: + path: ./transform.py diff --git a/acceptance/bundle/dms/readplan/out.test.toml b/acceptance/bundle/dms/readplan/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/readplan/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/readplan/output.txt b/acceptance/bundle/dms/readplan/output.txt new file mode 100644 index 00000000000..371855dbcc0 --- /dev/null +++ b/acceptance/bundle/dms/readplan/output.txt @@ -0,0 +1,22 @@ + +=== Save a plan, then deploy from it: the deploy stamps the id and version onto the job and pipeline the plan predates +>>> [CLI] bundle plan -o json + +>>> [CLI] bundle deploy --plan tmp.plan.json +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-readplan-[UNIQUE_NAME]/default/files... +Created jobs.foo +Created pipelines.bar +Files: 7 uploaded, 0 deleted +Resources: 2 created, 0 changed, 0 deleted, 0 unchanged + +=== Re-plan: no drift, the deployed job and pipeline carry the deployment stamp +>>> [CLI] bundle plan +Plan: 0 to add, 0 to change, 0 to delete, 2 unchanged + +=== Both recorded operations carry deployment_id and version_id (lineage), not just kind +>>> print_requests.py --dms //api/2.0/bundle --sort --oneline +{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.foo", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "", "resource_id": "[NUMID]", "sequence_id": "0", "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-readplan-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":1,\"name\":\"foo\",\"queue\":{\"enabled\":true}}}", "status": "OPERATION_STATUS_SUCCEEDED"}} +{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/pipelines.bar", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "", "resource_id": "[UUID]", "sequence_id": "0", "state": "{\"state\":{\"catalog\":\"main\",\"channel\":\"CURRENT\",\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-readplan-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"edition\":\"ADVANCED\",\"libraries\":[{\"file\":{\"path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-readplan-[UNIQUE_NAME]/default/files/transform.py\"}}],\"name\":\"bar-[UNIQUE_NAME]\",\"schema\":\"default\",\"serverless\":true}}", "status": "OPERATION_STATUS_SUCCEEDED"}} +{"method": "POST", "path": "/api/2.0/bundle/deployments", "body": {"display_name": "dms-readplan-[UNIQUE_NAME]", "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-readplan-[UNIQUE_NAME]/default/state", "target_name": "default", "workspace_info": {"file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-readplan-[UNIQUE_NAME]/default/files", "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-readplan-[UNIQUE_NAME]/default"}}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions", "q": {"version_id": "1"}, "body": {"cli_version": "[CLI_VERSION]", "version_type": "VERSION_TYPE_DEPLOY", "operations": [{"resource_key": "jobs.foo", "action_type": "OPERATION_ACTION_TYPE_CREATE"}, {"resource_key": "pipelines.bar", "action_type": "OPERATION_ACTION_TYPE_CREATE"}]}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", "body": {"completion_reason": "VERSION_COMPLETE_SUCCESS"}} diff --git a/acceptance/bundle/dms/readplan/script b/acceptance/bundle/dms/readplan/script new file mode 100644 index 00000000000..40bd110bf00 --- /dev/null +++ b/acceptance/bundle/dms/readplan/script @@ -0,0 +1,13 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Save a plan, then deploy from it: the deploy stamps the id and version onto the job and pipeline the plan predates" +trace $CLI bundle plan -o json > tmp.plan.json +trace $CLI bundle deploy --plan tmp.plan.json + +title "Re-plan: no drift, the deployed job and pipeline carry the deployment stamp" +trace $CLI bundle plan + +title "Both recorded operations carry deployment_id and version_id (lineage), not just kind" +trace print_requests.py --dms //api/2.0/bundle --sort --oneline | contains.py deployment_id version_id + +rm -f tmp.plan.json diff --git a/acceptance/bundle/dms/readplan/transform.py b/acceptance/bundle/dms/readplan/transform.py new file mode 100644 index 00000000000..c07007592a6 --- /dev/null +++ b/acceptance/bundle/dms/readplan/transform.py @@ -0,0 +1 @@ +# Minimal source so the pipeline has a library, which the API requires. diff --git a/acceptance/bundle/dms/record-failure/databricks.yml.tmpl b/acceptance/bundle/dms/record-failure/databricks.yml.tmpl new file mode 100644 index 00000000000..87f0eb4d1a9 --- /dev/null +++ b/acceptance/bundle/dms/record-failure/databricks.yml.tmpl @@ -0,0 +1,9 @@ +bundle: + name: dms-record-failure-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + doomed: + name: doomed diff --git a/acceptance/bundle/dms/record-failure/out.test.toml b/acceptance/bundle/dms/record-failure/out.test.toml new file mode 100644 index 00000000000..9921e91a794 --- /dev/null +++ b/acceptance/bundle/dms/record-failure/out.test.toml @@ -0,0 +1,3 @@ +Cloud = false +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/record-failure/output.txt b/acceptance/bundle/dms/record-failure/output.txt new file mode 100644 index 00000000000..479acca7a84 --- /dev/null +++ b/acceptance/bundle/dms/record-failure/output.txt @@ -0,0 +1,75 @@ + +=== A resource that fails to apply is recorded as a failed operation carrying the error, so the deployment history says why rather than omitting the resource +>>> fault.py POST /api/2.2/jobs/create 400 0 1 INVALID_PARAMETER_VALUE + +>>> musterr [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-record-failure-[UNIQUE_NAME]/default/files... +Error: cannot create resources.jobs.doomed: Fault injected by test. (400 INVALID_PARAMETER_VALUE) + +Endpoint: POST [DATABRICKS_URL]/api/2.2/jobs/create +HTTP Status: 400 Bad Request +API error_code: INVALID_PARAMETER_VALUE +API message: Fault injected by test. + +Files: 6 uploaded, 0 deleted + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments", + "body": { + "display_name": "dms-record-failure-[UNIQUE_NAME]", + "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-record-failure-[UNIQUE_NAME]/default/state", + "target_name": "default", + "workspace_info": { + "file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-record-failure-[UNIQUE_NAME]/default/files", + "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-record-failure-[UNIQUE_NAME]/default" + } + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "1" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "operations": [ + { + "resource_key": "jobs.doomed", + "action_type": "OPERATION_ACTION_TYPE_CREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.doomed", + "q": { + "update_mask": "error_message,status" + }, + "body": { + "error_message": "Fault injected by test. (400 INVALID_PARAMETER_VALUE)", + "sequence_id": "0", + "status": "OPERATION_STATUS_FAILED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_FAILURE" + } +} + +=== The failed resource is not listed at all: state is what projects a resource, and a failed create records none, so a later deploy plans to create it rather than treating it as already deployed +>>> MSYS_NO_PATHCONV=1 [CLI] api get /api/2.0/bundle/deployments/[NUMID]/resources +{} + +=== Redeploying from DMS state alone still creates the failed resource: it was never applied, so it must not be skipped as unchanged +>>> [CLI] bundle plan +create jobs.doomed + +Plan: 1 to add, 0 to change, 0 to delete, 0 unchanged diff --git a/acceptance/bundle/dms/record-failure/script b/acceptance/bundle/dms/record-failure/script new file mode 100644 index 00000000000..bc0947a1d91 --- /dev/null +++ b/acceptance/bundle/dms/record-failure/script @@ -0,0 +1,21 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "A resource that fails to apply is recorded as a failed operation carrying the error, so the deployment history says why rather than omitting the resource" +trace fault.py "POST /api/2.2/jobs/create" 400 0 1 INVALID_PARAMETER_VALUE +trace musterr $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle + +title "The failed resource is not listed at all: state is what projects a resource, and a failed create records none, so a later deploy plans to create it rather than treating it as already deployed" +# The deployment ID is the workspace node's ID; read it back the way the CLI does. +# Extracted with python, not jq: the ID exceeds 2^53 and jq 1.6 rounds it. +deployment_id=$(MSYS_NO_PATHCONV=1 $CLI workspace get-status "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-record-failure-${UNIQUE_NAME}/default/state/resources.deployment.json" -o json | python3 -c 'import sys,json; print(json.load(sys.stdin)["object_id"])') +# MSYS_NO_PATHCONV as above: Git Bash on Windows would rewrite the leading-'/' API +# path into C:/Program Files/Git/api/2.0/... before the CLI saw it. +trace MSYS_NO_PATHCONV=1 $CLI api get "/api/2.0/bundle/deployments/${deployment_id}/resources" + +title "Redeploying from DMS state alone still creates the failed resource: it was never applied, so it must not be skipped as unchanged" +rm -rf .databricks +trace $CLI bundle plan +# plan probes the state files concurrently, so the recorded order varies. Only the +# operations above are asserted; drop the rest rather than diff a racy order. +rm -f out.requests.txt diff --git a/acceptance/bundle/dms/record-failure/test.toml b/acceptance/bundle/dms/record-failure/test.toml new file mode 100644 index 00000000000..8a850ba07c5 --- /dev/null +++ b/acceptance/bundle/dms/record-failure/test.toml @@ -0,0 +1,5 @@ +# Local only: the failure is injected, and fault.py registers its rule on the fake, which +# a cloud run does not have. Simulating it for real instead - a catalog or principal that +# does not exist - does not work either: the fake accepts both, so the case would stop +# failing locally. Making it portable needs the fake to model that existence. +Cloud = false diff --git a/acceptance/bundle/dms/record/databricks.yml.tmpl b/acceptance/bundle/dms/record/databricks.yml.tmpl new file mode 100644 index 00000000000..214793eca38 --- /dev/null +++ b/acceptance/bundle/dms/record/databricks.yml.tmpl @@ -0,0 +1,9 @@ +bundle: + name: dms-record-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + foo: + name: foo diff --git a/acceptance/bundle/dms/record/out.test.toml b/acceptance/bundle/dms/record/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/record/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/record/output.txt b/acceptance/bundle/dms/record/output.txt new file mode 100644 index 00000000000..beb068424a4 --- /dev/null +++ b/acceptance/bundle/dms/record/output.txt @@ -0,0 +1,254 @@ + +=== Deploy: the server assigns the deployment ID, and a version + create operation are recorded +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/files... +Created jobs.foo +Files: 5 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --get --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments", + "body": { + "display_name": "dms-record-[UNIQUE_NAME]", + "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/state", + "target_name": "default", + "workspace_info": { + "file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/files", + "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default" + } + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "1" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "operations": [ + { + "resource_key": "jobs.foo", + "action_type": "OPERATION_ACTION_TYPE_CREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.foo", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "[NUMID]", + "sequence_id": "0", + "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":1,\"name\":\"foo\",\"queue\":{\"enabled\":true}}}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} + +=== The deployment ID is the ID of the workspace node the service registered under initial_parent_path; the CLI stores nothing locally +>>> MSYS_NO_PATHCONV=1 [CLI] workspace get-status /Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/state/resources.deployment.json +{ + "object_type": "BUNDLE_DEPLOYMENT", + "path": "/Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/state/resources.deployment.json" +} + +>>> jq has("deployment_id") .databricks/bundle/default/resources.json +false + +=== The state file holds no resources at all - the service does. All it carries is the feature, which a CLI that does not know it refuses rather than deploying over the deployment +>>> jq {state_version, features, resources: (.state | keys)} .databricks/bundle/default/resources.json +{ + "state_version": 3, + "features": { + "record_deployment_history": {} + }, + "resources": [] +} + +=== The same header-only state is uploaded to the workspace: that upload is where a redeploy from a clean cache reads the feature back from +>>> MSYS_NO_PATHCONV=1 [CLI] workspace export /Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/state/resources.json +{ + "state_version": 3, + "features": { + "record_deployment_history": {} + }, + "resources": [] +} + +=== Redeploy after deleting the local cache: the deployment ID is resolved from that node, the same deployment is reused, and the version increments (no new CreateDeployment) +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/files... +Files: 5 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 1 unchanged + +>>> print_requests.py --get --dms //api/2.0/bundle +{ + "method": "GET", + "path": "/api/2.0/bundle/deployments/[NUMID]" +} +{ + "method": "GET", + "path": "/api/2.0/bundle/deployments/[NUMID]/resources" +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "2" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "previous_version_id": "1" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} + +=== Destroy: a destroy version and delete operation are recorded, then the deployment is deleted +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.jobs.foo + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default + +Destroy: 1 deleted + +>>> print_requests.py --get --dms //api/2.0/bundle +{ + "method": "GET", + "path": "/api/2.0/bundle/deployments/[NUMID]" +} +{ + "method": "GET", + "path": "/api/2.0/bundle/deployments/[NUMID]/resources" +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "3" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DESTROY", + "previous_version_id": "2", + "operations": [ + { + "resource_key": "jobs.foo", + "action_type": "OPERATION_ACTION_TYPE_DELETE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/3/operations/jobs.foo", + "q": { + "update_mask": "state,error_message,status" + }, + "body": { + "error_message": "", + "sequence_id": "0", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/3/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} +{ + "method": "DELETE", + "path": "/api/2.0/bundle/deployments/[NUMID]" +} + +=== Deploy again: the destroy took the node with it, so there is nothing to resolve and a fresh deployment starts at version 1 +>>> MSYS_NO_PATHCONV=1 musterr [CLI] workspace get-status /Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/state/resources.deployment.json +Error: Path (/Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/state/resources.deployment.json) doesn't exist. + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/files... +Created jobs.foo +Files: 5 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> MSYS_NO_PATHCONV=1 [CLI] workspace get-status /Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/state/resources.deployment.json +{ + "object_type": "BUNDLE_DEPLOYMENT", + "path": "/Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/state/resources.deployment.json" +} + +>>> print_requests.py --get --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments", + "body": { + "display_name": "dms-record-[UNIQUE_NAME]", + "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/state", + "target_name": "default", + "workspace_info": { + "file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/files", + "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default" + } + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "1" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "operations": [ + { + "resource_key": "jobs.foo", + "action_type": "OPERATION_ACTION_TYPE_CREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.foo", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "[NUMID]", + "sequence_id": "0", + "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-record-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":1,\"name\":\"foo\",\"queue\":{\"enabled\":true}}}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} diff --git a/acceptance/bundle/dms/record/script b/acceptance/bundle/dms/record/script new file mode 100644 index 00000000000..970edaabf9f --- /dev/null +++ b/acceptance/bundle/dms/record/script @@ -0,0 +1,34 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +# --get so the reads show up too: this file is the whole DMS call budget, so an extra +# round-trip added to any phase turns up as a diff here. +title "Deploy: the server assigns the deployment ID, and a version + create operation are recorded" +trace $CLI bundle deploy +trace print_requests.py --get --dms //api/2.0/bundle + +title "The deployment ID is the ID of the workspace node the service registered under initial_parent_path; the CLI stores nothing locally" +# MSYS_NO_PATHCONV prevents Git Bash from rewriting the leading-/ path on Windows. +# Set per command rather than test.toml so trace can export it to its subshell. +trace MSYS_NO_PATHCONV=1 $CLI workspace get-status "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-record-${UNIQUE_NAME}/default/state/resources.deployment.json" | jq '{object_type,path}' +trace jq 'has("deployment_id")' .databricks/bundle/default/resources.json + +title "The state file holds no resources at all - the service does. All it carries is the feature, which a CLI that does not know it refuses rather than deploying over the deployment" +trace jq '{state_version, features, resources: (.state | keys)}' .databricks/bundle/default/resources.json + +title "The same header-only state is uploaded to the workspace: that upload is where a redeploy from a clean cache reads the feature back from" +trace MSYS_NO_PATHCONV=1 $CLI workspace export "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-record-${UNIQUE_NAME}/default/state/resources.json" | jq '{state_version, features, resources: (.state | keys)}' + +title "Redeploy after deleting the local cache: the deployment ID is resolved from that node, the same deployment is reused, and the version increments (no new CreateDeployment)" +rm -rf .databricks +trace $CLI bundle deploy +trace print_requests.py --get --dms //api/2.0/bundle + +title "Destroy: a destroy version and delete operation are recorded, then the deployment is deleted" +trace $CLI bundle destroy --auto-approve +trace print_requests.py --get --dms //api/2.0/bundle + +title "Deploy again: the destroy took the node with it, so there is nothing to resolve and a fresh deployment starts at version 1" +trace MSYS_NO_PATHCONV=1 musterr $CLI workspace get-status "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-record-${UNIQUE_NAME}/default/state/resources.deployment.json" +trace $CLI bundle deploy +trace MSYS_NO_PATHCONV=1 $CLI workspace get-status "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-record-${UNIQUE_NAME}/default/state/resources.deployment.json" | jq '{object_type,path}' +trace print_requests.py --get --dms //api/2.0/bundle diff --git a/acceptance/bundle/dms/requires-recording/databricks.yml.tmpl b/acceptance/bundle/dms/requires-recording/databricks.yml.tmpl new file mode 100644 index 00000000000..ae8d964d03a --- /dev/null +++ b/acceptance/bundle/dms/requires-recording/databricks.yml.tmpl @@ -0,0 +1,9 @@ +bundle: + name: dms-requires-recording-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + one: + name: one diff --git a/acceptance/bundle/dms/requires-recording/out.test.toml b/acceptance/bundle/dms/requires-recording/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/requires-recording/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/requires-recording/output.txt b/acceptance/bundle/dms/requires-recording/output.txt new file mode 100644 index 00000000000..a432a70137b --- /dev/null +++ b/acceptance/bundle/dms/requires-recording/output.txt @@ -0,0 +1,98 @@ + +=== Deploy with recording on: the state records the feature +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-requires-recording-[UNIQUE_NAME]/default/files... +Created jobs.one +Files: 5 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> jq .features .databricks/bundle/default/resources.json +{ + "record_deployment_history": {} +} + +=== Turning recording off is refused: the service holds this deployment, so deploying without recording would leave it describing resources that have moved on +>>> update_file.py databricks.yml record_deployment_history: true record_deployment_history: false + +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= [CLI] bundle deploy +Error: unsetting experimental.record_deployment_history is not supported + +This deployment's resources are recorded with the deployment metadata service. Set experimental.record_deployment_history: true to deploy or destroy this bundle + + +=== Destroy is refused for the same reason, which is why the error says to put the setting back +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= [CLI] bundle destroy --auto-approve +Error: unsetting experimental.record_deployment_history is not supported + +This deployment's resources are recorded with the deployment metadata service. Set experimental.record_deployment_history: true to deploy or destroy this bundle + + +=== With recording back on, deploy and destroy work again +>>> update_file.py databricks.yml record_deployment_history: false record_deployment_history: true + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-requires-recording-[UNIQUE_NAME]/default/files... +Files: 2 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 1 unchanged + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.jobs.one + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-requires-recording-[UNIQUE_NAME]/default + +Destroy: 1 deleted + +=== Destroy leaves the state file behind, but drops the marker: nothing is recorded any more, so it has nothing left to protect +>>> jq {state_version, features, resources: (.state | keys)} .databricks/bundle/default/resources.json +{ + "state_version": 3, + "features": null, + "resources": [] +} + +=== So recording can be turned off afterwards, rather than the destroyed bundle being stuck with it forever +>>> update_file.py databricks.yml record_deployment_history: true record_deployment_history: false + +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-requires-recording-[UNIQUE_NAME]/default/files... +Created jobs.one +Files: 5 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.jobs.one + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-requires-recording-[UNIQUE_NAME]/default + +Destroy: 1 deleted + +=== bind and unbind are refused on a recorded state even with the setting dropped: their writes would be discarded +>>> update_file.py databricks.yml record_deployment_history: false record_deployment_history: true + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-requires-recording-[UNIQUE_NAME]/default/files... +Created jobs.one +Files: 5 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> update_file.py databricks.yml record_deployment_history: true record_deployment_history: false + +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= [CLI] bundle deployment unbind one +Error: unbind is not supported for a bundle that records deployment history + + +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= [CLI] bundle deployment bind one [ONE_ID] --auto-approve +Error: bind is not supported for a bundle that records deployment history + + +>>> update_file.py databricks.yml record_deployment_history: false record_deployment_history: true + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.jobs.one + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-requires-recording-[UNIQUE_NAME]/default + +Destroy: 1 deleted diff --git a/acceptance/bundle/dms/requires-recording/script b/acceptance/bundle/dms/requires-recording/script new file mode 100644 index 00000000000..bca90e750d6 --- /dev/null +++ b/acceptance/bundle/dms/requires-recording/script @@ -0,0 +1,35 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy with recording on: the state records the feature" +trace $CLI bundle deploy +trace jq '.features' .databricks/bundle/default/resources.json + +title "Turning recording off is refused: the service holds this deployment, so deploying without recording would leave it describing resources that have moved on" +trace update_file.py databricks.yml "record_deployment_history: true" "record_deployment_history: false" +musterr trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= $CLI bundle deploy + +title "Destroy is refused for the same reason, which is why the error says to put the setting back" +musterr trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= $CLI bundle destroy --auto-approve + +title "With recording back on, deploy and destroy work again" +trace update_file.py databricks.yml "record_deployment_history: false" "record_deployment_history: true" +trace $CLI bundle deploy +trace $CLI bundle destroy --auto-approve + +title "Destroy leaves the state file behind, but drops the marker: nothing is recorded any more, so it has nothing left to protect" +trace jq '{state_version, features, resources: (.state | keys)}' .databricks/bundle/default/resources.json + +title "So recording can be turned off afterwards, rather than the destroyed bundle being stuck with it forever" +trace update_file.py databricks.yml "record_deployment_history: true" "record_deployment_history: false" +trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= $CLI bundle deploy +trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= $CLI bundle destroy --auto-approve + +title "bind and unbind are refused on a recorded state even with the setting dropped: their writes would be discarded" +trace update_file.py databricks.yml "record_deployment_history: false" "record_deployment_history: true" +trace $CLI bundle deploy +job_id=$(read_id.py one) +trace update_file.py databricks.yml "record_deployment_history: true" "record_deployment_history: false" +musterr trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= $CLI bundle deployment unbind one +musterr trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY= $CLI bundle deployment bind one "$job_id" --auto-approve +trace update_file.py databricks.yml "record_deployment_history: false" "record_deployment_history: true" +trace $CLI bundle destroy --auto-approve diff --git a/acceptance/bundle/dms/requires-recording/test.toml b/acceptance/bundle/dms/requires-recording/test.toml new file mode 100644 index 00000000000..cb125e34d6b --- /dev/null +++ b/acceptance/bundle/dms/requires-recording/test.toml @@ -0,0 +1,3 @@ +# This test asserts the CLI's own output, not the calls behind it; bundle/dms/record is where +# the call budget is pinned. +RecordRequests = false diff --git a/acceptance/bundle/dms/resource-lifecycle/databricks.yml.tmpl b/acceptance/bundle/dms/resource-lifecycle/databricks.yml.tmpl new file mode 100644 index 00000000000..808d75dc3be --- /dev/null +++ b/acceptance/bundle/dms/resource-lifecycle/databricks.yml.tmpl @@ -0,0 +1,11 @@ +bundle: + name: dms-resource-lifecycle-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + schemas: + foo: + name: dms_resource_lifecycle_schema_$UNIQUE_NAME + catalog_name: main + comment: v1 diff --git a/acceptance/bundle/dms/resource-lifecycle/out.requests.txt b/acceptance/bundle/dms/resource-lifecycle/out.requests.txt new file mode 100644 index 00000000000..eb169f26a0c --- /dev/null +++ b/acceptance/bundle/dms/resource-lifecycle/out.requests.txt @@ -0,0 +1,7 @@ +{ + "method": "DELETE", + "path": "/api/2.1/unity-catalog/catalogs/dms_other_[UNIQUE_NAME]", + "q": { + "force": "true" + } +} diff --git a/acceptance/bundle/dms/resource-lifecycle/out.test.toml b/acceptance/bundle/dms/resource-lifecycle/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/resource-lifecycle/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/resource-lifecycle/output.txt b/acceptance/bundle/dms/resource-lifecycle/output.txt new file mode 100644 index 00000000000..475995d9c71 --- /dev/null +++ b/acceptance/bundle/dms/resource-lifecycle/output.txt @@ -0,0 +1,180 @@ + +=== Deploy: the state write records the resource +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-resource-lifecycle-[UNIQUE_NAME]/default/files... +Created schemas.foo +Files: 5 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments", + "body": { + "display_name": "dms-resource-lifecycle-[UNIQUE_NAME]", + "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-resource-lifecycle-[UNIQUE_NAME]/default/state", + "target_name": "default", + "workspace_info": { + "file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-resource-lifecycle-[UNIQUE_NAME]/default/files", + "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-resource-lifecycle-[UNIQUE_NAME]/default" + } + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "1" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "operations": [ + { + "resource_key": "schemas.foo", + "action_type": "OPERATION_ACTION_TYPE_CREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/schemas.foo", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "main.dms_resource_lifecycle_schema_[UNIQUE_NAME]", + "sequence_id": "0", + "state": "{\"state\":{\"catalog_name\":\"main\",\"comment\":\"v1\",\"name\":\"dms_resource_lifecycle_schema_[UNIQUE_NAME]\"}}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} + +=== Recreate writes state twice - the entry is dropped, then the new resource is saved +>>> update_file.py databricks.yml catalog_name: main catalog_name: dms_other_[UNIQUE_NAME] + +>>> [CLI] bundle deploy --auto-approve +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-resource-lifecycle-[UNIQUE_NAME]/default/files... + +This action will result in the deletion or recreation of the following UC schemas. Any underlying data may be lost: + recreate resources.schemas.foo +Recreated schemas.foo +Files: 4 uploaded, 0 deleted +Resources: 1 created, 0 changed, 1 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "2" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DEPLOY", + "previous_version_id": "1", + "operations": [ + { + "resource_key": "schemas.foo", + "action_type": "OPERATION_ACTION_TYPE_RECREATE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/operations/schemas.foo", + "q": { + "update_mask": "state,error_message,status" + }, + "body": { + "error_message": "", + "sequence_id": "0", + "status": "OPERATION_STATUS_PENDING" + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/operations/schemas.foo", + "q": { + "update_mask": "state,error_message,resource_id,status" + }, + "body": { + "error_message": "", + "resource_id": "dms_other_[UNIQUE_NAME].dms_resource_lifecycle_schema_[UNIQUE_NAME]", + "sequence_id": "1", + "state": "{\"state\":{\"catalog_name\":\"dms_other_[UNIQUE_NAME]\",\"comment\":\"v1\",\"name\":\"dms_resource_lifecycle_schema_[UNIQUE_NAME]\"}}", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/2/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} + +=== Destroy: the delete is recorded with the id and no state +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.schemas.foo + +This action will result in the deletion of the following UC schemas. Any underlying data may be lost: + delete resources.schemas.foo + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-resource-lifecycle-[UNIQUE_NAME]/default + +Destroy: 1 deleted + +>>> print_requests.py --dms //api/2.0/bundle +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions", + "q": { + "version_id": "3" + }, + "body": { + "cli_version": "[CLI_VERSION]", + "version_type": "VERSION_TYPE_DESTROY", + "previous_version_id": "2", + "operations": [ + { + "resource_key": "schemas.foo", + "action_type": "OPERATION_ACTION_TYPE_DELETE" + } + ] + } +} +{ + "method": "PATCH", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/3/operations/schemas.foo", + "q": { + "update_mask": "state,error_message,status" + }, + "body": { + "error_message": "", + "sequence_id": "0", + "status": "OPERATION_STATUS_SUCCEEDED" + } +} +{ + "method": "POST", + "path": "/api/2.0/bundle/deployments/[NUMID]/versions/3/complete", + "body": { + "completion_reason": "VERSION_COMPLETE_SUCCESS" + } +} +{ + "method": "DELETE", + "path": "/api/2.0/bundle/deployments/[NUMID]" +} diff --git a/acceptance/bundle/dms/resource-lifecycle/script b/acceptance/bundle/dms/resource-lifecycle/script new file mode 100644 index 00000000000..43050cc7c8f --- /dev/null +++ b/acceptance/bundle/dms/resource-lifecycle/script @@ -0,0 +1,20 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Deploy: the state write records the resource" +trace $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle + +title "Recreate writes state twice - the entry is dropped, then the new resource is saved" +# One operation per resource per version; both writes land on the same one. +# The drop opens it IN_PROGRESS, the save patches it to SUCCEEDED. +# Unity Catalog has no catalog called "other", so make one to move the schema into. +other_catalog="dms_other_${UNIQUE_NAME}" +$CLI catalogs create "$other_catalog" &> LOG.catalog +trap '$CLI catalogs delete "$other_catalog" --force >> LOG.catalog 2>&1' EXIT +trace update_file.py databricks.yml "catalog_name: main" "catalog_name: ${other_catalog}" +trace $CLI bundle deploy --auto-approve +trace print_requests.py --dms //api/2.0/bundle + +title "Destroy: the delete is recorded with the id and no state" +trace $CLI bundle destroy --auto-approve +trace print_requests.py --dms //api/2.0/bundle diff --git a/acceptance/bundle/dms/stale-deployment/empty.yml.tmpl b/acceptance/bundle/dms/stale-deployment/empty.yml.tmpl new file mode 100644 index 00000000000..4998e0e4b9c --- /dev/null +++ b/acceptance/bundle/dms/stale-deployment/empty.yml.tmpl @@ -0,0 +1,2 @@ +bundle: + name: dms-stale-deployment-$UNIQUE_NAME diff --git a/acceptance/bundle/dms/stale-deployment/out.test.toml b/acceptance/bundle/dms/stale-deployment/out.test.toml new file mode 100644 index 00000000000..d73c45e3119 --- /dev/null +++ b/acceptance/bundle/dms/stale-deployment/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/dms/stale-deployment/output.txt b/acceptance/bundle/dms/stale-deployment/output.txt new file mode 100644 index 00000000000..ba9ba06ac1f --- /dev/null +++ b/acceptance/bundle/dms/stale-deployment/output.txt @@ -0,0 +1,61 @@ + +=== Record a bundle that has no resources yet. The deployment is registered before anything is planned, so it exists even though nothing was deployed and no state file was written +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-stale-deployment-[UNIQUE_NAME]/default/files... +Files: 7 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_requests.py --dms //api/2.0/bundle --oneline +{"method": "POST", "path": "/api/2.0/bundle/deployments", "body": {"display_name": "dms-stale-deployment-[UNIQUE_NAME]", "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-stale-deployment-[UNIQUE_NAME]/default/state", "target_name": "default", "workspace_info": {"file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-stale-deployment-[UNIQUE_NAME]/default/files", "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-stale-deployment-[UNIQUE_NAME]/default"}}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions", "q": {"version_id": "1"}, "body": {"cli_version": "[CLI_VERSION]", "version_type": "VERSION_TYPE_DEPLOY"}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", "body": {"completion_reason": "VERSION_COMPLETE_SUCCESS"}} + +>>> find.py resources.json --expect 0 + +=== Add a job and deploy with recording off. The job is tracked in an ordinary state file the service knows nothing about, while the deployment from the first step is still there +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-stale-deployment-[UNIQUE_NAME]/default/files... +Created jobs.one +Files: 3 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> jq {state_version, features, resources: (.state | keys)} .databricks/bundle/default/resources.json +{ + "state_version": 2, + "features": null, + "resources": [ + "resources.jobs.one" + ] +} + +=== Turning recording back on is refused. The deployment does resolve, but this state was never recorded, so letting the service be authoritative would create the job a second time +>>> DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true [CLI] bundle deploy +Error: cannot record deployment history for a bundle that already has deployed resources tracked in [TEST_TMP_DIR]/.databricks/bundle/default/resources.json: only new deployments can be recorded + +To record this bundle's history, start it over as a new deployment: + 1. remove experimental.record_deployment_history from your bundle configuration + 2. run "databricks bundle destroy" to delete the existing resources + 3. add experimental.record_deployment_history back and deploy again + +To keep the existing resources instead, unset experimental.record_deployment_history + + +=== The job is still tracked by the state file, and nothing was recorded against the stale deployment +>>> jq {state_version, features, resources: (.state | keys)} .databricks/bundle/default/resources.json +{ + "state_version": 2, + "features": null, + "resources": [ + "resources.jobs.one" + ] +} + +>>> print_requests.py --dms //api/2.0/bundle --oneline + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.jobs.one + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-stale-deployment-[UNIQUE_NAME]/default + +Destroy: 1 deleted diff --git a/acceptance/bundle/dms/stale-deployment/script b/acceptance/bundle/dms/stale-deployment/script new file mode 100755 index 00000000000..7ba6b19ddb4 --- /dev/null +++ b/acceptance/bundle/dms/stale-deployment/script @@ -0,0 +1,24 @@ +envsubst < empty.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +title "Record a bundle that has no resources yet. The deployment is registered before anything is planned, so it exists even though nothing was deployed and no state file was written" +trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle --oneline +trace find.py 'resources.json' --expect 0 + +title "Add a job and deploy with recording off. The job is tracked in an ordinary state file the service knows nothing about, while the deployment from the first step is still there" +envsubst < with-job.yml.tmpl > databricks.yml +trace $CLI bundle deploy +trace jq '{state_version, features, resources: (.state | keys)}' .databricks/bundle/default/resources.json + +title "Turning recording back on is refused. The deployment does resolve, but this state was never recorded, so letting the service be authoritative would create the job a second time" +musterr trace DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY=true $CLI bundle deploy + +title "The job is still tracked by the state file, and nothing was recorded against the stale deployment" +trace jq '{state_version, features, resources: (.state | keys)}' .databricks/bundle/default/resources.json +trace print_requests.py --dms //api/2.0/bundle --oneline diff --git a/acceptance/bundle/dms/stale-deployment/test.toml b/acceptance/bundle/dms/stale-deployment/test.toml new file mode 100644 index 00000000000..3227096ed19 --- /dev/null +++ b/acceptance/bundle/dms/stale-deployment/test.toml @@ -0,0 +1,3 @@ +# This test turns recording on and off per command, so it opts out of the parent's DMS=true +# and drives DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY inline instead. +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/dms/stale-deployment/with-job.yml.tmpl b/acceptance/bundle/dms/stale-deployment/with-job.yml.tmpl new file mode 100644 index 00000000000..d06d9594561 --- /dev/null +++ b/acceptance/bundle/dms/stale-deployment/with-job.yml.tmpl @@ -0,0 +1,7 @@ +bundle: + name: dms-stale-deployment-$UNIQUE_NAME + +resources: + jobs: + one: + name: one diff --git a/acceptance/bundle/dms/stale-plan/databricks.yml.tmpl b/acceptance/bundle/dms/stale-plan/databricks.yml.tmpl new file mode 100644 index 00000000000..dea8fbd9a8d --- /dev/null +++ b/acceptance/bundle/dms/stale-plan/databricks.yml.tmpl @@ -0,0 +1,9 @@ +bundle: + name: dms-stale-plan-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + foo: + name: foo diff --git a/acceptance/bundle/dms/stale-plan/out.test.toml b/acceptance/bundle/dms/stale-plan/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/stale-plan/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/stale-plan/output.txt b/acceptance/bundle/dms/stale-plan/output.txt new file mode 100644 index 00000000000..2ce3b598d1c --- /dev/null +++ b/acceptance/bundle/dms/stale-plan/output.txt @@ -0,0 +1,21 @@ + +=== Save a plan, then deploy it: records version 1 +>>> [CLI] bundle plan -o json + +>>> [CLI] bundle deploy --plan tmp.plan.json +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-stale-plan-[UNIQUE_NAME]/default/files... +Created jobs.foo +Files: 6 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +=== Replay: re-deploying the same plan is rejected - it predates the recorded version +>>> musterr [CLI] bundle deploy --plan tmp.plan.json +Error: this plan predates the deployment's current version 1; run 'bundle plan' again + + +=== Only the first deploy recorded a version; the rejected replay created none +>>> print_requests.py --dms //api/2.0/bundle --oneline +{"method": "POST", "path": "/api/2.0/bundle/deployments", "body": {"display_name": "dms-stale-plan-[UNIQUE_NAME]", "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-stale-plan-[UNIQUE_NAME]/default/state", "target_name": "default", "workspace_info": {"file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-stale-plan-[UNIQUE_NAME]/default/files", "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-stale-plan-[UNIQUE_NAME]/default"}}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions", "q": {"version_id": "1"}, "body": {"cli_version": "[CLI_VERSION]", "version_type": "VERSION_TYPE_DEPLOY", "operations": [{"resource_key": "jobs.foo", "action_type": "OPERATION_ACTION_TYPE_CREATE"}]}} +{"method": "PATCH", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/operations/jobs.foo", "q": {"update_mask": "state,error_message,resource_id,status"}, "body": {"error_message": "", "resource_id": "[NUMID]", "sequence_id": "0", "state": "{\"state\":{\"deployment\":{\"deployment_id\":\"[NUMID]\",\"kind\":\"BUNDLE\",\"metadata_file_path\":\"/Workspace/Users/[USERNAME]/.bundle/dms-stale-plan-[UNIQUE_NAME]/default/state/metadata.json\",\"version_id\":\"1\"},\"edit_mode\":\"UI_LOCKED\",\"format\":\"MULTI_TASK\",\"max_concurrent_runs\":1,\"name\":\"foo\",\"queue\":{\"enabled\":true}}}", "status": "OPERATION_STATUS_SUCCEEDED"}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions/1/complete", "body": {"completion_reason": "VERSION_COMPLETE_SUCCESS"}} diff --git a/acceptance/bundle/dms/stale-plan/script b/acceptance/bundle/dms/stale-plan/script new file mode 100644 index 00000000000..1f9e792f30f --- /dev/null +++ b/acceptance/bundle/dms/stale-plan/script @@ -0,0 +1,13 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Save a plan, then deploy it: records version 1" +trace $CLI bundle plan -o json > tmp.plan.json +trace $CLI bundle deploy --plan tmp.plan.json + +title "Replay: re-deploying the same plan is rejected - it predates the recorded version" +trace musterr $CLI bundle deploy --plan tmp.plan.json + +title "Only the first deploy recorded a version; the rejected replay created none" +trace print_requests.py --dms //api/2.0/bundle --oneline + +rm -f tmp.plan.json diff --git a/acceptance/bundle/dms/state-from-service/databricks.yml.tmpl b/acceptance/bundle/dms/state-from-service/databricks.yml.tmpl new file mode 100644 index 00000000000..7f526744d53 --- /dev/null +++ b/acceptance/bundle/dms/state-from-service/databricks.yml.tmpl @@ -0,0 +1,26 @@ +bundle: + name: dms-state-from-service-$UNIQUE_NAME + +experimental: + record_deployment_history: true + +resources: + jobs: + # source is stamped with the deployment (jobs and pipelines are), and dependent references + # its id, so the pair covers a dependency edge surviving the round trip through the service. + source: + name: source + tags: + source_id: placeholder + dependent: + name: dependent + tags: + upstream: ${resources.jobs.source.id} + + # A secret scope carries no deployment stamp, so it is the case where nothing about the resource + # changes between deploys: after a cache wipe it can only come back as unchanged if the service + # is really the state. + secret_scopes: + scope: + name: scope-$UNIQUE_NAME + backend_type: DATABRICKS diff --git a/acceptance/bundle/dms/state-from-service/out.test.toml b/acceptance/bundle/dms/state-from-service/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/state-from-service/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/state-from-service/output.txt b/acceptance/bundle/dms/state-from-service/output.txt new file mode 100644 index 00000000000..c207b025371 --- /dev/null +++ b/acceptance/bundle/dms/state-from-service/output.txt @@ -0,0 +1,232 @@ + +=== Deploy: the service records all three resources, including the dependency edge +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-state-from-service-[UNIQUE_NAME]/default/files... +Created jobs.dependent +Created jobs.source +Created secret_scopes.scope +Created secret_scopes.scope.permissions +Files: 5 uploaded, 0 deleted +Resources: 4 created, 0 changed, 0 deleted, 0 unchanged + +>>> print_state.py +{ + "state_version": 3, + "cli_version": "[CLI_VERSION]", + "lineage": "[UUID]", + "serial": 1, + "features": { + "record_deployment_history": {} + }, + "state": { + "resources.jobs.dependent": { + "__id__": "[NUMID]", + "state": { + "deployment": { + "deployment_id": "[NUMID]", + "kind": "BUNDLE", + "metadata_file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-state-from-service-[UNIQUE_NAME]/default/state/metadata.json", + "version_id": "1" + }, + "edit_mode": "UI_LOCKED", + "format": "MULTI_TASK", + "max_concurrent_runs": 1, + "name": "dependent", + "queue": { + "enabled": true + }, + "tags": { + "upstream": "[NUMID]" + } + }, + "depends_on": [ + { + "node": "resources.jobs.source", + "label": "${resources.jobs.source.id}" + } + ] + }, + "resources.jobs.source": { + "__id__": "[NUMID]", + "state": { + "deployment": { + "deployment_id": "[NUMID]", + "kind": "BUNDLE", + "metadata_file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-state-from-service-[UNIQUE_NAME]/default/state/metadata.json", + "version_id": "1" + }, + "edit_mode": "UI_LOCKED", + "format": "MULTI_TASK", + "max_concurrent_runs": 1, + "name": "source", + "queue": { + "enabled": true + }, + "tags": { + "source_id": "placeholder" + } + } + }, + "resources.secret_scopes.scope": { + "__id__": "scope-[UNIQUE_NAME]", + "state": { + "scope": "scope-[UNIQUE_NAME]", + "scope_backend_type": "DATABRICKS" + } + }, + "resources.secret_scopes.scope.permissions": { + "__id__": "scope-[UNIQUE_NAME]", + "state": { + "scope_name": "scope-[UNIQUE_NAME]", + "acls": [ + { + "permission": "MANAGE", + "principal": "[USERNAME]" + } + ] + }, + "depends_on": [ + { + "node": "resources.secret_scopes.scope", + "label": "${resources.secret_scopes.scope.name}" + } + ] + } + } +} + +=== Throw away every local trace of the deployment. The state file the deploy left is only a header, so anything the next deploy knows has to come from the service +>>> MSYS_NO_PATHCONV=1 [CLI] workspace export /Workspace/Users/[USERNAME]/.bundle/dms-state-from-service-[UNIQUE_NAME]/default/state/resources.json +{ + "state_version": 3, + "features": { + "record_deployment_history": {} + }, + "resources": [] +} + +=== Redeploy: nothing is created a second time, and nothing even reads as changed - what the service holds matches the config, stamp included +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-state-from-service-[UNIQUE_NAME]/default/files... +Files: 5 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 4 unchanged + +=== And the recovered state has the ids and the dependency edge back, from the service +>>> print_state.py +{ + "state_version": 3, + "cli_version": "[CLI_VERSION]", + "lineage": "[UUID]", + "serial": 1, + "features": { + "record_deployment_history": {} + }, + "state": { + "resources.jobs.dependent": { + "__id__": "[NUMID]", + "state": { + "deployment": { + "deployment_id": "[NUMID]", + "kind": "BUNDLE", + "metadata_file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-state-from-service-[UNIQUE_NAME]/default/state/metadata.json", + "version_id": "1" + }, + "edit_mode": "UI_LOCKED", + "format": "MULTI_TASK", + "max_concurrent_runs": 1, + "name": "dependent", + "queue": { + "enabled": true + }, + "tags": { + "upstream": "[NUMID]" + } + }, + "depends_on": [ + { + "node": "resources.jobs.source", + "label": "${resources.jobs.source.id}" + } + ] + }, + "resources.jobs.source": { + "__id__": "[NUMID]", + "state": { + "deployment": { + "deployment_id": "[NUMID]", + "kind": "BUNDLE", + "metadata_file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-state-from-service-[UNIQUE_NAME]/default/state/metadata.json", + "version_id": "1" + }, + "edit_mode": "UI_LOCKED", + "format": "MULTI_TASK", + "max_concurrent_runs": 1, + "name": "source", + "queue": { + "enabled": true + }, + "tags": { + "source_id": "placeholder" + } + } + }, + "resources.secret_scopes.scope": { + "__id__": "scope-[UNIQUE_NAME]", + "state": { + "scope": "scope-[UNIQUE_NAME]", + "scope_backend_type": "DATABRICKS" + } + }, + "resources.secret_scopes.scope.permissions": { + "__id__": "scope-[UNIQUE_NAME]", + "state": { + "scope_name": "scope-[UNIQUE_NAME]", + "acls": [ + { + "permission": "MANAGE", + "principal": "[USERNAME]" + } + ] + }, + "depends_on": [ + { + "node": "resources.secret_scopes.scope", + "label": "${resources.secret_scopes.scope.name}" + } + ] + } + } +} + +=== Strip the marker from the local state, keeping its lineage. The resources still come from the service, so the deploy is a no-op - and because it writes nothing, the file keeps the stripped header until some later deploy does write +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-state-from-service-[UNIQUE_NAME]/default/files... +Files: 1 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 4 unchanged + +>>> jq {state_version, features} .databricks/bundle/default/resources.json +{ + "state_version": 3, + "features": null +} + +=== Now delete the remote state file too and wipe the local cache again. No state file exists anywhere, so the service is the only record of the deployment left +>>> MSYS_NO_PATHCONV=1 [CLI] workspace delete /Workspace/Users/[USERNAME]/.bundle/dms-state-from-service-[UNIQUE_NAME]/default/state/resources.json + +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-state-from-service-[UNIQUE_NAME]/default/files... +Files: 5 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 4 unchanged + +=== And no state file comes back: the deploy changed nothing, so it wrote nothing. Under recording the file is optional - the service is the state +>>> find.py resources.json --expect 0 + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.jobs.dependent + delete resources.jobs.source + delete resources.secret_scopes.scope + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-state-from-service-[UNIQUE_NAME]/default + +Destroy: 3 deleted diff --git a/acceptance/bundle/dms/state-from-service/script b/acceptance/bundle/dms/state-from-service/script new file mode 100644 index 00000000000..efd431d0add --- /dev/null +++ b/acceptance/bundle/dms/state-from-service/script @@ -0,0 +1,34 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +title "Deploy: the service records all three resources, including the dependency edge" +trace $CLI bundle deploy +trace print_state.py + +title "Throw away every local trace of the deployment. The state file the deploy left is only a header, so anything the next deploy knows has to come from the service" +rm -rf .databricks +trace MSYS_NO_PATHCONV=1 $CLI workspace export "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-state-from-service-${UNIQUE_NAME}/default/state/resources.json" | jq '{state_version, features, resources: (.state | keys)}' + +title "Redeploy: nothing is created a second time, and nothing even reads as changed - what the service holds matches the config, stamp included" +trace $CLI bundle deploy + +title "And the recovered state has the ids and the dependency edge back, from the service" +trace print_state.py + +title "Strip the marker from the local state, keeping its lineage. The resources still come from the service, so the deploy is a no-op - and because it writes nothing, the file keeps the stripped header until some later deploy does write" +jq 'del(.features)' .databricks/bundle/default/resources.json > tmp.json && mv tmp.json .databricks/bundle/default/resources.json +trace $CLI bundle deploy +trace jq '{state_version, features}' .databricks/bundle/default/resources.json + +title "Now delete the remote state file too and wipe the local cache again. No state file exists anywhere, so the service is the only record of the deployment left" +trace MSYS_NO_PATHCONV=1 $CLI workspace delete "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-state-from-service-${UNIQUE_NAME}/default/state/resources.json" +rm -rf .databricks +trace $CLI bundle deploy + +title "And no state file comes back: the deploy changed nothing, so it wrote nothing. Under recording the file is optional - the service is the state" +trace find.py 'resources.json' --expect 0 diff --git a/acceptance/bundle/dms/state-from-service/test.toml b/acceptance/bundle/dms/state-from-service/test.toml new file mode 100644 index 00000000000..c4010cbd3f0 --- /dev/null +++ b/acceptance/bundle/dms/state-from-service/test.toml @@ -0,0 +1,2 @@ +# This test asserts what the state holds, not the calls behind it. +RecordRequests = false diff --git a/acceptance/bundle/dms/summary/databricks.yml.tmpl b/acceptance/bundle/dms/summary/databricks.yml.tmpl new file mode 100644 index 00000000000..1c2fa3c7f20 --- /dev/null +++ b/acceptance/bundle/dms/summary/databricks.yml.tmpl @@ -0,0 +1,9 @@ +bundle: + name: dms-summary-$UNIQUE_NAME +experimental: + record_deployment_history: true + +resources: + jobs: + foo: + name: foo diff --git a/acceptance/bundle/dms/summary/out.test.toml b/acceptance/bundle/dms/summary/out.test.toml new file mode 100644 index 00000000000..23c07f70dca --- /dev/null +++ b/acceptance/bundle/dms/summary/out.test.toml @@ -0,0 +1,3 @@ +Cloud = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/summary/output.txt b/acceptance/bundle/dms/summary/output.txt new file mode 100644 index 00000000000..233f2416dc3 --- /dev/null +++ b/acceptance/bundle/dms/summary/output.txt @@ -0,0 +1,37 @@ + +=== Summary reports the deployment recorded with the metadata service, so a caller can find the deployment and the version it is on +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-summary-[UNIQUE_NAME]/default/files... +Created jobs.foo +Files: 5 uploaded, 0 deleted +Resources: 1 created, 0 changed, 0 deleted, 0 unchanged + +>>> [CLI] bundle summary -o json +{ + "deployment_id": "[NUMID]", + "latest_version_id": "1" +} + +=== Redeploying advances the version the summary reports +>>> [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-summary-[UNIQUE_NAME]/default/files... +Files: 2 uploaded, 0 deleted +Resources: 0 created, 0 changed, 0 deleted, 1 unchanged + +>>> [CLI] bundle summary -o json +{ + "deployment_id": "[NUMID]", + "latest_version_id": "2" +} + +=== After a destroy the deployment is gone, so the summary reports no history rather than a dangling ID +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.jobs.foo + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/dms-summary-[UNIQUE_NAME]/default + +Destroy: 1 deleted + +>>> [CLI] bundle summary -o json +false diff --git a/acceptance/bundle/dms/summary/script b/acceptance/bundle/dms/summary/script new file mode 100644 index 00000000000..75ec8612ffe --- /dev/null +++ b/acceptance/bundle/dms/summary/script @@ -0,0 +1,17 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +title "Summary reports the deployment recorded with the metadata service, so a caller can find the deployment and the version it is on" +trace $CLI bundle deploy +trace $CLI bundle summary -o json | jq .bundle.deployment.history + +title "Redeploying advances the version the summary reports" +trace $CLI bundle deploy +trace $CLI bundle summary -o json | jq .bundle.deployment.history + +title "After a destroy the deployment is gone, so the summary reports no history rather than a dangling ID" +trace $CLI bundle destroy --auto-approve +trace $CLI bundle summary -o json | jq '.bundle.deployment | has("history")' + +# This test asserts the summary output, not the requests behind it; the file uploads +# recorded here are ordered nondeterministically. +rm -f out.requests.txt diff --git a/acceptance/bundle/dms/test.toml b/acceptance/bundle/dms/test.toml new file mode 100644 index 00000000000..32a52823ff7 --- /dev/null +++ b/acceptance/bundle/dms/test.toml @@ -0,0 +1,19 @@ +Cloud = true + +# Deployment Metadata Service (DMS) recording is only supported by the direct +# engine; it is a no-op on terraform. +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] + + +RecordRequests = true + +Ignore = [ + '.databricks', + 'databricks.yml', +] + +# These tests set experimental.record_deployment_history in databricks.yml; the DMS env var +# both records and permits that otherwise-gated field. bundle/dms/not-supported covers the +# rejection path. Pinned to "true" (not the suite's ["", "true"]) since the field already +# records - the empty variant would just duplicate it. +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/version-never-created/databricks.yml b/acceptance/bundle/dms/version-never-created/databricks.yml new file mode 100644 index 00000000000..a7077f18b1f --- /dev/null +++ b/acceptance/bundle/dms/version-never-created/databricks.yml @@ -0,0 +1,10 @@ +bundle: + name: dms-version-never-created + +experimental: + record_deployment_history: true + +resources: + jobs: + foo: + name: foo diff --git a/acceptance/bundle/dms/version-never-created/out.test.toml b/acceptance/bundle/dms/version-never-created/out.test.toml new file mode 100644 index 00000000000..9921e91a794 --- /dev/null +++ b/acceptance/bundle/dms/version-never-created/out.test.toml @@ -0,0 +1,3 @@ +Cloud = false +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/dms/version-never-created/output.txt b/acceptance/bundle/dms/version-never-created/output.txt new file mode 100644 index 00000000000..beadce201e3 --- /dev/null +++ b/acceptance/bundle/dms/version-never-created/output.txt @@ -0,0 +1,36 @@ + +=== The first version fails, so no deployment record exists - only the node naming its ID +>>> musterr [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-version-never-created/default/files... +Error: failed to create deployment version: Internal error (500 INTERNAL_ERROR) + +Endpoint: POST [DATABRICKS_URL]/api/2.0/bundle/deployments/[NUMID]/versions?version_id=1 +HTTP Status: 500 Internal Server Error +API error_code: INTERNAL_ERROR +API message: Internal error + +Files: 5 uploaded, 0 deleted + +>>> MSYS_NO_PATHCONV=1 [CLI] workspace get-status /Workspace/Users/[USERNAME]/.bundle/dms-version-never-created/default/state/resources.deployment.json +{ + "object_type": "BUNDLE_DEPLOYMENT" +} + +=== The next deploy reuses the ID that node names and retries version 1, rather than creating a second deployment +>>> musterr [CLI] bundle deploy +Uploading bundle files to /Workspace/Users/[USERNAME]/.bundle/dms-version-never-created/default/files... +Error: failed to create deployment version: Internal error (500 INTERNAL_ERROR) + +Endpoint: POST [DATABRICKS_URL]/api/2.0/bundle/deployments/[NUMID]/versions?version_id=1 +HTTP Status: 500 Internal Server Error +API error_code: INTERNAL_ERROR +API message: Internal error + +Files: 2 uploaded, 0 deleted + +>>> print_requests.py --dms //api/2.0/bundle --get --oneline +{"method": "POST", "path": "/api/2.0/bundle/deployments", "body": {"display_name": "dms-version-never-created", "initial_parent_path": "/Workspace/Users/[USERNAME]/.bundle/dms-version-never-created/default/state", "target_name": "default", "workspace_info": {"file_path": "/Workspace/Users/[USERNAME]/.bundle/dms-version-never-created/default/files", "root_path": "/Workspace/Users/[USERNAME]/.bundle/dms-version-never-created/default"}}} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions", "q": {"version_id": "1"}, "body": {"cli_version": "[CLI_VERSION]", "version_type": "VERSION_TYPE_DEPLOY", "operations": [{"resource_key": "jobs.foo", "action_type": "OPERATION_ACTION_TYPE_CREATE"}]}} +{"method": "GET", "path": "/api/2.0/bundle/deployments/[NUMID]"} +{"method": "GET", "path": "/api/2.0/bundle/deployments/[NUMID]/resources"} +{"method": "POST", "path": "/api/2.0/bundle/deployments/[NUMID]/versions", "q": {"version_id": "1"}, "body": {"cli_version": "[CLI_VERSION]", "version_type": "VERSION_TYPE_DEPLOY", "operations": [{"resource_key": "jobs.foo", "action_type": "OPERATION_ACTION_TYPE_CREATE"}]}} diff --git a/acceptance/bundle/dms/version-never-created/script b/acceptance/bundle/dms/version-never-created/script new file mode 100644 index 00000000000..462e18de914 --- /dev/null +++ b/acceptance/bundle/dms/version-never-created/script @@ -0,0 +1,7 @@ +title "The first version fails, so no deployment record exists - only the node naming its ID" +trace musterr $CLI bundle deploy +trace MSYS_NO_PATHCONV=1 $CLI workspace get-status "/Workspace/Users/${CURRENT_USER_NAME}/.bundle/dms-version-never-created/default/state/resources.deployment.json" | jq '{object_type}' + +title "The next deploy reuses the ID that node names and retries version 1, rather than creating a second deployment" +trace musterr $CLI bundle deploy +trace print_requests.py --dms //api/2.0/bundle --get --oneline diff --git a/acceptance/bundle/dms/version-never-created/test.toml b/acceptance/bundle/dms/version-never-created/test.toml new file mode 100644 index 00000000000..6553e7c09bb --- /dev/null +++ b/acceptance/bundle/dms/version-never-created/test.toml @@ -0,0 +1,12 @@ +# Local only: the failure has to land on CreateVersion and not on the CreateDeployment +# that precedes it, which fault.py's trailing-* pattern cannot express, so this case +# keeps a [[Server]] stub - and the cloud harness ignores stubs. +Cloud = false + +# The first version fails, so the deployment record is never created - only the +# workspace node CreateDeployment registered. The next deploy resolves the ID from +# that node and has to cope with a deployment that has no record yet. +[[Server]] +Pattern = "POST /api/2.0/bundle/deployments/{deployment_id}/versions" +Response.StatusCode = 500 +Response.Body = '''{"error_code": "INTERNAL_ERROR", "message": "Internal error"}''' diff --git a/acceptance/bundle/escaped_refs/output.txt b/acceptance/bundle/escaped_refs/output.txt index 6e12dbfd8fc..342535d0037 100644 --- a/acceptance/bundle/escaped_refs/output.txt +++ b/acceptance/bundle/escaped_refs/output.txt @@ -15,7 +15,7 @@ Created jobs.example_ingestion_job Files: 6 uploaded, 0 deleted Resources: 1 created, 0 changed, 0 deleted, 0 unchanged ->>> print_requests.py //jobs +>>> print_requests.py //jobs --nostamp { "method": "POST", "path": "/api/2.2/jobs/create", diff --git a/acceptance/bundle/escaped_refs/script b/acceptance/bundle/escaped_refs/script index 34640492656..5ff97b09bcb 100644 --- a/acceptance/bundle/escaped_refs/script +++ b/acceptance/bundle/escaped_refs/script @@ -18,4 +18,6 @@ trace $CLI bundle plan -o json > out.plan.$DATABRICKS_BUNDLE_ENGINE.json # that the payload below is identical either way. title "Deploy: payload sent to the jobs API\n" $CLI bundle deploy $(readplanarg out.plan.$DATABRICKS_BUNDLE_ENGINE.json) -trace print_requests.py //jobs +# --nostamp: under deployment-history recording the job payload carries the DMS deployment +# stamp; drop it so the assertion is the same whether or not recording is on. +trace print_requests.py //jobs --nostamp diff --git a/acceptance/bundle/invariant/delete_idempotent/out.test.toml b/acceptance/bundle/invariant/delete_idempotent/out.test.toml index 59018deb1ce..8439713320e 100644 --- a/acceptance/bundle/invariant/delete_idempotent/out.test.toml +++ b/acceptance/bundle/invariant/delete_idempotent/out.test.toml @@ -1,6 +1,6 @@ Cloud = true EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] -EnvMatrix.DMS = [""] +EnvMatrix.DMS = ["", "true"] EnvMatrix.INPUT_CONFIG = [ "alert.yml.tmpl", "app.yml.tmpl", diff --git a/acceptance/bundle/invariant/delete_idempotent/test.toml b/acceptance/bundle/invariant/delete_idempotent/test.toml index f876726848d..c9ff20b59b4 100644 --- a/acceptance/bundle/invariant/delete_idempotent/test.toml +++ b/acceptance/bundle/invariant/delete_idempotent/test.toml @@ -1,9 +1,10 @@ -# Recording needs a bundle from the start. This test rewinds state and wipes the -# deployment record path, so recording refuses it. -EnvMatrix.DMS = [""] - EnvMatrix.READPLAN = ["", "1"] +# A 1000-task job serializes to ~110 KB, over the 64 KB per-operation state limit the +# deployment metadata service accepts, so recording it fails the deploy. Raising the limit +# or splitting the state is a service-side decision. +EnvMatrixExclude.dms_state_too_large = ["DMS=true", "INPUT_CONFIG=job_pydabs_1000_tasks.yml.tmpl"] + # Snapshot of pre-delete state used to re-run the delete on state that still # references the (now-gone) resources; may linger if the test fails mid-run. Ignore = [".databricks.backup"] diff --git a/acceptance/bundle/invariant/destroy_idempotent/out.test.toml b/acceptance/bundle/invariant/destroy_idempotent/out.test.toml index 59018deb1ce..8439713320e 100644 --- a/acceptance/bundle/invariant/destroy_idempotent/out.test.toml +++ b/acceptance/bundle/invariant/destroy_idempotent/out.test.toml @@ -1,6 +1,6 @@ Cloud = true EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] -EnvMatrix.DMS = [""] +EnvMatrix.DMS = ["", "true"] EnvMatrix.INPUT_CONFIG = [ "alert.yml.tmpl", "app.yml.tmpl", diff --git a/acceptance/bundle/invariant/destroy_idempotent/test.toml b/acceptance/bundle/invariant/destroy_idempotent/test.toml index d86b5366f20..d44e1cf47eb 100644 --- a/acceptance/bundle/invariant/destroy_idempotent/test.toml +++ b/acceptance/bundle/invariant/destroy_idempotent/test.toml @@ -1,9 +1,10 @@ -# Recording needs a bundle from the start. This test rewinds state and wipes the -# deployment record path, so recording refuses it. -EnvMatrix.DMS = [""] - EnvMatrix.READPLAN = ["", "1"] +# A 1000-task job serializes to ~110 KB, over the 64 KB per-operation state limit the +# deployment metadata service accepts, so recording it fails the deploy. Raising the limit +# or splitting the state is a service-side decision. +EnvMatrixExclude.dms_state_too_large = ["DMS=true", "INPUT_CONFIG=job_pydabs_1000_tasks.yml.tmpl"] + # Snapshot of pre-destroy state used to re-run destroy on state that still # references the (now-gone) resources; may linger if the test fails mid-run. Ignore = [".databricks.backup"] diff --git a/acceptance/bundle/resource_deps/escaped_ref/output.txt b/acceptance/bundle/resource_deps/escaped_ref/output.txt index 09857524d69..3089e5c6995 100644 --- a/acceptance/bundle/resource_deps/escaped_ref/output.txt +++ b/acceptance/bundle/resource_deps/escaped_ref/output.txt @@ -18,7 +18,7 @@ Created jobs.foo Files: 6 uploaded, 0 deleted Resources: 2 created, 0 changed, 0 deleted, 0 unchanged ->>> print_requests.py //jobs --sort +>>> print_requests.py //jobs --sort --nostamp { "method": "POST", "path": "/api/2.2/jobs/create", diff --git a/acceptance/bundle/resource_deps/escaped_ref/script b/acceptance/bundle/resource_deps/escaped_ref/script index 413394d8b7d..c53b9b85671 100644 --- a/acceptance/bundle/resource_deps/escaped_ref/script +++ b/acceptance/bundle/resource_deps/escaped_ref/script @@ -12,4 +12,6 @@ trace jq '.plan | map_values(.depends_on)' plan.json # that the payload below is identical either way. title "Payload: escaped stays literal, real is resolved\n" $CLI bundle deploy $(readplanarg plan.json) -trace print_requests.py //jobs --sort +# --nostamp: under deployment-history recording the job payload carries the DMS deployment +# stamp; drop it so the assertion is the same whether or not recording is on. +trace print_requests.py //jobs --sort --nostamp diff --git a/acceptance/bundle/resources/jobs/big_id/test.toml b/acceptance/bundle/resources/jobs/big_id/test.toml index b15d8f9e757..8957ed9ce06 100644 --- a/acceptance/bundle/resources/jobs/big_id/test.toml +++ b/acceptance/bundle/resources/jobs/big_id/test.toml @@ -3,8 +3,8 @@ EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ['direct'] EnvMatrix.READPLAN = ["", "1"] -# `bundle deploy --plan` applies pre-saved state; the stamp isn't written into the plan, -# so the next plan reports it as a change. Recording skipped until stamp reaches saved plans. +# Dumps raw state/plan, which carry the DMS deployment stamp under recording (applied at deploy, +# not saved in the plan). deploy --plan recording is covered by bundle/dms, so opt out here. EnvMatrix.DMS = [""] [[Repls]] diff --git a/acceptance/bundle/resources/jobs/delete_task/test.toml b/acceptance/bundle/resources/jobs/delete_task/test.toml index 46a4d91b848..04d6ea1e5b3 100644 --- a/acceptance/bundle/resources/jobs/delete_task/test.toml +++ b/acceptance/bundle/resources/jobs/delete_task/test.toml @@ -1,5 +1,5 @@ RecordRequests = false EnvMatrix.READPLAN = ["", "1"] -# `bundle deploy --plan` applies pre-saved state; the stamp isn't written into the plan, -# so the next plan reports it as a change. Recording skipped until stamp reaches saved plans. +# Dumps raw state/plan, which carry the DMS deployment stamp under recording (applied at deploy, +# not saved in the plan). deploy --plan recording is covered by bundle/dms, so opt out here. EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/resources/jobs/remote_delete/deploy/test.toml b/acceptance/bundle/resources/jobs/remote_delete/deploy/test.toml index 46a4d91b848..04d6ea1e5b3 100644 --- a/acceptance/bundle/resources/jobs/remote_delete/deploy/test.toml +++ b/acceptance/bundle/resources/jobs/remote_delete/deploy/test.toml @@ -1,5 +1,5 @@ RecordRequests = false EnvMatrix.READPLAN = ["", "1"] -# `bundle deploy --plan` applies pre-saved state; the stamp isn't written into the plan, -# so the next plan reports it as a change. Recording skipped until stamp reaches saved plans. +# Dumps raw state/plan, which carry the DMS deployment stamp under recording (applied at deploy, +# not saved in the plan). deploy --plan recording is covered by bundle/dms, so opt out here. EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/resources/jobs/update/test.toml b/acceptance/bundle/resources/jobs/update/test.toml index 20c8733641d..a8a43da097a 100644 --- a/acceptance/bundle/resources/jobs/update/test.toml +++ b/acceptance/bundle/resources/jobs/update/test.toml @@ -1,4 +1,4 @@ EnvMatrix.READPLAN = ["", "1"] -# `bundle deploy --plan` applies pre-saved state; the stamp isn't written into the plan, -# so the next plan reports it as a change. Recording skipped until stamp reaches saved plans. +# Dumps raw state/plan, which carry the DMS deployment stamp under recording (applied at deploy, +# not saved in the plan). deploy --plan recording is covered by bundle/dms, so opt out here. EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/resources/permissions/jobs/destroy_without_mgmtperms/test.toml b/acceptance/bundle/resources/permissions/jobs/destroy_without_mgmtperms/test.toml index 921045dfd09..4ca61be3f36 100644 --- a/acceptance/bundle/resources/permissions/jobs/destroy_without_mgmtperms/test.toml +++ b/acceptance/bundle/resources/permissions/jobs/destroy_without_mgmtperms/test.toml @@ -1,4 +1,3 @@ -# Recording needs a bundle it has seen from the start. This test seeds a state file, -# so recording refuses it. TODO(DMS): drop this once existing state can be -# handed over to the service (see the TODO in dstate.Open). +# Deploy runs as the service principal, later commands as the user - who resolves no deployment of +# its own, so bundle summary reads the job id back null. Recording needs state staged for the reader. EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/resources/postgres_branches/purge_on_delete_transitions/script b/acceptance/bundle/resources/postgres_branches/purge_on_delete_transitions/script index 919fe6e4f4f..f743dc45177 100644 --- a/acceptance/bundle/resources/postgres_branches/purge_on_delete_transitions/script +++ b/acceptance/bundle/resources/postgres_branches/purge_on_delete_transitions/script @@ -16,7 +16,7 @@ trap cleanup EXIT # resources.json. The field is omitted from JSON when unset (omitempty + # ForceSendFields tracking), so an absent value falls back to "(unset)". get_purge() { - gron.py < .databricks/bundle/default/resources.json | grep 'postgres_branches.branch.state.purge_on_delete' || echo '(unset)' + print_state.py | gron.py | grep 'postgres_branches.branch.state.purge_on_delete' || echo '(unset)' } title "Step 1: deploy with purge_on_delete unset" diff --git a/acceptance/bundle/resources/postgres_projects/purge_on_delete_transitions/script b/acceptance/bundle/resources/postgres_projects/purge_on_delete_transitions/script index 1bdc077e6e1..958d4e2d980 100644 --- a/acceptance/bundle/resources/postgres_projects/purge_on_delete_transitions/script +++ b/acceptance/bundle/resources/postgres_projects/purge_on_delete_transitions/script @@ -12,7 +12,7 @@ trap cleanup EXIT # resources.json. The field is omitted from JSON when unset (omitempty + # ForceSendFields tracking), so an absent value falls back to "(unset)". get_purge() { - gron.py < .databricks/bundle/default/resources.json | grep purge_on_delete || echo '(unset)' + print_state.py | gron.py | grep purge_on_delete || echo '(unset)' } title "Step 1: deploy with purge_on_delete unset" diff --git a/acceptance/bundle/resources/postgres_roles/inherited-role-bind/out.test.toml b/acceptance/bundle/resources/postgres_roles/inherited-role-bind/out.test.toml index ce8be6534d3..26f5e3debde 100644 --- a/acceptance/bundle/resources/postgres_roles/inherited-role-bind/out.test.toml +++ b/acceptance/bundle/resources/postgres_roles/inherited-role-bind/out.test.toml @@ -2,4 +2,4 @@ Cloud = false CloudEnvs.azure = false CloudEnvs.gcp = false EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] -EnvMatrix.DMS = ["", "true"] +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/resources/postgres_roles/inherited-role-bind/test.toml b/acceptance/bundle/resources/postgres_roles/inherited-role-bind/test.toml index 6de86c5f2b6..01b05580cec 100644 --- a/acceptance/bundle/resources/postgres_roles/inherited-role-bind/test.toml +++ b/acceptance/bundle/resources/postgres_roles/inherited-role-bind/test.toml @@ -7,3 +7,7 @@ Cloud = false # bind/deploy are engine-agnostic here; run on direct for a single stable output. EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] + +# bind and unbind refuse to run when deployment history recording is on, so the +# escape hatch this test covers is not available there yet. +EnvMatrix.DMS = [""] diff --git a/acceptance/bundle/resources/secrets/update-value/output.txt b/acceptance/bundle/resources/secrets/update-value/output.txt index 9e94921e2f3..3a6267216c8 100644 --- a/acceptance/bundle/resources/secrets/update-value/output.txt +++ b/acceptance/bundle/resources/secrets/update-value/output.txt @@ -117,20 +117,14 @@ secrets secret1 catalog_name='main' schema_name='default' name='test_secret' com === Verify state does not contain actual secret value >>> print_state.py { - "state_version": 2, - "cli_version": "[CLI_VERSION]", - "lineage": "[UUID]", - "serial": 2, - "state": { "resources.secrets.secret1": { - "__id__": "main.default.test_secret", - "state": { - "catalog_name": "main", - "comment": "Test secret", - "name": "test_secret", - "schema_name": "default", - "value": "" - } + "__id__": "main.default.test_secret", + "state": { + "catalog_name": "main", + "comment": "Test secret", + "name": "test_secret", + "schema_name": "default", + "value": "" + } } - } } diff --git a/acceptance/bundle/resources/secrets/update-value/script b/acceptance/bundle/resources/secrets/update-value/script index a5c1596e29c..977c2f22378 100755 --- a/acceptance/bundle/resources/secrets/update-value/script +++ b/acceptance/bundle/resources/secrets/update-value/script @@ -11,6 +11,6 @@ trace print_requests.py //unity-catalog read_state.py secrets secret1 catalog_name schema_name name comment value title "Verify state does not contain actual secret value" -{ trace print_state.py | contains.py "!initial-secret-value" "!updated-secret-value"; } || true +{ trace print_state.py | jq .state | contains.py "!initial-secret-value" "!updated-secret-value"; } || true rm -f out.requests.txt diff --git a/acceptance/bundle/state/feature_flags/output.txt b/acceptance/bundle/state/feature_flags/output.txt index df55e7c6cee..90326dfe2cd 100644 --- a/acceptance/bundle/state/feature_flags/output.txt +++ b/acceptance/bundle/state/feature_flags/output.txt @@ -1,5 +1,5 @@ -=== a version-3 state recording a feature is rejected (this CLI records no features yet) +=== a version-3 state recording a feature this CLI does not write is rejected >>> errcode [CLI] bundle plan Error: migrating state [TEST_TMP_DIR]/.databricks/bundle/default/resources.json: the deployment state requires features this CLI does not support: future_feature; upgrade to the latest CLI version and see https://docs.databricks.com/aws/en/dev-tools/bundles/state-features#state-features for more information diff --git a/acceptance/bundle/state/feature_flags/script b/acceptance/bundle/state/feature_flags/script index e70b562f2ff..0212a4102be 100644 --- a/acceptance/bundle/state/feature_flags/script +++ b/acceptance/bundle/state/feature_flags/script @@ -1,6 +1,6 @@ mkdir -p .databricks/bundle/default -title "a version-3 state recording a feature is rejected (this CLI records no features yet)" +title "a version-3 state recording a feature this CLI does not write is rejected" cp resources.with_feature.json .databricks/bundle/default/resources.json trace errcode $CLI bundle plan 2>&1 | contains.py "requires features this CLI does not support: future_feature" "upgrade to the latest CLI version" "https://docs.databricks.com/aws/en/dev-tools/bundles/state-features#state-features" diff --git a/acceptance/bundle/templates/record-deployment-history/out.test.toml b/acceptance/bundle/templates/record-deployment-history/out.test.toml index 27ec2a7fcd6..9921e91a794 100644 --- a/acceptance/bundle/templates/record-deployment-history/out.test.toml +++ b/acceptance/bundle/templates/record-deployment-history/out.test.toml @@ -1,3 +1,3 @@ Cloud = false EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] -EnvMatrix.DMS = [""] +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/templates/record-deployment-history/test.toml b/acceptance/bundle/templates/record-deployment-history/test.toml index a1d3232167a..89b85620c2a 100644 --- a/acceptance/bundle/templates/record-deployment-history/test.toml +++ b/acceptance/bundle/templates/record-deployment-history/test.toml @@ -2,3 +2,7 @@ Env.DATABRICKS_BUNDLE_INIT_RECORD_DEPLOYMENT_HISTORY = "true" # What is under test is what `bundle init` writes, so one engine is enough. EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] + +# The generated project sets experimental.record_deployment_history; DMS=true permits it so +# the validate step below loads instead of rejecting it. +EnvMatrix.DMS = ["true"] diff --git a/acceptance/bundle/test.toml b/acceptance/bundle/test.toml index 6a259762f65..2db98f4b429 100644 --- a/acceptance/bundle/test.toml +++ b/acceptance/bundle/test.toml @@ -10,14 +10,6 @@ EnvMatrix.DMS = ["", "true"] # DMS recording is only supported by the direct engine; it is a no-op on terraform. EnvMatrixExclude.dms_needs_direct = ["DMS=true", "DATABRICKS_BUNDLE_ENGINE=terraform"] -# Saved plans don't carry the deployment stamp. A first plan writes the deployment record, -# so `deploy --plan` creates resources without it and reports drift on the next plan. -EnvMatrixExclude.dms_no_readplan = ["DMS=true", "READPLAN=1"] - -# Recording is gated off for users (see validate.ValidateRecordDeploymentHistory), so -# force it on: the point of this run is to exercise it. -Env.DATABRICKS_BUNDLE_FORCE_ALLOW_RECORD_DEPLOYMENT_HISTORY = "1" - # The DMS run asserts the same golden files as the engine runs. EnvRepl.DMS = false diff --git a/bundle/bundle.go b/bundle/bundle.go index c58fba10d77..d3d01bcd6f0 100644 --- a/bundle/bundle.go +++ b/bundle/bundle.go @@ -328,6 +328,14 @@ func (b *Bundle) WorkspaceClient(ctx context.Context) *databricks.WorkspaceClien return client } +// RecordsDeploymentHistory reports whether this bundle records deployment history with the +// deployment metadata service, from experimental.record_deployment_history or +// DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY. +func (b *Bundle) RecordsDeploymentHistory(ctx context.Context) bool { + configured := b.Config.Experimental != nil && b.Config.Experimental.RecordDeploymentHistory + return env.RecordsDeploymentHistory(ctx, configured) +} + // SetWorkpaceClient sets the workspace client for this bundle. // This is used to inject a mock client for testing. func (b *Bundle) SetWorkpaceClient(w *databricks.WorkspaceClient) { diff --git a/bundle/config/deployment.go b/bundle/config/deployment.go index b7efb4456f9..b59d1b1da02 100644 --- a/bundle/config/deployment.go +++ b/bundle/config/deployment.go @@ -7,4 +7,20 @@ type Deployment struct { // Lock configures locking behavior on deployment. Lock Lock `json:"lock,omitempty"` + + // History reports what the deployment metadata service has recorded for this + // bundle. Output only: it is read from the service for 'bundle summary' and is + // unset when the bundle does not record deployment history. + History *DeploymentHistory `json:"history,omitempty" bundle:"readonly"` +} + +// DeploymentHistory identifies the bundle's deployment in the deployment +// metadata service. +type DeploymentHistory struct { + // DeploymentID is the ID the service assigned to this bundle's deployment. + DeploymentID string `json:"deployment_id,omitempty"` + + // LatestVersionID is the most recent version recorded for the deployment. It is + // unset when the deployment exists but has no version yet. + LatestVersionID string `json:"latest_version_id,omitempty"` } diff --git a/bundle/config/experimental.go b/bundle/config/experimental.go index 658f1cea819..005c4dfcade 100644 --- a/bundle/config/experimental.go +++ b/bundle/config/experimental.go @@ -53,6 +53,9 @@ type Experimental struct { // RecordDeploymentHistory opts the bundle into the deployment metadata // service (DMS), which records deployment history and tracks what changed // across deployments. + // + // Only for bundles with no deployed resources yet: DMS becomes the source of + // truth for their state. RecordDeploymentHistory bool `json:"record_deployment_history,omitempty"` } diff --git a/bundle/config/validate/validate_record_deployment_history.go b/bundle/config/validate/validate_record_deployment_history.go new file mode 100644 index 00000000000..d9bde2b4967 --- /dev/null +++ b/bundle/config/validate/validate_record_deployment_history.go @@ -0,0 +1,41 @@ +package validate + +import ( + "context" + + "github.com/databricks/cli/bundle" + "github.com/databricks/cli/bundle/env" + "github.com/databricks/cli/libs/diag" + "github.com/databricks/cli/libs/dyn" +) + +const recordDeploymentHistoryPath = "experimental.record_deployment_history" + +func ValidateRecordDeploymentHistory() bundle.ReadOnlyMutator { + return &validateRecordDeploymentHistory{} +} + +type validateRecordDeploymentHistory struct{ bundle.RO } + +func (v *validateRecordDeploymentHistory) Name() string { + return "validate:validate_record_deployment_history" +} + +// Apply rejects experimental.record_deployment_history. The feature is complete +// but not yet exposed: DMS is dev/staging only, and turning it on makes DMS the +// source of truth for state (irreversible). Setting DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY +// permits it, for CLI tests and DMS development. +func (v *validateRecordDeploymentHistory) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics { + if b.Config.Experimental == nil || !b.Config.Experimental.RecordDeploymentHistory { + return nil + } + if env.RecordDeploymentHistoryEnv(ctx) { + return nil + } + return diag.Diagnostics{{ + Severity: diag.Error, + Summary: recordDeploymentHistoryPath + " is not supported yet; remove this setting from your bundle configuration", + Paths: []dyn.Path{dyn.MustPathFromString(recordDeploymentHistoryPath)}, + Locations: b.Config.GetLocations(recordDeploymentHistoryPath), + }} +} diff --git a/bundle/config/validate/validate_record_deployment_history_test.go b/bundle/config/validate/validate_record_deployment_history_test.go new file mode 100644 index 00000000000..4f20e61af55 --- /dev/null +++ b/bundle/config/validate/validate_record_deployment_history_test.go @@ -0,0 +1,55 @@ +package validate + +import ( + "testing" + + "github.com/databricks/cli/bundle" + "github.com/databricks/cli/bundle/config" + bundleenv "github.com/databricks/cli/bundle/env" + "github.com/databricks/cli/libs/diag" + "github.com/databricks/cli/libs/env" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestValidateRecordDeploymentHistory(t *testing.T) { + tests := []struct { + name string + enabled bool + recordEnv string + wantError bool + }{ + {name: "flag unset", enabled: false, wantError: false}, + {name: "flag set", enabled: true, wantError: true}, + {name: "flag set with record env", enabled: true, recordEnv: "true", wantError: false}, + {name: "flag set with empty record env", enabled: true, recordEnv: "", wantError: true}, + {name: "flag unset with record env", enabled: false, recordEnv: "true", wantError: false}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + b := &bundle.Bundle{ + Config: config.Root{ + Experimental: &config.Experimental{RecordDeploymentHistory: tc.enabled}, + }, + } + + ctx := env.Set(t.Context(), bundleenv.RecordDeploymentHistoryVariable, tc.recordEnv) + diags := ValidateRecordDeploymentHistory().Apply(ctx, b) + + if !tc.wantError { + assert.Empty(t, diags) + return + } + require.Len(t, diags, 1) + assert.Equal(t, diag.Error, diags[0].Severity) + assert.Equal(t, "experimental.record_deployment_history is not supported yet; remove this setting from your bundle configuration", diags[0].Summary) + assert.Equal(t, recordDeploymentHistoryPath, diags[0].Paths[0].String()) + }) + } +} + +func TestValidateRecordDeploymentHistoryNoExperimentalBlock(t *testing.T) { + b := &bundle.Bundle{Config: config.Root{}} + assert.Empty(t, ValidateRecordDeploymentHistory().Apply(t.Context(), b)) +} diff --git a/bundle/configsync/diff.go b/bundle/configsync/diff.go index ea45903508b..6149bd7b7c9 100644 --- a/bundle/configsync/diff.go +++ b/bundle/configsync/diff.go @@ -149,7 +149,7 @@ func OpenDeploymentState(ctx context.Context, b *bundle.Bundle, engine engine.En deployBundle := &direct.DeploymentBundle{} _, statePath := b.StateFilenameConfigSnapshot(ctx) - if err := deployBundle.StateDB.Open(ctx, statePath, dstate.WithRecovery(true), dstate.WithWrite(false)); err != nil { + if err := deployBundle.StateDB.Open(ctx, statePath, dstate.WithRecovery(true), dstate.WithWrite(false), nil, ""); err != nil { return nil, fmt.Errorf("failed to open state: %w", err) } return deployBundle, nil diff --git a/bundle/configsync/variables.go b/bundle/configsync/variables.go index 65cddeaff19..91cce00f65b 100644 --- a/bundle/configsync/variables.go +++ b/bundle/configsync/variables.go @@ -156,7 +156,7 @@ func resourceIDLookup(ctx context.Context, b *bundle.Bundle) func(string) string } _, statePath := b.StateFilenameConfigSnapshot(ctx) db := &dstate.DeploymentState{} - if err := db.Open(ctx, statePath, dstate.WithRecovery(false), dstate.WithWrite(false)); err != nil { + if err := db.Open(ctx, statePath, dstate.WithRecovery(false), dstate.WithWrite(false), nil, ""); err != nil { log.Debugf(ctx, "variable restoration: failed to open state DB at %s: %v", statePath, err) return nil } diff --git a/bundle/deploy/metadata/annotate_deployment_version.go b/bundle/deploy/metadata/annotate_deployment_version.go new file mode 100644 index 00000000000..c08f7b52345 --- /dev/null +++ b/bundle/deploy/metadata/annotate_deployment_version.go @@ -0,0 +1,65 @@ +package metadata + +import ( + "context" + "strconv" + + "github.com/databricks/cli/bundle" + "github.com/databricks/cli/libs/diag" +) + +type annotateDeployment struct { + deploymentID string +} + +// AnnotateDeployment stamps the DMS deployment onto every job and pipeline, so a workspace +// resource points back at the deployment that produced it - how lineage resolves a job to its +// bundle. It runs before the plan, or the stamp would show as drift against local config. +func AnnotateDeployment(deploymentID string) bundle.Mutator { + return &annotateDeployment{deploymentID: deploymentID} +} + +func (m *annotateDeployment) Name() string { + return "metadata.AnnotateDeployment" +} + +func (m *annotateDeployment) Apply(_ context.Context, b *bundle.Bundle) diag.Diagnostics { + for _, job := range b.Config.Resources.Jobs { + // Deployment is set by AnnotateJobs, which runs during initialize. + job.Deployment.DeploymentId = m.deploymentID + } + + for _, pipeline := range b.Config.Resources.Pipelines { + pipeline.Deployment.DeploymentId = m.deploymentID + } + + return nil +} + +type annotateDeploymentVersion struct { + version int64 +} + +// AnnotateDeploymentVersion stamps the DMS version onto every job and pipeline. +// Separate from AnnotateDeployment because version only exists after CreateVersion runs. +func AnnotateDeploymentVersion(version int64) bundle.Mutator { + return &annotateDeploymentVersion{version: version} +} + +func (m *annotateDeploymentVersion) Name() string { + return "metadata.AnnotateDeploymentVersion" +} + +func (m *annotateDeploymentVersion) Apply(_ context.Context, b *bundle.Bundle) diag.Diagnostics { + versionID := strconv.FormatInt(m.version, 10) + + for _, job := range b.Config.Resources.Jobs { + job.Deployment.VersionId = versionID + } + + for _, pipeline := range b.Config.Resources.Pipelines { + pipeline.Deployment.VersionId = versionID + } + + return nil +} diff --git a/bundle/deploy/metadata/annotate_deployment_version_test.go b/bundle/deploy/metadata/annotate_deployment_version_test.go new file mode 100644 index 00000000000..297ba95f8ee --- /dev/null +++ b/bundle/deploy/metadata/annotate_deployment_version_test.go @@ -0,0 +1,50 @@ +package metadata + +import ( + "testing" + + "github.com/databricks/cli/bundle" + "github.com/databricks/cli/bundle/config" + "github.com/databricks/cli/bundle/config/resources" + "github.com/databricks/databricks-sdk-go/service/jobs" + "github.com/databricks/databricks-sdk-go/service/pipelines" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAnnotateDeploymentVersion(t *testing.T) { + b := &bundle.Bundle{ + Config: config.Root{ + Resources: config.Resources{ + Jobs: map[string]*resources.Job{ + "my-job": { + JobSettings: jobs.JobSettings{ + Deployment: &jobs.JobDeployment{Kind: jobs.JobDeploymentKindBundle}, + }, + }, + }, + Pipelines: map[string]*resources.Pipeline{ + "my-pipeline": { + CreatePipeline: pipelines.CreatePipeline{ + Deployment: &pipelines.PipelineDeployment{Kind: pipelines.DeploymentKindBundle}, + }, + }, + }, + }, + }, + } + + diags := bundle.ApplySeq(t.Context(), b, AnnotateDeployment("dep-123"), AnnotateDeploymentVersion(7)) + require.NoError(t, diags.Error()) + + job := b.Config.Resources.Jobs["my-job"].Deployment + assert.Equal(t, "dep-123", job.DeploymentId) + assert.Equal(t, "7", job.VersionId) + // The kind set by AnnotateJobs is preserved. + assert.Equal(t, jobs.JobDeploymentKindBundle, job.Kind) + + pipeline := b.Config.Resources.Pipelines["my-pipeline"].Deployment + assert.Equal(t, "dep-123", pipeline.DeploymentId) + assert.Equal(t, "7", pipeline.VersionId) + assert.Equal(t, pipelines.DeploymentKindBundle, pipeline.Kind) +} diff --git a/bundle/deployplan/plan.go b/bundle/deployplan/plan.go index c9f5bec3516..dac0efef687 100644 --- a/bundle/deployplan/plan.go +++ b/bundle/deployplan/plan.go @@ -16,11 +16,12 @@ import ( const currentPlanVersion = 2 type Plan struct { - PlanVersion int `json:"plan_version,omitempty"` - CLIVersion string `json:"cli_version,omitempty"` - Lineage string `json:"lineage,omitempty"` - Serial int `json:"serial,omitempty"` - Plan map[string]*PlanEntry `json:"plan,omitzero"` + PlanVersion int `json:"plan_version,omitempty"` + CLIVersion string `json:"cli_version,omitempty"` + Lineage string `json:"lineage,omitempty"` + Serial int `json:"serial,omitempty"` + + Plan map[string]*PlanEntry `json:"plan,omitzero"` // NotSelected is the number of resources removed by FilterToSelected via the // --select flag. Serialized so the summary survives a deploy from a plan file diff --git a/bundle/direct/apply.go b/bundle/direct/apply.go index 6b2fffe9a16..af2a7277c77 100644 --- a/bundle/direct/apply.go +++ b/bundle/direct/apply.go @@ -58,6 +58,7 @@ func (d *DeploymentUnit) Deploy(ctx context.Context, db *dstate.DeploymentState, } } +// Create creates the resource and records its state. func (d *DeploymentUnit) Create(ctx context.Context, db *dstate.DeploymentState, newState any) error { var newID string var remoteState any @@ -83,7 +84,7 @@ func (d *DeploymentUnit) Create(ctx context.Context, db *dstate.DeploymentState, return err } - err = d.saveState(db, newID, newState, d.DependsOn) + err = d.saveState(ctx, db, newID, newState, d.DependsOn) if err != nil { return fmt.Errorf("saving state after creating id=%s: %w", newID, err) } @@ -126,7 +127,10 @@ func (d *DeploymentUnit) Recreate(ctx context.Context, db *dstate.DeploymentStat // Drop the state entry so a subsequent failure of Create or WaitAfterDelete // leaves no malformed (empty-ID) entry behind. The next plan will see "no // state" and retry as Create. - err = db.DeleteState(d.ResourceKey) + // + // Recorded as a recreate rather than a delete: if the create below fails, this is the + // operation DMS is left with, and it says the resource is mid-recreate. + err = db.DeleteState(ctx, d.ResourceKey, true) if err != nil { return fmt.Errorf("deleting state: %w", err) } @@ -168,12 +172,12 @@ func (d *DeploymentUnit) Update(ctx context.Context, db *dstate.DeploymentState, // The update emptied the resource out (e.g. all grants revoked). Keeping an entry // would report the node as tracked-and-unchanged forever, while a fresh deploy of // the same config plans no node at all; drop it so the two agree. - err = db.DeleteState(d.ResourceKey) + err = db.DeleteState(ctx, d.ResourceKey, false) if err != nil { return fmt.Errorf("deleting state id=%s: %w", id, err) } } else { - err = d.saveState(db, id, newState, d.DependsOn) + err = d.saveState(ctx, db, id, newState, d.DependsOn) if err != nil { return fmt.Errorf("saving state id=%s: %w", id, err) } @@ -218,7 +222,7 @@ func (d *DeploymentUnit) UpdateWithID(ctx context.Context, db *dstate.Deployment return err } - err = d.saveState(db, newID, newState, d.DependsOn) + err = d.saveState(ctx, db, newID, newState, d.DependsOn) if err != nil { return fmt.Errorf("saving state id=%s: %w", oldID, err) } @@ -256,11 +260,15 @@ func (d *DeploymentUnit) Delete(ctx context.Context, db *dstate.DeploymentState, } else if d.deleteConfirmedGone(ctx, oldID) { log.Warnf(ctx, "Treating %s id=%s as already deleted despite delete error: %s", d.ResourceKey, oldID, err) } else { - return fmt.Errorf("deleting id=%s: %w", oldID, err) + // The resource is still there, so the history says why rather than leaving its + // operation pending. The state write below is what records a delete that worked. + err = fmt.Errorf("deleting id=%s: %w", oldID, err) + db.RecordFailure(d.ResourceKey, oldID, err) + return err } } - err = db.DeleteState(d.ResourceKey) + err = db.DeleteState(ctx, d.ResourceKey, false) if err != nil { return fmt.Errorf("deleting state id=%s: %w", oldID, err) } @@ -305,7 +313,7 @@ func (d *DeploymentUnit) Resize(ctx context.Context, db *dstate.DeploymentState, return fmt.Errorf("resizing id=%s: %w", id, err) } - err = d.saveState(db, id, newState, d.DependsOn) + err = d.saveState(ctx, db, id, newState, d.DependsOn) if err != nil { return fmt.Errorf("saving state id=%s: %w", id, err) } @@ -315,11 +323,11 @@ func (d *DeploymentUnit) Resize(ctx context.Context, db *dstate.DeploymentState, // saveState saves a state with sensitive fields replaced by a placeholder value so secrets are never written // to disk in plaintext. -func (d *DeploymentUnit) saveState(db *dstate.DeploymentState, newID string, state any, dependsOn []deployplan.DependsOnEntry) error { +func (d *DeploymentUnit) saveState(ctx context.Context, db *dstate.DeploymentState, newID string, state any, dependsOn []deployplan.DependsOnEntry) error { if err := zeroSensitiveFields(d.Adapter, state); err != nil { return fmt.Errorf("redacting state: %w", err) } - return db.SaveState(d.ResourceKey, newID, state, dependsOn) + return db.SaveState(ctx, d.ResourceKey, newID, state, dependsOn) } func parseState(destType reflect.Type, raw json.RawMessage) (any, error) { diff --git a/bundle/direct/bind.go b/bundle/direct/bind.go index 9760ce95666..0a3ad2592f5 100644 --- a/bundle/direct/bind.go +++ b/bundle/direct/bind.go @@ -2,6 +2,7 @@ package direct import ( "context" + "errors" "fmt" "os" "strings" @@ -61,12 +62,21 @@ type BindResult struct { // Call Finalize to commit the state or Cancel to discard. func (b *DeploymentBundle) Bind(ctx context.Context, client *databricks.WorkspaceClient, configRoot *config.Root, statePath, resourceKey, resourceID string) (*BindResult, error) { // Check if the resource is already managed (bound to a different ID) + // The state is opened without a DMS client, so the writes below record nothing; + // phases.Bind and phases.Unbind refuse to run at all when recording is enabled. var checkStateDB dstate.DeploymentState - if err := checkStateDB.Open(ctx, statePath, dstate.WithRecovery(true), dstate.WithWrite(false)); err == nil { + if err := checkStateDB.Open(ctx, statePath, dstate.WithRecovery(true), dstate.WithWrite(false), nil, ""); err == nil { + // The setting can be dropped from the config while the state still records the feature, + // which the phases-level refusal misses. The writes below would then be discarded and + // the command would report a bind that did not happen. + recorded := checkStateDB.RequiresDeploymentHistory() existingID := checkStateDB.GetResourceID(resourceKey) if _, err := checkStateDB.Finalize(ctx); err != nil { log.Warnf(ctx, "failed to finalize state: %v", err) } + if recorded { + return nil, errors.New("bind is not supported for a bundle that records deployment history") + } if existingID != "" { return nil, ErrResourceAlreadyBound{ ResourceKey: resourceKey, @@ -86,14 +96,14 @@ func (b *DeploymentBundle) Bind(ctx context.Context, client *databricks.Workspac } // Open temp state - err := b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(false), dstate.WithWrite(true)) + err := b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(false), dstate.WithWrite(true), nil, "") if err != nil { os.Remove(tmpStatePath) return nil, err } // Save state with ID and empty state (like migrate does) - err = b.StateDB.SaveState(resourceKey, resourceID, struct{}{}, nil) + err = b.StateDB.SaveState(ctx, resourceKey, resourceID, struct{}{}, nil) if err != nil { os.Remove(tmpStatePath) return nil, err @@ -109,7 +119,7 @@ func (b *DeploymentBundle) Bind(ctx context.Context, client *databricks.Workspac log.Infof(ctx, "Bound %s to id=%s (in temp state)", resourceKey, resourceID) // First plan + update: populate state with resolved config - err = b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(true), dstate.WithWrite(false)) + err = b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(true), dstate.WithWrite(false), nil, "") if err != nil { os.Remove(tmpStatePath) return nil, err @@ -145,13 +155,13 @@ func (b *DeploymentBundle) Bind(ctx context.Context, client *databricks.Workspac } } - err = b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(true), dstate.WithWrite(true)) + err = b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(true), dstate.WithWrite(true), nil, "") if err != nil { os.Remove(tmpStatePath) return nil, err } - err = b.StateDB.SaveState(resourceKey, resourceID, sv.Value, dependsOn) + err = b.StateDB.SaveState(ctx, resourceKey, resourceID, sv.Value, dependsOn) if err != nil { os.Remove(tmpStatePath) return nil, err @@ -165,7 +175,7 @@ func (b *DeploymentBundle) Bind(ctx context.Context, client *databricks.Workspac } // Second plan: this is the plan to present to the user (change between remote resource and config) - err = b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(true), dstate.WithWrite(false)) + err = b.StateDB.Open(ctx, tmpStatePath, dstate.WithRecovery(true), dstate.WithWrite(false), nil, "") if err != nil { os.Remove(tmpStatePath) return nil, err @@ -215,13 +225,19 @@ func (result *BindResult) Cancel() { // Unbind removes a resource from direct engine state without deleting // the workspace resource. Also removes associated permissions/grants entries. func (b *DeploymentBundle) Unbind(ctx context.Context, statePath, resourceKey string) error { - err := b.StateDB.Open(ctx, statePath, dstate.WithRecovery(true), dstate.WithWrite(true)) + err := b.StateDB.Open(ctx, statePath, dstate.WithRecovery(true), dstate.WithWrite(true), nil, "") if err != nil { return err } + // See the note in Bind: the state's marker outlives the config setting the phases-level + // refusal reads, and the deletes below would be discarded. + if b.StateDB.RequiresDeploymentHistory() { + return errors.New("unbind is not supported for a bundle that records deployment history") + } + // Delete the main resource - err = b.StateDB.DeleteState(resourceKey) + err = b.StateDB.DeleteState(ctx, resourceKey, false) if err != nil { return err } @@ -235,7 +251,7 @@ func (b *DeploymentBundle) Unbind(ctx context.Context, statePath, resourceKey st for key := range b.StateDB.Data.State { if key == permissionsKey || key == grantsKey || strings.HasPrefix(key, resourceKey+".") { - err = b.StateDB.DeleteState(key) + err = b.StateDB.DeleteState(ctx, key, false) if err != nil { return err } diff --git a/bundle/direct/bundle_apply.go b/bundle/direct/bundle_apply.go index 424ae2bdec9..e8910c5eacb 100644 --- a/bundle/direct/bundle_apply.go +++ b/bundle/direct/bundle_apply.go @@ -43,6 +43,11 @@ func (b *DeploymentBundle) Apply(ctx context.Context, client *databricks.Workspa return } + // The state DB records every write with DMS from here on, so the service mirrors the WAL. + // Writes go out on one background goroutine, off the apply path, and are drained below + // once every worker has finished recording. + b.StateDB.RegisterOperationBuffer(b.DmsAsyncOperationClient) + g.Run(defaultParallelism, func(resourceKey string, failedDependency *string) bool { entry, err := plan.WriteLockEntry(resourceKey) if err != nil { @@ -73,6 +78,14 @@ func (b *DeploymentBundle) Apply(ctx context.Context, client *databricks.Workspa return false } + // Stop resource CRUD once recording state with DMS has failed. + if buf := b.DmsAsyncOperationClient; buf != nil { + if err := buf.Err(); err != nil { + logdiag.LogError(ctx, fmt.Errorf("%s: %w", errorPrefix, err)) + return false + } + } + adapter, err := b.getAdapterForKey(resourceKey) if adapter == nil { logdiag.LogError(ctx, fmt.Errorf("%s: internal error: cannot get adapter: %w", errorPrefix, err)) @@ -103,7 +116,7 @@ func (b *DeploymentBundle) Apply(ctx context.Context, client *databricks.Workspa if entry.Gone { // Planning confirmed the resource is already deleted remotely; only // remove it from the state, without calling the delete API. - err = b.StateDB.DeleteState(resourceKey) + err = b.StateDB.DeleteState(ctx, resourceKey, false) } else { err = d.Destroy(ctx, &b.StateDB) } @@ -134,8 +147,15 @@ func (b *DeploymentBundle) Apply(ctx context.Context, client *databricks.Workspa } // TODO: redo calcDiff to downgrade planned action if possible (?) + // + // Success is recorded by the state writes inside Deploy, so a recreate reports + // each of its steps. err = d.Deploy(ctx, &b.StateDB, sv.Value, action, entry) if err != nil { + // Empty for a create that never got an ID, and for a recreate whose delete + // step already dropped it. + failedID := b.StateDB.GetResourceID(resourceKey) + b.StateDB.RecordFailure(resourceKey, failedID, err) logdiag.LogError(ctx, fmt.Errorf("%s: %w", errorPrefix, err)) return false } @@ -162,6 +182,14 @@ func (b *DeploymentBundle) Apply(ctx context.Context, client *databricks.Workspa return true }) + + // Wait for the uploads and report a failure here, with the deploy's other errors. The phase + // completes the version afterwards and drains again, quietly, so this is not printed twice. + if buf := b.DmsAsyncOperationClient; buf != nil { + if err := buf.Drain(); err != nil { + logdiag.LogError(ctx, err) + } + } } func (b *DeploymentBundle) LookupReferencePostDeploy(ctx context.Context, path *structpath.PathNode) (any, error) { diff --git a/bundle/direct/bundle_plan.go b/bundle/direct/bundle_plan.go index 739ca3bd8e7..ff5e99239ad 100644 --- a/bundle/direct/bundle_plan.go +++ b/bundle/direct/bundle_plan.go @@ -25,6 +25,7 @@ import ( "github.com/databricks/cli/libs/structs/structvar" "github.com/databricks/databricks-sdk-go" "github.com/databricks/databricks-sdk-go/apierr" + "github.com/databricks/databricks-sdk-go/service/jobs" ) var errDelayed = errors.New("must be resolved after apply") @@ -58,9 +59,10 @@ func ValidatePlanAgainstState(stateDB *dstate.DeploymentState, plan *deployplan. return nil } -// InitForApply initializes the DeploymentBundle for applying a pre-computed plan. +// InitForApply initializes the DeploymentBundle for applying a pre-computed plan. A non-empty +// deploymentID/versionID (recording) is stamped onto each job/pipeline here, not into the saved plan. // StateDB must already be open for write before calling this function. -func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks.WorkspaceClient, plan *deployplan.Plan) error { +func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks.WorkspaceClient, plan *deployplan.Plan, deploymentID, versionID string) error { b.StateDB.AssertOpenedForWrite() err := b.init(client) @@ -91,6 +93,25 @@ func (b *DeploymentBundle) InitForApply(ctx context.Context, client *databricks. if err != nil { return fmt.Errorf("loading plan entry %s: %w", resourceKey, err) } + // Stamp the DMS id and version here (see InitForApply doc), not into the saved plan. + if deploymentID != "" { + var stamped bool + switch v := sv.Value.(type) { + case *jobs.JobSettings: + v.Deployment.DeploymentId = deploymentID + v.Deployment.VersionId = versionID + stamped = true + case *dresources.PipelineState: + v.Deployment.DeploymentId = deploymentID + v.Deployment.VersionId = versionID + stamped = true + } + if stamped { + if err := sv.SyncToJSON(entry.NewState); err != nil { + return fmt.Errorf("%s: stamping deployment into loaded plan: %w", resourceKey, err) + } + } + } b.StateCache.Store(resourceKey, sv) } diff --git a/bundle/direct/dstate/dms.go b/bundle/direct/dstate/dms.go new file mode 100644 index 00000000000..c0d4ffb2a7f --- /dev/null +++ b/bundle/direct/dstate/dms.go @@ -0,0 +1,58 @@ +package dstate + +import ( + "encoding/json" + "fmt" + + "github.com/databricks/cli/bundle/deployplan" + "github.com/databricks/cli/libs/dms" +) + +// RecordedState is what the CLI serializes into the DMS operation's state field. It wraps the +// config so depends_on survives the round trip: DMS has no field for dependency edges, and +// nesting them in the config would collide with resource fields of the same name. +type RecordedState struct { + State json.RawMessage `json:"state"` + DependsOn []deployplan.DependsOnEntry `json:"depends_on,omitempty"` +} + +// applyDMSState replaces the file-derived resource state with what DMS recorded. DMS owns the +// resource set outright, so this runs on every recorded open and the file's copy is never read +// back as the truth: an empty set means the service tracks nothing, whether because the deploy +// created nothing or because the deployment is gone. The caller holds db.mu. +func (db *DeploymentState) applyDMSState(recorded []dms.Resource) error { + // Built first and assigned together, so a malformed envelope leaves the state as it was + // rather than half replaced. + resources := make(map[string]ResourceEntry, len(recorded)) + stateIDs := make(map[string]string, len(recorded)) + for _, res := range recorded { + entry, err := stateEntry(res) + if err != nil { + return err + } + resources[res.Key] = entry + stateIDs[res.Key] = entry.ID + } + + db.Data.State = resources + db.stateIDs = stateIDs + return nil +} + +// stateEntry unwraps the envelope the write path recorded for a resource. +func stateEntry(res dms.Resource) (ResourceEntry, error) { + var recorded RecordedState + if res.State != "" { + // The service stores state as an opaque string, so it arrives as the serialized + // envelope the write side sent. + if err := json.Unmarshal([]byte(res.State), &recorded); err != nil { + return ResourceEntry{}, fmt.Errorf("interpreting state recorded for %s: %w", res.Key, err) + } + } + + return ResourceEntry{ + ID: res.ID, + State: recorded.State, + DependsOn: recorded.DependsOn, + }, nil +} diff --git a/bundle/direct/dstate/dms_test.go b/bundle/direct/dstate/dms_test.go new file mode 100644 index 00000000000..8edcf563ee8 --- /dev/null +++ b/bundle/direct/dstate/dms_test.go @@ -0,0 +1,100 @@ +package dstate + +import ( + "encoding/json" + "testing" + + "github.com/databricks/cli/bundle/deployplan" + "github.com/databricks/cli/libs/dms" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestApplyDMSState(t *testing.T) { + // The service stores state as an opaque string, so the envelope the write path sent + // arrives verbatim. + envelope := `{"state":{"name":"foo"},"depends_on":[{"node":"resources.pipelines.bar","label":"${resources.pipelines.bar.id}"}]}` + + // What the file loaded, for the cases that check it is replaced or survives. + fileState := map[string]ResourceEntry{ + "resources.jobs.bar": {ID: "file-id", State: json.RawMessage(`{"name":"from-file"}`)}, + } + + tests := []struct { + name string + existing map[string]ResourceEntry + recorded []dms.Resource + want map[string]ResourceEntry + wantErr string + }{ + { + name: "the envelope is unwrapped, depends_on and all", + recorded: []dms.Resource{ + {Key: "resources.jobs.foo", ID: "123", State: envelope}, + {Key: "resources.pipelines.bar", ID: "456"}, + }, + // depends_on comes back from the envelope, so a bundle whose local state was + // wiped still has the edges needed for delete ordering. + want: map[string]ResourceEntry{ + "resources.jobs.foo": { + ID: "123", + State: json.RawMessage(`{"name":"foo"}`), + DependsOn: []deployplan.DependsOnEntry{{Node: "resources.pipelines.bar", Label: "${resources.pipelines.bar.id}"}}, + }, + "resources.pipelines.bar": {ID: "456"}, + }, + }, + { + name: "what DMS holds replaces what the file loaded", + existing: fileState, + recorded: []dms.Resource{{Key: "resources.jobs.foo", ID: "dms-id", State: `{"state":{"name":"from-dms"}}`}}, + want: map[string]ResourceEntry{"resources.jobs.foo": {ID: "dms-id", State: json.RawMessage(`{"name":"from-dms"}`)}}, + }, + { + // Nil is what a list holding nothing returns, and it means a successful deploy of + // nothing rather than missing data. + name: "nothing recorded empties the state", + existing: fileState, + want: map[string]ResourceEntry{}, + }, + { + // The good resource comes first, so the error lands mid-way: what the file loaded + // has to survive whole rather than end up half replaced. + name: "a malformed envelope leaves the state as it was", + existing: fileState, + recorded: []dms.Resource{ + {Key: "resources.jobs.ok", ID: "999", State: `{"state":{"name":"ok"}}`}, + {Key: "resources.jobs.foo", ID: "123", State: "not json"}, + }, + wantErr: "interpreting state recorded for resources.jobs.foo", + want: fileState, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var db DeploymentState + db.Data.State = tt.existing + db.stateIDs = stateIDsOf(tt.existing) + + err := db.applyDMSState(tt.recorded) + if tt.wantErr != "" { + assert.ErrorContains(t, err, tt.wantErr) + } else { + require.NoError(t, err) + } + + assert.Equal(t, tt.want, db.Data.State) + assert.Equal(t, stateIDsOf(tt.want), db.stateIDs) + }) + } +} + +// stateIDsOf is the id index the state keeps alongside its entries. +func stateIDsOf(entries map[string]ResourceEntry) map[string]string { + ids := make(map[string]string, len(entries)) + for key, entry := range entries { + ids[key] = entry.ID + } + return ids +} diff --git a/bundle/direct/dstate/migrate.go b/bundle/direct/dstate/migrate.go index e4d21a7054a..422ff0e60a1 100644 --- a/bundle/direct/dstate/migrate.go +++ b/bundle/direct/dstate/migrate.go @@ -15,19 +15,25 @@ import ( // migrateState runs all necessary migrations on the database. // It is called after loading state from disk. func migrateState(db *Database) error { - // featureStateVersion states carry a feature list this CLI does not yet write or - // understand (see the featureStateVersion doc comment). A featureStateVersion + // featureStateVersion states carry a feature list this CLI may not recognize + // (see the featureStateVersion doc comment). A featureStateVersion // state with no features is equivalent to currentStateVersion, so accept it and // return without running the migrations below, leaving the on-disk version at - // featureStateVersion rather than flipping it down. One that records any feature - // depends on capabilities this CLI lacks, so refuse it and tell the user to upgrade. + // featureStateVersion rather than flipping it down. One that records an + // unrecognized feature depends on capabilities this CLI lacks, so refuse it and + // tell the user to upgrade. if db.StateVersion == featureStateVersion { if len(db.Features) == 0 { return nil } features := make([]string, 0, len(db.Features)) for name := range db.Features { - features = append(features, name) + if _, ok := recognizedFeatures[name]; !ok { + features = append(features, name) + } + } + if len(features) == 0 { + return nil } slices.Sort(features) return fmt.Errorf("the deployment state requires features this CLI does not support: %s; upgrade to the latest CLI version and see %s for more information", strings.Join(features, ", "), featuresDocURL) diff --git a/bundle/direct/dstate/state.go b/bundle/direct/dstate/state.go index af2e2638eb3..2263a6d02e0 100644 --- a/bundle/direct/dstate/state.go +++ b/bundle/direct/dstate/state.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "io/fs" + "maps" "os" "path/filepath" "sync" @@ -16,6 +17,7 @@ import ( "github.com/databricks/cli/bundle/deployplan" "github.com/databricks/cli/bundle/statemgmt/resourcestate" "github.com/databricks/cli/internal/build" + "github.com/databricks/cli/libs/dms" "github.com/databricks/cli/libs/log" "github.com/google/uuid" ) @@ -28,12 +30,13 @@ const ( maxWalEntrySize = 10 * 1024 * 1024 walSuffix = ".wal" - // featureStateVersion is the schema version a future CLI will write once it - // records deployment state "feature flags" (see Header.Features). This CLI does - // not write it and records no features; it exists now only so this CLI reads - // such states correctly (see migrateState): + // featureStateVersion is the schema version a CLI writes once it + // records deployment state "feature flags" (see Header.Features). This CLI writes + // it for a state that records a feature, and reads such states as follows + // (see migrateState): // - featureStateVersion with no features -> accept and leave the version as-is - // - featureStateVersion with any feature -> refuse, tell the user to upgrade + // - featureStateVersion with recognized features -> accept and leave the version as-is + // - featureStateVersion with any other feature -> refuse, tell the user to upgrade // // A featureStateVersion state with no features is equivalent to // currentStateVersion, but we deliberately do not flip the on-disk version down @@ -47,11 +50,27 @@ const ( // supportedStateVersion is the highest schema version this CLI can read. It is // normally equal to currentStateVersion — the version this CLI reads is the // version it writes — and exceeds it only during a two-phase version bump like - // the current feature-flag scaffolding, where this CLI reads (but does not - // write) featureStateVersion. A state newer than this is rejected as too new. + // the current feature-flag scaffolding, where this CLI writes featureStateVersion + // only for a state that records a feature. A state newer than this is rejected as too new. supportedStateVersion = featureStateVersion ) +// featureRecordDeploymentHistory marks a state whose resources are also recorded with the +// deployment metadata service. Both stores are kept in step, so the marker is what tells a +// reader the two already agree. A CLI that does not know the name refuses the state rather +// than deploying over a deployment it would leave the service out of step with. +// +// The marker is sticky: once a deployment is recorded, the service holds resources that a +// CLI which is not recording must not touch. So turning recording off does not clear it, and +// deploying such a state without recording is refused (see RequiresDeploymentHistory). +const featureRecordDeploymentHistory = "record_deployment_history" + +// recognizedFeatures are the state features this CLI understands. A state recording anything +// outside this set is refused (see migrateState). +var recognizedFeatures = map[string]struct{}{ + featureRecordDeploymentHistory: {}, +} + // featuresDocURL is the single documentation page describing deployment state // feature flags. It is shown when a state records a feature this CLI does not // support; it is a fixed link for all features. The #state-features anchor points @@ -70,6 +89,10 @@ type DeploymentState struct { // Maps resource key to ID. Unlike Data.State, this is up to date during writes (deploys). stateIDs map[string]string + + // operationBuffer records each state write with DMS. Nil unless the bundle records deployment + // history, in which case RegisterOperationBuffer installs it once the version exists. + operationBuffer *dms.OperationBuffer } type Header struct { @@ -84,10 +107,9 @@ type Header struct { Serial int `json:"serial"` // Features maps each feature flag this state depends on to a (currently empty) - // value. This CLI writes no features; it only reads the field to detect a state - // that depends on features it lacks and refuse it (see migrateState). It is a - // map so a future CLI can attach per-feature data without reshaping the state. - // Empty/omitted for states that use no features. + // value. It is read to detect a state that depends on features this CLI lacks and + // refuse it (see migrateState). It is a map so a future CLI can attach per-feature + // data without reshaping the state. Empty/omitted for states that use no features. Features map[string]struct{} `json:"features,omitempty"` } @@ -111,6 +133,51 @@ type WALEntry struct { Value *ResourceEntry `json:"v,omitempty"` // nil means delete } +// RegisterOperationBuffer has every subsequent state write recorded through buf, so what the +// service holds mirrors the WAL. A nil buffer records nothing. Called once the version exists, +// which is why it is not an Open option. +func (db *DeploymentState) RegisterOperationBuffer(buf *dms.OperationBuffer) { + if buf == nil { + return + } + + db.mu.Lock() + defer db.mu.Unlock() + db.operationBuffer = buf +} + +// RecordFailure records that a resource did not apply, so the history says why rather than +// leaving the resource out. resourceID is the id it had before the failure. +func (db *DeploymentState) RecordFailure(resourceKey, resourceID string, cause error) { + r := db.recorder() + if r == nil { + return + } + + // The service refuses a failure that leaves a live resource described by nothing, so re-state + // what it still has. An empty resourceID means there is nothing left: a create that never + // landed, or a recreate whose delete already went through. + var recorded json.RawMessage + if entry, ok := db.GetResourceEntry(resourceKey); resourceID != "" && ok && len(entry.State) > 0 { + var err error + recorded, err = json.Marshal(RecordedState{State: entry.State, DependsOn: entry.DependsOn}) + if err != nil { + // Nothing the caller can act on, so record the failure without the state. + recorded = nil + } + } + + r.RecordFailure(resourceKey, resourceID, recorded, cause) +} + +// recorder reads the buffer under db.mu, which guards it, and returns nil when the bundle does +// not record deployment history. +func (db *DeploymentState) recorder() *dms.OperationBuffer { + db.mu.Lock() + defer db.mu.Unlock() + return db.operationBuffer +} + func NewDatabase(lineage string, serial int) Database { return Database{ Header: Header{ @@ -123,47 +190,81 @@ func NewDatabase(lineage string, serial int) Database { } } -func (db *DeploymentState) SaveState(key, newID string, state any, dependsOn []deployplan.DependsOnEntry) error { +// SaveState records the resource's state after an operation was applied to it. +func (db *DeploymentState) SaveState(ctx context.Context, key, newID string, state any, dependsOn []deployplan.DependsOnEntry) error { db.AssertOpenedForWrite() - db.mu.Lock() - defer db.mu.Unlock() - - if db.Data.State == nil { - db.Data.State = make(map[string]ResourceEntry) - } jsonMessage, err := json.Marshal(state) if err != nil { return err } - entry := ResourceEntry{ ID: newID, State: json.RawMessage(jsonMessage), DependsOn: dependsOn, } + db.mu.Lock() + if db.Data.State == nil { + db.Data.State = make(map[string]ResourceEntry) + } err = appendJSONLine(db.walFile, WALEntry{Key: key, Value: &entry}) if err == nil { db.stateIDs[key] = newID } - return err + buf := db.operationBuffer + db.mu.Unlock() + + if err != nil { + return err + } + if buf == nil { + return nil + } + + // Recorded after the WAL write, so DMS never reports state the deploy failed to persist, + // and outside db.mu because recording waits when the service is behind - waiting under the + // lock would hold up every other resource's write. + recorded, err := json.Marshal(RecordedState{State: entry.State, DependsOn: dependsOn}) + if err != nil { + return err + } + buf.RecordOperation(ctx, key, false, newID, recorded) + + return nil } -func (db *DeploymentState) DeleteState(key string) error { +// DeleteState drops the resource's state entry: the resource is gone. inProgress records the +// operation as unfinished, which is what the first half of a recreate wants - an interrupted +// deploy must not leave the resource described as finished. +func (db *DeploymentState) DeleteState(ctx context.Context, key string, inProgress bool) error { db.AssertOpenedForWrite() - db.mu.Lock() - defer db.mu.Unlock() + db.mu.Lock() if db.Data.State == nil { + db.mu.Unlock() return nil } - + // Read before the delete: DMS needs the id to say which resource went away. + deletedID := db.stateIDs[key] err := appendJSONLine(db.walFile, WALEntry{Key: key}) if err == nil { delete(db.stateIDs, key) } - return err + buf := db.operationBuffer + db.mu.Unlock() + + if err != nil { + return err + } + + // State is nil: the resource no longer exists. Recorded outside the lock for the + // same reason as SaveState. + if buf != nil { + buf.RecordOperation(ctx, key, inProgress, deletedID, nil) + } + + return nil } func (db *DeploymentState) GetResourceEntry(key string) (ResourceEntry, bool) { @@ -201,6 +302,18 @@ func (db *DeploymentState) StateCLIVersion() string { return db.Data.CLIVersion } +// RequiresDeploymentHistory reports whether the state depends on the deployment metadata +// service recording it. Deploying such a state without recording would leave the service +// holding a deployment that no longer matches, so the caller refuses instead. +func (db *DeploymentState) RequiresDeploymentHistory() bool { + db.AssertOpenedForReadOrWrite() + db.mu.Lock() + defer db.mu.Unlock() + + _, ok := db.Data.Features[featureRecordDeploymentHistory] + return ok +} + // GetOrInitLineage returns the deployment lineage, generating and storing a new // one if the state does not have one yet. It is the single place the lineage is // initialized, shared so the direct deployment engine (when it writes state, via @@ -230,7 +343,12 @@ type ( WithWrite bool ) -func (db *DeploymentState) Open(ctx context.Context, path string, withRecovery WithRecovery, withWrite WithWrite) error { +// Open reads the deployment state from disk, recovering the WAL when withRecovery is set. +// With a non-nil dmsClient the resources come from DMS instead, and dmsDeploymentID is the id +// the service holds for the deployment, empty before its first recorded deploy; lineage and +// serial still come from the file, since that is what the write path increments. Open only reads +// through the client - RegisterOperationBuffer installs the write path, once a version exists. +func (db *DeploymentState) Open(ctx context.Context, path string, withRecovery WithRecovery, withWrite WithWrite, dmsClient *dms.Client, dmsDeploymentID string) error { db.mu.Lock() defer db.mu.Unlock() @@ -238,7 +356,7 @@ func (db *DeploymentState) Open(ctx context.Context, path string, withRecovery W panic(fmt.Sprintf("state already opened: %v, cannot open %v", db.Path, path)) } - err := db.unlockedOpen(ctx, path, withRecovery, withWrite) + err := db.unlockedOpen(ctx, path, withRecovery, withWrite, dmsClient, dmsDeploymentID) if err != nil { // A failed open must leave the receiver closed. unlockedOpen assigns // db.Path before every fallible step, so without this the receiver stays @@ -260,7 +378,7 @@ func (db *DeploymentState) reset() { db.stateIDs = nil } -func (db *DeploymentState) unlockedOpen(ctx context.Context, path string, withRecovery WithRecovery, withWrite WithWrite) error { +func (db *DeploymentState) unlockedOpen(ctx context.Context, path string, withRecovery WithRecovery, withWrite WithWrite, dmsClient *dms.Client, dmsDeploymentID string) error { db.Path = path data, err := os.ReadFile(db.Path) if err != nil { @@ -280,6 +398,12 @@ func (db *DeploymentState) unlockedOpen(ctx context.Context, path string, withRe db.stateIDs[key] = entry.ID } + // Read off the committed file, before the WAL replay below changes it. Resources the WAL adds + // come from a deploy that was already recording, so they are not resources the service never + // saw; see the guard in the dmsClient block below. + _, fileRecorded := db.Data.Features[featureRecordDeploymentHistory] + fileHasResources := len(db.Data.State) > 0 + walPath := db.Path + walSuffix _, err = os.Stat(walPath) switch { @@ -301,6 +425,49 @@ func (db *DeploymentState) unlockedOpen(ctx context.Context, path string, withRe return fmt.Errorf("migrating state %s: %w", path, err) } + if dmsClient != nil { + // Only empty bundles can be recorded. Once DMS owns the deployment, pre-existing + // resources it never saw would be created again. TODO: support migration via state + // upgrade with feature flag and per-resource tombstones. + // + // The resources have to be ones the committed file tracked without recording them, and + // still tracks after recovery: a WAL that deletes them leaves nothing to clash with. The + // check cannot key off the deployment resolving instead - a deployment can exist while + // the file tracks resources it never recorded (an empty first recorded deploy creates one + // and writes no state), and applyDMSState below would then silently drop them. + if !fileRecorded && fileHasResources && len(db.Data.State) > 0 { + // The remedy is ordered deliberately: this error also blocks destroy, so the + // setting has to come out first or there is no way to tear the bundle down. + return fmt.Errorf(`cannot record deployment history for a bundle that already has deployed resources tracked in %s: only new deployments can be recorded + +To record this bundle's history, start it over as a new deployment: + 1. remove experimental.record_deployment_history from your bundle configuration + 2. run "databricks bundle destroy" to delete the existing resources + 3. add experimental.record_deployment_history back and deploy again + +To keep the existing resources instead, unset experimental.record_deployment_history`, path) + } + + // Mark the state as depending on the service: a CLI that does not recognize the feature + // refuses it (see migrateState) instead of deploying over the deployment and leaving the + // service behind. unlockedSave then writes the header alone. + db.Data.StateVersion = featureStateVersion + if db.Data.Features == nil { + db.Data.Features = make(map[string]struct{}, 1) + } + db.Data.Features[featureRecordDeploymentHistory] = struct{}{} + + if dmsDeploymentID != "" { + recorded, err := dmsClient.ListResources(ctx, dmsDeploymentID) + if err != nil { + return err + } + if err := db.applyDMSState(recorded); err != nil { + return err + } + } + } + if withWrite { if err := os.MkdirAll(filepath.Dir(walPath), 0o755); err != nil { return fmt.Errorf("failed to create state directory: %w", err) @@ -405,6 +572,7 @@ func (db *DeploymentState) mergeWalIntoState(ctx context.Context) (bool, error) if header.Serial > expectedSerial { return false, fmt.Errorf("WAL serial (%d) is ahead of expected (%d), state may be corrupted", header.Serial, expectedSerial) } + newSerial = header.Serial newCLIVersion = header.CLIVersion } else { @@ -604,7 +772,7 @@ func (db *DeploymentState) ExportState(ctx context.Context) resourcestate.Export // the WAL. A torn write would therefore leave a state file that Open rejects // next to an intact WAL it never reads. func (db *DeploymentState) unlockedSave() error { - data, err := json.MarshalIndent(db.Data, "", " ") + data, err := json.MarshalIndent(db.dataToPersist(), "", " ") if err != nil { return err } @@ -640,6 +808,28 @@ func (db *DeploymentState) unlockedSave() error { return nil } +// dataToPersist returns what the state file should hold: db.Data itself, unless the deployment +// records its history, in which case it is the header alone. The service holds those resources and +// is where they are read back from, so writing them here too would be a second, never-read copy. +// Returns a copy, leaving the in-memory state - what the rest of the deploy works from - untouched. +func (db *DeploymentState) dataToPersist() Database { + data := db.Data + if _, recorded := data.Features[featureRecordDeploymentHistory]; !recorded { + return data + } + + // A destroy leaves nothing recorded, so the marker has nothing left to protect. Keeping it + // would refuse every later deploy that does not record, with no way back. + if len(data.State) == 0 { + data.Features = maps.Clone(data.Features) + delete(data.Features, featureRecordDeploymentHistory) + return data + } + + data.State = map[string]ResourceEntry{} + return data +} + func appendJSONLine(file *os.File, obj any) error { data, err := json.Marshal(obj) if err != nil { diff --git a/bundle/direct/dstate/state_test.go b/bundle/direct/dstate/state_test.go index 34ed9ff1c5a..c54370d5536 100644 --- a/bundle/direct/dstate/state_test.go +++ b/bundle/direct/dstate/state_test.go @@ -21,14 +21,14 @@ func TestOpenSaveFinalizeRoundTrip(t *testing.T) { path := filepath.Join(t.TempDir(), "state.json") var db DeploymentState - require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true))) + require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true), nil, "")) - require.NoError(t, db.SaveState("jobs.my_job", "123", map[string]string{"key": "val"}, nil)) + require.NoError(t, db.SaveState(t.Context(), "jobs.my_job", "123", map[string]string{"key": "val"}, nil)) mustFinalize(t, &db) // Re-open and verify persisted data. var db2 DeploymentState - require.NoError(t, db2.Open(t.Context(), path, WithRecovery(false), WithWrite(false))) + require.NoError(t, db2.Open(t.Context(), path, WithRecovery(false), WithWrite(false), nil, "")) assert.Equal(t, 1, db2.Data.Serial) assert.Equal(t, "123", db2.GetResourceID("jobs.my_job")) mustFinalize(t, &db2) @@ -38,7 +38,7 @@ func TestFinalizeWithNoEntriesDoesNotWriteStateFile(t *testing.T) { path := filepath.Join(t.TempDir(), "state.json") var db DeploymentState - require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true))) + require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true), nil, "")) mustFinalize(t, &db) _, err := os.Stat(path) @@ -94,10 +94,10 @@ func TestPanicOnDoubleOpen(t *testing.T) { path := filepath.Join(t.TempDir(), "state.json") var db DeploymentState - require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true))) + require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true), nil, "")) assert.Panics(t, func() { - _ = db.Open(t.Context(), path, WithRecovery(true), WithWrite(true)) + _ = db.Open(t.Context(), path, WithRecovery(true), WithWrite(true), nil, "") }) mustFinalize(t, &db) } @@ -115,12 +115,12 @@ func TestCLIVersionRecordsLastWriter(t *testing.T) { require.NoError(t, os.WriteFile(path, []byte(seed), 0o600)) var db DeploymentState - require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true))) - require.NoError(t, db.SaveState("resources.jobs.my_job", "123", map[string]string{"k": "v"}, nil)) + require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true), nil, "")) + require.NoError(t, db.SaveState(t.Context(), "resources.jobs.my_job", "123", map[string]string{"k": "v"}, nil)) mustFinalize(t, &db) var reopened DeploymentState - require.NoError(t, reopened.Open(t.Context(), path, WithRecovery(false), WithWrite(false))) + require.NoError(t, reopened.Open(t.Context(), path, WithRecovery(false), WithWrite(false), nil, "")) assert.Equal(t, build.GetInfo().Version, reopened.Data.CLIVersion) assert.Equal(t, 2, reopened.Data.Serial) mustFinalize(t, &reopened) @@ -142,7 +142,7 @@ func TestHeaderOnlyWALDoesNotUpdateCLIVersion(t *testing.T) { require.NoError(t, os.WriteFile(walPath, append(headerLine, '\n'), 0o600)) var recovered DeploymentState - require.NoError(t, recovered.Open(t.Context(), path, WithRecovery(true), WithWrite(false))) + require.NoError(t, recovered.Open(t.Context(), path, WithRecovery(true), WithWrite(false), nil, "")) assert.Equal(t, "0.1.2", recovered.Data.CLIVersion, "a header-only WAL wrote no state, so the version must not move") assert.Equal(t, 1, recovered.Data.Serial) mustFinalize(t, &recovered) @@ -154,12 +154,12 @@ func TestHeaderOnlyWALRecoveryDoesNotAdvanceSerial(t *testing.T) { // Commit serial 1 with one resource. var db DeploymentState - require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true))) - require.NoError(t, db.SaveState("jobs.my_job", "123", map[string]string{}, nil)) + require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true), nil, "")) + require.NoError(t, db.SaveState(t.Context(), "jobs.my_job", "123", map[string]string{}, nil)) mustFinalize(t, &db) var committed DeploymentState - require.NoError(t, committed.Open(t.Context(), path, WithRecovery(false), WithWrite(false))) + require.NoError(t, committed.Open(t.Context(), path, WithRecovery(false), WithWrite(false), nil, "")) lineage := committed.Data.Lineage require.Equal(t, 1, committed.Data.Serial) mustFinalize(t, &committed) @@ -175,7 +175,7 @@ func TestHeaderOnlyWALRecoveryDoesNotAdvanceSerial(t *testing.T) { require.NoError(t, os.WriteFile(walPath, append(headerLine, '\n'), 0o600)) var recovered DeploymentState - require.NoError(t, recovered.Open(t.Context(), path, WithRecovery(true), WithWrite(false))) + require.NoError(t, recovered.Open(t.Context(), path, WithRecovery(true), WithWrite(false), nil, "")) assert.Equal(t, 1, recovered.Data.Serial) assert.Equal(t, "123", recovered.GetResourceID("jobs.my_job")) assert.NoFileExists(t, walPath) @@ -185,7 +185,7 @@ func TestHeaderOnlyWALRecoveryDoesNotAdvanceSerial(t *testing.T) { // TestEmptyFeatureStateAcceptedWithoutFlippingVersion pins the special case that a // featureStateVersion state with no features is accepted as-is — the on-disk version // is left at featureStateVersion, not flipped down to currentStateVersion — and that -// a featureStateVersion state recording any feature is refused. This is scaffolding +// a featureStateVersion state recording an unrecognized feature is refused. This is scaffolding // for the deferred version bump, special-cased to featureStateVersion only (see the // featureStateVersion doc comment). // @@ -201,7 +201,7 @@ func TestEmptyFeatureStateAcceptedWithoutFlippingVersion(t *testing.T) { require.NoError(t, migrateState(empty)) assert.Equal(t, featureStateVersion, empty.StateVersion, "v3 + no features keeps its on-disk version, not flipped to v2") - // v3 that records a feature is refused: this CLI does not understand features. + // v3 that records an unrecognized feature is refused. withFeature := &Database{Header: Header{ StateVersion: featureStateVersion, Features: map[string]struct{}{"future_feature": {}}, @@ -214,21 +214,83 @@ func TestEmptyFeatureStateAcceptedWithoutFlippingVersion(t *testing.T) { assert.Contains(t, err.Error(), featuresDocURL) } +// TestSupportedFeatureAcceptedUnknownOneNamed covers the features this CLI does write: +// a state recording only those loads, and an unsupported feature alongside one of them +// is still refused — naming only the feature the user has to upgrade for. +func TestSupportedFeatureAcceptedUnknownOneNamed(t *testing.T) { + supported := &Database{Header: Header{ + StateVersion: featureStateVersion, + Features: map[string]struct{}{featureRecordDeploymentHistory: {}}, + }} + require.NoError(t, migrateState(supported)) + assert.Equal(t, featureStateVersion, supported.StateVersion) + assert.Contains(t, supported.Features, featureRecordDeploymentHistory, "a supported feature is left on the state, not stripped") + + mixed := &Database{Header: Header{ + StateVersion: featureStateVersion, + Features: map[string]struct{}{featureRecordDeploymentHistory: {}, "future_feature": {}}, + }} + err := migrateState(mixed) + require.Error(t, err) + assert.Contains(t, err.Error(), "future_feature") + assert.NotContains(t, err.Error(), featureRecordDeploymentHistory) +} + +// TestDataToPersistOnlyStripsRecordedState pins that the header-only write is scoped to a +// recorded deployment: an ordinary one persists its resources untouched. It also pins that the +// in-memory state survives, since the rest of the deploy reads from it. +func TestDataToPersistOnlyStripsRecordedState(t *testing.T) { + entries := map[string]ResourceEntry{ + "resources.jobs.my_job": {ID: "123", State: json.RawMessage(`{"name":"n"}`)}, + } + + var plain DeploymentState + plain.Data = NewDatabase("test-lineage", 1) + plain.Data.State = entries + assert.Equal(t, entries, plain.dataToPersist().State, "an unrecorded deployment persists its resources") + + var recorded DeploymentState + recorded.Data = NewDatabase("test-lineage", 1) + recorded.Data.State = entries + recorded.Data.StateVersion = featureStateVersion + recorded.Data.Features = map[string]struct{}{featureRecordDeploymentHistory: {}} + + persisted := recorded.dataToPersist() + assert.Empty(t, persisted.State, "a recorded deployment persists the header alone") + assert.Equal(t, featureStateVersion, persisted.StateVersion) + assert.Contains(t, persisted.Features, featureRecordDeploymentHistory) + assert.Equal(t, entries, recorded.Data.State, "the in-memory state is what the deploy reads, so it must not be cleared") +} + +// TestDataToPersistDropsMarkerWhenNothingIsRecorded pins that a recorded state which has lost its +// last resource - what a destroy leaves behind - stops recording the feature. Keeping it would +// refuse every later deploy that does not record, with nothing left for the marker to protect. +func TestDataToPersistDropsMarkerWhenNothingIsRecorded(t *testing.T) { + var db DeploymentState + db.Data = NewDatabase("test-lineage", 1) + db.Data.StateVersion = featureStateVersion + db.Data.Features = map[string]struct{}{featureRecordDeploymentHistory: {}} + + persisted := db.dataToPersist() + assert.NotContains(t, persisted.Features, featureRecordDeploymentHistory) + assert.Contains(t, db.Data.Features, featureRecordDeploymentHistory, "the in-memory copy is untouched") +} + func TestDeleteState(t *testing.T) { path := filepath.Join(t.TempDir(), "state.json") var db DeploymentState - require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true))) - require.NoError(t, db.SaveState("jobs.my_job", "123", map[string]string{}, nil)) + require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true), nil, "")) + require.NoError(t, db.SaveState(t.Context(), "jobs.my_job", "123", map[string]string{}, nil)) mustFinalize(t, &db) var db2 DeploymentState - require.NoError(t, db2.Open(t.Context(), path, WithRecovery(true), WithWrite(true))) - require.NoError(t, db2.DeleteState("jobs.my_job")) + require.NoError(t, db2.Open(t.Context(), path, WithRecovery(true), WithWrite(true), nil, "")) + require.NoError(t, db2.DeleteState(t.Context(), "jobs.my_job", false)) mustFinalize(t, &db2) var db3 DeploymentState - require.NoError(t, db3.Open(t.Context(), path, WithRecovery(false), WithWrite(false))) + require.NoError(t, db3.Open(t.Context(), path, WithRecovery(false), WithWrite(false), nil, "")) assert.Equal(t, 2, db3.Data.Serial) assert.Empty(t, db3.GetResourceID("jobs.my_job")) mustFinalize(t, &db3) @@ -240,7 +302,7 @@ func TestGetOrInitLineageReadableBeforeWriteAndPersisted(t *testing.T) { // Fresh state opened read-only, as the deploy does before planning: no // lineage yet. var db DeploymentState - require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(false))) + require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(false), nil, "")) require.Empty(t, db.Data.Lineage) // GetOrInitLineage initializes the lineage and makes it readable before any @@ -252,12 +314,12 @@ func TestGetOrInitLineageReadableBeforeWriteAndPersisted(t *testing.T) { // Upgrading to write reuses the same lineage (it goes into the WAL header), // and a write makes it durable. require.NoError(t, db.UpgradeToWrite()) - require.NoError(t, db.SaveState("jobs.my_job", "123", map[string]string{}, nil)) + require.NoError(t, db.SaveState(t.Context(), "jobs.my_job", "123", map[string]string{}, nil)) mustFinalize(t, &db) // Re-open: the persisted lineage matches the one read before the write. var reopened DeploymentState - require.NoError(t, reopened.Open(t.Context(), path, WithRecovery(false), WithWrite(false))) + require.NoError(t, reopened.Open(t.Context(), path, WithRecovery(false), WithWrite(false), nil, "")) assert.Equal(t, lineage, reopened.Data.Lineage) mustFinalize(t, &reopened) } @@ -271,13 +333,13 @@ func TestOpenFailureLeavesStateClosed(t *testing.T) { require.NoError(t, os.WriteFile(path, []byte("{not json"), 0o600)) var db DeploymentState - require.Error(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true))) + require.Error(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true), nil, "")) assert.Empty(t, db.Path) // Once the state file is readable, the same receiver opens without panicking. seed := `{"state_version":2,"cli_version":"0.1.2","lineage":"test-lineage","serial":1,"state":{}}` require.NoError(t, os.WriteFile(path, []byte(seed), 0o600)) - require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true))) + require.NoError(t, db.Open(t.Context(), path, WithRecovery(true), WithWrite(true), nil, "")) assert.Equal(t, "test-lineage", db.Data.Lineage) mustFinalize(t, &db) } diff --git a/bundle/direct/pkg.go b/bundle/direct/pkg.go index ea7ae1e51b6..764397d5fc3 100644 --- a/bundle/direct/pkg.go +++ b/bundle/direct/pkg.go @@ -11,6 +11,7 @@ import ( "github.com/databricks/cli/bundle/direct/dresources" "github.com/databricks/cli/bundle/direct/dstate" "github.com/databricks/cli/bundle/statemgmt/resourcestate" + "github.com/databricks/cli/libs/dms" "github.com/databricks/cli/libs/structs/structvar" ) @@ -50,6 +51,13 @@ type DeploymentBundle struct { Plan *deployplan.Plan RemoteStateCache sync.Map StateCache structvar.Cache + + // DMS carries deployment-history recording across the phases; nil unless the bundle records + // history. DmsApiClient is set where the state is opened. The deployment id and version live + // in bundle.deployment.history, not here. DmsAsyncOperationClient is opened once the deploy + // phase creates the version, and Apply drains it before returning. + DmsApiClient *dms.Client + DmsAsyncOperationClient *dms.OperationBuffer } // SetRemoteState updates the remote state with type validation and marks as fresh. diff --git a/bundle/env/dms.go b/bundle/env/dms.go new file mode 100644 index 00000000000..1e5002e0960 --- /dev/null +++ b/bundle/env/dms.go @@ -0,0 +1,23 @@ +package env + +import "context" + +// RecordDeploymentHistoryVariable enables recording without setting the config field. +// Exists for CLI acceptance tests so the whole bundle suite runs with recording on. +// Deliberately undocumented; see validate.ValidateRecordDeploymentHistory. +const RecordDeploymentHistoryVariable = "DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY" + +// RecordDeploymentHistoryEnv reports whether the environment turns on deployment history +// recording. Only "true" turns it on: anything else - including a typo like "TRUE" or "yes" - +// leaves a gated feature off rather than silently enabling it. Setting it is also what permits +// the otherwise-gated experimental.record_deployment_history (see validate.ValidateRecordDeploymentHistory). +func RecordDeploymentHistoryEnv(ctx context.Context) bool { + value, _ := get(ctx, []string{RecordDeploymentHistoryVariable}) + return value == "true" +} + +// RecordsDeploymentHistory reports whether recording is on, from config or env var. +// Single predicate for all recording code paths; keeps them in sync. +func RecordsDeploymentHistory(ctx context.Context, configured bool) bool { + return configured || RecordDeploymentHistoryEnv(ctx) +} diff --git a/bundle/env/dms_test.go b/bundle/env/dms_test.go new file mode 100644 index 00000000000..15bfe0e63f0 --- /dev/null +++ b/bundle/env/dms_test.go @@ -0,0 +1,41 @@ +package env + +import ( + "testing" + + "github.com/databricks/cli/libs/env" + "github.com/stretchr/testify/assert" +) + +func TestRecordDeploymentHistoryEnv(t *testing.T) { + for _, tc := range []struct { + value string + want bool + }{ + {"true", true}, + {"", false}, + {"0", false}, + {"false", false}, + // Only "true" counts, so a near miss leaves recording off. + {"1", false}, + {"TRUE", false}, + {"yes", false}, + } { + ctx := env.Set(t.Context(), RecordDeploymentHistoryVariable, tc.value) + assert.Equal(t, tc.want, RecordDeploymentHistoryEnv(ctx), "value %q", tc.value) + } +} + +func TestRecordDeploymentHistoryEnvUnset(t *testing.T) { + assert.False(t, RecordDeploymentHistoryEnv(t.Context())) +} + +func TestRecordsDeploymentHistory(t *testing.T) { + // The bundle setting alone is enough, and so is the environment; the env var + // exists so the acceptance suite can record without touching every databricks.yml. + assert.True(t, RecordsDeploymentHistory(t.Context(), true)) + assert.False(t, RecordsDeploymentHistory(t.Context(), false)) + + ctx := env.Set(t.Context(), RecordDeploymentHistoryVariable, "true") + assert.True(t, RecordsDeploymentHistory(ctx, false)) +} diff --git a/bundle/migrate/build_state.go b/bundle/migrate/build_state.go index e8b382b370d..7afa577ba8c 100644 --- a/bundle/migrate/build_state.go +++ b/bundle/migrate/build_state.go @@ -205,7 +205,7 @@ func BuildStateFromTF( } } - if err := stateDB.SaveState(node, id, sv.Value, dependsOn); err != nil { + if err := stateDB.SaveState(ctx, node, id, sv.Value, dependsOn); err != nil { return warningsSeen, fmt.Errorf("%s: SaveState: %w", node, err) } } diff --git a/bundle/phases/bind.go b/bundle/phases/bind.go index 81f110f5095..b3023e83991 100644 --- a/bundle/phases/bind.go +++ b/bundle/phases/bind.go @@ -33,6 +33,11 @@ func Bind(ctx context.Context, b *bundle.Bundle, opts *terraform.BindOptions, en }() if engine.IsDirect() { + if b.RecordsDeploymentHistory(ctx) { + logdiag.LogError(ctx, errors.New("bind is not supported for a bundle that records deployment history")) + return + } + // Direct engine: import into temp state, run plan, check for changes // This follows the same pattern as terraform import groupName, ok := terraform.TerraformToGroupName[opts.ResourceType] @@ -94,7 +99,8 @@ func Bind(ctx context.Context, b *bundle.Bundle, opts *terraform.BindOptions, en } } else { // Terraform engine: use terraform import - bundle.ApplySeqContext(ctx, b, + bundle.ApplySeqContext( + ctx, b, terraform.Interpolate(), terraform.Write(), terraform.Import(opts), @@ -129,6 +135,11 @@ func Unbind(ctx context.Context, b *bundle.Bundle, bundleType, tfResourceType, r }() if engine.IsDirect() { + if b.RecordsDeploymentHistory(ctx) { + logdiag.LogError(ctx, errors.New("unbind is not supported for a bundle that records deployment history")) + return + } + groupName, ok := terraform.TerraformToGroupName[tfResourceType] if !ok { groupName = tfResourceType @@ -141,7 +152,8 @@ func Unbind(ctx context.Context, b *bundle.Bundle, bundleType, tfResourceType, r return } } else { - bundle.ApplySeqContext(ctx, b, + bundle.ApplySeqContext( + ctx, b, terraform.Interpolate(), terraform.Write(), terraform.Unbind(bundleType, tfResourceType, resourceKey), diff --git a/bundle/phases/deploy.go b/bundle/phases/deploy.go index f16088e4518..e089c976419 100644 --- a/bundle/phases/deploy.go +++ b/bundle/phases/deploy.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "slices" + "strconv" "strings" "github.com/databricks/cli/bundle" @@ -26,9 +27,11 @@ import ( "github.com/databricks/cli/bundle/statemgmt" "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/dms" "github.com/databricks/cli/libs/log" "github.com/databricks/cli/libs/logdiag" "github.com/databricks/cli/libs/sync" + "github.com/databricks/databricks-sdk-go/service/bundledeployments" ) var deployApprovalGroups = []approvalGroup{ @@ -110,7 +113,8 @@ func deployCore(ctx context.Context, b *bundle.Bundle, plan *deployplan.Plan, st return } - bundle.ApplySeqContext(ctx, b, + bundle.ApplySeqContext( + ctx, b, statemgmt.Load(state), metadata.Compute(), metadata.Upload(), @@ -168,7 +172,8 @@ func logDeploySummary(ctx context.Context, b *bundle.Bundle, plan *deployplan.Pl // It also cleans up the artifacts directory and transforms wheel tasks. // It is called by only "bundle deploy". func uploadLibraries(ctx context.Context, b *bundle.Bundle, libs map[string][]libraries.LocationToUpdate) { - bundle.ApplySeqContext(ctx, b, + bundle.ApplySeqContext( + ctx, b, artifacts.CleanUp(), libraries.Upload(libs), ) @@ -179,12 +184,13 @@ func uploadLibraries(ctx context.Context, b *bundle.Bundle, libs map[string][]li // stateEngine is the engine the resolved state file uses; requestedEngine is // what bundle.engine / DATABRICKS_BUNDLE_ENGINE asked for and may differ (used // only by the post-deploy migration check). -func Deploy(ctx context.Context, b *bundle.Bundle, outputHandler sync.OutputHandler, stateEngine engine.EngineType, requestedEngine engine.EngineSetting, libs map[string][]libraries.LocationToUpdate, plan *deployplan.Plan) { +func Deploy(ctx context.Context, b *bundle.Bundle, outputHandler sync.OutputHandler, stateEngine engine.EngineType, requestedEngine engine.EngineSetting, libs map[string][]libraries.LocationToUpdate, plan *deployplan.Plan, dmsDeployment *bundledeployments.Deployment) { log.Info(ctx, "Phase: deploy") // Core mutators that CRUD resources and modify deployment state. These // mutators need informed consent if they are potentially destructive. - bundle.ApplySeqContext(ctx, b, + bundle.ApplySeqContext( + ctx, b, scripts.Execute(config.ScriptPreDeploy), lock.Acquire(lock.GoalDeploy), ) @@ -195,7 +201,13 @@ func Deploy(ctx context.Context, b *bundle.Bundle, outputHandler sync.OutputHand } // lock is acquired here + // + // The version is created only after approval; CompleteVersion is deferred before + // lock.Release and no-ops until then. defer func() { + if _, err := drainOperationsAndCompleteVersion(ctx, b, !logdiag.HasError(ctx)); err != nil { + logdiag.LogError(ctx, err) + } bundle.ApplyContext(ctx, b, lock.Release(lock.GoalDeploy)) }() @@ -209,7 +221,8 @@ func Deploy(ctx context.Context, b *bundle.Bundle, outputHandler sync.OutputHand // Upload all source files and built artifacts as a single immutable snapshot. // snapshot.Upload() sets workspace.snapshot_path; the variable-resolution // pass expands ${workspace.snapshot_path} placeholders written by translate_paths. - bundle.ApplySeqContext(ctx, b, + bundle.ApplySeqContext( + ctx, b, snapshot.Upload(), mutator.ResolveVariableReferencesOnlyResources("workspace"), ) @@ -246,7 +259,8 @@ func Deploy(ctx context.Context, b *bundle.Bundle, outputHandler sync.OutputHand } }() - bundle.ApplySeqContext(ctx, b, + bundle.ApplySeqContext( + ctx, b, deploy.StateUpdate(), deploy.StatePush(), permissions.ApplyWorkspaceRootPermissions(), @@ -259,6 +273,23 @@ func Deploy(ctx context.Context, b *bundle.Bundle, outputHandler sync.OutputHand } planFromFile := plan != nil + if b.DeploymentBundle.DmsApiClient != nil { + // Create the deployment before planning so it exists to stamp. + createOrUpdateDeployment(ctx, b, dmsDeployment) + if logdiag.HasError(ctx) { + return + } + // A normal deploy stamps id + version onto the config, off the plan, so RunPlan carries them + // into the applied plan; deploy --plan stamps the loaded plan in InitForApply below instead. + if !planFromFile { + deploymentID, version := recordedDeployment(b) + bundle.ApplySeqContext(ctx, b, metadata.AnnotateDeployment(deploymentID), metadata.AnnotateDeploymentVersion(version)) + if logdiag.HasError(ctx) { + return + } + } + } + if plan == nil { // State is already open for read by process.go (for direct engine) plan = RunPlan(ctx, b, stateEngine) @@ -280,8 +311,10 @@ func Deploy(ctx context.Context, b *bundle.Bundle, outputHandler sync.OutputHand } if planFromFile { - // Initialize DeploymentBundle for applying the loaded plan - err := b.DeploymentBundle.InitForApply(ctx, b.WorkspaceClient(ctx), plan) + // Stamp the deployment id and version onto the loaded plan here, not into the saved plan. + // Non-recording deploys pass "" and stamp nothing. + deploymentID, version := recordedDeployment(b) + err := b.DeploymentBundle.InitForApply(ctx, b.WorkspaceClient(ctx), plan, deploymentID, strconv.FormatInt(version, 10)) if err != nil { logdiag.LogError(ctx, err) return @@ -295,17 +328,35 @@ func Deploy(ctx context.Context, b *bundle.Bundle, outputHandler sync.OutputHand return } - haveApproval, err := approvalForDeploy(ctx, b, plan) + haveApproval, approvalErr := approvalForDeploy(ctx, b, plan) + if !haveApproval { + // No version was created, so the deferred CompleteVersion is a no-op and the version + // number is left for the next deploy. Both the user declining and a console that + // cannot prompt land here. + if approvalErr != nil { + logdiag.LogError(ctx, approvalErr) + return + } + cmdio.LogString(ctx, "Deployment cancelled!") + return + } + + // Create the version the plan was stamped with, staging an operation for every resource + // it touches. Doing it here rather than before the prompt means a declined deploy never + // claims a version number. + staged, err := stagedOperations(plan) if err != nil { logdiag.LogError(ctx, err) return } - if haveApproval { - deployCore(ctx, b, plan, stateEngine) - } else { - cmdio.LogString(ctx, "Deployment cancelled!") + if err := startVersion(ctx, b, dms.VersionTypeDeploy, staged); err != nil { + logdiag.LogError(ctx, err) return } + deploymentID, versionID := recordedDeployment(b) + logDeploymentVersion(ctx, b, deploymentID, versionID) + + deployCore(ctx, b, plan, stateEngine) if logdiag.HasError(ctx) { return @@ -358,7 +409,8 @@ func RunPlan(ctx context.Context, b *bundle.Bundle, engine engine.EngineType) *d // b.Select is rejected for the terraform engine in ProcessBundleRet, so it is // never set here. - bundle.ApplySeqContext(ctx, b, + bundle.ApplySeqContext( + ctx, b, terraform.Interpolate(), terraform.Write(), terraform.Plan(terraform.PlanGoal("deploy")), diff --git a/bundle/phases/destroy.go b/bundle/phases/destroy.go index 201c3928e28..17cd755eed4 100644 --- a/bundle/phases/destroy.go +++ b/bundle/phases/destroy.go @@ -16,6 +16,7 @@ import ( "github.com/databricks/cli/bundle/deployplan" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/diag" + "github.com/databricks/cli/libs/dms" "github.com/databricks/cli/libs/log" "github.com/databricks/cli/libs/logdiag" "github.com/databricks/databricks-sdk-go/apierr" @@ -158,6 +159,21 @@ func destroyCore(ctx context.Context, b *bundle.Bundle, plan *deployplan.Plan, e return } + // Complete version before deleting remote files; the deployment node is under statePath. + completed, err := drainOperationsAndCompleteVersion(ctx, b, true) + if err != nil { + logdiag.LogError(ctx, err) + return + } + // A completed destroy's resources are gone, so its deployment record is deleted too. + if completed { + deploymentID, _ := recordedDeployment(b) + if err := b.DeploymentBundle.DmsApiClient.DeleteDeployment(ctx, deploymentID); err != nil { + logdiag.LogError(ctx, fmt.Errorf("failed to delete deployment: %w", err)) + return + } + } + bundle.ApplyContext(ctx, b, files.Delete()) if !logdiag.HasError(ctx) && b.Quiet < bundle.QuietAll { @@ -196,12 +212,26 @@ func Destroy(ctx context.Context, b *bundle.Bundle, engine engine.EngineType) { return } + // DMS recording of this destroy: the version is created after approval, so a cancelled + // destroy records nothing. Deferred before lock.Release to hold the lock; a no-op once + // destroyCore has completed the version. defer func() { + completed, err := drainOperationsAndCompleteVersion(ctx, b, !logdiag.HasError(ctx)) + if err != nil { + logdiag.LogError(ctx, err) + } else if completed { + // A completed destroy's resources are gone, so its deployment record is deleted too. + deploymentID, _ := recordedDeployment(b) + if err := b.DeploymentBundle.DmsApiClient.DeleteDeployment(ctx, deploymentID); err != nil { + logdiag.LogError(ctx, fmt.Errorf("failed to delete deployment: %w", err)) + } + } bundle.ApplyContext(ctx, b, lock.Release(lock.GoalDestroy)) }() if !engine.IsDirect() { - bundle.ApplySeqContext(ctx, b, + bundle.ApplySeqContext( + ctx, b, // We need to resolve artifact variable (how we do it in build phase) // because some of the to-be-destroyed resource might use this variable. // Not resolving might lead to terraform "Reference to undeclared resource" error @@ -253,6 +283,22 @@ func Destroy(ctx context.Context, b *bundle.Bundle, engine engine.EngineType) { return } } + // Record a destroy version now that it is approved and the state WAL is open, but only + // under a deployment that already exists: a missing one was already cleaned up (or the + // bundle does not record history). Destroy never creates or updates the deployment - it + // is about to be deleted. + deploymentID, _ := recordedDeployment(b) + if b.DeploymentBundle.DmsApiClient != nil && deploymentID != "" { + staged, err := stagedOperations(plan) + if err != nil { + logdiag.LogError(ctx, err) + return + } + if err := startVersion(ctx, b, dms.VersionTypeDestroy, staged); err != nil { + logdiag.LogError(ctx, err) + return + } + } destroyCore(ctx, b, plan, engine) } else { cmdio.LogString(ctx, "Destroy cancelled!") diff --git a/bundle/phases/dms.go b/bundle/phases/dms.go new file mode 100644 index 00000000000..2dc12a0da96 --- /dev/null +++ b/bundle/phases/dms.go @@ -0,0 +1,249 @@ +package phases + +import ( + "context" + "fmt" + "net/url" + "strconv" + "strings" + + "github.com/databricks/cli/bundle" + "github.com/databricks/cli/bundle/config" + "github.com/databricks/cli/bundle/deployplan" + "github.com/databricks/cli/internal/build" + "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/dms" + "github.com/databricks/cli/libs/log" + "github.com/databricks/cli/libs/logdiag" + "github.com/databricks/cli/libs/workspaceurls" + "github.com/databricks/databricks-sdk-go/service/bundledeployments" +) + +// stagedOperations lists the resources the plan will touch, for CreateVersion to stage an +// operation each. Skipped and undefined actions are left out: nothing is applied for them, so +// their operations would stay pending and the service would hold no state for them. +func stagedOperations(plan *deployplan.Plan) ([]dms.StagedOperation, error) { + actions := plan.GetActions() + staged := make([]dms.StagedOperation, 0, len(actions)) + for _, action := range actions { + if action.ActionType == deployplan.Skip || action.ActionType == deployplan.Undefined { + continue + } + actionType, err := actionToSDK(action.ActionType) + if err != nil { + return nil, fmt.Errorf("%s: %w", action.ResourceKey, err) + } + staged = append(staged, dms.StagedOperation{ + ResourceKey: action.ResourceKey, + ActionType: actionType, + }) + } + return staged, nil +} + +// actionToSDK maps a deployplan action to the DMS action type a staged operation records. +// Only actions that mutate a resource are recordable; Skip and Undefined are rejected +// rather than silently coerced. +func actionToSDK(a deployplan.ActionType) (bundledeployments.OperationActionType, error) { + switch a { + case deployplan.Create: + return bundledeployments.OperationActionTypeOperationActionTypeCreate, nil + case deployplan.Update: + return bundledeployments.OperationActionTypeOperationActionTypeUpdate, nil + case deployplan.UpdateWithID: + return bundledeployments.OperationActionTypeOperationActionTypeUpdateWithId, nil + case deployplan.Recreate: + return bundledeployments.OperationActionTypeOperationActionTypeRecreate, nil + case deployplan.Resize: + return bundledeployments.OperationActionTypeOperationActionTypeResize, nil + case deployplan.Delete: + return bundledeployments.OperationActionTypeOperationActionTypeDelete, nil + default: + return "", fmt.Errorf("cannot record operation: unsupported action %q", a) + } +} + +// recordedDeployment reads, from the history the recording set, the deployment id and the version +// this run will create (one past the deployment's most recent). Both zero when nothing is recorded +// - the bundle records no history, so version 0 marks "no version" for logDeploymentVersion. +func recordedDeployment(b *bundle.Bundle) (string, int64) { + h := b.Config.Bundle.Deployment.History + if h == nil { + return "", 0 + } + // LatestVersionID comes from the service as an integer, so this does not fail in practice. + version, err := dms.NextVersion(h.LatestVersionID) + if err != nil { + version = 1 + } + return h.DeploymentID, version +} + +// createOrUpdateDeployment creates the deployment on a first deploy, or updates the metadata this +// run changed. current is the record the service holds (nil before the first recorded deploy), +// diffed to mask the update down to what changed. Runs before the plan, so the deployment exists +// to be stamped onto the resources; the version it will create is settled in process.go. +func createOrUpdateDeployment(ctx context.Context, b *bundle.Bundle, current *bundledeployments.Deployment) { + db := &b.DeploymentBundle + metadata := deploymentMetadata(b) + deploymentID, _ := recordedDeployment(b) + switch mask := metadata.StaleFields(current); { + case deploymentID == "": + id, err := db.DmsApiClient.CreateDeployment(ctx, b.Config.Workspace.StatePath, metadata) + if err != nil { + logdiag.LogError(ctx, fmt.Errorf("failed to create deployment: %w", err)) + return + } + deploymentID = id + case mask != "": + if err := db.DmsApiClient.UpdateDeployment(ctx, deploymentID, metadata, mask); err != nil { + logdiag.LogError(ctx, fmt.Errorf("failed to update deployment: %w", err)) + return + } + } + + // A first deploy had no deployment to read at startup, so its id enters the history here. + bundle.ApplyFuncContext(ctx, b, func(_ context.Context, b *bundle.Bundle) { + if b.Config.Bundle.Deployment.History == nil { + b.Config.Bundle.Deployment.History = &config.DeploymentHistory{} + } + b.Config.Bundle.Deployment.History.DeploymentID = deploymentID + }) +} + +// startVersion claims the version the run settled on and opens the buffer that records +// each state write under it. Called after approval, so a declined deploy never claims a number. +// A no-op when the bundle does not record deployment history. +func startVersion(ctx context.Context, b *bundle.Bundle, versionType dms.VersionType, staged []dms.StagedOperation) error { + db := &b.DeploymentBundle + if db.DmsApiClient == nil { + return nil + } + deploymentID, versionID := recordedDeployment(b) + + // The version this run creates is one past the deployment's most recent, so the previous is + // one below it - empty for the first version. + previousVersionID := "" + if versionID > 1 { + previousVersionID = strconv.FormatInt(versionID-1, 10) + } + + // The server rejects this unless the version number exceeds last_version_id and + // previous_version_id matches it, which is what makes claiming the number up front + // safe: a deploy that took it in the meantime is reported, not overwritten. + var gitInfo *bundledeployments.GitInfo + if git := b.Config.Bundle.Git; git.Branch != "" || git.Commit != "" || git.OriginURL != "" { + gitInfo = &bundledeployments.GitInfo{ + Branch: git.Branch, + Commit: git.Commit, + OriginUrl: git.OriginURL, + } + } + version, err := db.DmsApiClient.CreateVersion(ctx, deploymentID, versionID, dms.CreateVersionRequest{ + CliVersion: build.GetInfo().Version, + VersionType: versionType, + PreviousVersionId: previousVersionID, + Operations: staged, + GitInfo: gitInfo, + }) + if err != nil { + return fmt.Errorf("failed to create deployment version: %w", err) + } + log.Infof(ctx, "Created deployment version: deployment=%s version=%s", deploymentID, version.VersionId) + + db.DmsAsyncOperationClient = dms.StartOperationBuffer(ctx, db.DmsApiClient, deploymentID, versionID) + return nil +} + +// drainOperationsAndCompleteVersion drains the buffered operations and completes the version. +// It returns whether the version completed successfully, which a destroy uses to decide whether +// to delete the deployment. Idempotent: the first call clears the buffer, so a deferred +// safety-net after an explicit completion is a no-op returning false. Also false when no version +// was created. +func drainOperationsAndCompleteVersion(ctx context.Context, b *bundle.Bundle, success bool) (bool, error) { + db := &b.DeploymentBundle + buf := db.DmsAsyncOperationClient + if buf == nil { + return false, nil + } + db.DmsAsyncOperationClient = nil + + // Drain first; a recording error fails the deploy even when the resources applied. Its error + // is left to whoever drained (apply), not returned twice. + if buf.Drain() != nil { + success = false + } + + reason := bundledeployments.VersionCompleteVersionCompleteSuccess + if !success { + reason = bundledeployments.VersionCompleteVersionCompleteFailure + } + deploymentID, versionID := recordedDeployment(b) + if err := db.DmsApiClient.CompleteVersion(ctx, deploymentID, versionID, reason); err != nil { + return false, err + } + log.Infof(ctx, "Completed deployment version: deployment=%s version=%d reason=%s", deploymentID, versionID, reason) + + return success, nil +} + +// logDeploymentVersion logs the deployment version URL. Workspace ID is omitted +// so the page stays clickable in a terminal and redirects correctly without it. +func logDeploymentVersion(ctx context.Context, b *bundle.Bundle, deploymentID string, version int64) { + if version == 0 { + return + } + + baseURL, err := url.Parse(b.WorkspaceClient(ctx).Config.CanonicalHostName()) + if err != nil { + // Only the link is lost, so report the version without it rather than failing + // a deploy over it. + log.Debugf(ctx, "Not linking to the recorded deployment: %s", err) + cmdio.LogString(ctx, fmt.Sprintf("Current Deployment Version: %s version %d", deploymentID, version)) + return + } + + cmdio.LogString(ctx, "Current Deployment Version: "+workspaceurls.DeploymentURL(*baseURL, deploymentID, version)) +} + +// deploymentMetadata describes the bundle this deploy came from and where it +// landed, mirroring what bundle/deploy/metadata computes for the metadata file. +func deploymentMetadata(b *bundle.Bundle) dms.Metadata { + p := dms.Metadata{ + DisplayName: b.Config.Bundle.Name, + TargetName: b.Config.Bundle.Target, + Mode: deploymentModeToSDK(b.Config.Bundle.Mode), + } + + ws := &bundledeployments.WorkspaceInfo{ + RootPath: b.Config.Workspace.RootPath, + FilePath: b.Config.Workspace.FilePath, + } + // In a source-linked deployment files are not copied, so resources read them + // from the sync root instead of file_path (see bundle/deploy/metadata.Compute). + if config.IsExplicitlyEnabled(b.Config.Presets.SourceLinkedDeployment) { + ws.FilePath = b.SyncRootPath + ws.SourceLinked = true + } + // Only a deploy from a Databricks Git folder has one; a local worktree does not. + // bundle_root_path is relative to it, so the service requires both or neither. + if b.WorktreeRoot != nil && strings.HasPrefix(b.WorktreeRoot.Native(), "/Workspace/") { + ws.GitFolderPath = b.WorktreeRoot.Native() + ws.BundleRootPath = b.Config.Bundle.Git.BundleRootPath + } + p.Workspace = ws + return p +} + +// deploymentModeToSDK maps the bundle target's mode to the DMS enum. An unset mode +// maps to empty, which the service reads as "not reported". +func deploymentModeToSDK(mode config.Mode) bundledeployments.DeploymentMode { + switch mode { + case config.Development: + return bundledeployments.DeploymentModeDeploymentModeDevelopment + case config.Production: + return bundledeployments.DeploymentModeDeploymentModeProduction + default: + return "" + } +} diff --git a/bundle/phases/dms_test.go b/bundle/phases/dms_test.go new file mode 100644 index 00000000000..f6854999db9 --- /dev/null +++ b/bundle/phases/dms_test.go @@ -0,0 +1,81 @@ +package phases + +import ( + "testing" + + "github.com/databricks/cli/bundle/deployplan" + "github.com/databricks/cli/libs/dms" + "github.com/databricks/databricks-sdk-go/service/bundledeployments" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestStagedOperationsCoversEveryTouchedResource(t *testing.T) { + // The version fixes its operation set, so anything the apply will write has to appear + // here. Keys go out in the service's form, without the CLI's "resources." prefix. + plan := &deployplan.Plan{Plan: map[string]*deployplan.PlanEntry{ + "resources.jobs.foo": {Action: deployplan.Create}, + "resources.pipelines.bar": {Action: deployplan.Recreate}, + "resources.schemas.baz": {Action: deployplan.Delete}, + "resources.clusters.small": {Action: deployplan.Resize}, + }} + + staged, err := stagedOperations(plan) + require.NoError(t, err) + + assert.ElementsMatch(t, []dms.StagedOperation{ + {ResourceKey: "resources.jobs.foo", ActionType: bundledeployments.OperationActionTypeOperationActionTypeCreate}, + {ResourceKey: "resources.pipelines.bar", ActionType: bundledeployments.OperationActionTypeOperationActionTypeRecreate}, + {ResourceKey: "resources.schemas.baz", ActionType: bundledeployments.OperationActionTypeOperationActionTypeDelete}, + {ResourceKey: "resources.clusters.small", ActionType: bundledeployments.OperationActionTypeOperationActionTypeResize}, + }, staged) +} + +func TestStagedOperationsLeavesOutUntouchedResources(t *testing.T) { + // A skipped resource is never applied, so staging it would leave an operation pending for + // the life of the version. Undefined is not a real action either. + plan := &deployplan.Plan{Plan: map[string]*deployplan.PlanEntry{ + "resources.jobs.touched": {Action: deployplan.Update}, + "resources.jobs.unchanged": {Action: deployplan.Skip}, + "resources.jobs.unknown": {Action: deployplan.Undefined}, + }} + + staged, err := stagedOperations(plan) + require.NoError(t, err) + + assert.Equal(t, []dms.StagedOperation{ + {ResourceKey: "resources.jobs.touched", ActionType: bundledeployments.OperationActionTypeOperationActionTypeUpdate}, + }, staged) +} + +func TestStagedOperationsEmptyPlan(t *testing.T) { + staged, err := stagedOperations(&deployplan.Plan{Plan: map[string]*deployplan.PlanEntry{}}) + require.NoError(t, err) + assert.Empty(t, staged) +} + +func TestActionToSDK(t *testing.T) { + cases := []struct { + action deployplan.ActionType + want bundledeployments.OperationActionType + }{ + {deployplan.Create, bundledeployments.OperationActionTypeOperationActionTypeCreate}, + {deployplan.Update, bundledeployments.OperationActionTypeOperationActionTypeUpdate}, + {deployplan.UpdateWithID, bundledeployments.OperationActionTypeOperationActionTypeUpdateWithId}, + {deployplan.Recreate, bundledeployments.OperationActionTypeOperationActionTypeRecreate}, + {deployplan.Resize, bundledeployments.OperationActionTypeOperationActionTypeResize}, + {deployplan.Delete, bundledeployments.OperationActionTypeOperationActionTypeDelete}, + } + for _, c := range cases { + got, err := actionToSDK(c.action) + require.NoError(t, err) + assert.Equal(t, c.want, got) + } + + // Nothing is applied for these, so stagedOperations leaves them out rather than + // mapping them; the guard is here in case a new action type arrives without a mapping. + _, err := actionToSDK(deployplan.Skip) + assert.Error(t, err) + _, err = actionToSDK(deployplan.Undefined) + assert.Error(t, err) +} diff --git a/bundle/phases/initialize.go b/bundle/phases/initialize.go index b15e1c30df6..41d2374900d 100644 --- a/bundle/phases/initialize.go +++ b/bundle/phases/initialize.go @@ -185,6 +185,11 @@ func Initialize(ctx context.Context, b *bundle.Bundle) { // They are set by the CLI to track the bundle deployment and must not be set by the user. validate.ValidateDeploymentFields(), + // Reads (typed): b.Config.Experimental.RecordDeploymentHistory + // Reads (env): DATABRICKS_BUNDLE_RECORD_DEPLOYMENT_HISTORY ("true" permits it) + // Rejects experimental.record_deployment_history: the feature is not usable yet. + validate.ValidateRecordDeploymentHistory(), + // Reject configured job_runs.idempotency_token; the CLI sets it on run-now. validate.ValidateJobRunIdempotencyToken(), diff --git a/bundle/statemgmt/direct_migration.go b/bundle/statemgmt/direct_migration.go index 7b88290930c..6099cebdd14 100644 --- a/bundle/statemgmt/direct_migration.go +++ b/bundle/statemgmt/direct_migration.go @@ -172,7 +172,8 @@ func checkPlanOnTempState(ctx context.Context, b *bundle.Bundle, tempStatePath s }() var planBundle direct.DeploymentBundle - if err := planBundle.StateDB.Open(planCtx, tempStatePath, false, false); err != nil { + // This plan check does not record deployment history, so no DMS client or deployment id. + if err := planBundle.StateDB.Open(planCtx, tempStatePath, false, false, nil, ""); err != nil { return fmt.Errorf("opening migrated state for plan check: %w", err) } diff --git a/cmd/bundle/generate/dashboard.go b/cmd/bundle/generate/dashboard.go index 086ec1d600a..48ceebd8908 100644 --- a/cmd/bundle/generate/dashboard.go +++ b/cmd/bundle/generate/dashboard.go @@ -404,7 +404,13 @@ func (d *dashboard) runForResource(ctx context.Context, b *bundle.Bundle) { var state statemgmt.ExportedResourcesMap if stateDesc.Engine.IsDirect() { _, localPath := b.StateFilenameDirect(ctx) - if err := b.DeploymentBundle.StateDB.Open(ctx, localPath, dstate.WithRecovery(true), dstate.WithWrite(false)); err != nil { + // While recording, the resources come from the service and not the state file. + dmsClient, dmsDeploymentID, err := utils.DmsStateSource(ctx, b) + if err != nil { + logdiag.LogError(ctx, err) + return + } + if err := b.DeploymentBundle.StateDB.Open(ctx, localPath, dstate.WithRecovery(true), dstate.WithWrite(false), dmsClient, dmsDeploymentID); err != nil { logdiag.LogError(ctx, err) return } diff --git a/cmd/bundle/generate/genie_space.go b/cmd/bundle/generate/genie_space.go index 6d938c5e03d..82ed6708b20 100644 --- a/cmd/bundle/generate/genie_space.go +++ b/cmd/bundle/generate/genie_space.go @@ -322,7 +322,13 @@ func (g *genieSpace) runForResource(ctx context.Context, b *bundle.Bundle) { var state statemgmt.ExportedResourcesMap if stateDesc.Engine.IsDirect() { _, localPath := b.StateFilenameDirect(ctx) - if err := b.DeploymentBundle.StateDB.Open(ctx, localPath, dstate.WithRecovery(true), dstate.WithWrite(false)); err != nil { + // While recording, the resources come from the service and not the state file. + dmsClient, dmsDeploymentID, err := utils.DmsStateSource(ctx, b) + if err != nil { + logdiag.LogError(ctx, err) + return + } + if err := b.DeploymentBundle.StateDB.Open(ctx, localPath, dstate.WithRecovery(true), dstate.WithWrite(false), dmsClient, dmsDeploymentID); err != nil { logdiag.LogError(ctx, err) return } diff --git a/cmd/bundle/utils/process.go b/cmd/bundle/utils/process.go index fa5471e8f99..0e7c28b4ea4 100644 --- a/cmd/bundle/utils/process.go +++ b/cmd/bundle/utils/process.go @@ -4,13 +4,17 @@ import ( "context" "errors" "fmt" + "path" "path/filepath" + "strconv" "time" "github.com/databricks/cli/bundle" + "github.com/databricks/cli/bundle/config" "github.com/databricks/cli/bundle/config/engine" "github.com/databricks/cli/bundle/config/mutator" "github.com/databricks/cli/bundle/config/validate" + "github.com/databricks/cli/bundle/deploy/metadata" "github.com/databricks/cli/bundle/deploy/terraform" "github.com/databricks/cli/bundle/deployplan" "github.com/databricks/cli/bundle/direct" @@ -21,11 +25,15 @@ import ( "github.com/databricks/cli/internal/build" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/diag" + "github.com/databricks/cli/libs/dms" "github.com/databricks/cli/libs/dyn" "github.com/databricks/cli/libs/log" "github.com/databricks/cli/libs/logdiag" "github.com/databricks/cli/libs/sync" "github.com/databricks/cli/libs/telemetry/protos" + "github.com/databricks/databricks-sdk-go" + "github.com/databricks/databricks-sdk-go/apierr" + "github.com/databricks/databricks-sdk-go/service/bundledeployments" "github.com/spf13/cobra" "golang.org/x/mod/semver" ) @@ -189,6 +197,11 @@ func ProcessBundleRet(cmd *cobra.Command, opts ProcessOptions) (b *bundle.Bundle return b, nil, err } + // The current deployment read from the service (nil, id "" if there is none yet). Used for the + // metadata diff and to reject a saved plan that predates the deployment's recorded version. + var dmsDeployment *bundledeployments.Deployment + var dmsDeploymentID string + shouldReadState := opts.ReadState || opts.AlwaysPull || opts.InitIDs || opts.ErrorOnEmptyState || opts.PreDeployChecks || opts.Deploy || opts.ReadPlanPath != "" if shouldReadState { @@ -232,11 +245,53 @@ func ProcessBundleRet(cmd *cobra.Command, opts ProcessOptions) (b *bundle.Bundle needDirectState := stateDesc.Engine.IsDirect() && (opts.InitIDs || opts.ErrorOnEmptyState || opts.Deploy || opts.ReadPlanPath != "" || opts.PreDeployChecks || opts.PostStateFunc != nil) if needDirectState { _, localPath := b.StateFilenameDirect(ctx) - if err := b.DeploymentBundle.StateDB.Open(ctx, localPath, dstate.WithRecovery(true), dstate.WithWrite(false)); err != nil { + + var dmsClient *dms.Client + if b.RecordsDeploymentHistory(ctx) { + deploymentID, deployment, err := fetchDeploymentFromStatePath(ctx, b.WorkspaceClient(ctx), b.Config.Workspace.StatePath) + if err != nil { + logdiag.LogError(ctx, err) + return b, stateDesc, root.ErrAlreadyPrinted + } + + dmsClient, err = dms.NewClient(b.WorkspaceClient(ctx)) + if err != nil { + logdiag.LogError(ctx, err) + return b, stateDesc, root.ErrAlreadyPrinted + } + dmsDeploymentID = deploymentID + dmsDeployment = deployment + b.DeploymentBundle.DmsApiClient = dmsClient + + // A resolved deployment id goes into history and is stamped onto resources to avoid drift + // (empty on a first deploy; the deploy phase stamps the created id; version_id is DMS-managed). + if deploymentID != "" { + bundle.ApplyFuncContext(ctx, b, func(_ context.Context, b *bundle.Bundle) { + b.Config.Bundle.Deployment.History = &config.DeploymentHistory{ + DeploymentID: deploymentID, + LatestVersionID: deployment.LastVersionId, + } + }) + bundle.ApplyContext(ctx, b, metadata.AnnotateDeployment(deploymentID)) + if logdiag.HasError(ctx) { + return b, stateDesc, root.ErrAlreadyPrinted + } + } + } + if err := b.DeploymentBundle.StateDB.Open(ctx, localPath, dstate.WithRecovery(true), dstate.WithWrite(false), dmsClient, dmsDeploymentID); err != nil { logdiag.LogError(ctx, err) return b, stateDesc, root.ErrAlreadyPrinted } + // The service holds this deployment, so it has to keep being recorded: deploying + // without recording would leave it describing resources that have moved on. + if !b.RecordsDeploymentHistory(ctx) && b.DeploymentBundle.StateDB.RequiresDeploymentHistory() { + logdiag.LogError(ctx, errors.New(`unsetting experimental.record_deployment_history is not supported + +This deployment's resources are recorded with the deployment metadata service. Set experimental.record_deployment_history: true to deploy or destroy this bundle`)) + return b, stateDesc, root.ErrAlreadyPrinted + } + // Warn when the state was last written by a newer CLI than the one // running now. The state schema version is a hard gate (dstate.Open // rejects a too-new state_version), but a state can be written by a @@ -277,6 +332,7 @@ func ProcessBundleRet(cmd *cobra.Command, opts ProcessOptions) (b *bundle.Bundle return b, stateDesc, root.ErrAlreadyPrinted } } + } var plan *deployplan.Plan @@ -307,6 +363,13 @@ func ProcessBundleRet(cmd *cobra.Command, opts ProcessOptions) (b *bundle.Bundle logdiag.LogError(ctx, err) return b, stateDesc, root.ErrAlreadyPrinted } + + // A first-deploy plan has empty lineage, so ValidatePlanAgainstState skips it; if the deployment + // has since recorded a version, reject the replay (a non-empty lineage is covered above). + if plan.Lineage == "" && dmsDeployment != nil && dmsDeployment.LastVersionId != "" { + logdiag.LogError(ctx, fmt.Errorf("this plan predates the deployment's current version %s; run 'bundle plan' again", dmsDeployment.LastVersionId)) + return b, stateDesc, root.ErrAlreadyPrinted + } } else if opts.Deploy { opts.Build = true opts.PreDeployChecks = true @@ -373,7 +436,7 @@ func ProcessBundleRet(cmd *cobra.Command, opts ProcessOptions) (b *bundle.Bundle } t3 := time.Now() - phases.Deploy(ctx, b, outputHandler, stateDesc.Engine, requiredEngine, libs, plan) + phases.Deploy(ctx, b, outputHandler, stateDesc.Engine, requiredEngine, libs, plan, dmsDeployment) b.Metrics.ExecutionTimes = append(b.Metrics.ExecutionTimes, protos.IntMapEntry{ Key: "phases.Deploy", Value: time.Since(t3).Milliseconds(), @@ -427,6 +490,48 @@ func ResolveEngineSetting(ctx context.Context, b *bundle.Bundle) (engine.EngineS return engine.EngineSetting{Type: engine.Default, Source: engine.SourceDefault, IsDefault: true}, nil } +// DmsStateSource returns the client and deployment id dstate.Open needs to read a recorded +// bundle's resources from the deployment metadata service. Both are zero when the bundle does not +// record: while recording the state file holds only the marker, so a command that opens state +// without these sees no resources at all. +func DmsStateSource(ctx context.Context, b *bundle.Bundle) (*dms.Client, string, error) { + if !b.RecordsDeploymentHistory(ctx) { + return nil, "", nil + } + + deploymentID, _, err := fetchDeploymentFromStatePath(ctx, b.WorkspaceClient(ctx), b.Config.Workspace.StatePath) + if err != nil { + return nil, "", err + } + + client, err := dms.NewClient(b.WorkspaceClient(ctx)) + if err != nil { + return nil, "", err + } + return client, deploymentID, nil +} + +// Lookup and return the deployment object from ${workspace.state_path}/resources.deployment.json +func fetchDeploymentFromStatePath(ctx context.Context, w *databricks.WorkspaceClient, statePath string) (string, *bundledeployments.Deployment, error) { + nodePath := path.Join(statePath, dms.DeploymentNodeName) + + obj, err := w.Workspace.GetStatusByPath(ctx, nodePath) + if errors.Is(err, apierr.ErrNotFound) || errors.Is(err, apierr.ErrResourceDoesNotExist) { + return "", nil, nil + } + if err != nil { + return "", nil, fmt.Errorf("looking up deployment at %s: %w", nodePath, err) + } + deploymentID := strconv.FormatInt(obj.ObjectId, 10) + deployment, err := w.BundleDeployments.GetDeployment(ctx, bundledeployments.GetDeploymentRequest{ + Name: dms.DeploymentName(deploymentID), + }) + if err != nil { + return "", nil, err + } + return deploymentID, deployment, nil +} + // isNewerVersion reports whether the state's recorded CLI version is strictly // newer than the running build. Both are bare versions without a leading "v". // An empty stateVersion (state not written by any CLI yet) or an unparseable diff --git a/libs/dms/client.go b/libs/dms/client.go new file mode 100644 index 00000000000..8dbf9915399 --- /dev/null +++ b/libs/dms/client.go @@ -0,0 +1,250 @@ +package dms + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/databricks/cli/libs/auth" + "github.com/databricks/databricks-sdk-go" + "github.com/databricks/databricks-sdk-go/client" + "github.com/databricks/databricks-sdk-go/service/bundledeployments" +) + +// DeploymentNodeName is the workspace node DMS creates per deployment. Must +// match DeploymentWhsClient.DEPLOYMENT_NODE_NAME on the service side. +const DeploymentNodeName = "resources.deployment.json" + +// statePrefix is what a bundle state key carries and a DMS resource key does not: state calls a +// job "resources.jobs.foo", DMS calls it "jobs.foo". Every exported name here takes the state +// form; the prefix comes off where a request is built, and back on where a resource is read. +const statePrefix = "resources." + +// Client carries the calls the CLI makes to DMS, as methods below. Each one goes out through one +// of two halves: the generated client for the calls it can express, and hand-written requests +// for the two it cannot. +// +// TODO: Remove this and replace with the SDK. +type Client struct { + // Service is the generated client. + Service bundledeployments.BundleDeploymentsInterface + + // raw sends what the generated client cannot; see requester. + raw requester +} + +// NewClient returns a Client for the workspace w. +func NewClient(w *databricks.WorkspaceClient) (*Client, error) { + api, err := client.New(w.Config) + if err != nil { + return nil, err + } + return &Client{Service: w.BundleDeployments, raw: &rawClient{client: api}}, nil +} + +// DeploymentName and versionName are the two resource-name formats the service uses. Every +// call builds its name here, so a caller only ever passes ids. +func DeploymentName(deploymentID string) string { + return "deployments/" + deploymentID +} + +func versionName(deploymentID string, version int64) string { + return fmt.Sprintf("deployments/%s/versions/%d", deploymentID, version) +} + +// CreateDeployment registers a deployment under parentPath and returns the id the server +// assigned it, which is the id of the workspace node it creates there. +func (c *Client) CreateDeployment(ctx context.Context, parentPath string, metadata Metadata) (string, error) { + dep := metadata.deployment() + dep.InitialParentPath = parentPath + + created, err := c.Service.CreateDeployment(ctx, bundledeployments.CreateDeploymentRequest{Deployment: dep}) + if err != nil { + return "", err + } + return deploymentIDFromName(created.Name) +} + +// UpdateDeployment writes the fields mask names onto the deployment. The service ignores every +// other field, so the mask is what decides the write. +func (c *Client) UpdateDeployment(ctx context.Context, deploymentID string, metadata Metadata, mask string) error { + return c.raw.UpdateDeployment(ctx, deploymentID, metadata.deployment(), mask) +} + +// DeleteDeployment removes the deployment record, which a completed destroy does. +func (c *Client) DeleteDeployment(ctx context.Context, deploymentID string) error { + return c.Service.DeleteDeployment(ctx, bundledeployments.DeleteDeploymentRequest{ + Name: DeploymentName(deploymentID), + }) +} + +// CreateVersion claims the version and stages the operations body carries. +func (c *Client) CreateVersion(ctx context.Context, deploymentID string, version int64, body CreateVersionRequest) (*bundledeployments.Version, error) { + return c.raw.CreateVersion(ctx, deploymentID, strconv.FormatInt(version, 10), body) +} + +// CompleteVersion closes the version out, which is what stops the service expiring its lease. +func (c *Client) CompleteVersion(ctx context.Context, deploymentID string, version int64, reason bundledeployments.VersionComplete) error { + _, err := c.Service.CompleteVersion(ctx, bundledeployments.CompleteVersionRequest{ + Name: versionName(deploymentID, version), + CompletionReason: reason, + }) + return err +} + +// UpdateOperation fills in one operation the version staged, and returns the sequence id the +// next update for that resource must send. +func (c *Client) UpdateOperation(ctx context.Context, deploymentID string, version int64, stateKey, sequenceID string, update OperationUpdate) (string, error) { + return c.raw.UpdateOperation(ctx, deploymentID, version, stateKey, sequenceID, update) +} + +// deploymentIDFromName extracts the deployment ID from a DMS resource name of +// the form "deployments/{deployment_id}". +func deploymentIDFromName(name string) (string, error) { + id, ok := strings.CutPrefix(name, DeploymentName("")) + if !ok || id == "" { + return "", fmt.Errorf("unexpected deployment name %q from deployment metadata service", name) + } + return id, nil +} + +// requester sends the two requests the generated client cannot express, so a test can capture +// what the CLI puts on the wire. Both are TODO(DMS): drop them once the spec catches up. +type requester interface { + // CreateVersion is hand-written because the generated struct has no operations: the field + // is at DEVELOPMENT stage, which keeps it out of the SDK until it is promoted. + CreateVersion(ctx context.Context, deploymentID, versionID string, body CreateVersionRequest) (*bundledeployments.Version, error) + + // UpdateDeployment is hand-written because the generated client has no such call yet. + UpdateDeployment(ctx context.Context, deploymentID string, deployment bundledeployments.Deployment, mask string) error + + // UpdateOperation is hand-written because the SDK types sequence_id as an int64 while + // the service sends a JSON string, so it cannot read the response. sequenceID is the + // token the previous update for this resource returned, or 0 for the first, which is + // what staging leaves. + UpdateOperation(ctx context.Context, deploymentID string, version int64, stateKey, sequenceID string, update OperationUpdate) (next string, err error) +} + +// CreateVersionRequest is the CreateVersion request body. +type CreateVersionRequest struct { + CliVersion string `json:"cli_version"` + VersionType VersionType `json:"version_type"` + // PreviousVersionId is the deployment's most recent version, unset for a + // deployment's first version. + PreviousVersionId string `json:"previous_version_id,omitempty"` + // GitInfo records where this version's source came from. The rest of the provenance - + // display name, target, mode, workspace paths - belongs to the deployment. + GitInfo *bundledeployments.GitInfo `json:"git_info,omitempty"` + // Operations is every resource this version will touch; see StagedOperation. It sits in this + // body with the version's own fields because the request binds body: "version", and is input + // only - the response never carries it back. + Operations []StagedOperation `json:"operations,omitempty"` +} + +// StagedOperation is one resource the version will record an operation for. The service +// creates it in OPERATION_STATUS_PENDING at sequence id 0, and the CLI fills in the outcome +// with UpdateOperation as the resource is applied. +type StagedOperation struct { + // ResourceKey is the bundle state key; the request carries the form the service uses. + ResourceKey string `json:"resource_key"` + ActionType bundledeployments.OperationActionType `json:"action_type"` +} + +// operationResponse is the part of an operation response the CLI reads back. +type operationResponse struct { + // SequenceId is the concurrency token for the next update, typed as the service sends it. + SequenceId string `json:"sequence_id,omitempty"` +} + +// rawClient sends the requests the generated client cannot express. +type rawClient struct { + client *client.DatabricksClient +} + +func (r *rawClient) CreateVersion(ctx context.Context, deploymentID, versionID string, body CreateVersionRequest) (*bundledeployments.Version, error) { + staged := make([]StagedOperation, len(body.Operations)) + for i, op := range body.Operations { + op.ResourceKey = strings.TrimPrefix(op.ResourceKey, statePrefix) + staged[i] = op + } + body.Operations = staged + + var version bundledeployments.Version + path := "/api/2.0/bundle/" + DeploymentName(deploymentID) + "/versions" + err := r.client.Do(ctx, http.MethodPost, path, + auth.WorkspaceIDHeaders(r.client.Config), + map[string]any{"version_id": versionID}, + body, &version) + if err != nil { + return nil, err + } + return &version, nil +} + +// newDeploymentUpdate builds the request body for update, holding exactly the masked fields for +// the same reason newUpdateRequest does. A map, not the SDK struct, whose omitempty tags would +// drop a masked field that is empty - which is how deployment_mode is cleared when a target stops +// setting mode. +func newDeploymentUpdate(deployment bundledeployments.Deployment, mask string) map[string]any { + values := map[string]any{ + "display_name": deployment.DisplayName, + "target_name": deployment.TargetName, + "deployment_mode": deployment.DeploymentMode, + "workspace_info": deployment.WorkspaceInfo, + } + + body := map[string]any{} + for field := range strings.SplitSeq(mask, ",") { + body[field] = values[field] + } + return body +} + +func (r *rawClient) UpdateDeployment(ctx context.Context, deploymentID string, deployment bundledeployments.Deployment, mask string) error { + path := "/api/2.0/bundle/" + DeploymentName(deploymentID) + return r.client.Do(ctx, http.MethodPatch, path, + auth.WorkspaceIDHeaders(r.client.Config), + map[string]any{"update_mask": mask}, + newDeploymentUpdate(deployment, mask), nil) +} + +// newUpdateRequest builds the request body for update. A field is in the body when the mask +// names it and absent otherwise, which is what the service requires: it rejects an update +// whose mask names a field the body leaves out, and an empty value is how a field is cleared - +// no state means the resource is gone, no error_message means an earlier failure is resolved. +// A map, not a struct, so presence cannot drift from the mask through an omitempty tag. +func newUpdateRequest(update OperationUpdate, sequenceID string) map[string]any { + body := map[string]any{"sequence_id": sequenceID} + // A masked state with no value is how the service is told the resource is gone, so a nil + // state is left out rather than sent empty. + if update.Fields.Has(FieldState) && update.State != nil { + body["state"] = string(update.State) + } + if update.Fields.Has(FieldResourceID) { + body["resource_id"] = update.ResourceID + } + if update.Fields.Has(FieldErrorMessage) { + body["error_message"] = update.ErrorMessage + } + if update.Fields.Has(FieldStatus) { + body["status"] = update.Status + } + return body +} + +func (r *rawClient) UpdateOperation(ctx context.Context, deploymentID string, version int64, stateKey, sequenceID string, update OperationUpdate) (string, error) { + body := newUpdateRequest(update, sequenceID) + + var result operationResponse + path := "/api/2.0/bundle/" + versionName(deploymentID, version) + "/operations/" + strings.TrimPrefix(stateKey, statePrefix) + err := r.client.Do(ctx, http.MethodPatch, path, + auth.WorkspaceIDHeaders(r.client.Config), + map[string]any{"update_mask": update.Fields.Mask()}, + body, &result) + if err != nil { + return "", err + } + return result.SequenceId, nil +} diff --git a/libs/dms/client_test.go b/libs/dms/client_test.go new file mode 100644 index 00000000000..867655bca4e --- /dev/null +++ b/libs/dms/client_test.go @@ -0,0 +1,67 @@ +package dms + +import ( + "encoding/json" + "errors" + "testing" + + "github.com/databricks/databricks-sdk-go/service/bundledeployments" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestClientNamesEveryResourceTheSameWay(t *testing.T) { + // One format each, so a call only ever passes ids. + assert.Equal(t, "deployments/dep-1", DeploymentName("dep-1")) + assert.Equal(t, "deployments/dep-1/versions/2", versionName("dep-1", 2)) +} + +func TestDeploymentIDFromName(t *testing.T) { + id, err := deploymentIDFromName("deployments/abc-123") + require.NoError(t, err) + assert.Equal(t, "abc-123", id) + + _, err = deploymentIDFromName("abc-123") + assert.Error(t, err) + + _, err = deploymentIDFromName("deployments/") + assert.Error(t, err) +} + +func TestUpdateRequestSendsExactlyTheMaskedFields(t *testing.T) { + // The service rejects an update whose mask names a field the body leaves out, and treats a + // field it does carry as written - so the body has to hold every masked field and nothing + // else, empty values included. Both masks the CLI builds are asserted on the wire by + // acceptance/bundle/dms; this pins the rule they both rely on. + update := OperationUpdate{ + Fields: DescribesResource, + State: json.RawMessage(`{"state":{"name":"foo"}}`), + ResourceID: "job-1", + Status: bundledeployments.OperationStatusOperationStatusSucceeded, + } + + // A successful write reports no error, and the empty value is what clears an earlier one. + assert.Equal(t, map[string]any{ + "state": `{"state":{"name":"foo"}}`, + "resource_id": "job-1", + "error_message": "", + "status": bundledeployments.OperationStatusOperationStatusSucceeded, + "sequence_id": "3", + }, newUpdateRequest(update, "3")) + + // A failure keeps the recorded state, so state is absent rather than empty: naming it + // would clear what the resource last recorded. + assert.Equal(t, map[string]any{ + "error_message": "boom", + "status": bundledeployments.OperationStatusOperationStatusFailed, + "sequence_id": "3", + }, newUpdateRequest(NewFailureUpdate("job-1", nil, errors.New("boom")), "3")) + + // The deployment's own fields follow the same rule. Clearing deployment_mode - a target that + // stops setting mode - sends it empty, which the SDK struct's omitempty would have dropped. + deployment := Metadata{DisplayName: "b", TargetName: "t"}.deployment() + assert.Equal(t, map[string]any{ + "target_name": "t", + "deployment_mode": bundledeployments.DeploymentMode(""), + }, newDeploymentUpdate(deployment, "target_name,deployment_mode")) +} diff --git a/libs/dms/fields.go b/libs/dms/fields.go new file mode 100644 index 00000000000..05d39b387d7 --- /dev/null +++ b/libs/dms/fields.go @@ -0,0 +1,59 @@ +package dms + +import "strings" + +// Fields is the set of operation fields an update writes, sent as its update mask. The +// service rejects any other path, so this is the whole vocabulary. +type Fields uint8 + +const ( + FieldState Fields = 1 << iota + FieldErrorMessage + FieldResourceID + FieldStatus +) + +// DescribesResource is what a write that says how the resource looks claims: every field +// an update may change. +const DescribesResource = FieldState | FieldErrorMessage | FieldResourceID | FieldStatus + +// ClearsState is what a write that leaves no resource claims: a delete, and the delete half of +// a recreate. State is named so the service reads the absent value as a clear, which is what +// drops the resource from the deployment. It cannot name resource_id either: the service counts +// only a state it was given as recording one, so an id alongside a cleared state is refused. +const ClearsState = FieldState | FieldErrorMessage | FieldStatus + +// KeepsState is what a failure claims: mark it failed and leave state alone. State means +// the resource is as it was written; no state means a delete went through and nothing +// replaced it, so the resource really is gone and the deployment should say so. +// +// It cannot name resource_id: the service requires state in any mask that names the id, and +// naming state here would overwrite what the resource last recorded. +const KeepsState = FieldErrorMessage | FieldStatus + +// wireNames pairs each field with its name on the wire, in the order a mask lists them. +var wireNames = []struct { + field Fields + name string +}{ + {FieldState, "state"}, + {FieldErrorMessage, "error_message"}, + {FieldResourceID, "resource_id"}, + {FieldStatus, "status"}, +} + +// Has reports whether f contains every field in other. +func (f Fields) Has(other Fields) bool { + return f&other == other +} + +// Mask renders f as the update_mask the service expects, always in the same order. +func (f Fields) Mask() string { + names := make([]string, 0, len(wireNames)) + for _, w := range wireNames { + if f.Has(w.field) { + names = append(names, w.name) + } + } + return strings.Join(names, ",") +} diff --git a/libs/dms/fields_test.go b/libs/dms/fields_test.go new file mode 100644 index 00000000000..198a55efca8 --- /dev/null +++ b/libs/dms/fields_test.go @@ -0,0 +1,23 @@ +package dms + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestFieldsMask(t *testing.T) { + // The order is fixed, so the same set always sends the same mask. + assert.Equal(t, "state,error_message,resource_id,status", DescribesResource.Mask()) + assert.Equal(t, "error_message,status", KeepsState.Mask()) + assert.Equal(t, "state", FieldState.Mask()) + assert.Empty(t, Fields(0).Mask()) +} + +func TestFieldsHas(t *testing.T) { + assert.True(t, DescribesResource.Has(FieldState)) + assert.False(t, KeepsState.Has(FieldState)) + // Has asks for every field, not any of them. + assert.True(t, DescribesResource.Has(FieldState|FieldStatus)) + assert.False(t, KeepsState.Has(FieldState|FieldStatus)) +} diff --git a/libs/dms/metadata.go b/libs/dms/metadata.go new file mode 100644 index 00000000000..d63154a4790 --- /dev/null +++ b/libs/dms/metadata.go @@ -0,0 +1,95 @@ +package dms + +import ( + "fmt" + "reflect" + "strconv" + "strings" + + "github.com/databricks/databricks-sdk-go/service/bundledeployments" +) + +// VersionType identifies the kind of deployment a version records. +type VersionType = bundledeployments.VersionType + +const ( + VersionTypeDeploy VersionType = bundledeployments.VersionTypeVersionTypeDeploy + VersionTypeDestroy VersionType = bundledeployments.VersionTypeVersionTypeDestroy +) + +// Metadata is what a version records about the bundle, its source and where it +// landed. The service copies these onto the deployment, so they describe it as of +// its most recent version. +type Metadata struct { + // DisplayName is the bundle's name, which the deployment is listed under. + DisplayName string + // TargetName is the bundle target that was deployed. + TargetName string + // Mode is the bundle target's mode, empty when the target sets none. + Mode bundledeployments.DeploymentMode + Workspace *bundledeployments.WorkspaceInfo +} + +// deploymentFields are the deployment's own metadata, in the order a mask lists them. Git is not +// among them: the service derives the deployment's from the version that carried it. +var deploymentFields = []string{"display_name", "target_name", "deployment_mode", "workspace_info"} + +// sameWorkspaceInfo compares the paths alone. The SDK records which fields a response carried in +// ForceSendFields, so a record read back never deep-equals one built here, and comparing the +// structs whole would report every run as a change. +func sameWorkspaceInfo(want, current *bundledeployments.WorkspaceInfo) bool { + if want == nil || current == nil { + return want == nil && current == nil + } + + a, b := *want, *current + a.ForceSendFields, b.ForceSendFields = nil, nil + return reflect.DeepEqual(a, b) +} + +// deployment renders the metadata the deployment owns. +func (m Metadata) deployment() bundledeployments.Deployment { + return bundledeployments.Deployment{ + DisplayName: m.DisplayName, + TargetName: m.TargetName, + DeploymentMode: m.Mode, + WorkspaceInfo: m.Workspace, + } +} + +// StaleFields returns the mask that brings current up to m, empty when the deployment already +// says what this run would say. current is nil before the first recorded deploy. +func (m Metadata) StaleFields(current *bundledeployments.Deployment) string { + if current == nil { + return strings.Join(deploymentFields, ",") + } + + want := m.deployment() + var stale []string + if want.DisplayName != current.DisplayName { + stale = append(stale, "display_name") + } + if want.TargetName != current.TargetName { + stale = append(stale, "target_name") + } + if want.DeploymentMode != current.DeploymentMode { + stale = append(stale, "deployment_mode") + } + if !sameWorkspaceInfo(want.WorkspaceInfo, current.WorkspaceInfo) { + stale = append(stale, "workspace_info") + } + return strings.Join(stale, ",") +} + +// NextVersion is the version number this run will create, given the deployment's most recent +// one. lastVersionID is empty before the deployment has any version. +func NextVersion(lastVersionID string) (int64, error) { + if lastVersionID == "" { + return 1, nil + } + last, err := strconv.ParseInt(lastVersionID, 10, 64) + if err != nil { + return 0, fmt.Errorf("failed to parse last_version_id %q: %w", lastVersionID, err) + } + return last + 1, nil +} diff --git a/libs/dms/metadata_test.go b/libs/dms/metadata_test.go new file mode 100644 index 00000000000..e3446466407 --- /dev/null +++ b/libs/dms/metadata_test.go @@ -0,0 +1,25 @@ +package dms + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNextVersion(t *testing.T) { + for _, tt := range []struct { + last string + want int64 + }{ + {"", 1}, + {"4", 5}, + } { + got, err := NextVersion(tt.last) + require.NoError(t, err) + assert.Equal(t, tt.want, got) + } + + _, err := NextVersion("not-a-number") + assert.ErrorContains(t, err, "last_version_id") +} diff --git a/libs/dms/operation.go b/libs/dms/operation.go new file mode 100644 index 00000000000..38113853460 --- /dev/null +++ b/libs/dms/operation.go @@ -0,0 +1,129 @@ +package dms + +import ( + "encoding/json" + "fmt" + "unicode/utf8" + + "github.com/databricks/cli/libs/diag" + "github.com/databricks/databricks-sdk-go/service/bundledeployments" +) + +// maxStateSize is the largest serialized state DMS accepts per operation. More than this +// and the resource cannot be recorded at all, so the deploy fails rather than leaving the +// service holding a resource with no state. +const maxStateSize = 64 * 1024 + +// maxErrorMessageSize is how much of a failure's message the service stores. +const maxErrorMessageSize = 16 * 1024 + +// StatusPending is what the service calls an operation it has recorded but not applied, which +// is where a recreate sits between deleting the old resource and creating the new one. Not in +// the SDK: the enum ships server-first while it is staged DEVELOPMENT, so the generated client +// carries only the terminal two. +const StatusPending bundledeployments.OperationStatus = "OPERATION_STATUS_PENDING" + +// OperationUpdate is one write to an operation the version staged: the fields it claims +// and their values. It is built where the outcome is known, so a malformed one fails the +// resource that produced it rather than the upload at the end of apply. +type OperationUpdate struct { + // Fields is the mask to send. It is taken literally: a field named here is written, + // one left out keeps the value it had. + Fields Fields + + // State is the serialized state after the operation, and nil for a delete. + State json.RawMessage + + ResourceID string + Status bundledeployments.OperationStatus + ErrorMessage string +} + +// NewStateUpdate describes how the resource looks now: state is the serialized envelope the +// state DB just persisted, and nil for a delete. inProgress marks a write that is half of a +// larger change - a recreate's delete - so an interrupted deploy does not report it finished. +func NewStateUpdate(resourceID string, state json.RawMessage, inProgress bool) (OperationUpdate, error) { + if len(state) > maxStateSize { + return OperationUpdate{}, fmt.Errorf("serialized state is %d bytes, which exceeds the %d byte limit for recording deployment history", len(state), maxStateSize) + } + + status := bundledeployments.OperationStatusOperationStatusSucceeded + if inProgress { + status = StatusPending + } + + // No state means nothing is left to describe, so the write clears it rather than recording + // it as empty: an empty value is a state the service refuses on a delete that succeeded, + // while an absent one is how the resource stops being listed at all. + if state == nil { + return OperationUpdate{ + Fields: ClearsState, + Status: status, + }, nil + } + + return OperationUpdate{ + Fields: DescribesResource, + State: state, + ResourceID: resourceID, + Status: status, + }, nil +} + +// NewFailureUpdate records that an operation did not apply, so the history says why a resource +// failed rather than leaving it pending. state is what the resource still has, which the service +// requires of a failure on a live one; nil when nothing is left to describe. +func NewFailureUpdate(resourceID string, state json.RawMessage, cause error) OperationUpdate { + // Summarized, not cause.Error(): for an API failure that adds the status and error + // code, which is often the most actionable part of the history. + message := diag.FormatAPIErrorSummary(cause) + if len(message) > maxErrorMessageSize { + message = message[:maxErrorMessageSize] + // The cut can land inside a rune, and the service stores a string. Drop the partial + // one: at most UTFMax-1 bytes of it can be left, so a message that was already + // invalid loses those bytes rather than being stripped away entirely. + for range utf8.UTFMax - 1 { + if utf8.ValidString(message) { + break + } + message = message[:len(message)-1] + } + } + + fields := KeepsState + if state != nil { + // The id travels with the state, which the service requires of any mask naming one. + fields = DescribesResource + } + + return OperationUpdate{ + Fields: fields, + State: state, + ResourceID: resourceID, + Status: bundledeployments.OperationStatusOperationStatusFailed, + ErrorMessage: message, + } +} + +// Merge folds a later update into u, for a resource written twice before either upload ran. +// Each field comes from whichever update claimed it, newer winning when both did, and the +// mask is the union. What an update claims is decided where it is built, not here. +func (u OperationUpdate) Merge(newer OperationUpdate) OperationUpdate { + merged := u + merged.Fields = u.Fields | newer.Fields + + if newer.Fields.Has(FieldState) { + merged.State = newer.State + } + if newer.Fields.Has(FieldResourceID) { + merged.ResourceID = newer.ResourceID + } + if newer.Fields.Has(FieldErrorMessage) { + merged.ErrorMessage = newer.ErrorMessage + } + if newer.Fields.Has(FieldStatus) { + merged.Status = newer.Status + } + + return merged +} diff --git a/libs/dms/operation_buffer.go b/libs/dms/operation_buffer.go new file mode 100644 index 00000000000..bc58ff5285e --- /dev/null +++ b/libs/dms/operation_buffer.go @@ -0,0 +1,171 @@ +package dms + +import ( + "context" + "encoding/json" + "fmt" + "sync" +) + +// bufferedOperations caps how far ahead of the service a deploy may get; DMS is what the next +// plan reads. +const bufferedOperations = 10 + +// stagedSequenceID is what version creation leaves on a staged operation, so a resource's first +// update sends it as the precondition. +const stagedSequenceID = "0" + +// OperationBuffer records each state write with DMS for one deployment version, off the apply +// path: writes are queued and sent on one background goroutine. It exists only while a bundle +// records deployment history; callers hold a nil buffer otherwise and must not call it. +type OperationBuffer struct { + client *Client + deploymentID string + versionNum int64 + + // The buffer. queue holds bundle state keys, and pending the newest update per key, so a + // second write for a resource replaces the first. + queue chan string + done chan struct{} + stopQueue func() + + // sequenceIDs holds the token the last update for a resource returned. A resource absent + // from it has only what staging left, so its first update sends that. Unguarded: run is the + // only goroutine that writes, one update at a time. + sequenceIDs map[string]string + + // mu guards the fields below. + mu sync.Mutex + + // pending holds the newest update per resource key, absent once the writer takes it. + pending map[string]OperationUpdate + + err error +} + +// StartOperationBuffer opens the buffer for the version the caller just created. The version +// must already exist: operations record under it, and nothing here creates it. +func StartOperationBuffer(ctx context.Context, client *Client, deploymentID string, versionNum int64) *OperationBuffer { + b := &OperationBuffer{ + client: client, + deploymentID: deploymentID, + versionNum: versionNum, + queue: make(chan string, bufferedOperations), + done: make(chan struct{}), + pending: make(map[string]OperationUpdate), + sequenceIDs: make(map[string]string), + } + b.stopQueue = sync.OnceFunc(func() { close(b.queue) }) + go b.run(ctx) + return b +} + +// RecordOperation records a state write. state is the serialized envelope, nil for a delete. +// An earlier failure does not stop it: keep recording, best effort. +func (b *OperationBuffer) RecordOperation(ctx context.Context, resourceKey string, inProgress bool, resourceID string, state json.RawMessage) { + update, err := NewStateUpdate(resourceID, state, inProgress) + if err != nil { + b.setErr(fmt.Errorf("recording operation for %s: %w", resourceKey, err)) + return + } + + b.record(resourceKey, update) +} + +// RecordFailure records that a resource did not apply, so the history says why rather +// than leaving the resource out. +func (b *OperationBuffer) RecordFailure(resourceKey, resourceID string, state json.RawMessage, cause error) { + b.record(resourceKey, NewFailureUpdate(resourceID, state, cause)) +} + +// record makes update the one waiting for resourceKey, waiting itself while the queue is +// full. Recording after Drain panics, so every caller must return before Drain. +func (b *OperationBuffer) record(resourceKey string, update OperationUpdate) { + b.mu.Lock() + waiting, queued := b.pending[resourceKey] + if queued { + update = waiting.Merge(update) + } + b.pending[resourceKey] = update + b.mu.Unlock() + + // when already queued: the writer reads the map when it gets to the key, + // so it picks up what was just stored. + // + // Only when the resource is not already queued, enqueue it. + if !queued { + b.queue <- resourceKey + } +} + +// take claims the update waiting for resourceKey. +func (b *OperationBuffer) take(resourceKey string) (OperationUpdate, bool) { + b.mu.Lock() + defer b.mu.Unlock() + + update, ok := b.pending[resourceKey] + delete(b.pending, resourceKey) + return update, ok +} + +func (b *OperationBuffer) run(ctx context.Context) { + defer close(b.done) + + for resourceKey := range b.queue { + update, ok := b.take(resourceKey) + if !ok { + // Unreachable: a key is queued only when nothing was waiting for it. Guard so + // a stray key could never write a zero-valued update. + continue + } + + // Keep going after a failure, so one bad write does not drop everything behind it. + if err := b.write(ctx, resourceKey, update); err != nil { + b.setErr(fmt.Errorf("recording operation for %s: %w", resourceKey, err)) + } + } +} + +// write sends one update, at the sequence id the resource is at. +func (b *OperationBuffer) write(ctx context.Context, key string, update OperationUpdate) error { + sequenceID, written := b.sequenceIDs[key] + if !written { + sequenceID = stagedSequenceID + } + + next, err := b.client.UpdateOperation(ctx, b.deploymentID, b.versionNum, key, sequenceID, update) + if err != nil { + return err + } + + // The next write for this resource echoes the sequence id this one earned. + b.sequenceIDs[key] = next + + return nil +} + +// Drain waits for everything buffered to reach the service and returns the first write error, +// which fails the deploy: DMS is the source of truth for what exists. Safe to call twice. +func (b *OperationBuffer) Drain() error { + b.stopQueue() + <-b.done + return b.Err() +} + +// setErr keeps the first error; one failure is enough to fail the deploy. +func (b *OperationBuffer) setErr(err error) { + b.mu.Lock() + defer b.mu.Unlock() + + if b.err == nil { + b.err = err + } +} + +// Err returns the first recording error, or nil. +func (b *OperationBuffer) Err() error { + b.mu.Lock() + defer b.mu.Unlock() + + return b.err +} diff --git a/libs/dms/operation_buffer_test.go b/libs/dms/operation_buffer_test.go new file mode 100644 index 00000000000..a57f25c7de5 --- /dev/null +++ b/libs/dms/operation_buffer_test.go @@ -0,0 +1,78 @@ +package dms + +import ( + "encoding/json" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// What the service ends up holding - the version a deploy claims, the operations it stages, the +// completion it reports - is asserted end to end by acceptance/bundle/dms. What is left here is +// what a deploy cannot reach: the queue's coalescing and the size limit. No test here goes +// through the API - the queue is driven directly, so nothing waits on a request. + +// queued builds a buffer whose queue nothing drains, so a test drives record and take itself. +func queued() *OperationBuffer { + return &OperationBuffer{ + queue: make(chan string, bufferedOperations), + pending: make(map[string]OperationUpdate), + } +} + +func stateUpdate(t *testing.T, name string) OperationUpdate { + t.Helper() + update, err := NewStateUpdate("id-1", json.RawMessage(`{"state":{"name":"`+name+`"}}`), false) + require.NoError(t, err) + return update +} + +func TestBufferCoalescesWhileAKeyIsPending(t *testing.T) { + s := queued() + + // Two writes for one resource with nothing draining. They carry the resource's full + // state, so only the newest needs to go: one slot in the queue, not two. + s.record("resources.jobs.foo", stateUpdate(t, "v1")) + s.record("resources.jobs.foo", stateUpdate(t, "v2")) + + assert.Len(t, s.queue, 1) + update, ok := s.take("resources.jobs.foo") + require.True(t, ok) + assert.JSONEq(t, `{"state":{"name":"v2"}}`, string(update.State)) + + // Taken means a request has it, and an in-flight request cannot be recalled, so the next + // write gets its own slot rather than joining it. + s.record("resources.jobs.foo", stateUpdate(t, "v3")) + assert.Len(t, s.queue, 2) + update, ok = s.take("resources.jobs.foo") + require.True(t, ok) + assert.JSONEq(t, `{"state":{"name":"v3"}}`, string(update.State)) +} + +func TestBufferFailsOnOversizedState(t *testing.T) { + // The service will not take a state this large, so the resource cannot be recorded. + // Failing here says so, where reporting nothing would leave DMS without the resource + // and the next plan would create it again. + s := queued() + + s.RecordOperation(t.Context(), "resources.jobs.foo", false, "id-1", json.RawMessage(strings.Repeat("x", maxStateSize+1))) + + assert.ErrorContains(t, s.Err(), "exceeds the 65536 byte limit") + assert.Empty(t, s.queue) + assert.Empty(t, s.pending) +} + +func TestDrainIsIdempotent(t *testing.T) { + // Nothing recorded, so no transport is needed: this is the second drain, which must not + // panic on an already closed queue. + s := queued() + s.done = make(chan struct{}) + s.stopQueue = sync.OnceFunc(func() { close(s.queue) }) + go s.run(t.Context()) + + require.NoError(t, s.Drain()) + require.NoError(t, s.Drain()) +} diff --git a/libs/dms/operation_test.go b/libs/dms/operation_test.go new file mode 100644 index 00000000000..2bae9a81144 --- /dev/null +++ b/libs/dms/operation_test.go @@ -0,0 +1,83 @@ +package dms + +import ( + "encoding/json" + "errors" + "strings" + "testing" + "unicode/utf8" + + "github.com/databricks/databricks-sdk-go/service/bundledeployments" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// What these updates put on the wire - the mask, the status, the state a write carries and a +// failure leaves alone - is asserted by acceptance/bundle/dms. What is left here are the limits +// and the merge, which a deploy cannot reach. + +func TestNewFailureUpdateTruncatesLongError(t *testing.T) { + // Truncated rather than rejected: a message over the limit would make recording + // fail and hide the error it is reporting. + update := NewFailureUpdate("job-123", nil, errors.New(strings.Repeat("x", maxErrorMessageSize+100))) + + assert.Len(t, update.ErrorMessage, maxErrorMessageSize) +} + +func TestNewFailureUpdatePreservesUTF8OnTruncation(t *testing.T) { + // The cut lands one byte into the emoji, so a byte-wise truncation would leave a partial + // rune behind and the service stores state and messages as strings. + msg := strings.Repeat("a", maxErrorMessageSize-1) + "❌" + "x" + + update := NewFailureUpdate("job-123", nil, errors.New(msg)) + + assert.True(t, utf8.ValidString(update.ErrorMessage)) + // The whole emoji went, so the message is shorter than the limit rather than exactly it. + assert.Equal(t, strings.Repeat("a", maxErrorMessageSize-1), update.ErrorMessage) +} + +func TestMergeLetsAWriteSupersedeAFailure(t *testing.T) { + // A failure is not the last word. A retry that writes state wins whole - state, id and + // mask - and the mask names error_message so the recorded failure is cleared. The service + // rejects a succeeded operation that still carries an error. + failed := NewFailureUpdate("id-old", nil, errors.New("boom")) + retried, err := NewStateUpdate("id-new", json.RawMessage(`{"state":{"name":"after"}}`), false) + require.NoError(t, err) + + merged := failed.Merge(retried) + + assert.Equal(t, bundledeployments.OperationStatusOperationStatusSucceeded, merged.Status) + assert.Empty(t, merged.ErrorMessage) + assert.Equal(t, "id-new", merged.ResourceID) + assert.JSONEq(t, `{"state":{"name":"after"}}`, string(merged.State)) + assert.Equal(t, DescribesResource, merged.Fields) +} + +func TestMergeKeepsTheWritesStateAndMask(t *testing.T) { + // A failure claims only status and error_message, so the write's state, id and mask + // survive: the resource stays listed as it was written, now marked failed. + write, err := NewStateUpdate("id-new", json.RawMessage(`{"state":{"name":"before"}}`), false) + require.NoError(t, err) + failed := NewFailureUpdate("id-old", nil, errors.New("boom")) + + merged := write.Merge(failed) + + assert.Equal(t, bundledeployments.OperationStatusOperationStatusFailed, merged.Status) + assert.Equal(t, "boom", merged.ErrorMessage) + assert.Equal(t, "id-new", merged.ResourceID) + assert.JSONEq(t, `{"state":{"name":"before"}}`, string(merged.State)) + assert.Equal(t, DescribesResource, merged.Fields) +} + +func TestMergeLetsADeleteClearTheState(t *testing.T) { + // A delete legitimately carries no state, and merging must let it through: the resource + // is gone, and keeping the state it replaces would leave it listed. + write, err := NewStateUpdate("id-1", json.RawMessage(`{"state":{"name":"before"}}`), false) + require.NoError(t, err) + deleted, err := NewStateUpdate("id-1", nil, false) + require.NoError(t, err) + + merged := write.Merge(deleted) + + assert.Nil(t, merged.State) +} diff --git a/libs/dms/resources.go b/libs/dms/resources.go new file mode 100644 index 00000000000..565571415f6 --- /dev/null +++ b/libs/dms/resources.go @@ -0,0 +1,41 @@ +package dms + +import ( + "context" + "fmt" + + "github.com/databricks/databricks-sdk-go/service/bundledeployments" +) + +// Resource is what DMS holds for one resource of a deployment, as of the last operation +// that recorded it. +type Resource struct { + // Key is the bundle state key, as everything outside this package spells it. + Key string + ID string + + // State is the state the last operation recorded, as the opaque string the service + // stores, and empty when no operation recorded one. + State string +} + +// ListResources returns every resource DMS holds for the deployment. +func (c *Client) ListResources(ctx context.Context, deploymentID string) ([]Resource, error) { + it := c.Service.ListResources(ctx, bundledeployments.ListResourcesRequest{ + Parent: DeploymentName(deploymentID), + }) + + var out []Resource + for it.HasNext(ctx) { + res, err := it.Next(ctx) + if err != nil { + return nil, fmt.Errorf("listing resources from deployment metadata service: %w", err) + } + out = append(out, Resource{ + Key: statePrefix + res.ResourceKey, + ID: res.ResourceId, + State: res.State, + }) + } + return out, nil +} diff --git a/libs/testserver/bundledeployments.go b/libs/testserver/bundledeployments.go new file mode 100644 index 00000000000..3545036297a --- /dev/null +++ b/libs/testserver/bundledeployments.go @@ -0,0 +1,615 @@ +package testserver + +import ( + "bytes" + "encoding/json" + "fmt" + "path" + "slices" + "strconv" + "strings" + + "github.com/databricks/databricks-sdk-go/service/bundledeployments" + "github.com/databricks/databricks-sdk-go/service/workspace" +) + +// Handlers for the Deployment Metadata Service (DMS) API under /api/2.0/bundle. + +// maxOperationsPerVersion mirrors the service's compiled-in default. A bundle past it cannot +// be recorded, since the operation set is fixed when the version is created. +const maxOperationsPerVersion = 800 + +// operationStatusPending is what CreateVersion leaves on a staged operation. Declared here +// because the SDK enum is generated from the OpenAPI spec, which trails the service proto. +const operationStatusPending bundledeployments.OperationStatus = "OPERATION_STATUS_PENDING" + +// State is kept in FakeWorkspace.DmsDeployments, keyed by deployment ID. + +// dmsDeploymentNodeName is the workspace node name the service uses for deployments. +// It must match DEPLOYMENT_NODE_NAME on the service side (DeploymentWhsClient). +const dmsDeploymentNodeName = "resources.deployment.json" + +// dmsUpdatableOperationFields are the update_mask paths UpdateOperation accepts. Any +// other path is rejected, and action_type in particular is fixed when the operation is +// created. +var dmsUpdatableOperationFields = []string{"state", "error_message", "resource_id", "status"} + +// DmsDeployment holds a deployment record together with the versions and +// resources recorded under it, so the read APIs (ListVersions/ListResources) +// can serve back what deploys wrote. +type DmsDeployment struct { + Deployment bundledeployments.Deployment + Versions map[string]*bundledeployments.Version + // resources is the latest resource state per resource key, updated as + // operations are recorded. + Resources map[string]bundledeployments.Resource + // operations holds the recorded operations by resource name. The service keeps + // one per resource per version, so a resource written twice in a version updates + // its operation rather than adding another. + Operations map[string]*bundledeployments.Operation + // lastSuccessfulVersionID is the highest version completed successfully. + // The read path treats a non-empty value as "DMS owns the state"; + // the SDK Deployment struct does not yet carry this field. + LastSuccessfulVersionID string +} + +func (s *FakeWorkspace) CreateDeployment(req Request) Response { + var dep bundledeployments.Deployment + if err := json.Unmarshal(req.Body, &dep); err != nil { + return Response{StatusCode: 400, Body: map[string]string{"message": err.Error()}} + } + if dep.InitialParentPath == "" { + return Response{ + StatusCode: 400, + Body: map[string]string{"error_code": "INVALID_PARAMETER_VALUE", "message": "initial_parent_path is required"}, + } + } + + defer s.LockUnlock()() + + // The service registers the deployment as a workspace node under + // initial_parent_path and uses that node's ID as the deployment ID, so a + // get-status on the node path is how clients look the deployment back up. + nodePath := path.Join(dep.InitialParentPath, dmsDeploymentNodeName) + if resp, ok := s.requireParentDirectory(nodePath); !ok { + return resp + } + objectID := nextID() + s.files[nodePath] = FileEntry{ + Info: workspace.ObjectInfo{ + // The service registers its own node type, which get-status reports back; + // a plain FILE is what the fake used to claim and the real API never returns. + ObjectType: "BUNDLE_DEPLOYMENT", + Path: nodePath, + ObjectId: objectID, + }, + } + + // The record carries no version yet; last_version_id stays empty until + // the first CreateVersion. A failed registration leaves a record with no versions. + deploymentID := strconv.FormatInt(objectID, 10) + s.DmsDeploymentNodes[deploymentID] = nodePath + + if resp, ok := checkWorkspaceInfo(dep.WorkspaceInfo); !ok { + return resp + } + + dep.Name = "deployments/" + deploymentID + dep.Status = bundledeployments.DeploymentStatusDeploymentStatusActive + s.DmsDeployments[deploymentID] = &DmsDeployment{ + Deployment: dep, + Versions: map[string]*bundledeployments.Version{}, + Resources: map[string]bundledeployments.Resource{}, + Operations: map[string]*bundledeployments.Operation{}, + } + return Response{Body: dep} +} + +func (s *FakeWorkspace) GetDeployment(deploymentID string) Response { + defer s.LockUnlock()() + + d, ok := s.DmsDeployments[deploymentID] + if !ok { + return dmsNotFound("deployment " + deploymentID) + } + + body, err := deploymentBody(d) + if err != nil { + return Response{StatusCode: 500, Body: map[string]string{"message": err.Error()}} + } + return Response{Body: body} +} + +// deploymentBody renders a deployment with last_successful_version_id, which +// the SDK struct doesn't yet carry. Embedding in a wrapper won't work because +// Deployment.MarshalJSON silently drops sibling fields. +func deploymentBody(d *DmsDeployment) (map[string]any, error) { + raw, err := json.Marshal(d.Deployment) + if err != nil { + return nil, err + } + + var body map[string]any + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + if err := dec.Decode(&body); err != nil { + return nil, err + } + + if d.LastSuccessfulVersionID != "" { + body["last_successful_version_id"] = d.LastSuccessfulVersionID + } + return body, nil +} + +// dmsUpdatableDeploymentFields are the update_mask paths UpdateDeployment accepts. +var dmsUpdatableDeploymentFields = []string{"display_name", "target_name", "deployment_mode", "workspace_info"} + +// checkWorkspaceInfo rejects a bundle_root_path without the git_folder_path it is relative to, +// which is what the service does. +func checkWorkspaceInfo(ws *bundledeployments.WorkspaceInfo) (Response, bool) { + if ws != nil && (ws.GitFolderPath == "") != (ws.BundleRootPath == "") { + return dmsInvalidArgument("workspace_info.git_folder_path and workspace_info.bundle_root_path must be set together"), false + } + return Response{}, true +} + +func (s *FakeWorkspace) UpdateDeployment(req Request, deploymentID string) Response { + var raw map[string]json.RawMessage + if err := json.Unmarshal(req.Body, &raw); err != nil { + return Response{StatusCode: 400, Body: map[string]string{"message": err.Error()}} + } + var dep bundledeployments.Deployment + if err := json.Unmarshal(req.Body, &dep); err != nil { + return Response{StatusCode: 400, Body: map[string]string{"message": err.Error()}} + } + + updateMask := req.URL.Query().Get("update_mask") + if updateMask == "" { + return dmsInvalidArgument("update_mask is required") + } + update := map[string]bool{} + for path := range strings.SplitSeq(updateMask, ",") { + path = strings.TrimSpace(path) + if !slices.Contains(dmsUpdatableDeploymentFields, path) { + return dmsInvalidArgument("update_mask path " + path + " is not updatable") + } + if _, sent := raw[path]; !sent { + // An empty value is how a field is cleared, so the field has to be there to say so. + return dmsInvalidArgument(path + " is required when '" + path + "' is in update_mask (an empty value clears it)") + } + update[path] = true + } + + if resp, ok := checkWorkspaceInfo(dep.WorkspaceInfo); !ok { + return resp + } + + defer s.LockUnlock()() + + d, ok := s.DmsDeployments[deploymentID] + if !ok { + return dmsNotFound("deployment " + deploymentID) + } + + // Only the masked paths are written; every other field of the body is ignored. + if update["display_name"] { + d.Deployment.DisplayName = dep.DisplayName + } + if update["target_name"] { + d.Deployment.TargetName = dep.TargetName + } + if update["deployment_mode"] { + d.Deployment.DeploymentMode = dep.DeploymentMode + } + if update["workspace_info"] { + d.Deployment.WorkspaceInfo = dep.WorkspaceInfo + } + + body, err := deploymentBody(d) + if err != nil { + return Response{StatusCode: 500, Body: map[string]string{"message": err.Error()}} + } + return Response{Body: body} +} + +func (s *FakeWorkspace) DeleteDeployment(deploymentID string) Response { + defer s.LockUnlock()() + + // The service trashes the deployment's workspace node, so a later get-status + // on the node path reports the deployment as absent. + if nodePath, ok := s.DmsDeploymentNodes[deploymentID]; ok { + delete(s.files, nodePath) + } + delete(s.DmsDeploymentNodes, deploymentID) + delete(s.DmsDeployments, deploymentID) + return Response{Body: map[string]any{}} +} + +func (s *FakeWorkspace) CreateVersion(req Request, deploymentID string) Response { + versionID := req.URL.Query().Get("version_id") + + var version bundledeployments.Version + if err := json.Unmarshal(req.Body, &version); err != nil { + return Response{StatusCode: 400, Body: map[string]string{"message": err.Error()}} + } + + // operations rides in the version body like every other field, but is absent from the + // generated struct while the field is at DEVELOPMENT stage, so it is read separately. + // Embedding Version instead would promote its own UnmarshalJSON and silently drop this + // field. It is input only, so it is read here and never returned. + var staged struct { + Operations []struct { + ResourceKey string `json:"resource_key"` + ActionType bundledeployments.OperationActionType `json:"action_type"` + } `json:"operations"` + } + if err := json.Unmarshal(req.Body, &staged); err != nil { + return Response{StatusCode: 400, Body: map[string]string{"message": err.Error()}} + } + + defer s.LockUnlock()() + + d, ok := s.DmsDeployments[deploymentID] + if !ok { + return dmsNotFound("deployment " + deploymentID) + } + + // version_id must be numerically greater than the most recent version, + // and previous_version_id must name that version to detect concurrent deploys. + next, err := strconv.ParseInt(versionID, 10, 64) + if err != nil || next < 1 { + return dmsInvalidArgument("version_id must be a positive integer, got " + versionID) + } + var last int64 + if d.Deployment.LastVersionId != "" { + last, _ = strconv.ParseInt(d.Deployment.LastVersionId, 10, 64) + } + if next <= last { + return dmsInvalidArgument("version_id " + versionID + " must be greater than the most recent version " + d.Deployment.LastVersionId) + } + if version.PreviousVersionId != d.Deployment.LastVersionId { + return dmsAborted("previous_version_id is outdated; the deployment's most recent version is " + d.Deployment.LastVersionId) + } + + // Note: deployment lock not modelled. Tests kill the CLI mid-apply, leaving + // the version in-progress forever, whereas the real service lets the lease expire. + + // A version records its whole operation set up front; there is no API to add one later. + if len(staged.Operations) > maxOperationsPerVersion { + return Response{ + StatusCode: 429, + Body: map[string]string{ + "error_code": "RESOURCE_EXHAUSTED", + "message": fmt.Sprintf("a version may stage at most %d operations, got %d", maxOperationsPerVersion, len(staged.Operations)), + }, + } + } + seen := make(map[string]bool, len(staged.Operations)) + for _, staged := range staged.Operations { + switch { + case staged.ResourceKey == "": + return dmsInvalidArgument("operations.resource_key is required") + case !strings.Contains(staged.ResourceKey, "."): + return dmsInvalidArgument("operations.resource_key must have a known resource type prefix (e.g. 'jobs.', 'pipelines.'): " + staged.ResourceKey) + case staged.ActionType == "": + return dmsInvalidArgument("operations.action_type is required and must not be UNSPECIFIED for resource " + staged.ResourceKey) + case seen[staged.ResourceKey]: + return dmsInvalidArgument("operations must have distinct resource_keys; duplicate: " + staged.ResourceKey) + } + seen[staged.ResourceKey] = true + } + + d.Deployment.LastVersionId = versionID + version.Name = "deployments/" + deploymentID + "/versions/" + versionID + version.VersionId = versionID + version.Status = bundledeployments.VersionStatusVersionStatusInProgress + d.Versions[versionID] = &version + + // The deployment's git provenance is derived from the version that carried it; the rest of + // its metadata is written through CreateDeployment and UpdateDeployment. + d.Deployment.GitInfo = version.GitInfo + + // Each staged operation starts pending at sequence 0, and the CLI fills in its outcome + // with UpdateOperation as the resource is applied. + for _, staged := range staged.Operations { + opName := "deployments/" + deploymentID + "/versions/" + versionID + "/operations/" + staged.ResourceKey + d.Operations[opName] = &bundledeployments.Operation{ + Name: opName, + ResourceKey: staged.ResourceKey, + ActionType: staged.ActionType, + Status: operationStatusPending, + SequenceId: 0, + } + } + + return Response{Body: version} +} + +func (s *FakeWorkspace) CompleteVersion(req Request, deploymentID, versionID string) Response { + var completeReq bundledeployments.CompleteVersionRequest + if err := json.Unmarshal(req.Body, &completeReq); err != nil { + return Response{StatusCode: 400, Body: map[string]string{"message": err.Error()}} + } + + defer s.LockUnlock()() + + d, ok := s.DmsDeployments[deploymentID] + if !ok { + return dmsNotFound("deployment " + deploymentID) + } + v, ok := d.Versions[versionID] + if !ok { + return dmsNotFound("version " + versionID) + } + + v.Status = bundledeployments.VersionStatusVersionStatusCompleted + v.CompletionReason = completeReq.CompletionReason + if completeReq.CompletionReason == bundledeployments.VersionCompleteVersionCompleteSuccess { + d.LastSuccessfulVersionID = versionID + } + return Response{Body: *v} +} + +func (s *FakeWorkspace) Heartbeat() Response { + return Response{Body: bundledeployments.HeartbeatResponse{}} +} + +// operationBody renders an operation the way the service does: sequence_id as a +// JSON string, which the SDK struct cannot express (it types the field int64). +func operationBody(op *bundledeployments.Operation) (map[string]any, error) { + raw, err := json.Marshal(op) + if err != nil { + return nil, err + } + + var body map[string]any + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + if err := dec.Decode(&body); err != nil { + return nil, err + } + + body["sequence_id"] = strconv.FormatInt(op.SequenceId, 10) + return body, nil +} + +// UpdateOperation applies a later write for a resource already recorded in this +// version. sequence_id is the concurrency precondition and increments on success. +func (s *FakeWorkspace) UpdateOperation(req Request, deploymentID, versionID, resourceKey string) Response { + // sequence_id arrives as a string, which the SDK struct cannot hold (it types the + // field int64), so read the body twice: once for the typed fields with that key + // removed, and once for the precondition alone. + var raw map[string]json.RawMessage + if err := json.Unmarshal(req.Body, &raw); err != nil { + return Response{StatusCode: 400, Body: map[string]string{"message": err.Error()}} + } + var precondition struct { + SequenceId string `json:"sequence_id"` + } + if err := json.Unmarshal(req.Body, &precondition); err != nil { + return Response{StatusCode: 400, Body: map[string]string{"message": err.Error()}} + } + delete(raw, "sequence_id") + typedBody, err := json.Marshal(raw) + if err != nil { + return Response{StatusCode: 500, Body: map[string]string{"message": err.Error()}} + } + var op bundledeployments.Operation + if err := json.Unmarshal(typedBody, &op); err != nil { + return Response{StatusCode: 400, Body: map[string]string{"message": err.Error()}} + } + + updateMask := req.URL.Query().Get("update_mask") + if updateMask == "" { + return dmsInvalidArgument("update_mask is required") + } + // Only masked paths are written; other fields keep their values. + // Omitting state keeps the already-recorded state. + update := map[string]bool{} + for path := range strings.SplitSeq(updateMask, ",") { + path = strings.TrimSpace(path) + if !slices.Contains(dmsUpdatableOperationFields, path) { + return dmsInvalidArgument("update_mask path " + path + " is not updatable") + } + // state is the exception: masked with no value is how the service is told the resource + // is gone, which is what stops it being listed. + if _, sent := raw[path]; !sent && path != "state" { + // An empty value is how a field is cleared, so the field has to be there to say so. + return dmsInvalidArgument(path + " is required when '" + path + "' is in update_mask (an empty value clears it)") + } + update[path] = true + } + + // The service parses the status as a proto enum, so a value outside the enum arrives as + // UNSPECIFIED and is refused. Checked here too: a status the API does not have otherwise + // passes every local test and fails only against a real workspace. + if update["status"] { + switch op.Status { + case bundledeployments.OperationStatusOperationStatusSucceeded, + bundledeployments.OperationStatusOperationStatusFailed, + operationStatusPending: + default: + return dmsInvalidArgument("status is required and must not be UNSPECIFIED when 'status' is in update_mask") + } + } + + // The service counts only a state it was given as recording one, so these ask whether a + // value arrived rather than whether the mask names the field. + _, stateSent := raw["state"] + recordsState := update["state"] && stateSent + + // A resource_id can be written but not cleared, and only alongside the state it belongs to. + if update["resource_id"] { + if op.ResourceId == "" { + return dmsInvalidArgument("resource_id is required when 'resource_id' is in update_mask") + } + if !recordsState { + return dmsInvalidArgument("state must be in update_mask when 'resource_id' is") + } + } + + defer s.LockUnlock()() + + d, ok := s.DmsDeployments[deploymentID] + if !ok { + return dmsNotFound("deployment " + deploymentID) + } + + opName := "deployments/" + deploymentID + "/versions/" + versionID + "/operations/" + resourceKey + existing, ok := d.Operations[opName] + if !ok { + return dmsNotFound("operation " + opName) + } + if precondition.SequenceId != strconv.FormatInt(existing.SequenceId, 10) { + return dmsAborted("sequence_id is outdated; the operation is at " + strconv.FormatInt(existing.SequenceId, 10)) + } + + // Invariants check the operation after the update, not the request. + // The mask leaves unspecified fields unchanged. + after := *existing + if update["state"] { + after.State = op.State + } + if update["error_message"] { + after.ErrorMessage = op.ErrorMessage + } + if update["resource_id"] { + after.ResourceId = op.ResourceId + } + if update["status"] { + after.Status = op.Status + } + + failed := after.Status == bundledeployments.OperationStatusOperationStatusFailed + if !failed && after.ErrorMessage != "" { + return dmsInvalidArgument("error_message is only allowed when status is OPERATION_STATUS_FAILED") + } + + // A failure may leave no state only where nothing is left to describe: a create that never + // landed, or a recreate whose delete already went through. + if failed && after.State == "" && leavesLiveResource(after.ActionType) { + return dmsInvalidArgument("state is required for a " + string(after.ActionType) + + " operation, because it acts on a resource that already exists and cannot destroy it, even when it fails") + } + + // An operation with state must identify its resource via resource_id, + // even for failed operations reporting prior state. + if after.State != "" && after.ResourceId == "" { + return dmsInvalidArgument("resource_id is required for an operation that records state") + } + + // Only the masked fields change; action_type and resource_key stay as created. + if update["state"] { + existing.State = op.State + } + if update["error_message"] { + existing.ErrorMessage = op.ErrorMessage + } + if update["resource_id"] { + existing.ResourceId = op.ResourceId + } + if update["status"] { + existing.Status = op.Status + } + existing.SequenceId++ + + body, err := operationBody(existing) + if err != nil { + return Response{StatusCode: 500, Body: map[string]string{"message": err.Error()}} + } + + // Only an update that names state moves the resource: naming it with no value clears + // it and removes the resource, and an update that leaves it out - a failure reporting + // its outcome - must not disturb what the deployment already holds. Every version + // stages its operations without state, so re-deriving this from the operation + // regardless of the mask would drop a resource whose deploy failed before writing. + if update["state"] { + if existing.State == "" { + delete(d.Resources, resourceKey) + } else { + d.Resources[resourceKey] = bundledeployments.Resource{ + Name: "deployments/" + deploymentID + "/resources/" + resourceKey, + ResourceKey: resourceKey, + ResourceId: existing.ResourceId, + ResourceType: existing.ResourceType, + LastActionType: existing.ActionType, + LastVersionId: versionID, + State: existing.State, + } + } + } else if resource, projected := d.Resources[resourceKey]; projected && update["resource_id"] { + // resource_id is mirrored too, for a resource the deployment still holds. + resource.ResourceId = existing.ResourceId + d.Resources[resourceKey] = resource + } + + return Response{Body: body} +} + +func (s *FakeWorkspace) ListResources(deploymentID string) Response { + defer s.LockUnlock()() + + d, ok := s.DmsDeployments[deploymentID] + if !ok { + return dmsNotFound("deployment " + deploymentID) + } + + // Sort by resource key so the response order is deterministic. + keys := make([]string, 0, len(d.Resources)) + for key := range d.Resources { + keys = append(keys, key) + } + slices.Sort(keys) + + resources := make([]bundledeployments.Resource, 0, len(keys)) + for _, key := range keys { + resources = append(resources, d.Resources[key]) + } + return Response{Body: bundledeployments.ListResourcesResponse{Resources: resources}} +} + +// leavesLiveResource reports whether a failed operation of this type leaves a resource behind +// that it still has to describe. A create leaves nothing, and a recreate already deleted. +func leavesLiveResource(action bundledeployments.OperationActionType) bool { + switch action { + case bundledeployments.OperationActionTypeOperationActionTypeCreate, + bundledeployments.OperationActionTypeOperationActionTypeRecreate: + return false + default: + return true + } +} + +// dmsNotFound returns the RESOURCE_DOES_NOT_EXIST error shape the DMS API uses, +// which the SDK maps to apierr.ErrNotFound. +func dmsNotFound(what string) Response { + return Response{ + StatusCode: 404, + // Content-Type is required for the SDK to parse the body into a typed error, + // which is what callers match against apierr.ErrResourceDoesNotExist. + Headers: map[string][]string{"Content-Type": {"application/json"}}, + Body: map[string]string{ + "error_code": "RESOURCE_DOES_NOT_EXIST", + "message": what + " does not exist", + }, + } +} + +// dmsAborted returns the 409 ABORTED error the server uses for the version +// optimistic-concurrency check. +func dmsInvalidArgument(message string) Response { + return Response{ + StatusCode: 400, + Headers: map[string][]string{"Content-Type": {"application/json"}}, + Body: map[string]string{"error_code": "INVALID_PARAMETER_VALUE", "message": message}, + } +} + +func dmsAborted(message string) Response { + return Response{ + StatusCode: 409, + Headers: map[string][]string{"Content-Type": {"application/json"}}, + Body: map[string]string{"error_code": "ABORTED", "message": message}, + } +} diff --git a/libs/testserver/fake_workspace.go b/libs/testserver/fake_workspace.go index 2f077b1b631..b544c17538e 100644 --- a/libs/testserver/fake_workspace.go +++ b/libs/testserver/fake_workspace.go @@ -248,6 +248,15 @@ type FakeWorkspace struct { // clusterVenvs caches Python venvs per existing cluster ID, // matching cloud behavior where libraries are cached on running clusters. clusterVenvs map[string]*clusterEnv + + // DmsDeployments holds Deployment Metadata Service (DMS) records, keyed by + // deployment ID. Each record carries its versions and latest resource state. + DmsDeployments map[string]*DmsDeployment + + // DmsDeploymentNodes maps deployment ID to the workspace node CreateDeployment made for + // it. An ID appears here before DmsDeployments has a record, which its first version + // creates, so the node is what makes the ID valid in between. + DmsDeploymentNodes map[string]string } func (s *FakeWorkspace) LockUnlock() func() { @@ -496,6 +505,8 @@ func NewFakeWorkspace(url, token string) *FakeWorkspace { postgresImplicitBranches: map[string]bool{}, postgresImplicitEndpoints: map[string]bool{}, clusterVenvs: map[string]*clusterEnv{}, + DmsDeployments: map[string]*DmsDeployment{}, + DmsDeploymentNodes: map[string]string{}, Alerts: map[string]sql.AlertV2{}, Experiments: map[string]ml.GetExperimentResponse{}, ModelRegistryModels: map[string]ml.Model{}, diff --git a/libs/testserver/handlers.go b/libs/testserver/handlers.go index 8c44d97eae7..33a742cc2ce 100644 --- a/libs/testserver/handlers.go +++ b/libs/testserver/handlers.go @@ -279,6 +279,35 @@ func AddDefaultHandlers(server *Server) { return req.Workspace.JobsCreate(req) }) + // Deployment Metadata Service (DMS) endpoints. + server.Handle("POST", "/api/2.0/bundle/deployments", func(req Request) any { + return req.Workspace.CreateDeployment(req) + }) + server.Handle("GET", "/api/2.0/bundle/deployments/{deployment_id}", func(req Request) any { + return req.Workspace.GetDeployment(req.Vars["deployment_id"]) + }) + server.Handle("PATCH", "/api/2.0/bundle/deployments/{deployment_id}", func(req Request) any { + return req.Workspace.UpdateDeployment(req, req.Vars["deployment_id"]) + }) + server.Handle("DELETE", "/api/2.0/bundle/deployments/{deployment_id}", func(req Request) any { + return req.Workspace.DeleteDeployment(req.Vars["deployment_id"]) + }) + server.Handle("POST", "/api/2.0/bundle/deployments/{deployment_id}/versions", func(req Request) any { + return req.Workspace.CreateVersion(req, req.Vars["deployment_id"]) + }) + server.Handle("POST", "/api/2.0/bundle/deployments/{deployment_id}/versions/{version_id}/complete", func(req Request) any { + return req.Workspace.CompleteVersion(req, req.Vars["deployment_id"], req.Vars["version_id"]) + }) + server.Handle("POST", "/api/2.0/bundle/deployments/{deployment_id}/versions/{version_id}/heartbeat", func(req Request) any { + return req.Workspace.Heartbeat() + }) + server.Handle("PATCH", "/api/2.0/bundle/deployments/{deployment_id}/versions/{version_id}/operations/{resource_key}", func(req Request) any { + return req.Workspace.UpdateOperation(req, req.Vars["deployment_id"], req.Vars["version_id"], req.Vars["resource_key"]) + }) + server.Handle("GET", "/api/2.0/bundle/deployments/{deployment_id}/resources", func(req Request) any { + return req.Workspace.ListResources(req.Vars["deployment_id"]) + }) + server.Handle("POST", "/api/2.2/jobs/delete", func(req Request) any { var request jobs.DeleteJob if err := json.Unmarshal(req.Body, &request); err != nil { diff --git a/libs/workspaceurls/urls.go b/libs/workspaceurls/urls.go index 61c3f271468..0b6a80fd71b 100644 --- a/libs/workspaceurls/urls.go +++ b/libs/workspaceurls/urls.go @@ -4,6 +4,7 @@ import ( "fmt" "net/url" "slices" + "strconv" "strings" ) @@ -71,6 +72,22 @@ func ResourceTypes() []string { return names } +// DeploymentURL returns the workspace URL for a bundle deployment: +// /deployments/?version=. Version pins the page to the deploy that produced it. +func DeploymentURL(baseURL url.URL, deploymentID string, version int64) string { + if deploymentID == "" { + return "" + } + + baseURL.Path = "deployments/" + deploymentID + if version > 0 { + values := baseURL.Query() + values.Set("version", strconv.FormatInt(version, 10)) + baseURL.RawQuery = values.Encode() + } + return baseURL.String() +} + // JobRunPath returns the modern workspace path for a job run, of the form // // jobs//runs/ diff --git a/libs/workspaceurls/urls_test.go b/libs/workspaceurls/urls_test.go index a398167e027..b92df037c84 100644 --- a/libs/workspaceurls/urls_test.go +++ b/libs/workspaceurls/urls_test.go @@ -141,6 +141,55 @@ func TestResourceURL(t *testing.T) { } } +func TestDeploymentURL(t *testing.T) { + tests := []struct { + name string + deploymentID string + version int64 + base url.URL + expected string + }{ + { + name: "id and version", + deploymentID: "996980114684409", + version: 2, + base: url.URL{Scheme: "https", Host: "host.com"}, + expected: "https://host.com/deployments/996980114684409?version=2", + }, + { + // The version is only known once CreateVersion has run, so link to the + // deployment itself rather than emitting version=0. + name: "zero version omits the query", + deploymentID: "996980114684409", + version: 0, + base: url.URL{Scheme: "https", Host: "host.com"}, + expected: "https://host.com/deployments/996980114684409", + }, + { + // A base URL carrying ?w= keeps it, so a vanity or legacy + // host still addresses the right workspace. + name: "preserves an existing query", + deploymentID: "42", + version: 7, + base: url.URL{Scheme: "https", Host: "host.com", RawQuery: "w=123"}, + expected: "https://host.com/deployments/42?version=7&w=123", + }, + { + name: "empty id returns empty", + deploymentID: "", + version: 1, + base: url.URL{Scheme: "https", Host: "host.com"}, + expected: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.expected, DeploymentURL(tt.base, tt.deploymentID, tt.version)) + }) + } +} + func TestHasWorkspaceIDInHostname(t *testing.T) { tests := []struct { name string