-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathdatabricks.py
More file actions
2253 lines (1934 loc) · 86.3 KB
/
Copy pathdatabricks.py
File metadata and controls
2253 lines (1934 loc) · 86.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Databricks workspace integration: CLI auth, token retrieval, model
discovery, AI Gateway v2 enforcement, SQL warehouse discovery, URL builders."""
from __future__ import annotations
import configparser
import functools
import json
import logging
import logging.handlers
import os
import platform
import re
import shlex
import shutil
import subprocess
import time
from concurrent.futures import (
ThreadPoolExecutor,
as_completed,
)
from concurrent.futures import (
TimeoutError as FutureTimeoutError,
)
from pathlib import Path
from typing import Literal, cast, overload
from urllib import error as urllib_error
from urllib import request as urllib_request
from urllib.parse import quote, urlencode, urlparse
from databricks.sql.exc import ServerOperationError
from ucode.config_io import APP_DIR
from ucode.ui import (
err_console,
normalize_workspace_url,
print_kv,
print_note,
print_section,
print_success,
print_warning,
spinner,
)
UNIX_DATABRICKS_INSTALL_URL = (
"https://raw.githubusercontent.com/databricks/setup-cli/main/install.sh"
)
WINDOWS_DATABRICKS_INSTALL_URL = (
"https://raw.githubusercontent.com/databricks/setup-cli/main/install.ps1"
)
AI_GATEWAY_V2_DOCS_URL = "https://docs.databricks.com/aws/en/ai-gateway/overview-beta"
MIN_DATABRICKS_CLI_VERSION = (0, 298, 0)
TOKEN_REFRESH_INTERVAL_SECONDS = 1800
def _debug_enabled() -> bool:
return os.environ.get("UCODE_DEBUG") == "1"
_DEBUG_LOGGER: logging.Logger | None = None
def _get_debug_logger() -> logging.Logger | None:
"""Lazily configure a rotating file logger when UCODE_DEBUG=1.
Returns the logger on first call (and caches it), or None if debug is
disabled or the log file could not be opened. A one-time breadcrumb is
printed to stderr so the user knows where to tail."""
global _DEBUG_LOGGER
if _DEBUG_LOGGER is not None or not _debug_enabled():
return _DEBUG_LOGGER
log_path = APP_DIR / "debug.log"
try:
log_path.parent.mkdir(parents=True, exist_ok=True)
handler = logging.handlers.RotatingFileHandler(
log_path,
maxBytes=1_000_000,
backupCount=3,
encoding="utf-8",
)
handler.setFormatter(
logging.Formatter("%(asctime)s %(message)s", datefmt="%Y-%m-%dT%H:%M:%S")
)
except OSError:
return None
logger = logging.getLogger("ucode.debug")
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.propagate = False
_DEBUG_LOGGER = logger
err_console.print(f"[dim]\\[ucode debug] logging to {log_path}[/dim]")
return _DEBUG_LOGGER
def _debug(label: str, detail: str) -> None:
"""When UCODE_DEBUG=1, append a timestamped entry to ~/.ucode/debug.log."""
logger = _get_debug_logger()
if logger is not None:
logger.debug("%s: %s", label, detail)
_SECRET_KEY_PATTERN = re.compile(r"(token|secret|password|bearer|api_key|apikey)", re.IGNORECASE)
def _format_subprocess_result(
result: subprocess.CompletedProcess[str],
) -> str:
"""Format a CompletedProcess for the debug log without leaking tokens.
On success, stdout is suppressed (it often contains the access token).
On failure, stdout/stderr are included truncated."""
stderr = (result.stderr or "").strip()[:500]
if result.returncode == 0:
return f"rc=0 stderr={stderr!r}"
stdout = (result.stdout or "").strip()[:500]
return f"rc={result.returncode} stdout={stdout!r} stderr={stderr!r}"
def _scrub_databrickscfg(text: str) -> str:
"""Redact value of any INI key that looks secret-bearing."""
out: list[str] = []
for line in text.splitlines():
stripped = line.lstrip()
if "=" in stripped and not stripped.startswith(("#", ";")):
key = stripped.split("=", 1)[0].strip()
if _SECRET_KEY_PATTERN.search(key):
indent = line[: len(line) - len(stripped)]
out.append(f"{indent}{key} = <redacted>")
continue
out.append(line)
return "\n".join(out)
def _scrub_json(value: object) -> object:
if isinstance(value, dict):
return {
k: (
"<redacted>"
if isinstance(k, str) and _SECRET_KEY_PATTERN.search(k)
else _scrub_json(v)
)
for k, v in value.items()
}
if isinstance(value, list):
return [_scrub_json(v) for v in value]
return value
@functools.cache
def _log_auth_diagnostics() -> None:
"""Dump CLI version, profiles, and ~/.databrickscfg (scrubbed) to the debug log.
No-op unless UCODE_DEBUG=1; cached so it runs at most once per process."""
if not _debug_enabled():
return
try:
version_result = subprocess.run(
["databricks", "--version"],
check=False,
capture_output=True,
text=True,
timeout=10,
)
version = (version_result.stdout or version_result.stderr or "").strip()
_debug("databricks --version", version[:200])
except (OSError, subprocess.TimeoutExpired) as exc:
_debug("databricks --version", f"exception: {type(exc).__name__}: {exc}")
try:
profiles_result = subprocess.run(
["databricks", "auth", "profiles", "--output", "json"],
check=False,
capture_output=True,
text=True,
timeout=10,
)
_debug(
"databricks auth profiles",
f"rc={profiles_result.returncode} "
f"stderr={(profiles_result.stderr or '').strip()[:300]!r}",
)
if profiles_result.returncode == 0 and profiles_result.stdout:
try:
payload = json.loads(profiles_result.stdout)
_debug("profiles json", json.dumps(_scrub_json(payload))[:2000])
except json.JSONDecodeError as exc:
_debug("profiles json", f"decode error: {exc}")
except (OSError, subprocess.TimeoutExpired) as exc:
_debug("databricks auth profiles", f"exception: {type(exc).__name__}: {exc}")
cfg_path = Path(os.environ.get("DATABRICKS_CONFIG_FILE") or "~/.databrickscfg").expanduser()
try:
if cfg_path.is_file():
raw = cfg_path.read_text(encoding="utf-8", errors="replace")
_debug(f"databrickscfg ({cfg_path})", _scrub_databrickscfg(raw)[:4000])
else:
_debug(f"databrickscfg ({cfg_path})", "not present")
except OSError as exc:
_debug(f"databrickscfg ({cfg_path})", f"read error: {exc}")
def _http_get_json(
url: str, token: str, *, timeout: int = 10
) -> tuple[dict | list | None, str | None]:
"""GET a JSON endpoint. Returns (payload, None) on success, (None, reason) on failure.
Honors UCODE_DEBUG=1 to append status + truncated body to ~/.ucode/debug.log.
"""
request = urllib_request.Request(
url,
headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},
)
try:
with urllib_request.urlopen(request, timeout=timeout) as response:
body = response.read().decode("utf-8")
_debug(f"GET {url}", f"HTTP 200, {len(body)} bytes")
if _debug_enabled():
_debug("body", body[:4000])
try:
return json.loads(body), None
except json.JSONDecodeError as exc:
return None, f"response was not valid JSON ({exc.msg})"
except urllib_error.HTTPError as exc:
body = ""
try:
body = exc.read().decode("utf-8", errors="replace") if exc.fp else ""
except Exception:
body = ""
_debug(f"GET {url}", f"HTTP {exc.code} {exc.reason}")
if _debug_enabled() and body:
_debug("body", body[:4000])
reason = f"HTTP {exc.code} {exc.reason}"
# Surface the response body too — gateway auth failures return 400
# with body `Invalid Token`, which is invisible without this.
body_excerpt = body.strip()[:200]
if body_excerpt:
reason = f"{reason}: {body_excerpt}"
return None, reason
except urllib_error.URLError as exc:
_debug(f"GET {url}", f"URLError: {exc.reason}")
return None, f"network error: {exc.reason}"
def _http_post_json(
url: str, token: str, payload: dict, *, timeout: int = 10
) -> tuple[dict | list | None, str | None]:
"""POST a JSON body to an endpoint. Returns (payload, None) on success,
(None, reason) on failure. Mirrors `_http_get_json`."""
body_bytes = json.dumps(payload).encode("utf-8")
request = urllib_request.Request(
url,
data=body_bytes,
method="POST",
headers={
"Authorization": f"Bearer {token}",
"Accept": "application/json",
"Content-Type": "application/json",
},
)
try:
with urllib_request.urlopen(request, timeout=timeout) as response:
body = response.read().decode("utf-8")
_debug(f"POST {url}", f"HTTP {response.status}, {len(body)} bytes")
if _debug_enabled():
_debug("body", body[:4000])
try:
return json.loads(body), None
except json.JSONDecodeError as exc:
return None, f"response was not valid JSON ({exc.msg})"
except urllib_error.HTTPError as exc:
body = ""
try:
body = exc.read().decode("utf-8", errors="replace") if exc.fp else ""
except Exception:
body = ""
_debug(f"POST {url}", f"HTTP {exc.code} {exc.reason}")
if _debug_enabled() and body:
_debug("body", body[:4000])
reason = f"HTTP {exc.code} {exc.reason}"
body_excerpt = body.strip()[:200]
if body_excerpt:
reason = f"{reason}: {body_excerpt}"
return None, reason
except urllib_error.URLError as exc:
_debug(f"POST {url}", f"URLError: {exc.reason}")
return None, f"network error: {exc.reason}"
def get_current_user_name(workspace: str, token: str) -> str | None:
"""Return the current user's login (email) via SCIM `Me`, or None on failure.
Databricks puts the workspace login in `userName`; fall back to the first
`emails` entry for workspaces that diverge."""
hostname = workspace_hostname(workspace)
payload, _ = _http_get_json(f"https://{hostname}/api/2.0/preview/scim/v2/Me", token)
if not isinstance(payload, dict):
return None
user_name = payload.get("userName")
if isinstance(user_name, str) and user_name.strip():
return user_name.strip()
emails = payload.get("emails")
if isinstance(emails, list):
for entry in emails:
if isinstance(entry, dict) and isinstance(entry.get("value"), str):
return entry["value"].strip()
return None
# Experiment tag Databricks sets when an experiment's traces are written to a
# Unity Catalog table. Its value is the UC destination, e.g.
# "my_catalog.my_schema.my_table". A plain (file/DBFS-backed) experiment does
# not carry this tag, so its presence is our signal that traces land in UC.
UC_TRACE_DESTINATION_TAG = "mlflow.experiment.databricksTraceDestinationPath"
def _experiment_tags(experiment: dict) -> dict[str, str | None]:
"""Flatten an experiment's ``tags`` list ([{key, value}, ...]) into a dict."""
out: dict[str, str | None] = {}
tags = experiment.get("tags")
if isinstance(tags, list):
for tag in tags:
if isinstance(tag, dict) and isinstance(tag.get("key"), str):
out[tag["key"]] = tag.get("value")
return out
def _uc_trace_destination(experiment: dict) -> str | None:
"""The Unity Catalog destination (``catalog.schema.table``) an experiment
logs traces to, or None when it isn't UC-backed. Any three-part UC name
qualifies — the specific catalog/schema/table is not constrained."""
value = _experiment_tags(experiment).get(UC_TRACE_DESTINATION_TAG)
if isinstance(value, str):
parts = value.split(".")
if len(parts) == 3 and all(parts):
return value
return None
def find_uc_backed_experiment(
workspace: str, token: str, leaf_name: str
) -> tuple[dict | None, str | None]:
"""Find an existing experiment whose final path segment is ``leaf_name`` and
whose traces are backed by Unity Catalog.
Returns (experiment, reason). On success ``experiment`` is
``{"experiment_id", "experiment_name", "uc_destination"}`` and reason is
None. On failure ``experiment`` is None and reason explains why (no such
experiment, or it exists but isn't UC-backed) so the caller can tell the
user to create one."""
hostname = workspace_hostname(workspace)
# Leaf-match in the filter (anything ending in the name), then confirm the
# exact leaf segment in Python so "/Users/<me>/ucode-traces" matches but
# "team-ucode-traces" does not.
safe_leaf = leaf_name.replace("'", "")
payload, reason = _http_post_json(
f"https://{hostname}/api/2.0/mlflow/experiments/search",
token,
{"filter": f"name LIKE '%{safe_leaf}'", "max_results": 1000},
)
if not isinstance(payload, dict):
return None, reason or "could not search MLflow experiments"
experiments = payload.get("experiments")
named = [
exp
for exp in (experiments if isinstance(experiments, list) else [])
if isinstance(exp, dict)
and str(exp.get("name") or "").rsplit("/", 1)[-1] == leaf_name
and exp.get("experiment_id")
]
if not named:
return None, f"no experiment named '{leaf_name}' exists on this workspace"
for exp in named:
dest = _uc_trace_destination(exp)
if dest:
return {
"experiment_id": str(exp["experiment_id"]),
"experiment_name": str(exp.get("name") or leaf_name),
"uc_destination": dest,
}, None
return (
None,
f"experiment '{leaf_name}' exists but its traces are not backed by Unity Catalog",
)
def resolve_sql_warehouse_id(workspace: str, token: str) -> tuple[str | None, str | None]:
"""Pick a SQL warehouse for writing traces to a UC-backed experiment.
Writing traces to a Unity Catalog table requires a SQL warehouse
(``MLFLOW_TRACING_SQL_WAREHOUSE_ID``); without one the MLflow exporter
silently drops them. We prefer a RUNNING warehouse so the first trace isn't
blocked on a cold start, falling back to any existing warehouse (a stopped
one auto-starts on first query). Returns (warehouse_id, reason); reason is
None on success, else explains why none could be resolved."""
hostname = workspace_hostname(workspace)
payload, reason = _http_get_json(f"https://{hostname}/api/2.0/sql/warehouses", token)
if not isinstance(payload, dict):
return None, reason or "could not list SQL warehouses"
warehouses = payload.get("warehouses")
warehouses = (
[w for w in warehouses if isinstance(w, dict) and w.get("id")]
if isinstance(warehouses, list)
else []
)
if not warehouses:
return None, "no SQL warehouse exists on this workspace"
running = next((w for w in warehouses if str(w.get("state")).upper() == "RUNNING"), None)
chosen = running or warehouses[0]
return str(chosen["id"]), None
@overload
def run(
args: list[str],
*,
check: bool = True,
capture_output: bool = False,
text: Literal[True],
env: dict[str, str] | None = None,
timeout: int | None = None,
) -> subprocess.CompletedProcess[str]: ...
@overload
def run(
args: list[str],
*,
check: bool = True,
capture_output: bool = False,
text: Literal[False] = False,
env: dict[str, str] | None = None,
timeout: int | None = None,
) -> subprocess.CompletedProcess[bytes]: ...
def run(
args: list[str],
*,
check: bool = True,
capture_output: bool = False,
text: bool = False,
env: dict[str, str] | None = None,
timeout: int | None = None,
) -> subprocess.CompletedProcess[str] | subprocess.CompletedProcess[bytes]:
return subprocess.run(
args,
check=check,
capture_output=capture_output,
text=text,
env=env,
timeout=timeout,
)
def build_databricks_cli_env(workspace: str, profile: str | None = None) -> dict[str, str]:
env = os.environ.copy()
env["DATABRICKS_HOST"] = workspace
if profile is None:
env.pop("DATABRICKS_CONFIG_PROFILE", None)
return env
def workspace_hostname(workspace: str) -> str:
parsed = urlparse(normalize_workspace_url(workspace))
if not parsed.hostname:
raise RuntimeError(f"Unable to derive hostname from workspace URL: {workspace}")
return parsed.hostname
def _parse_databricks_cli_version(output: str) -> tuple[int, int, int] | None:
# Example output: "Databricks CLI v0.299.2"
match = re.search(r"v?(\d+)\.(\d+)\.(\d+)", output)
if not match:
return None
return (int(match.group(1)), int(match.group(2)), int(match.group(3)))
def _run_databricks_cli_installer(brew_subcommand: str = "install") -> None:
system = platform.system()
try:
if system == "Windows":
run(
["powershell", "-Command", f"irm {WINDOWS_DATABRICKS_INSTALL_URL} | iex"],
timeout=240,
)
elif system == "Darwin" and shutil.which("brew"):
run(["brew", brew_subcommand, "databricks/tap/databricks"], timeout=240)
elif shutil.which("curl"):
run(["sh", "-c", f"curl -fsSL {UNIX_DATABRICKS_INSTALL_URL} | sudo sh"], timeout=240)
elif shutil.which("wget"):
run(["sh", "-c", f"wget -qO- {UNIX_DATABRICKS_INSTALL_URL} | sudo sh"], timeout=240)
else:
raise RuntimeError("Neither curl nor wget is available.")
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, RuntimeError) as exc:
raise RuntimeError("Failed to install/upgrade Databricks CLI automatically.") from exc
def ensure_databricks_cli_version() -> None:
try:
result = run(
["databricks", "--version"],
check=False,
capture_output=True,
text=True,
timeout=10,
)
except (OSError, subprocess.TimeoutExpired) as exc:
raise RuntimeError("Failed to read Databricks CLI version.") from exc
raw = result.stdout or result.stderr or ""
output = (raw if isinstance(raw, str) else raw.decode(errors="replace")).strip()
version = _parse_databricks_cli_version(output)
if version is None:
raise RuntimeError(
f"Could not parse Databricks CLI version from `databricks --version` output: {output!r}"
)
if version < MIN_DATABRICKS_CLI_VERSION:
current = ".".join(str(n) for n in version)
required = ".".join(str(n) for n in MIN_DATABRICKS_CLI_VERSION)
print_warning(
f"Databricks CLI v{current} is too old (need v{required} or newer). Upgrading..."
)
_run_databricks_cli_installer(brew_subcommand="upgrade")
ensure_databricks_cli_version()
def install_databricks_cli() -> None:
if shutil.which("databricks"):
ensure_databricks_cli_version()
return
print_section("Bootstrap")
print_warning("`databricks` was not found. Installing Databricks CLI...")
_run_databricks_cli_installer(brew_subcommand="install")
if not shutil.which("databricks"):
raise RuntimeError(
"Databricks CLI install completed, but `databricks` is still not on PATH."
)
ensure_databricks_cli_version()
def _profile_args(profile: str | None) -> list[str]:
"""Return ``["--profile", profile]`` when set, otherwise an empty list.
Centralizing this keeps every `databricks` CLI invocation in this module
consistent when a workspace's `~/.databrickscfg` has more than one profile
pointing at the same host."""
return ["--profile", profile] if profile else []
def has_valid_databricks_auth(workspace: str, profile: str | None = None) -> bool:
# Honor the CI short-circuit (see ``get_databricks_token``): if a
# pre-fetched bearer is available, treat auth as valid and skip the
# `databricks auth token` shell-out (which only knows user-OAuth).
if os.environ.get("DATABRICKS_BEARER", "").strip():
return True
_log_auth_diagnostics()
# Mirror run_databricks_login: when ~/.databrickscfg has multiple
# profiles for the same host, `databricks auth token --host …` refuses
# to disambiguate without --profile, so resolve it from the host here.
profile = profile or find_profile_name_for_host(workspace)
try:
env = build_databricks_cli_env(workspace, profile)
result = run(
[
"databricks",
"auth",
"token",
"--host",
workspace,
*_profile_args(profile),
"--output",
"json",
],
check=False,
capture_output=True,
text=True,
env=env,
timeout=15,
)
_debug(
"has_valid_databricks_auth",
_format_subprocess_result(result),
)
if result.returncode != 0:
return False
data = json.loads(result.stdout or "{}")
return bool(data.get("access_token"))
except (json.JSONDecodeError, OSError, subprocess.TimeoutExpired) as exc:
_debug("has_valid_databricks_auth", f"exception: {type(exc).__name__}: {exc}")
return False
def list_profile_entries() -> list[dict]:
"""Return raw profile dicts ({"name", "host", "auth_type", ...}) from
`databricks auth profiles`.
Returns ``[]`` on any failure (CLI missing, timeout, non-zero exit, JSON
decode error). When ``UCODE_DEBUG=1`` each dropout path logs *why* the
result was empty so a silently-disappearing workspace picker is
diagnosable from ``~/.ucode/debug.log``.
"""
try:
result = run(
["databricks", "auth", "profiles", "--output", "json"],
check=False,
capture_output=True,
text=True,
timeout=20,
)
except (OSError, subprocess.TimeoutExpired) as exc:
_debug("list_profile_entries", f"subprocess error: {type(exc).__name__}: {exc}")
return []
if result.returncode != 0:
_debug("list_profile_entries", _format_subprocess_result(result))
return []
try:
profiles = json.loads(result.stdout or "{}").get("profiles") or []
except json.JSONDecodeError as exc:
_debug("list_profile_entries", f"json decode error: {exc.msg}")
return []
return [p for p in profiles if isinstance(p, dict)]
def get_databricks_profiles() -> list[tuple[str, str]]:
"""Return [(host_url, profile_name), ...] from Databricks CLI profiles."""
profiles = list_profile_entries()
# dict dedupes by host (first non-PAT profile wins).
out: dict[str, str] = {}
pat = 0
for p in profiles:
host = (p.get("host") or "").rstrip("/")
name = p.get("name")
if not host or not name:
continue
if p.get("auth_type") == "pat":
pat += 1
continue
out.setdefault(host, name)
_debug(
"get_databricks_profiles",
f"returned={len(out)} total={len(profiles)} pat={pat}",
)
return list(out.items())
def find_profile_name_for_host(workspace: str) -> str | None:
"""Find the Databricks CLI profile name matching a workspace URL."""
normalized = workspace.rstrip("/")
for host, name in get_databricks_profiles():
if host == normalized:
return name
return None
def profile_auth_type(profile: str) -> str | None:
"""Return the auth_type of a Databricks CLI profile (e.g. "pat"), or None."""
for p in list_profile_entries():
if p.get("name") == profile:
auth_type = p.get("auth_type")
return auth_type if isinstance(auth_type, str) else None
return None
def _read_databrickscfg_token(profile: str) -> str | None:
"""Read the static ``token`` value for a profile from ``~/.databrickscfg``.
`databricks auth token` only knows OAuth caches; for PAT profiles the PAT
itself is the credential, stored in the config file. The parser's default
section is pointed at a name that never appears in the file so a token in
``[DEFAULT]`` does not leak into every named profile."""
cfg_path = Path(os.environ.get("DATABRICKS_CONFIG_FILE") or "~/.databrickscfg").expanduser()
parser = configparser.ConfigParser(default_section="@ucode-no-defaults@", interpolation=None)
try:
if not parser.read(cfg_path, encoding="utf-8"):
return None
except (configparser.Error, OSError):
return None
if not parser.has_section(profile):
return None
token = (parser.get(profile, "token", fallback="") or "").strip()
return token or None
def resolve_pat_token(profile: str | None) -> str | None:
"""Return the static PAT of a PAT-type Databricks CLI profile, or None.
Only consulted when the user explicitly opted in via
``ucode configure --profiles <name> --use-pat`` — ucode never picks up a
PAT implicitly."""
if profile and profile_auth_type(profile) == "pat":
return _read_databrickscfg_token(profile)
return None
def ensure_pat_bearer(profile: str | None, pat: str | None = None) -> bool:
"""Ensure ``DATABRICKS_BEARER`` holds a usable token for a ``--use-pat`` profile.
If a non-empty bearer is already in the environment it wins (the CI escape
hatch). Otherwise the profile's static PAT is exported — callers that have
already resolved it (e.g. ``configure_shared_state``) pass it via ``pat`` to
skip a redundant ``~/.databrickscfg`` read; everyone else lets this resolve
it. An exported-but-*empty* ``DATABRICKS_BEARER`` is treated as absent —
matching ``get_databricks_token``'s own ``.strip()`` check — so a stray
``export DATABRICKS_BEARER=`` does not shadow the PAT and silently force the
OAuth path (which fails for PAT-only profiles).
Returns ``True`` iff a usable bearer is now present in the environment."""
if os.environ.get("DATABRICKS_BEARER", "").strip():
return True
pat = pat or resolve_pat_token(profile)
if pat:
os.environ["DATABRICKS_BEARER"] = pat
return True
return False
def apply_pat_environment(state: dict) -> None:
"""Export the configured profile's PAT as ``DATABRICKS_BEARER`` when the
workspace was configured with ``--use-pat``.
Every token fetch in this process (and in launched agent subprocesses,
which inherit the environment) then takes the existing static-bearer
short-circuit instead of the OAuth-only `databricks auth token` path.
A non-empty bearer already present in the environment is left untouched."""
if not state.get("use_pat"):
return
ensure_pat_bearer(state.get("profile"))
def run_databricks_login(workspace: str, profile: str | None = None) -> None:
"""Run databricks auth login unconditionally.
When ``profile`` is provided, it is passed via ``--profile``. Otherwise we
fall back to looking up an existing profile by host so a stored session is
refreshed in place rather than overwriting another profile's tokens."""
print_section("Databricks Login")
print_kv("Workspace", workspace)
print_note("A browser may open for `databricks auth login`.")
try:
profile_name = profile or find_profile_name_for_host(workspace)
cmd = [
"databricks",
"auth",
"login",
"--host",
workspace,
*_profile_args(profile_name),
]
run(cmd, env=build_databricks_cli_env(workspace, profile_name), timeout=300)
except subprocess.CalledProcessError as exc:
raise RuntimeError("`databricks auth login` failed.") from exc
except subprocess.TimeoutExpired as exc:
raise RuntimeError("`databricks auth login` timed out.") from exc
print_success("Databricks authentication complete")
def ensure_databricks_auth(workspace: str, profile: str | None = None) -> None:
"""Check auth and login only if needed (used by launch path)."""
with spinner("Checking Databricks auth..."):
auth_is_valid = has_valid_databricks_auth(workspace, profile)
if auth_is_valid:
print_success(f"Databricks auth already available for {workspace}")
return
run_databricks_login(workspace, profile)
def get_databricks_token(
workspace: str,
profile: str | None = None,
*,
force_refresh: bool = False,
) -> str:
# ``DATABRICKS_BEARER`` is the CI escape hatch: when set, skip the
# `databricks auth token` subprocess entirely and return the pre-fetched
# bearer directly. Used by the e2e job, where the protected runner has
# no `databricks auth login` cache and `databricks auth token` only knows
# how to read user-OAuth caches (not M2M client_credentials). Mirrors the
# same short-circuit baked into ``build_auth_shell_command``.
bearer = os.environ.get("DATABRICKS_BEARER", "").strip()
if bearer:
_debug("get_databricks_token", "using DATABRICKS_BEARER env var")
return bearer
_log_auth_diagnostics()
# See has_valid_databricks_auth: resolve the profile from the host when
# the caller didn't supply one, so duplicate-host cfgs don't break us.
profile = profile or find_profile_name_for_host(workspace)
env = build_databricks_cli_env(workspace, profile)
cmd = [
"databricks",
"auth",
"token",
"--host",
workspace,
*_profile_args(profile),
"--output",
"json",
]
if force_refresh:
cmd.append("--force-refresh")
_debug(
"get_databricks_token.env",
"set="
+ ",".join(sorted(k for k in env if k.startswith("DATABRICKS_") or k in {"BUNDLE_PROFILE"}))
+ f" profile={profile or '<none>'}",
)
def _fetch() -> str:
try:
result = run(
cmd,
check=False,
capture_output=True,
text=True,
env=env,
timeout=15,
)
_debug("auth token", _format_subprocess_result(result))
if result.returncode == 0:
return json.loads(result.stdout or "{}").get("access_token", "")
except (subprocess.TimeoutExpired, json.JSONDecodeError) as exc:
_debug("auth token", f"exception: {type(exc).__name__}: {exc}")
return ""
token = _fetch()
if not token:
# Session may have expired — attempt non-interactive re-auth and retry once.
_debug("auth token", "empty on first fetch; attempting auth login --no-browser")
try:
reauth = run(
[
"databricks",
"auth",
"login",
"--host",
workspace,
*_profile_args(profile),
"--no-browser",
],
capture_output=True,
text=True,
env=env,
timeout=30,
)
_debug("auth login", _format_subprocess_result(reauth))
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
_debug("auth login", f"exception: {type(exc).__name__}: {exc}")
token = _fetch()
if not token:
profile_name = profile or find_profile_name_for_host(workspace)
stale_profile_hint = ""
if profile_name:
stale_profile_hint = (
" The saved Databricks CLI profile may be stale or invalid. Try:\n"
f" databricks auth logout --profile {profile_name}\n"
f" databricks auth login --host {workspace} --profile {profile_name}"
)
raise RuntimeError(
f"Databricks CLI returned no access token for {workspace}. "
"Run `databricks auth login` to re-authenticate."
f"{stale_profile_hint}"
)
return token
def _extract_connection_page(payload: object) -> tuple[list[dict], str | None]:
if isinstance(payload, list):
return [item for item in payload if isinstance(item, dict)], None
if not isinstance(payload, dict):
raise RuntimeError("Databricks connections listing returned invalid JSON.")
payload_dict = cast(dict[str, object], payload)
raw_connections = payload_dict.get("connections") or []
if not isinstance(raw_connections, list):
raise RuntimeError("Databricks connections listing returned invalid JSON.")
next_page_token = payload_dict.get("next_page_token")
if next_page_token is not None and not isinstance(next_page_token, str):
raise RuntimeError("Databricks connections listing returned invalid JSON.")
return [item for item in raw_connections if isinstance(item, dict)], next_page_token
def list_databricks_connections(workspace: str, profile: str | None = None) -> list[dict]:
env = build_databricks_cli_env(workspace)
connections: list[dict] = []
page_token: str | None = None
seen_page_tokens: set[str] = set()
try:
while True:
cmd = [
"databricks",
"connections",
"list",
*_profile_args(profile),
"--max-results",
"0",
"--output",
"json",
]
if page_token:
cmd.extend(["--page-token", page_token])
result = run(
cmd,
capture_output=True,
text=True,
env=env,
timeout=30,
)
payload = json.loads(result.stdout or "{}")
page_connections, page_token = _extract_connection_page(payload)
connections.extend(page_connections)
if not page_token:
return connections
if page_token in seen_page_tokens:
raise RuntimeError("Databricks connections listing returned a repeated page token.")
seen_page_tokens.add(page_token)
except subprocess.CalledProcessError as exc:
raise RuntimeError(
"Failed to list Databricks connections via `databricks connections list`."
) from exc
except subprocess.TimeoutExpired as exc:
raise RuntimeError("Timed out while listing Databricks connections.") from exc
except json.JSONDecodeError as exc:
raise RuntimeError("Databricks connections listing returned invalid JSON.") from exc
def _extract_genie_spaces_page(payload: object) -> tuple[list[dict], str | None]:
if not isinstance(payload, dict):
raise RuntimeError("Databricks Genie spaces listing returned invalid JSON.")
payload_dict = cast(dict[str, object], payload)
raw_spaces = payload_dict.get("spaces") or []
if not isinstance(raw_spaces, list):
raise RuntimeError("Databricks Genie spaces listing returned invalid JSON.")
next_page_token = payload_dict.get("next_page_token")
if next_page_token is not None and not isinstance(next_page_token, str):
raise RuntimeError("Databricks Genie spaces listing returned invalid JSON.")
return [item for item in raw_spaces if isinstance(item, dict)], next_page_token
def list_genie_spaces(workspace: str, profile: str | None = None) -> list[dict]:
env = build_databricks_cli_env(workspace)
spaces: list[dict] = []
page_token: str | None = None
seen_page_tokens: set[str] = set()
try:
while True:
cmd = [
"databricks",
"genie",
"list-spaces",
*_profile_args(profile),
"--page-size",
"100",
"--output",
"json",
]
if page_token:
cmd.extend(["--page-token", page_token])
result = run(
cmd,
capture_output=True,
text=True,
env=env,
timeout=30,
)
payload = json.loads(result.stdout or "{}")
page_spaces, page_token = _extract_genie_spaces_page(payload)
spaces.extend(page_spaces)
if not page_token:
return spaces
if page_token in seen_page_tokens:
raise RuntimeError(
"Databricks Genie spaces listing returned a repeated page token."
)
seen_page_tokens.add(page_token)
except subprocess.CalledProcessError as exc: