-
Notifications
You must be signed in to change notification settings - Fork 625
Expand file tree
/
Copy pathclient.py
More file actions
502 lines (422 loc) · 17.1 KB
/
Copy pathclient.py
File metadata and controls
502 lines (422 loc) · 17.1 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
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import base64
import cloudpickle
import os
import re
import requests
import threading
import traceback
from configparser import ConfigParser
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import ParseResult, urlparse
from io import StringIO
from requests_kerberos import HTTPKerberosAuth, REQUIRED
from livy.job_handle import JobHandle
class HttpClient:
"""A http based client for submitting Spark-based jobs to a Livy backend.
Parameters
----------
url_str : string
Livy server url to create a new session or the url of an existing
session
load_defaults : boolean, optional
This parameter decides if the default config needs to be loaded
Default is True
conf_dict : dict, optional
The key-value pairs in the conf_dict will be loaded to the config
Default is None
Examples
--------
Imports needed to create an instance of HttpClient
>>> from livy.client import HttpClient
1) Creates a client that is loaded with default config
as 'load_defaults' is True by default
>>> client = HttpClient("http://example:8998/")
2) Creates a client that does not load default config, but loads
config that are passed in 'config_dict'
>>> config_dict = {'spark.app.name', 'Test App'}
>>> client = HttpClient("http://example:8998/", load_defaults=False,
>>> config_dict=config_dict)
"""
_CONFIG_SECTION = 'env'
_LIVY_CLIENT_CONF_DIR = "LIVY_CLIENT_CONF_DIR"
def __init__(self, url, load_defaults=True, conf_dict=None):
uri = urlparse(url)
self._config = ConfigParser()
self._load_config(load_defaults, conf_dict)
self._job_type = 'pyspark'
match = re.match(r'(.*)/sessions/([0-9]+)', uri.path)
if match:
base = ParseResult(scheme=uri.scheme, netloc=uri.netloc,
path=match.group(1), params=uri.params, query=uri.query,
fragment=uri.fragment)
self._set_uri(base)
self._conn = _LivyConnection(base, self._config)
self._session_id = int(match.group(2))
self._reconnect_to_existing_session()
else:
self._set_uri(uri)
session_conf_dict = dict(self._config.items(self._CONFIG_SECTION))
self._conn = _LivyConnection(uri, self._config)
self._session_id = self._create_new_session(
session_conf_dict).json()['id']
self._executor = ThreadPoolExecutor(max_workers=1)
self._stopped = False
self.lock = threading.Lock()
def submit(self, job):
"""
Submits a job for execution to the spark cluster.
Parameters
----------
job : function
The function must accept a single parameter, which is an instance
of JobContext.
Returns
-------
job_handle : an instance of the class JobHandle
A handle that can be used to monitor the job
Examples
-------
>>> def simple_spark_job(context):
>>> elements = [10, 20, 30, 40, 50]
>>> return context.sc.parallelize(elements, 2).count()
>>> client.submit(simple_spark_job)
"""
return self._send_job('submit-job', job)
def run(self, job):
"""
Asks the remote context to run a job immediately.
Normally, the remote context will queue jobs and execute them based on
how many worker threads have been configured. This method will run
the submitted job in the same thread processing the RPC message,
so that queueing does not apply.
It's recommended that this method only be used to run code that
finishes quickly. This avoids interfering with the normal operation
of the context.
Parameters
----------
job : function
The function must accept a single parameter, which is an instance
of JobContext. Spark jobs can be created with the help of
JobContext, which exposes the Spark libraries.
Returns
-------
future : concurrent.futures.Future
A future to monitor the status of the job
Examples
-------
>>> def simple_job(context):
>>> return "hello"
>>> client.run(simple_job)
"""
return self._send_job("run-job", job)
def add_file(self, file_uri):
"""
Adds a file to the running remote context.
Note that the URL should be reachable by the Spark driver process. If
running the driver in cluster mode, it may reside on a different
host, meaning "file:" URLs have to exist on that node (and not on
the client machine).
Parameters
----------
file_uri : string
String representation of the uri that points to the location
of the file
Returns
-------
future : concurrent.futures.Future
A future to monitor the status of the job
Examples
-------
>>> client.add_file("file:/test_add.txt")
>>> # Example job using the file added using add_file function
>>> def add_file_job(context):
>>> from pyspark import SparkFiles
>>> def func(iterator):
>>> with open(SparkFiles.get("test_add.txt")) as testFile:
>>> fileVal = int(testFile.readline())
>>> return [x * fileVal for x in iterator]
>>> return context.sc.parallelize([1, 2, 3, 4])
>>> .mapPartitions(func).collect()
>>> client.submit(add_file_job)
"""
return self._add_file_or_pyfile_job("add-file", file_uri)
def add_jar(self, file_uri):
"""
Adds a jar file to the running remote context.
Note that the URL should be reachable by the Spark driver process. If
running the driver in cluster mode, it may reside on a different host,
meaning "file:" URLs have to exist on that node (and not on the
client machine).
Parameters
----------
file_uri : string
String representation of the uri that points to the location
of the file
Returns
-------
future : concurrent.futures.Future
A future to monitor the status of the job
Examples
-------
>>> client.add_jar("file:/test_package.jar")
"""
return self._add_file_or_pyfile_job("add-jar", file_uri)
def add_pyfile(self, file_uri):
"""
Adds a .py or .zip to the running remote context.
Note that the URL should be reachable by the Spark driver process. If
running the driver in cluster mode, it may reside on a different host,
meaning "file:" URLs have to exist on that node (and not on the
client machine).
Parameters
----------
file_uri : string
String representation of the uri that points to the location
of the file
Returns
-------
future : concurrent.futures.Future
A future to monitor the status of the job
Examples
-------
>>> client.add_pyfile("file:/test_package.egg")
>>> # Example job using the file added using add_pyfile function
>>> def add_pyfile_job(context):
>>> # Importing module from test_package.egg
>>> from test.pyfile_test import TestClass
>>> test_class = TestClass()
>>> return test_class.say_hello()
>>> client.submit(add_pyfile_job)
"""
return self._add_file_or_pyfile_job("add-pyfile", file_uri)
def upload_file(self, file_path):
"""
Upload a file to be passed to the Spark application.
Parameters
----------
file_path : string
File path of the local file to be uploaded.
Returns
-------
future : concurrent.futures.Future
A future to monitor the status of the job
Examples
-------
>>> client.upload_file("/test_upload.txt")
>>> # Example job using the file uploaded using upload_file function
>>> def upload_file_job(context):
>>> from pyspark import SparkFiles
>>> def func(iterator):
>>> with open(SparkFiles.get("test_upload.txt")) as testFile:
>>> fileVal = int(testFile.readline())
>>> return [x * fileVal for x in iterator]
>>> return context.sc.parallelize([1, 2, 3, 4])
>>> .mapPartitions(func).collect()
>>> client.submit(add_file_job)
"""
return self._upload_file_or_pyfile("upload-file",
open(file_path, 'rb'))
def upload_pyfile(self, file_path):
"""
Upload a .py or .zip dependency to be passed to the Spark application.
Parameters
----------
file_path : string
File path of the local file to be uploaded.
Returns
-------
future : concurrent.futures.Future
A future to monitor the status of the job
Examples
-------
>>> client.upload_pyfile("/test_package.egg")
>>> # Example job using the file uploaded using upload_pyfile function
>>> def upload_pyfile_job(context):
>>> # Importing module from test_package.egg
>>> from test.pyfile_test import TestClass
>>> test_class = TestClass()
>>> return test_class.say_hello()
>>> client.submit(upload_pyfile_job)
"""
return self._upload_file_or_pyfile("upload-pyfile",
open(file_path, 'rb'))
def stop(self, shutdown_context):
"""
Stops the remote context.
The function will return immediately and will not wait for the pending
jobs to get completed
Parameters
----------
shutdown_context : Boolean
Whether to shutdown the underlying Spark context. If false, the
context will keep running and it's still possible to send commands
to it, if the backend being used supports it.
"""
with self.lock:
if not self._stopped:
self._executor.shutdown(wait=False)
try:
if shutdown_context:
session_uri = "/" + str(self._session_id)
headers = {'X-Requested-By': 'livy'}
self._conn.send_request("DELETE", session_uri,
headers=headers)
except Exception:
raise Exception(traceback.format_exc())
self._stopped = True
def _set_uri(self, uri):
if uri is not None and uri.scheme in ('http', 'https'):
self._config.set(self._CONFIG_SECTION, 'livy.uri', uri.geturl())
else:
url_exception = uri.geturl if uri is not None else None
raise ValueError('Cannot create client - Uri not supported - ',
url_exception)
def _set_conf(self, key, value):
if value is not None:
self._config.set(self._CONFIG_SECTION, key, value)
else:
self._delete_conf(key)
def _delete_conf(self, key):
self._config.remove_option(self._CONFIG_SECTION, key)
def _set_multiple_conf(self, conf_dict):
for key, value in list(conf_dict.items()):
self._set_conf(key, value)
def _load_config(self, load_defaults, conf_dict):
self._config.add_section(self._CONFIG_SECTION)
if load_defaults:
self._load_default_config()
if conf_dict is not None and len(conf_dict) > 0:
self._set_multiple_conf(conf_dict)
def _load_default_config(self):
config_dir = os.environ.get(self._LIVY_CLIENT_CONF_DIR)
if config_dir is not None:
config_files = os.listdir(config_dir)
default_conf_files = ['spark-defaults.conf', 'livy-client.conf']
for default_conf_file in default_conf_files:
if default_conf_file in config_files:
self._load_config_from_file(config_dir, default_conf_file)
def _load_config_from_file(self, config_dir, config_file):
path = os.path.join(config_dir, config_file)
data = "[" + self._CONFIG_SECTION + "]\n" + \
open(path, encoding='utf-8').read()
self._config.read_file(StringIO(data))
def _create_new_session(self, session_conf_dict):
data = {'kind': 'pyspark', 'conf': session_conf_dict}
response = self._conn.send_request('POST', "/",
headers=self._conn._JSON_HEADERS, data=data)
return response
def _reconnect_to_existing_session(self):
reconnect_uri = "/" + str(self._session_id) + "/connect"
self._conn.send_request('POST', reconnect_uri,
headers=self._conn._JSON_HEADERS)
def _send_job(self, command, job):
pickled_job = cloudpickle.dumps(job)
base64_pickled_job = base64.b64encode(pickled_job).decode('utf-8')
base64_pickled_job_data = \
{'job': base64_pickled_job, 'jobType': self._job_type}
handle = JobHandle(self._conn, self._session_id,
self._executor)
handle._start(command, base64_pickled_job_data)
return handle
def _add_file_or_pyfile_job(self, command, file_uri):
data = {'uri': file_uri}
suffix_url = "/" + str(self._session_id) + "/" + command
return self._executor.submit(self._add_or_upload_resource, suffix_url,
data=data, headers=self._conn._JSON_HEADERS)
def _upload_file_or_pyfile(self, command, open_file):
files = {'file': open_file}
suffix_url = "/" + str(self._session_id) + "/" + command
return self._executor.submit(self._add_or_upload_resource, suffix_url,
files=files)
def _add_or_upload_resource(
self,
suffix_url,
files=None,
data=None,
headers=None
):
return self._conn.send_request('POST', suffix_url, files=files,
data=data, headers=headers).content
class _LivyConnection:
_SESSIONS_URI = '/sessions'
# Timeout in seconds
_TIMEOUT = 10
_JSON_HEADERS = {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
_SPNEGO_ENABLED_CONF = 'livy.client.http.spnego.enable'
def __init__(self, uri, config):
self._server_url_prefix = uri.geturl() + self._SESSIONS_URI
self._requests = requests
self.lock = threading.Lock()
self._spnego_enabled = \
config.getboolean('env', self._SPNEGO_ENABLED_CONF) \
if config.has_option('env', self._SPNEGO_ENABLED_CONF) else False
def _spnego_auth(self):
if self._spnego_enabled:
return HTTPKerberosAuth(mutual_authentication=REQUIRED,
sanitize_mutual_error_response=False)
else:
return None
def send_request(
self,
method,
suffix_url,
headers=None,
files=None,
data=None
):
"""
Makes a HTTP request to the server for the given REST method and
endpoint.
This method takes care of closing the handles of the files that
are to be sent as part of the http request
Parameters
----------
method : string
REST verb
suffix_url : string
valid API endpoint
headers : dict, optional
Http headers for the request
Default is None
files : dict, optional
Files to be sent with the http request
Default is None
data : dict, optional
The payload to be sent with the http request
Default is None
Returns
-------
future : concurrent.futures.Future
A future to monitor the status of the job
"""
try:
with self.lock:
local_headers = {'X-Requested-By': 'livy'}
if headers:
local_headers.update(headers)
request_url = self._server_url_prefix + suffix_url
return self._requests.request(method, request_url,
timeout=self._TIMEOUT, headers=local_headers, files=files,
json=data, auth=self._spnego_auth())
finally:
if files is not None:
files.clear()