-
Notifications
You must be signed in to change notification settings - Fork 364
/
genie_3.py
373 lines (297 loc) · 12.6 KB
/
genie_3.py
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
"""
genie.jobs.adapter.genie_3
This module implements Genie 3 adapter.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import logging
import os
from functools import wraps
from multipledispatch import dispatch
from urlparse import urlparse
from ..auth import AuthHandler
from ..utils import (call,
is_str)
from ..jobs.utils import (is_attachment,
is_file)
from .genie_x import (GenieBaseAdapter,
substitute)
from ..exceptions import (GenieAttachmentError,
GenieHTTPError,
GenieJobError,
GenieJobNotFoundError,
GenieLogNotFoundError)
#jobs
from ..jobs.core import GenieJob
from ..jobs.hadoop import HadoopJob
from ..jobs.hive import HiveJob
from ..jobs.pig import PigJob
from ..jobs.presto import PrestoJob
from ..jobs.sqoop import SqoopJob
logger = logging.getLogger('com.netflix.genie.jobs.adapter.genie_3')
dispatch_ns = dict()
def set_jobname(func):
"""Decorator to update job name with script."""
@wraps(func)
def wrapper(*args, **kwargs):
"""Wraps func."""
payload = func(*args, **kwargs)
job = args[0]
script = job.get('script')
# handle job name if not set
if not job.get('job_name') and script:
payload['name'] = os.path.basename(script) if is_file(script) \
else script.replace('\n', ' ')[:40].strip()
return payload
return wrapper
def to_attachment(att):
if is_str(att) and os.path.isfile(att):
return (unicode(os.path.basename(att)), open(att, 'rb'))
elif is_str(att) and os.path.isdir(att):
_files = list()
for local_file in [os.path.join(att, d) for d in os.listdir(att)]:
if os.path.isfile(local_file) and \
os.path.getsize(local_file) > 0 and \
not os.path.basename(local_file).startswith('.'):
_files.append(
(unicode(os.path.basename(local_file)), open(local_file, 'rb'))
)
return _files
elif isinstance(att, dict):
try:
return (unicode(att['name']), unicode(att['data']))
except KeyError:
raise GenieAttachmentError("in-line attachment is missing required keys ('name', 'data') ({})".format(att))
raise GenieAttachmentError("cannot handle attachment '{}'".format(att))
class Genie3Adapter(GenieBaseAdapter):
"""Genie server 3"""
JOBS_ENDPOINT = 'api/v3/jobs'
def __init__(self, conf=None):
super(Genie3Adapter, self).__init__(conf=conf)
self.auth_handler = AuthHandler(conf=conf)
def __get_log(self, job_id, log, iterator=False, **kwargs):
url = '{}/output/{}'.format(self.__url_for_job(job_id), log)
try:
response = call(method='get',
url=url,
stream=iterator,
auth_handler=self.auth_handler,
**kwargs)
return response.iter_lines() if iterator else response.text
except GenieHTTPError as err:
if err.response.status_code == 404:
raise GenieLogNotFoundError("log not found at {}".format(url))
raise
def __url_for_job(self, job_id):
return '{}/{}/{}'.format(self.conf.genie.url,
Genie3Adapter.JOBS_ENDPOINT,
job_id)
@staticmethod
def construct_base_payload(job):
"""Returns a base payload for the job."""
attachments = list()
dependencies = list()
for dep in job.get('dependencies'):
if is_attachment(dep):
# attachment is an adhoc script so do parameter substitution
if isinstance(dep, dict) \
and dep.get('data') \
and hasattr(job, 'DEFAULT_SCRIPT_NAME') \
and dep.get('name') == job.DEFAULT_SCRIPT_NAME:
dep['data'] = substitute(dep['data'], job.get('parameters'))
att = to_attachment(dep)
if isinstance(att, list):
attachments.extend(att)
else:
attachments.append(att)
else:
dependencies.append(dep)
description = job.get('description')
if isinstance(description, dict):
description = json.dumps(description)
payload = {
'applications': job.get('application_ids'),
'attachments': attachments,
'clusterCriterias': [
{'tags': job.get('cluster_tags') or job.default_cluster_tags}
],
'commandArgs': job.get('command_arguments') or job.cmd_args,
'commandCriteria': job.get('command_tags') or job.default_command_tags,
'dependencies': dependencies,
'description': description,
'disableLogArchival': not job.get('archive'),
'email': job.get('email'),
'group': job.get('group'),
'id': job.get('job_id'),
'name': job.get('job_name'),
'setupFile': job.get('setup_file'),
'tags': job.get('tags'),
'timeout': job.get('timeout'),
'user': job.get('username'),
'version': job.get('job_version')
}
return payload
def get(self, job_id, path=None, if_not_found=None, **kwargs):
"""
Get information for a job.
Args:
job_id (str): The job id.
path (str, optional): Path to more job information (cluster, requests,
etc)
if_not_found (optional): If the job id is to a job that cannot be
found, if if_not_found is not None will return if_not_found
instead of raising error.
Returns:
json: JSON response data.
"""
url = self.__url_for_job(job_id)
if path:
url = '{}/{}'.format(url, path.lstrip('/'))
try:
return call(method='get',
url=url,
auth_handler=self.auth_handler,
**kwargs) \
.json()
except GenieHTTPError as err:
if err.response.status_code == 404:
msg = "job not found at {}".format(url)
if if_not_found is not None:
return if_not_found
raise GenieJobNotFoundError(msg)
raise
def get_info_for_rj(self, job_id, *args, **kwargs):
"""
Get information for RunningJob object.
"""
data = self.get(job_id, timeout=60)
request_data = self.get(job_id, path='request', timeout=60)
application_data = self.get(job_id,
path='applications',
if_not_found=list(),
timeout=60)
cluster_data = self.get(job_id,
path='cluster',
if_not_found=dict(),
timeout=60)
command_data = self.get(job_id,
path='command',
if_not_found=dict(),
timeout=60)
execution_data = self.get(job_id,
path='execution',
if_not_found=dict(),
timeout=60)
link = data.get('_links', {}).get('self', {}).get('href')
link_parts = urlparse(link)
output_link = '{scheme}://{netloc}/output/{job_id}/output' \
.format(scheme=link_parts.scheme,
netloc=link_parts.netloc,
job_id=data.get('id'))
job_link = '{scheme}://{netloc}/jobs?id={job_id}&showDetails={job_id}' \
.format(scheme=link_parts.scheme,
netloc=link_parts.netloc,
job_id=data.get('id'))
return {
'application_name': ','.join(a.get('id') for a in application_data),
'archive_location': data.get('archiveLocation'),
'attachments': None,
'client_host': execution_data.get('hostName'),
'cluster_id': cluster_data.get('id'),
'cluster_name': cluster_data.get('name'),
'command_args': data.get('commandArgs'),
'command_id': command_data.get('id'),
'command_name': command_data.get('name'),
'created': data.get('created'),
'description': data.get('description'),
'disable_archive': request_data.get('disableLogArchival'),
'email': request_data.get('email'),
'file_dependencies': request_data.get('dependencies'),
'finished': data.get('finished'),
'group': request_data.get('group'),
'id': data.get('id'),
'job_link': job_link,
'json_link': link,
'kill_uri': link,
'name': data.get('name'),
'output_uri': output_link,
'request_data': request_data,
'setup_file': request_data.get('setupFile'),
'started': data.get('started'),
'status': data.get('status'),
'status_msg': data.get('statusMsg'),
'tags': data.get('tags'),
'updated': data.get('updated'),
'user': data.get('user'),
'version': data.get('version')
}
def get_genie_log(self, job_id, **kwargs):
"""Get a genie log for a job."""
return self.__get_log(job_id, 'genie/logs/genie.log', **kwargs)
def get_status(self, job_id):
"""Get job status."""
return self.get(job_id, path='status', timeout=10).get('status')
def get_stderr(self, job_id, **kwargs):
"""Get a stderr log for a job."""
return self.__get_log(job_id, 'stderr', **kwargs)
def get_stdout(self, job_id, **kwargs):
"""Get a stdout log for a job."""
return self.__get_log(job_id, 'stdout', **kwargs)
def kill_job(self, job_id=None, kill_uri=None):
"""Kill a job."""
url = kill_uri if kill_uri is not None else self.__url_for_job(job_id)
try:
return call(method='delete',
url=url,
timeout=10,
auth_handler=self.auth_handler)
except GenieHTTPError as err:
if err.response.status_code == 404:
raise GenieJobNotFoundError("job not found at {}".format(url))
raise
def submit_job(self, job):
"""Submit a job execution to the server."""
payload = {
key: value for key, value in get_payload(job).iteritems() \
if value is not None \
and value != [] \
and value != {} \
and value != ''
}
attachments = payload.get('attachments', [])
if 'attachments' in payload:
del payload['attachments']
files = [('request', ('', json.dumps(payload), 'application/json'))]
for att in attachments:
files.append(('attachment', att))
logger.debug('adding attachment: %s', att)
logger.debug('payload to genie 3:')
logger.debug(json.dumps(payload,
sort_keys=True,
indent=4,
separators=(',', ': ')))
call(method='post',
url='{}/{}'.format(job.conf.genie.url, Genie3Adapter.JOBS_ENDPOINT),
files=files,
timeout=300,
auth_handler=self.auth_handler)
@dispatch(GenieJob, namespace=dispatch_ns)
def get_payload(job):
"""Construct payload for GenieJob -> Genie 3."""
try:
payload = Genie3Adapter.construct_base_payload(job)
except GenieJobError:
raise GenieJobError('trying to run GenieJob without explicitly setting ' \
'command line arguments (use .command_arguments())')
if not payload.get('commandCriteria'):
raise GenieJobError('trying to run GenieJob without specifying command tags')
return payload
@dispatch((HadoopJob, HiveJob, PigJob, PrestoJob), namespace=dispatch_ns)
@set_jobname
def get_payload(job):
"""Construct payload for jobs -> Genie 3."""
return Genie3Adapter.construct_base_payload(job)
@dispatch((SqoopJob), namespace=dispatch_ns)
def get_payload(job):
"""Construct payload for SqoopJob -> Genie 3."""
return Genie3Adapter.construct_base_payload(job)