Debian Codegraph @

src/devedeng/executor.py

raw
1 #!/usr/bin/env python3
2
3 # Copyright 2014 (C) Raster Software Vigo (Sergio Costas)
4 #
5 # This file is part of DeVeDe-NG
6 #
7 # DeVeDe-NG is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License version 3
9 # as published by the Free Software Foundation.
10 #
11 # DeVeDe-NG is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>
18
19 from gi.repository import GLib, GObject
20 import subprocess
21 import os
22 import signal
23 import devedeng.configuration_data
24
25
26 class executor(GObject.GObject):
27 """ This class encapsulates everything needed for launching processes """
28
29 __gsignals__ = {'ended': (GObject.SIGNAL_RUN_FIRST, None, (int,))}
30
31 def __init__(self):
32
33 GObject.GObject.__init__(self)
34
35 self.config = devedeng.configuration_data.configuration.get_config()
36 self.channel_stdin = None
37 self.channel_stdout = None
38 self.channel_stderr = None
39 self.text = ""
40 self.stdout_data = ""
41 self.stderr_data = ""
42 self.stdin_file = None
43 self.stdout_file = None
44
45 self.dependencies = None
46 self.childs = []
47 self.progress_bar = None
48 self.killed = False
49 self.pulse_mode = False
50 self.use_pulse_mode = False
51 self.pulse_text = None
52 self.handle = None
53
54 def add_dependency(self, dep):
55
56 self.add_dependency2(dep)
57
58 for child in dep.childs:
59 self.add_dependency2(child)
60
61 def add_dependency2(self, dep):
62
63 if (self.dependencies is None):
64 self.dependencies = []
65
66 if (self.dependencies.count(dep) == 0):
67 self.dependencies.append(dep)
68
69 # the childs have the same dependencies than the parent process
70 # because, from outside, it is viewed as a single process
71 for child in self.childs:
72 child.add_dependency(dep)
73
74 def remove_dependency(self, process):
75 # dependencies are removed only in the parent because the running class have all the processes, parents and childs, and calls
76 # this method on all of them
77 if (self.dependencies is not None):
78 tmp2 = []
79 for dep in self.dependencies:
80 if dep != process:
81 tmp2.append(dep)
82 if (len(tmp2) != 0):
83 self.dependencies = tmp2
84 else:
85 self.dependencies = None
86
87 def add_child_process(self, child):
88
89 # the childs have the same dependencies than the parent process
90 # because, from outside, it is viewed as a single process
91 if self.dependencies is not None:
92 for dep in self.dependencies:
93 child.add_dependency(dep)
94
95 if (self.childs.count(child) == 0):
96 self.childs.append(child)
97
98 def run(self, progress_bar):
99
100 self.progress_bar = progress_bar
101 self.progress_bar[0].set_label(self.text)
102 self.progress_bar[1].set_fraction(0.0)
103 self.progress_bar[0].show_all()
104 # call, if it exists, the pre-function
105 try:
106 self.pre_function()
107 except:
108 pass
109 self.launch_process(self.command_var)
110 if self.use_pulse_mode != self.pulse_mode:
111 self.set_pulse_mode(self.use_pulse_mode)
112
113 def remove_ansi(self, line):
114
115 output = ""
116 while True:
117 pos = line.find("\033[") # try with double-byte ESC
118 jump = 2
119 if pos == -1:
120 pos = line.find("\233") # if not, try with single-byte ESC
121 jump = 1
122 if pos == -1: # no ANSI characters; we ended
123 output += line
124 break
125
126 output += line[:pos]
127 line = line[pos + jump:]
128
129 while True:
130 if len(line) == 0:
131 break
132 if (ord(line[0]) < 64) or (ord(line[0]) > 126):
133 line = line[1:]
134 else:
135 line = line[1:]
136 break
137 return output
138
139 def launch_process(self, command, redirect_output=True):
140
141 if command is not None:
142 self.launch_command = "\n\nLaunching:"
143 for e in command:
144 self.launch_command += (" " + e)
145 self.launch_command += "\n"
146
147 self.config.append_log(self.text)
148 if command is not None:
149 self.config.append_log(self.launch_command)
150
151 try:
152 if (self.stdin_file is not None):
153 self.handle = subprocess.Popen(
154 command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
155 self.channel_stdin = GLib.IOChannel(self.handle.stdin.fileno())
156 self.channel_stdin.add_watch(
157 GLib.IO_OUT | GLib.IO_HUP, self.read_stdin_from_file)
158 self.file_in = open(self.stdin_file, "rb")
159 else:
160 self.handle = subprocess.Popen(
161 command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
162 except Exception as error_launch:
163 self.handle = None
164 self.stderr_data += str(error_launch)
165 self.wait_end()
166 return
167
168 if (redirect_output):
169 self.stdout_buf = ""
170 self.stderr_buf = ""
171 self.channel_stdout = GLib.IOChannel(self.handle.stdout.fileno())
172 self.channel_stderr = GLib.IOChannel(self.handle.stderr.fileno())
173 if (self.stdout_file is not None):
174 self.channel_stdout.add_watch(
175 GLib.IO_IN | GLib.IO_HUP, self.read_stdout_to_file)
176 self.file_out = open(self.stdout_file, "wb")
177 else:
178 self.channel_stdout.add_watch(
179 GLib.IO_IN | GLib.IO_HUP, self.read_stdout)
180 self.channel_stderr.add_watch(
181 GLib.IO_IN | GLib.IO_HUP, self.read_stderr)
182 else:
183 (stdout_r, stderr_r) = self.handle.communicate()
184 self.handle = None
185 self.config.append_log(self.launch_command)
186 try:
187 self.config.append_log(stdout_r.decode("utf-8"))
188 except:
189 self.config.append_log(stdout_r.decode("latin-1"))
190 try:
191 self.config.append_log(stderr_r.decode("utf-8"))
192 except:
193 self.config.append_log(stderr_r.decode("latin-1"))
194 return (stdout_r, stderr_r)
195
196 def set_pulse_mode(self, pulse_mode):
197
198 if pulse_mode == self.pulse_mode:
199 return
200
201 self.pulse_mode = pulse_mode
202
203 if pulse_mode:
204 self.timer_pulse = GLib.timeout_add(250, self.run_pulse)
205 else:
206 GLib.source_remove(self.timer_pulse)
207
208 def run_pulse(self, v=None):
209
210 if self.progress_bar is None:
211 return
212
213 if self.pulse_text is not None:
214 self.progress_bar[1].set_text(self.pulse_text)
215 self.progress_bar[1].pulse()
216 return True
217
218 def read_stdout_to_file(self, source, condition):
219
220 if (condition != GLib.IO_IN):
221 self.channel_stdout = None
222 if ((self.channel_stderr is None) and (self.channel_stdin is None)):
223 self.wait_end()
224 return False
225 else:
226 line_data = self.handle.stdout.read1(4096)
227 self.file_out.write(line_data)
228 return True
229
230 def read_stdin_from_file(self, source, condition):
231
232 line_data = self.file_in.read1(4096)
233 if (len(line_data) == 0):
234 self.channel_stdin = None
235 self.handle.stdin.close()
236 if ((self.channel_stderr is None) and (self.channel_stdout is None)):
237 self.wait_end()
238 return False
239 else:
240 self.handle.stdin.write(line_data)
241 return True
242
243 def read_stdout(self, source, condition):
244
245 if (condition != GLib.IO_IN):
246 self.channel_stdout = None
247 if ((self.channel_stderr is None) and (self.channel_stdin is None)):
248 self.wait_end()
249 return False
250 else:
251 read_data = self.handle.stdout.read1(4096)
252 try:
253 line_data = self.stdout_buf + (read_data.decode("utf-8"))
254 except:
255 line_data = self.stdout_buf + (read_data.decode("latin-1"))
256 self.stdout_data += line_data
257 data = (line_data).replace("\r", "\n").split("\n")
258 if (len(data) == 1):
259 final_data = []
260 self.stdout_buf = data[0]
261 else:
262 final_data = data[:-1]
263 self.stdout_buf = data[-1]
264 if (len(final_data) != 0):
265 self.process_stdout(final_data)
266 return True
267
268 def read_stderr(self, source, condition):
269
270 if (condition != GLib.IO_IN):
271 self.channel_stderr = None
272 if (((self.channel_stdout is None) or (self.stdout_file is not None)) and ((self.channel_stdin is None) or (self.stdin_file is not None))):
273 self.wait_end()
274 return False
275 else:
276 read_data = self.handle.stderr.read1(4096)
277 try:
278 line_data = self.stderr_buf + (read_data.decode("utf-8"))
279 except:
280 line_data = self.stderr_buf + (read_data.decode("latin-1"))
281 self.stderr_data += line_data
282 data = (line_data).replace("\r", "\n").split("\n")
283 if (len(data) == 1):
284 final_data = []
285 self.stderr_buf = data[0]
286 else:
287 final_data = data[:-1]
288 self.stderr_buf = data[-1]
289 if (len(final_data) != 0):
290 self.process_stderr(final_data)
291 return True
292
293 def cancel(self):
294 """ Called to kill this process. """
295
296 if self.handle is None:
297 return
298
299 self.killed = True
300 os.kill(self.handle.pid, signal.SIGKILL)
301
302 def wait_end(self):
303
304 if self.handle is not None:
305 retval = self.handle.wait()
306 self.handle = None
307 else:
308 retval = -1
309
310 self.set_pulse_mode(False)
311
312 # call, if it exists, the post-function
313 try:
314 self.post_function(retval, self.killed)
315 except:
316 pass
317
318 if self.killed:
319 retval = 0
320 else:
321 self.config.append_log(self.stdout_data)
322 self.config.append_log(self.stderr_data)
323
324 self.emit("ended", retval)
325
326 def expand_xml(self, text):
327
328 text = text.replace('&', '&amp;')
329 text = text.replace('<', '&lt;')
330 text = text.replace('>', '&gt;')
331 text = text.replace('"', '&quot;')
332 text = text.replace("'", '&apos;')
333 return text
334
335 def get_division(self, data):
336
337 pos = data.find("/")
338 pos2 = data.find(":")
339
340 if (pos == -1):
341 pos = pos2
342
343 if (pos == -1):
344 try:
345 return float(data)
346 except:
347 return 0
348 else:
349 try:
350 data1 = float(data[:pos])
351 data2 = float(data[pos + 1:])
352 except:
353 return 0
354 if (data2 == 0):
355 return 0
356 else:
357 return (float(int((data1 / data2) * 1000.0))) / 1000.0
358
359 def get_time(self, line):
360
361 time_string = ""
362
363 for letter in line.strip():
364 if (letter == ':') or (letter == '.') or (letter.isdigit()):
365 time_string += letter
366 else:
367 break
368
369 elements = time_string.split(":")
370
371 if (len(elements) == 0):
372 return -1
373
374 value = 0
375 for element in elements:
376 if (element == ''):
377 continue
378 value *= 60
379 value += int(0.5 + float(element))
380 return value