forked from Shippable/cexec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript_runner.py
372 lines (332 loc) · 15 KB
/
script_runner.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
import uuid
import os
import json
import stat
import subprocess
import threading
import time
import traceback
from base import Base
class ScriptRunner(Base):
def __init__(self, job_id, shippable_adapter, \
flushed_consoles_size_in_bytes, sent_console_truncated_message):
Base.__init__(self, __name__)
self.script_dir = self.config['HOME']
self.script_name = '{0}/{1}.sh'.format(self.script_dir, uuid.uuid4())
self.job_id = job_id
self.shippable_adapter = shippable_adapter
self.console_buffer = []
self.console_buffer_lock = threading.Lock()
self.continue_trigger_flush_console_output = True
self.max_consoles_size_in_bytes = self.config['MAX_CONSOLES_SIZE_BYTES']
self.flushed_consoles_size_in_bytes = flushed_consoles_size_in_bytes
self.sent_console_truncated_message = sent_console_truncated_message
def execute_script(self, script):
self.log.debug('executing script runner')
if not script:
error_message = 'No "script" provided for script runner'
self.log.error(error_message)
raise Exception(error_message)
self.__write_to_file(script)
self.log.debug('executing script file')
# First we need to enumerate all the files in SSH_DIR so we can
# assemble the ssh-add commands for all of them
ssh_dir = self.config['SSH_DIR']
ssh_add_fragment = ''
key_files = os.listdir(ssh_dir)
key_files.sort()
for file_name in key_files:
file_path = os.path.join(ssh_dir, file_name)
ssh_add_fragment += 'ssh-add {0};'.format(file_path)
run_script_cmd = 'ssh-agent bash -c \'{0} cd {1} && {2}\''.format(
ssh_add_fragment, self.script_dir, self.script_name)
script_status, exit_code, should_continue = self._run_command(
run_script_cmd, self.script_dir)
self.log.debug('Execute script completed with status: {0}'.format(
script_status))
return script_status, exit_code, should_continue, \
self.flushed_consoles_size_in_bytes, \
self.sent_console_truncated_message
def __write_to_file(self, script):
self.log.debug('Writing script to file')
if not os.path.isdir(self.script_dir):
os.mkdir(self.script_dir)
script_file = open(self.script_name, 'w')
script_file.write(script.encode('UTF-8'))
script_file.close()
# Make it executable
script_stat = os.stat(self.script_name)
os.chmod(self.script_name, script_stat.st_mode | stat.S_IEXEC)
def _run_command(self, cmd, working_dir):
self.log.debug('Executing streaming command: {0}\nDir: {1}'.format(
cmd, working_dir))
current_step_state = self.STATUS['FAILED']
command_thread_result = {
'success': False,
'returncode': None,
'should_continue': True
}
command_thread = threading.Thread(
target=self.__command_runner,
args=(cmd, working_dir, command_thread_result,))
command_thread.start()
console_flush_timer = threading.Timer(
self.config['CONSOLE_FLUSH_INTERVAL'],
self.__trigger_flush_console_output)
console_flush_timer.start()
self.log.debug('Waiting for command thread to complete')
command_thread.join()
self.log.debug('Command thread join has returned. Result: {0}'\
.format(command_thread_result))
if command_thread.is_alive():
self.append_command_err('Command timed out')
self.log.error('Command thread is still running')
is_command_success = False
current_step_state = self.STATUS['TIMEOUT']
should_continue = False
else:
self.log.debug('Command completed {0}'.format(cmd))
is_command_success = command_thread_result['success']
if is_command_success:
self.log.debug('command executed successfully: {0}'.format(cmd))
current_step_state = self.STATUS['SUCCESS']
else:
error_message = 'Command failed : {0}'.format(cmd)
exception = command_thread_result.get('exception', None)
if exception:
error_message += '\nException {0}'.format(exception)
self.log.error(error_message)
current_step_state = self.STATUS['FAILED']
self.log.error(error_message)
should_continue = command_thread_result['should_continue']
self.continue_trigger_flush_console_output = False
self.flush_console_buffer()
# For timeouts we want to inject our own exit code because the script
# hasn't returned yet
if current_step_state == self.STATUS['TIMEOUT']:
exit_code = self.STATUS['TIMEOUT']
else:
exit_code = command_thread_result['returncode']
return current_step_state, exit_code, should_continue
def __command_runner(self, cmd, working_dir, result):
# pylint: disable=too-many-statements
# pylint: disable=too-many-arguments
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
self.log.debug('command runner \nCmd: {0}\nDir: {1}'.format(
cmd, working_dir))
cmd = '{0} 2>&1'.format(cmd)
self.log.debug('Running {0}'.format(cmd))
proc = None
success = False
should_continue = True
try:
# Unset LD_LIBRARY_PATH
env = dict(os.environ)
env.pop('LD_LIBRARY_PATH', None)
proc = subprocess.Popen(
cmd, shell=True,
stdout=subprocess.PIPE,
cwd=working_dir,
env=env,
universal_newlines=True)
exception = 'Invalid or no script tags received'
current_group_info = None
current_group_name = None
current_cmd_info = None
for line in iter(proc.stdout.readline, ''):
timestamp = self.__get_timestamp()
self.log.debug(line)
line_split = line.split('|')
if line.startswith('__SH__GROUP__START__'):
current_group_info = line_split[1]
current_group_name = '|'.join(line_split[2:])
current_group_info = json.loads(current_group_info)
show_group = current_group_info.get('is_shown', True)
if show_group == 'false':
show_group = False
console_out = {
'consoleId': current_group_info.get('id'),
'parentConsoleId': 'root',
'type': 'grp',
'message': current_group_name,
'timestamp': timestamp,
'isShown': show_group
}
self.handle_console_output(console_out)
elif line.startswith('__SH__CMD__START__'):
current_cmd_info = line_split[1]
current_cmd_name = '|'.join(line_split[2:])
current_cmd_info = json.loads(current_cmd_info)
parent_id = current_group_info.get('id') if \
current_group_info else None
console_out = {
'consoleId': current_cmd_info.get('id'),
'parentConsoleId': parent_id,
'type': 'cmd',
'message': current_cmd_name,
'timestamp': timestamp,
}
if parent_id:
self.handle_console_output(console_out)
elif line.startswith('__SH__CMD__END__'):
current_cmd_end_info = line_split[1]
current_cmd_end_name = '|'.join(line_split[2:])
current_cmd_end_info = json.loads(current_cmd_end_info)
parent_id = current_group_info.get('id') if \
current_group_info else None
is_success = False
if current_cmd_end_info.get('exitcode') == '0':
is_success = True
console_out = {
'consoleId': current_cmd_info.get('id'),
'parentConsoleId': parent_id,
'type': 'cmd',
'message': current_cmd_end_name,
'timestamp': timestamp,
'timestampEndedAt': timestamp,
'isSuccess': is_success,
'isShown': show_group
}
if parent_id:
self.handle_console_output(console_out)
elif line.startswith('__SH__GROUP__END__'):
current_grp_end_info = line_split[1]
current_grp_end_name = '|'.join(line_split[2:])
current_grp_end_info = json.loads(current_grp_end_info)
is_success = False
if current_grp_end_info.get('exitcode') == '0':
is_success = True
console_out = {
'consoleId': current_group_info.get('id'),
'parentConsoleId': 'root',
'type': 'grp',
'message': current_grp_end_name,
'timestamp': timestamp,
'timestampEndedAt': timestamp,
'isSuccess': is_success,
'isShown': show_group
}
self.handle_console_output(console_out)
elif line.startswith('__SH__SCRIPT_END_SUCCESS__'):
success = True
break
elif line.startswith('__SH__SCRIPT_END_FAILURE__'):
success = False
exception = 'Script failure tag received'
break
elif line.startswith('__SH__SHOULD_NOT_CONTINUE__'):
should_continue = False
elif line.startswith('__SH__SHOULD_CONTINUE__'):
should_continue = True
else:
parent_id = current_cmd_info.get('id') if \
current_cmd_info else None
console_out = {
'consoleId': str(uuid.uuid4()),
'parentConsoleId': parent_id,
'type': 'msg',
'message': line,
'timestamp': timestamp,
}
if parent_id:
self.handle_console_output(console_out)
else:
self.log.debug(console_out)
proc.kill()
if success == False:
self.log.debug('Command failure')
result['returncode'] = 99
result['success'] = False
result['exception'] = exception
result['should_continue'] = should_continue
else:
self.log.debug('Command successful')
result['returncode'] = 0
result['success'] = True
result['should_continue'] = should_continue
# pylint: disable=broad-except
except Exception as exc:
self.log.error('Exception while running command: {0}'.format(exc))
trace = traceback.format_exc()
self.log.error(trace)
result['returncode'] = 98
result['success'] = False
result['exception'] = trace
self.log.debug('Command returned {0}'.format(result['returncode']))
def __get_timestamp(self):
# pylint: disable=no-self-use
return int(time.time() * 1000000)
def __trigger_flush_console_output(self):
if not self.continue_trigger_flush_console_output:
return
self.flush_console_buffer()
console_flush_timer = threading.Timer(
self.config['CONSOLE_FLUSH_INTERVAL'],
self.__trigger_flush_console_output)
console_flush_timer.start()
def append_command_err(self, err):
console_out = {
'consoleId': str(uuid.uuid4()),
'parentConsoleId': '',
'type': 'msg',
'message' : err,
'timestamp': self.__get_timestamp(),
'completed' : False
}
self.handle_console_output(console_out)
def handle_console_output(self, console_out):
with self.console_buffer_lock:
self.console_buffer.append(console_out)
if len(self.console_buffer) > self.config['CONSOLE_BUFFER_LENGTH']:
self.flush_console_buffer()
def flush_console_buffer(self):
if len(self.console_buffer) == 0:
self.log.debug('No console output to flush')
else:
with self.console_buffer_lock:
for console in self.console_buffer:
self.flushed_consoles_size_in_bytes += \
len(console['message'])
logs_exceed_limit = self.flushed_consoles_size_in_bytes > \
self.max_consoles_size_in_bytes
if logs_exceed_limit and \
not self.sent_console_truncated_message:
self.send_console_truncated_message()
self.sent_console_truncated_message = True
elif not self.sent_console_truncated_message:
self.log.debug('Flushing {0} console logs'.format(
len(self.console_buffer)))
req_body = {
'jobId': self.job_id,
'jobConsoleModels': self.console_buffer
}
self.shippable_adapter.post_job_consoles(self.job_id,
req_body)
del self.console_buffer
self.console_buffer = []
def send_console_truncated_message(self):
self.log.debug('Flushing final {0} MB limit message'.format(
self.max_consoles_size_in_bytes / (1024 * 1024)))
fatal_grp = {
'consoleId': str(uuid.uuid4()),
'parentConsoleId': 'root',
'type': 'grp',
'message': 'console_limit_error',
'timestamp': int(time.time() * 1000000),
'isSuccess': False
}
fatal_msg = {
'consoleId': str(uuid.uuid4()),
'parentConsoleId': fatal_grp['consoleId'],
'type': 'msg',
'message': 'Console size exceeds {0} MB limit. Truncated from \
here.'.format(self.max_consoles_size_in_bytes / (1024 * 1024)),
'timestamp': int(time.time() * 1000000),
'isSuccess': False
}
console = {
'jobId': self.job_id,
'jobConsoleModels': [fatal_grp, fatal_msg]
}
self.shippable_adapter.post_job_consoles(self.job_id, console)