-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathdba_client.py
More file actions
291 lines (227 loc) · 8.97 KB
/
dba_client.py
File metadata and controls
291 lines (227 loc) · 8.97 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
#!/usr/bin/env python3
"""Databricks App Client for making authenticated requests to live Databricks Apps.
Based on authentication patterns from databricks-solutions/custom-mcp-databricks-app.
"""
import json
import os
import subprocess
import sys
from typing import Any, Dict, Optional
import requests
from dotenv import load_dotenv
# Load environment variables from .env.local
load_dotenv('.env.local')
class DatabricksAppClient:
"""Client for making authenticated requests to Databricks Apps."""
def __init__(self, app_url: Optional[str] = None):
"""Initialize client with app URL.
Args:
app_url: Base URL of the Databricks app. If not provided, will be auto-detected from DATABRICKS_APP_NAME
"""
if app_url:
self.app_url = app_url.rstrip('/')
else:
self.app_url = self._get_app_url()
self._token_cache: Optional[str] = None
def _get_app_url(self) -> str:
"""Auto-detect app URL from DATABRICKS_APP_NAME environment variable."""
app_name = os.getenv('DATABRICKS_APP_NAME')
if not app_name:
raise Exception(
'DATABRICKS_APP_NAME environment variable is not set. Please run ./setup.sh or provide app_url explicitly.'
)
try:
profile = os.getenv('DATABRICKS_CONFIG_PROFILE')
host = os.getenv('DATABRICKS_HOST')
cmd = ['databricks', 'apps', 'get', app_name, '--output', 'json']
if profile:
cmd.extend(['--profile', profile])
elif host:
# For PAT auth, databricks CLI uses env vars automatically
pass
else:
raise Exception(
'Neither DATABRICKS_CONFIG_PROFILE nor DATABRICKS_HOST environment variable is set'
)
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
app_data = json.loads(result.stdout)
app_url = app_data.get('url')
if not app_url:
raise Exception(f'Could not get URL for app {app_name}')
print(f'✅ Auto-detected app URL: {app_url}')
return app_url
except subprocess.CalledProcessError as e:
raise Exception(f'Failed to get app URL for {app_name}: {e}')
except json.JSONDecodeError:
raise Exception(f'Failed to parse app data for {app_name}')
except FileNotFoundError:
raise Exception('databricks CLI not found. Please install databricks CLI.')
def _get_oauth_token(self) -> str:
"""Get OAuth token using Databricks CLI."""
try:
profile = os.getenv('DATABRICKS_CONFIG_PROFILE')
host = os.getenv('DATABRICKS_HOST')
cmd = ['databricks', 'auth', 'token']
if profile:
cmd.extend(['--profile', profile])
elif host:
cmd.extend(['--host', host])
else:
raise Exception(
'Neither DATABRICKS_CONFIG_PROFILE nor DATABRICKS_HOST environment variable is set'
)
# Try to get existing token first
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if result.returncode == 0 and result.stdout.strip():
token_output = result.stdout.strip()
# Parse JSON if the output is JSON formatted
try:
token_data = json.loads(token_output)
token = token_data.get('access_token', token_output)
except json.JSONDecodeError:
token = token_output
# Validate token
if self._validate_token(token):
return token
# If no valid token, try to login
print('No valid token found, attempting to login...')
login_cmd = ['databricks', 'auth', 'login']
if profile:
login_cmd.extend(['--profile', profile])
elif host:
login_cmd.extend(['--host', host])
login_result = subprocess.run(login_cmd, capture_output=True, text=True, check=False)
if login_result.returncode != 0:
raise Exception(f'Failed to login: {login_result.stderr}')
# Get token after login
token_result = subprocess.run(cmd, capture_output=True, text=True, check=True)
token_output = token_result.stdout.strip()
# Parse JSON if the output is JSON formatted
try:
token_data = json.loads(token_output)
return token_data.get('access_token', token_output)
except json.JSONDecodeError:
return token_output
except subprocess.CalledProcessError as e:
raise Exception(f'Failed to get OAuth token: {e}')
except FileNotFoundError:
raise Exception('Databricks CLI not found. Please install databricks CLI.')
def _validate_token(self, token: str) -> bool:
"""Validate token by making a request to SCIM endpoint."""
try:
headers = {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'}
# Use the workspace host from environment
import os
workspace_host = os.getenv('DATABRICKS_HOST')
if not workspace_host:
return False
response = requests.get(
f'{workspace_host}/api/2.0/preview/scim/v2/Me', headers=headers, timeout=10
)
return response.status_code == 200
except Exception:
return False
def _get_headers(self) -> Dict[str, str]:
"""Get request headers with authentication."""
if not self._token_cache or not self._validate_token(self._token_cache):
self._token_cache = self._get_oauth_token()
headers = {
'Authorization': f'Bearer {self._token_cache}',
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream',
}
print(f'DEBUG: Using token authentication (token preview: {self._token_cache[:50]}...)')
return headers
def get(
self, endpoint: str, params: Optional[Dict[str, Any]] = None, return_text: bool = False
) -> Any:
"""Make GET request to the app."""
url = f'{self.app_url}{endpoint}'
headers = self._get_headers()
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
if return_text:
return response.text
if response.text:
try:
return response.json()
except json.JSONDecodeError:
return response.text
return {}
def post(self, endpoint: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Make POST request to the app."""
url = f'{self.app_url}{endpoint}'
headers = self._get_headers()
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
if response.text:
return response.json()
return {}
def put(self, endpoint: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Make PUT request to the app."""
url = f'{self.app_url}{endpoint}'
headers = self._get_headers()
response = requests.put(url, headers=headers, json=data)
response.raise_for_status()
if response.text:
return response.json()
return {}
def delete(self, endpoint: str) -> Dict[str, Any]:
"""Make DELETE request to the app."""
url = f'{self.app_url}{endpoint}'
headers = self._get_headers()
response = requests.delete(url, headers=headers)
response.raise_for_status()
if response.text:
return response.json()
return {}
def main():
"""CLI interface for testing the client."""
import argparse
parser = argparse.ArgumentParser(
description='Databricks App Client for making authenticated requests',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Auto-detect app URL from DATABRICKS_APP_NAME
python dba_client.py /api/config/
python dba_client.py /api/user/me
python dba_client.py /api/data POST '{"key":"value"}'
# Or specify app URL explicitly
python dba_client.py /api/config/ --app_url https://my-app.aws.databricksapps.com
python dba_client.py /api/user/me --app_url https://my-app.aws.databricksapps.com
python dba_client.py /api/data POST '{"key":"value"}' --app_url https://my-app.aws.databricksapps.com
""",
)
parser.add_argument('endpoint', help='API endpoint to call')
parser.add_argument('--app_url', help='Base URL of the Databricks app (optional, auto-detected from DATABRICKS_APP_NAME if not provided)')
parser.add_argument(
'method', nargs='?', default='GET', help='HTTP method (GET, POST, PUT, DELETE)'
)
parser.add_argument('data', nargs='?', help='JSON data for POST/PUT requests')
args = parser.parse_args()
client = DatabricksAppClient(args.app_url)
try:
method = args.method.upper()
if method == 'GET':
result = client.get(args.endpoint)
elif method == 'POST':
data = json.loads(args.data) if args.data else None
result = client.post(args.endpoint, data)
elif method == 'PUT':
data = json.loads(args.data) if args.data else None
result = client.put(args.endpoint, data)
elif method == 'DELETE':
result = client.delete(args.endpoint)
else:
print(f'Unsupported method: {method}')
sys.exit(1)
if isinstance(result, dict):
print(json.dumps(result, indent=2))
else:
print(result)
except Exception as e:
print(f'Error: {e}', file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()