Skip to content

Commit 4017609

Browse files
Keep acceptance state output backed by DMS history
1 parent e6ef421 commit 4017609

1 file changed

Lines changed: 86 additions & 6 deletions

File tree

‎acceptance/bin/print_state.py‎

Lines changed: 86 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
#!/usr/bin/env python3
22
"""
3-
Print resources state from the default target, normalizing history metadata for comparisons.
3+
Print resources state from default target, and handle DMS (deployment metadata service) interactions.
44
55
Note, this intentionally has no logic on guessing what is the right state file (e.g. via DATABRICKS_BUNDLE_ENGINE),
66
the goal is to record all states that are available.
77
"""
88

99
import argparse
10+
import functools
1011
import glob
1112
import json
1213
import os
@@ -58,7 +59,11 @@ def get_state_file(target, backup):
5859
return filtered[0] if filtered else result[0]
5960

6061

62+
# DMS (deployment metadata service) interaction helpers
63+
# https://go.databricks.com/dms-service
64+
6165
CLI = os.environ.get("CLI", "databricks")
66+
DEPLOYMENT_NODE_NAME = "resources.deployment.json" # Must match dms.DeploymentNodeName
6267

6368

6469
def run_json(cmd, allow_failure=False):
@@ -96,17 +101,92 @@ def get_remote_state_path(target):
96101
return run_json(args)["workspace"]["state_path"]
97102

98103

104+
@functools.cache
105+
def get_deployment_id(target):
106+
"""The recorded deployment's id, or None when nothing is recorded.
107+
108+
Cached and shared: both the resource listing and the version lookup need it, and resolving it
109+
costs a workspace round trip. No node means nothing has been recorded, the conclusion
110+
dms.resolveDeploymentID also draws from a 404 - the deployment is gone once the bundle is
111+
destroyed.
112+
"""
113+
state_path = get_remote_state_path(target)
114+
if not state_path:
115+
return None
116+
node = run_json([CLI, "workspace", "get-status", f"{state_path}/{DEPLOYMENT_NODE_NAME}"], allow_failure=True)
117+
if not node or not node.get("object_id"):
118+
return None
119+
return node["object_id"]
120+
121+
122+
@functools.cache
123+
def get_resources(target):
124+
"""Map every recorded resource key ("jobs.foo") to its {"id", "state"}.
125+
126+
Empty when the bundle has no deployment recorded yet. Cached because a lookup costs three
127+
round trips and a script asks for one resource at a time.
128+
"""
129+
deployment_id = get_deployment_id(target)
130+
if not deployment_id:
131+
return {}
132+
133+
result = {}
134+
# The service pages at 50 resources; the local fake returns everything at once.
135+
page_token = None
136+
while True:
137+
url = f"/api/2.0/bundle/deployments/{deployment_id}/resources"
138+
if page_token:
139+
url += f"?page_token={page_token}"
140+
listed = run_json([CLI, "api", "get", url])
141+
for resource in listed.get("resources") or []:
142+
# The service stores state as the opaque envelope the CLI wrote (dstate.RecordedState),
143+
# so unwrap it to the resource state itself.
144+
envelope = json.loads(resource["state"]) if resource.get("state") else {}
145+
result[resource["resource_key"]] = {
146+
"id": resource.get("resource_id"),
147+
"state": envelope.get("state") or {},
148+
"depends_on": envelope.get("depends_on") or [],
149+
}
150+
page_token = listed.get("next_page_token")
151+
if not page_token:
152+
return result
153+
154+
155+
def get_recorded_state(target):
156+
"""The recorded resources in the on-disk state file's `state` shape (resources.<key> ->
157+
{__id__, state, depends_on}), so a recording run prints the same shape as a non-recording one."""
158+
state = {}
159+
for key, value in sorted(get_resources(target).items()):
160+
entry = {"__id__": value["id"], "state": value["state"]}
161+
if value["depends_on"]:
162+
entry["depends_on"] = value["depends_on"]
163+
state[f"resources.{key}"] = entry
164+
return state
165+
166+
167+
def get_last_version_id(target):
168+
"""The version the service has recorded for this deployment, or None when nothing is recorded."""
169+
deployment_id = get_deployment_id(target)
170+
if not deployment_id:
171+
return None
172+
deployment = run_json([CLI, "api", "get", f"/api/2.0/bundle/deployments/{deployment_id}"])
173+
return (deployment or {}).get("last_version_id")
174+
175+
99176
def print_recorded_state(filename, target):
100-
"""Normalize history state for comparisons with ordinary file-backed deployments.
177+
"""Print DMS resources using the state file's header.
101178
102-
Resource state and serial always come from the file, even when DMS history is incomplete.
179+
This checks history uploads even though resources.json remains authoritative.
180+
Use --no-dms to inspect the file state instead.
103181
"""
104182
data = json.loads(open(filename).read())
105183
# Recording stamps each resource payload with the deployment and version; drop it here so the
106184
# printed state matches a non-recording run without every caller piping through nostamp.
107-
data["state"] = scrub(data.get("state", {}))
185+
data["state"] = scrub(get_recorded_state(target))
108186

109-
serial = data.get("serial", 0)
187+
# Pair DMS resources with the DMS version. The file serial can advance independently.
188+
last_version_id = get_last_version_id(target)
189+
serial = int(last_version_id) if last_version_id else 0
110190

111191
# Recording itself is not what these tests assert, so drop the feature that marks it.
112192
features = {k: v for k, v in (data.get("features") or {}).items() if k != "deployment_history_best_effort"}
@@ -131,7 +211,7 @@ def main():
131211
parser.add_argument(
132212
"--no-dms",
133213
action="store_true",
134-
help="Print resources.json as-is without normalizing history metadata. "
214+
help="Print resources.json as-is without fetching state from DMS. "
135215
"Use in bundle/dms tests to assert the file state and its feature markers.",
136216
)
137217
args = parser.parse_args()

0 commit comments

Comments
 (0)