11#!/usr/bin/env python3
22"""
3- Print resources state from default target, and handle DMS (deployment metadata service) interactions .
3+ Print resources state from the default target, normalizing history metadata for comparisons .
44
55Note, this intentionally has no logic on guessing what is the right state file (e.g. via DATABRICKS_BUNDLE_ENGINE),
66the goal is to record all states that are available.
77"""
88
99import argparse
10- import functools
1110import glob
1211import json
1312import os
1413import posixpath
1514import subprocess
16- from pathlib import Path
1715
1816from nostamp import scrub
1917
@@ -60,11 +58,7 @@ def get_state_file(target, backup):
6058 return filtered [0 ] if filtered else result [0 ]
6159
6260
63- # DMS (deployment metadata service) interaction helpers
64- # https://go.databricks.com/dms-service
65-
6661CLI = os .environ .get ("CLI" , "databricks" )
67- DEPLOYMENT_NODE_NAME = "resources.deployment.json" # Must match dms.DeploymentNodeName
6862
6963
7064def run_json (cmd , allow_failure = False ):
@@ -102,116 +96,20 @@ def get_remote_state_path(target):
10296 return run_json (args )["workspace" ]["state_path" ]
10397
10498
105- @functools .cache
106- def get_deployment_id (target ):
107- """The recorded deployment's id, or None when nothing is recorded.
108-
109- Cached and shared: both the resource listing and the version lookup need it, and resolving it
110- costs a workspace round trip. No node means nothing has been recorded, the conclusion
111- dms.resolveDeploymentID also draws from a 404 - the deployment is gone once the bundle is
112- destroyed.
113- """
114- state_path = get_remote_state_path (target )
115- if not state_path :
116- return None
117- node = run_json ([CLI , "workspace" , "get-status" , f"{ state_path } /{ DEPLOYMENT_NODE_NAME } " ], allow_failure = True )
118- if not node or not node .get ("object_id" ):
119- return None
120- return node ["object_id" ]
121-
122-
123- @functools .cache
124- def get_resources (target ):
125- """Map every recorded resource key ("jobs.foo") to its {"id", "state"}.
126-
127- File-history state is read locally. Legacy DMS state is read from the service,
128- or is empty when no deployment has been recorded. Cached for repeated resource lookups.
129- """
130- filename = get_state_file (target , False )
131- if filename .endswith ("resources.json" ) and os .path .exists (filename ):
132- data = json .loads (Path (filename ).read_text ())
133- if "deployment_history_best_effort" in (data .get ("features" ) or {}):
134- # DMS can miss history updates. The file remains authoritative in this mode.
135- return {
136- key .removeprefix ("resources." ): {
137- "id" : entry .get ("__id__" ),
138- "state" : entry .get ("state" ) or {},
139- "depends_on" : entry .get ("depends_on" ) or [],
140- }
141- for key , entry in data .get ("state" , {}).items ()
142- }
143-
144- deployment_id = get_deployment_id (target )
145- if not deployment_id :
146- return {}
147-
148- result = {}
149- # The service pages at 50 resources; the local fake returns everything at once.
150- page_token = None
151- while True :
152- url = f"/api/2.0/bundle/deployments/{ deployment_id } /resources"
153- if page_token :
154- url += f"?page_token={ page_token } "
155- listed = run_json ([CLI , "api" , "get" , url ])
156- for resource in listed .get ("resources" ) or []:
157- # The service stores state as the opaque envelope the CLI wrote (dstate.RecordedState),
158- # so unwrap it to the resource state itself.
159- envelope = json .loads (resource ["state" ]) if resource .get ("state" ) else {}
160- result [resource ["resource_key" ]] = {
161- "id" : resource .get ("resource_id" ),
162- "state" : envelope .get ("state" ) or {},
163- "depends_on" : envelope .get ("depends_on" ) or [],
164- }
165- page_token = listed .get ("next_page_token" )
166- if not page_token :
167- return result
168-
169-
170- def get_recorded_state (target ):
171- """The recorded resources in the on-disk state file's `state` shape (resources.<key> ->
172- {__id__, state, depends_on}), so a recording run prints the same shape as a non-recording one."""
173- state = {}
174- for key , value in sorted (get_resources (target ).items ()):
175- entry = {"__id__" : value ["id" ], "state" : value ["state" ]}
176- if value ["depends_on" ]:
177- entry ["depends_on" ] = value ["depends_on" ]
178- state [f"resources.{ key } " ] = entry
179- return state
180-
181-
182- def get_last_version_id (target ):
183- """The version the service has recorded for this deployment, or None when nothing is recorded."""
184- deployment_id = get_deployment_id (target )
185- if not deployment_id :
186- return None
187- deployment = run_json ([CLI , "api" , "get" , f"/api/2.0/bundle/deployments/{ deployment_id } " ])
188- return (deployment or {}).get ("last_version_id" )
189-
190-
19199def print_recorded_state (filename , target ):
192100 """Normalize history state for comparisons with ordinary file-backed deployments.
193101
194- get_resources uses the file for best-effort history and the service for legacy DMS state .
102+ Resource state and serial always come from the file, even when DMS history is incomplete .
195103 """
196104 data = json .loads (open (filename ).read ())
197105 # Recording stamps each resource payload with the deployment and version; drop it here so the
198106 # printed state matches a non-recording run without every caller piping through nostamp.
199- data ["state" ] = scrub (get_recorded_state ( target ))
107+ data ["state" ] = scrub (data . get ( "state" , {} ))
200108
201- # The file's serial is a copy of the DMS version to ensure outdated resource state is not read.
202- # Rebuild in header order with the authoritative serial from the deployment.
203- if "deployment_history_best_effort" in (data .get ("features" ) or {}):
204- serial = data .get ("serial" , 0 )
205- else :
206- last_version_id = get_last_version_id (target )
207- serial = int (last_version_id ) if last_version_id else 0
109+ serial = data .get ("serial" , 0 )
208110
209111 # Recording itself is not what these tests assert, so drop the feature that marks it.
210- features = {
211- k : v
212- for k , v in (data .get ("features" ) or {}).items ()
213- if k not in {"deployment_history" , "deployment_history_best_effort" }
214- }
112+ features = {k : v for k , v in (data .get ("features" ) or {}).items () if k != "deployment_history_best_effort" }
215113
216114 rebuilt = {}
217115 for key in ("state_version" , "cli_version" , "lineage" ):
@@ -233,7 +131,7 @@ def main():
233131 parser .add_argument (
234132 "--no-dms" ,
235133 action = "store_true" ,
236- help = "Print resources.json as-is without fetching state from DMS . "
134+ help = "Print resources.json as-is without normalizing history metadata . "
237135 "Use in bundle/dms tests to assert the file state and its feature markers." ,
238136 )
239137 args = parser .parse_args ()
0 commit comments