forked from ragsden/cds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.py
executable file
·316 lines (294 loc) · 12.9 KB
/
base.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
import os
import time
import json
import uuid
import threading
import traceback
import subprocess
from config import Config
from app_logger import AppLogger
class Base(object):
STATUS = {
'WAITING': 0,
'QUEUED': 10,
'PROCESSING': 20,
'SUCCESS': 30,
'SKIPPED': 40,
'UNSTABLE': 50,
'TIMEOUT': 60,
'CANCELLED': 70,
'FAILED': 80
}
def __init__(self, module_name):
self.module = module_name
self.config = Config()
self.log = AppLogger(self.config, self.module)
def command(self, cmd, working_dir, script=False):
self.log.info('Executing command: {0}\nDir: {1}'.format(
cmd, working_dir))
if script:
self.log.debug('Executing user command')
return self.__exec_user_command(cmd, working_dir)
else:
self.log.debug('Executing system command')
self.__exec_system_command(cmd, working_dir)
def __exec_system_command(self, cmd, working_dir):
self.log.debug('System command runner \nCmd: {0}\nDir: {1}'.format(
cmd, working_dir))
cmd = '{0} 2>&1'.format(cmd)
self.log.info('Running {0}'.format(cmd))
proc = None
try:
proc = subprocess.Popen(
cmd, shell=True,
stdout=subprocess.PIPE,
cwd=working_dir,
env=os.environ.copy(),
universal_newlines=True)
stdout, stderr = proc.communicate()
returncode = proc.returncode
if returncode != 0:
command_status = self.STATUS['FAILED']
self.log.debug(stdout)
self.log.debug(stderr)
else:
self.log.debug('System command completed {0}\nOut:{1}'.format(
cmd, stdout))
command_status = self.STATUS['SUCCESS']
#self.log.log_command_op(stdout)
self.log.debug(stdout)
self.log.debug('Command completed {0}'.format(cmd))
except Exception as exc:
error_message = 'Error running system command. Err: {0}'.format(exc)
self.log.error(error_message)
trace = traceback.format_exc()
self.log.error(exc)
self.log.error(trace)
raise Exception(error_message)
self.log.debug('Returning command status: {0}'.format(command_status))
return command_status
def __exec_user_command(self, cmd, working_dir):
self.log.debug('Executing streaming command {0}'.format(cmd))
current_step_state = self.STATUS['FAILED']
command_thread_result = {
'success': False,
'returncode': None
}
command_thread = threading.Thread(
target=self.__command_runner,
args=(cmd, working_dir, command_thread_result,))
command_thread.start()
self.log.debug('Waiting for command thread to complete')
command_thread.join(self.config['MAX_COMMAND_SECONDS'])
self.log.debug('Command thread join has returned. Result: {0}'\
.format(command_thread_result))
if command_thread.is_alive():
self.log.log_command_err('Command timed out')
self.log.error('Command thread is still running')
is_command_success = False
current_step_state = self.STATUS['TIMEOUT']
self.log.log_command_err('Command thread timed out')
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)
self.log.flush_console_buffer()
return current_step_state
def __command_runner(self, cmd, working_dir, result):
self.log.debug('command runner \nCmd: {0}\nDir: {1}'.format(
cmd, working_dir))
cmd = '{0} 2>&1'.format(cmd)
self.log.info('Running {0}'.format(cmd))
proc = None
success = False
try:
proc = subprocess.Popen(
cmd, shell=True,
stdout=subprocess.PIPE,
cwd=working_dir,
env=os.environ.copy(),
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, ''):
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': '',
'type': 'grp',
'message': current_group_name,
'msgTimestamp': self.__get_timestamp(),
'completed': False,
'isShown': show_group
}
self.log.append_console_buffer(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,
'msgTimestamp': self.__get_timestamp(),
'completed': False
}
if parent_id:
self.log.append_console_buffer(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_completed = False
if current_cmd_end_info.get('completed') == '0':
is_completed = True
console_out = {
'consoleId': current_cmd_info.get('id'),
'parentConsoleId': parent_id,
'type': 'cmd',
'message': current_cmd_end_name,
'msgTimestamp': self.__get_timestamp(),
'completed': is_completed
}
if parent_id:
self.log.append_console_buffer(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_completed = False
if current_grp_end_info.get('completed') == '0':
is_completed = True
console_out = {
'consoleId': current_group_info.get('id'),
'parentConsoleId': '',
'type': 'grp',
'message': current_grp_end_name,
'msgTimestamp': self.__get_timestamp(),
'completed': is_completed
}
self.log.append_console_buffer(console_out)
elif line.startswith('__SH__SCRIPT_END_SUCCESS__'):
success = True
break
elif '__SH__ARCHIVE_END__' in line:
success = True
break
elif line.startswith('__SH__SCRIPT_END_FAILURE__'):
if current_group_info:
console_out = {
'consoleId': current_group_info.get('id'),
'parentConsoleId': '',
'type': 'grp',
'message': current_group_name,
'msgTimestamp': self.__get_timestamp(),
'completed': False
}
self.log.append_console_buffer(console_out)
success = False
exception = 'Script failure tag received'
break
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,
'msgTimestamp': self.__get_timestamp(),
'completed': False
}
if parent_id:
self.log.append_console_buffer(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
else:
self.log.debug('Command successful')
result['returncode'] = 0
result['success'] = True
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.info('Command returned {0}'.format(result['returncode']))
def __get_timestamp(self):
return int(time.time() * 1000000)
def pop_step(self, execute_plan, step):
self.log.debug('popping the top of stack: {0}'\
.format(execute_plan['steps']))
try:
for k in execute_plan['steps'].keys():
if k == step['step_key']:
del execute_plan['steps'][k]
self.log.debug('popped out top of stack. \n stack {0}'\
.format(execute_plan['steps']))
return execute_plan
except Exception as exc:
self.log.error('error occurred while poping ' \
'step: {0}'.format(str(exc)))
raise exc
def get_top_of_stack(self, execute_plan):
error_occurred = False
error_message = ''
try:
self.log.info('inside get_top_of_stack')
steps = execute_plan.get('steps', None)
if steps is None:
error_message = 'No steps found in the execute plan: {0}'\
.format(execute_plan)
error_occurred = True
return
if len(steps) == 0:
self.log.info('No steps present in execute plan, returning' \
'empty TopOfStack')
return None
keys = []
for k in steps.keys():
keys.append(int(str(k)))
self.log.debug('steps keys {0}'.format(keys))
keys.sort()
self.log.debug('sorted keys {0}'.format(keys))
current_step_key = str(keys[0])
current_step = steps[current_step_key]
current_step['step_key'] = current_step_key
return current_step
except Exception as exc:
error_message = 'Error occurred while trying to get the step' \
' from execute plan \nError: {0} execute plan: {1}' \
.format(str(exc), execute_plan)
error_occurred = True
finally:
if error_occurred:
raise Exception(error_message)