forked from yaooqinn/spark-history-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
285 lines (237 loc) · 10.6 KB
/
Copy pathclient.py
File metadata and controls
285 lines (237 loc) · 10.6 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
"""REST API client for the Spark History Server.
Wraps all /api/v1/* endpoints with typed methods.
"""
from __future__ import annotations
import os
from typing import Any
from urllib.parse import urljoin
import requests
class HistoryServerError(Exception):
"""Raised when the History Server returns an error."""
def __init__(self, status_code: int, message: str, url: str = ""):
self.status_code = status_code
self.url = url
super().__init__(f"HTTP {status_code}: {message}" + (f" ({url})" if url else ""))
class SparkHistoryClient:
"""Client for the Spark History Server REST API (/api/v1)."""
def __init__(
self,
server_url: str = "http://localhost:18080",
timeout: int = 30,
basic_auth_username: str | None = None,
basic_auth_password: str | None = None,
):
self.server_url = server_url.rstrip("/")
self.base_url = f"{self.server_url}/api/v1"
self.timeout = timeout
self._session = requests.Session()
if basic_auth_username is not None:
self._session.auth = (basic_auth_username, basic_auth_password or "")
self._attempt_cache: dict[str, str | None] = {}
def _resolve_attempt(self, app_id: str) -> str:
"""Return the URL base for an app, auto-resolving the attempt ID.
The SHS requires /applications/{appId}/{attemptId}/... for apps
that have attempt IDs. This method fetches the app info once,
caches the latest attempt ID, and returns the correct URL prefix.
"""
if app_id not in self._attempt_cache:
try:
app = self._get(f"applications/{app_id}")
attempts = app.get("attempts", [])
attempt_id = attempts[0].get("attemptId") if attempts else None
self._attempt_cache[app_id] = attempt_id
except HistoryServerError:
self._attempt_cache[app_id] = None
attempt_id = self._attempt_cache[app_id]
if attempt_id:
return f"applications/{app_id}/{attempt_id}"
return f"applications/{app_id}"
def _get(self, path: str, params: dict | None = None, stream: bool = False) -> Any:
"""Make a GET request and return the JSON response."""
url = f"{self.base_url}/{path.lstrip('/')}"
try:
resp = self._session.get(url, params=params, timeout=self.timeout, stream=stream)
except requests.ConnectionError:
raise HistoryServerError(
0, f"Cannot connect to Spark History Server at {self.server_url}. "
"Is it running?", url
)
except requests.Timeout:
raise HistoryServerError(0, f"Request timed out after {self.timeout}s", url)
if stream:
resp.raise_for_status()
return resp
if resp.status_code != 200:
try:
msg = resp.json().get("message", resp.text)
except Exception:
msg = resp.text
raise HistoryServerError(resp.status_code, msg, url)
return resp.json()
# ── Version ───────────────────────────────────────────────────────
def get_version(self) -> dict:
return self._get("version")
# ── Applications ──────────────────────────────────────────────────
def list_applications(
self,
status: str | None = None,
min_date: str | None = None,
max_date: str | None = None,
min_end_date: str | None = None,
max_end_date: str | None = None,
limit: int | None = None,
) -> list[dict]:
params: dict[str, Any] = {}
if status:
params["status"] = status
if min_date:
params["minDate"] = min_date
if max_date:
params["maxDate"] = max_date
if min_end_date:
params["minEndDate"] = min_end_date
if max_end_date:
params["maxEndDate"] = max_end_date
if limit is not None:
params["limit"] = limit
return self._get("applications", params=params)
def get_application(self, app_id: str) -> dict:
return self._get(f"applications/{app_id}")
def get_attempt(self, app_id: str, attempt_id: str) -> dict:
return self._get(f"applications/{app_id}/{attempt_id}")
# ── Jobs ──────────────────────────────────────────────────────────
def list_jobs(self, app_id: str, status: str | None = None) -> list[dict]:
params = {"status": status} if status else {}
base = self._resolve_attempt(app_id)
return self._get(f"{base}/jobs", params=params)
def get_job(self, app_id: str, job_id: int) -> dict:
base = self._resolve_attempt(app_id)
return self._get(f"{base}/jobs/{job_id}")
# ── Stages ────────────────────────────────────────────────────────
def list_stages(
self,
app_id: str,
status: str | None = None,
details: bool = False,
) -> list[dict]:
params: dict[str, Any] = {}
if status:
params["status"] = status
if details:
params["details"] = "true"
base = self._resolve_attempt(app_id)
return self._get(f"{base}/stages", params=params)
def get_stage(self, app_id: str, stage_id: int) -> list[dict]:
base = self._resolve_attempt(app_id)
return self._get(f"{base}/stages/{stage_id}")
def get_stage_attempt(
self,
app_id: str,
stage_id: int,
attempt_id: int,
details: bool = True,
) -> dict:
params = {"details": str(details).lower()}
base = self._resolve_attempt(app_id)
return self._get(
f"{base}/stages/{stage_id}/{attempt_id}", params=params
)
def get_task_summary(
self,
app_id: str,
stage_id: int,
attempt_id: int,
quantiles: str = "0.05,0.25,0.5,0.75,0.95",
) -> dict:
base = self._resolve_attempt(app_id)
return self._get(
f"{base}/stages/{stage_id}/{attempt_id}/taskSummary",
params={"quantiles": quantiles},
)
def list_tasks(
self,
app_id: str,
stage_id: int,
attempt_id: int,
offset: int = 0,
length: int = 20,
sort_by: str = "ID",
) -> list[dict]:
base = self._resolve_attempt(app_id)
return self._get(
f"{base}/stages/{stage_id}/{attempt_id}/taskList",
params={"offset": offset, "length": length, "sortBy": sort_by},
)
# ── Executors ─────────────────────────────────────────────────────
def list_executors(self, app_id: str) -> list[dict]:
base = self._resolve_attempt(app_id)
return self._get(f"{base}/executors")
def list_all_executors(self, app_id: str) -> list[dict]:
base = self._resolve_attempt(app_id)
return self._get(f"{base}/allexecutors")
# ── Storage ───────────────────────────────────────────────────────
def list_rdds(self, app_id: str) -> list[dict]:
base = self._resolve_attempt(app_id)
return self._get(f"{base}/storage/rdd")
def get_rdd(self, app_id: str, rdd_id: int) -> dict:
base = self._resolve_attempt(app_id)
return self._get(f"{base}/storage/rdd/{rdd_id}")
# ── Environment ───────────────────────────────────────────────────
def get_environment(self, app_id: str) -> dict:
base = self._resolve_attempt(app_id)
return self._get(f"{base}/environment")
# ── SQL ────────────────────────────────────────────────────────────
def list_sql(
self,
app_id: str,
details: bool = True,
plan_description: bool = True,
offset: int = 0,
length: int = 20,
) -> list[dict]:
base = self._resolve_attempt(app_id)
return self._get(
f"{base}/sql",
params={
"details": str(details).lower(),
"planDescription": str(plan_description).lower(),
"offset": offset,
"length": length,
},
)
def get_sql(
self,
app_id: str,
execution_id: int,
details: bool = True,
plan_description: bool = True,
) -> dict:
base = self._resolve_attempt(app_id)
return self._get(
f"{base}/sql/{execution_id}",
params={
"details": str(details).lower(),
"planDescription": str(plan_description).lower(),
},
)
# ── Event Logs ────────────────────────────────────────────────────
def download_logs(self, app_id: str, output_path: str) -> str:
"""Download event logs as a ZIP file. Returns the output path."""
resp = self._get(f"applications/{app_id}/logs", stream=True)
os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
with open(output_path, "wb") as f:
for chunk in resp.iter_content(chunk_size=8192):
f.write(chunk)
return output_path
# ── Miscellaneous ─────────────────────────────────────────────────
def list_misc_processes(self, app_id: str) -> list[dict]:
base = self._resolve_attempt(app_id)
return self._get(f"{base}/allmiscellaneousprocess")
# ── Health check ──────────────────────────────────────────────────
def check_health(self) -> bool:
"""Check if the History Server is reachable."""
try:
self.get_version()
return True
except Exception:
return False