9a7684250008c295087f17516793d911fddd0cfb
[enigma2.git] / lib / python / Components / Task.py
1 # A Job consists of many "Tasks".
2 # A task is the run of an external tool, with proper methods for failure handling
3
4 from Tools.CList import CList
5
6 class Job(object):
7         NOT_STARTED, IN_PROGRESS, FINISHED, FAILED = range(4)
8         def __init__(self, name):
9                 self.tasks = [ ]
10                 self.resident_tasks = [ ]
11                 self.workspace = "/tmp"
12                 self.current_task = 0
13                 self.callback = None
14                 self.name = name
15                 self.finished = False
16                 self.end = 100
17                 self.__progress = 0
18                 self.weightScale = 1
19
20                 self.state_changed = CList()
21
22                 self.status = self.NOT_STARTED
23
24         # description is a dict
25         def fromDescription(self, description):
26                 pass
27
28         def createDescription(self):
29                 return None
30
31         def getProgress(self):
32                 if self.current_task == len(self.tasks):
33                         return self.end
34                 t = self.tasks[self.current_task]
35                 jobprogress = t.weighting * t.progress / float(t.end) + sum([task.weighting for task in self.tasks[:self.current_task]])
36                 return int(jobprogress*self.weightScale)
37
38         progress = property(getProgress)
39
40         def getStatustext(self):
41                 return { self.NOT_STARTED: _("Waiting"), self.IN_PROGRESS: _("In Progress"), self.FINISHED: _("Finished"), self.FAILED: _("Failed") }[self.status]
42
43         def task_progress_changed_CB(self):
44                 self.state_changed()
45
46         def addTask(self, task):
47                 task.job = self
48                 task.task_progress_changed = self.task_progress_changed_CB
49                 self.tasks.append(task)
50
51         def start(self, callback):
52                 assert self.callback is None
53                 self.callback = callback
54                 self.restart()
55
56         def restart(self):
57                 self.status = self.IN_PROGRESS
58                 self.state_changed()
59                 self.runNext()
60                 sumTaskWeightings = sum([t.weighting for t in self.tasks]) or 1
61                 self.weightScale = self.end / float(sumTaskWeightings)
62
63         def runNext(self):
64                 if self.current_task == len(self.tasks):
65                         if len(self.resident_tasks) == 0:
66                                 cb = self.callback
67                                 self.callback = None
68                                 self.status = self.FINISHED
69                                 self.state_changed()
70                                 cb(self, None, [])
71                         else:
72                                 print "still waiting for %d resident task(s) %s to finish" % (len(self.resident_tasks), str(self.resident_tasks))
73                 else:
74                         self.tasks[self.current_task].run(self.taskCallback)
75                         self.state_changed()
76
77         def taskCallback(self, task, res, stay_resident = False):
78                 cb_idx = self.tasks.index(task)
79                 if stay_resident:
80                         if cb_idx not in self.resident_tasks:
81                                 self.resident_tasks.append(self.current_task)
82                                 print "task going resident:", task
83                         else:
84                                 print "task keeps staying resident:", task
85                                 return
86                 if len(res):
87                         print ">>> Error:", res
88                         self.status = self.FAILED
89                         self.state_changed()
90                         self.callback(self, task, res)
91                 if cb_idx != self.current_task:
92                         if cb_idx in self.resident_tasks:
93                                 print "resident task finished:", task
94                                 self.resident_tasks.remove(cb_idx)
95                 if res == []:
96                         self.state_changed()
97                         self.current_task += 1
98                         self.runNext()
99
100         def retry(self):
101                 assert self.status == self.FAILED
102                 self.restart()
103
104         def abort(self):
105                 if self.current_task < len(self.tasks):
106                         self.tasks[self.current_task].abort()
107                 for i in self.resident_tasks:
108                         self.tasks[i].abort()
109
110         def cancel(self):
111                 # some Jobs might have a better idea of how to cancel a job
112                 self.abort()
113
114 class Task(object):
115         def __init__(self, job, name):
116                 self.name = name
117                 self.immediate_preconditions = [ ]
118                 self.global_preconditions = [ ]
119                 self.postconditions = [ ]
120                 self.returncode = None
121                 self.initial_input = None
122                 self.job = None
123
124                 self.end = 100
125                 self.weighting = 100
126                 self.__progress = 0
127                 self.cmd = None
128                 self.cwd = "/tmp"
129                 self.args = [ ]
130                 self.task_progress_changed = None
131                 self.output_line = ""
132                 job.addTask(self)
133
134         def setCommandline(self, cmd, args):
135                 self.cmd = cmd
136                 self.args = args
137
138         def setTool(self, tool):
139                 self.cmd = tool
140                 self.args = [tool]
141                 self.global_preconditions.append(ToolExistsPrecondition())
142                 self.postconditions.append(ReturncodePostcondition())
143
144         def checkPreconditions(self, immediate = False):
145                 not_met = [ ]
146                 if immediate:
147                         preconditions = self.immediate_preconditions
148                 else:
149                         preconditions = self.global_preconditions
150                 for precondition in preconditions:
151                         if not precondition.check(self):
152                                 not_met.append(precondition)
153                 return not_met
154
155         def run(self, callback):
156                 failed_preconditions = self.checkPreconditions(True) + self.checkPreconditions(False)
157                 if len(failed_preconditions):
158                         callback(self, failed_preconditions)
159                         return
160                 self.prepare()
161
162                 self.callback = callback
163                 from enigma import eConsoleAppContainer
164                 self.container = eConsoleAppContainer()
165                 self.container.appClosed.append(self.processFinished)
166                 self.container.stdoutAvail.append(self.processStdout)
167                 self.container.stderrAvail.append(self.processStderr)
168
169                 assert self.cmd is not None
170                 assert len(self.args) >= 1
171
172                 if self.cwd is not None:
173                         self.container.setCWD(self.cwd)
174
175                 print "execute:", self.container.execute(self.cmd, *self.args), self.cmd, self.args
176                 if self.initial_input:
177                         self.writeInput(self.initial_input)
178
179         def prepare(self):
180                 pass
181
182         def cleanup(self, failed):
183                 pass
184         
185         def processStdout(self, data):
186                 self.processOutput(data)
187                 
188         def processStderr(self, data):
189                 self.processOutput(data)
190
191         def processOutput(self, data):
192                 self.output_line += data
193                 while True:
194                         i = self.output_line.find('\n')
195                         if i == -1:
196                                 break
197                         self.processOutputLine(self.output_line[:i+1])
198                         self.output_line = self.output_line[i+1:]
199
200         def processOutputLine(self, line):
201                 pass
202
203         def processFinished(self, returncode):
204                 self.returncode = returncode
205                 self.finish()
206
207         def abort(self):
208                 self.container.kill()
209                 self.finish(aborted = True)
210
211         def finish(self, aborted = False):
212                 self.afterRun()
213                 not_met = [ ]
214                 if aborted:
215                         not_met.append(AbortedPostcondition())
216                 else:
217                         for postcondition in self.postconditions:
218                                 if not postcondition.check(self):
219                                         not_met.append(postcondition)
220                 self.cleanup(not_met)
221                 self.callback(self, not_met)
222
223         def afterRun(self):
224                 pass
225
226         def writeInput(self, input):
227                 self.container.write(input)
228
229         def getProgress(self):
230                 return self.__progress
231
232         def setProgress(self, progress):
233                 if progress > self.end:
234                         progress = self.end
235                 if progress < 0:
236                         progress = 0
237                 self.__progress = progress
238                 if self.task_progress_changed:
239                         self.task_progress_changed()
240
241         progress = property(getProgress, setProgress)
242
243 # The jobmanager will execute multiple jobs, each after another.
244 # later, it will also support suspending jobs (and continuing them after reboot etc)
245 # It also supports a notification when some error occured, and possibly a retry.
246 class JobManager:
247         def __init__(self):
248                 self.active_jobs = [ ]
249                 self.failed_jobs = [ ]
250                 self.job_classes = [ ]
251                 self.in_background = False
252                 self.active_job = None
253
254         def AddJob(self, job):
255                 self.active_jobs.append(job)
256                 self.kick()
257
258         def kick(self):
259                 if self.active_job is None:
260                         if len(self.active_jobs):
261                                 self.active_job = self.active_jobs.pop(0)
262                                 self.active_job.start(self.jobDone)
263
264         def jobDone(self, job, task, problems):
265                 print "job", job, "completed with", problems, "in", task
266                 from Tools import Notifications
267                 if self.in_background:
268                         from Screens.TaskView import JobView
269                         self.in_background = False
270                         Notifications.AddNotification(JobView, self.active_job)
271                 if problems:
272                         from Screens.MessageBox import MessageBox
273                         if problems[0].RECOVERABLE:
274                                 Notifications.AddNotificationWithCallback(self.errorCB, MessageBox, _("Error: %s\nRetry?") % (problems[0].getErrorMessage(task)))
275                         else:
276                                 Notifications.AddNotification(MessageBox, _("Error") + (': %s') % (problems[0].getErrorMessage(task)), type = MessageBox.TYPE_ERROR )
277                                 self.errorCB(False)
278                         return
279                         #self.failed_jobs.append(self.active_job)
280
281                 self.active_job = None
282                 self.kick()
283
284         def errorCB(self, answer):
285                 if answer:
286                         print "retrying job"
287                         self.active_job.retry()
288                 else:
289                         print "not retrying job."
290                         self.failed_jobs.append(self.active_job)
291                         self.active_job = None
292                         self.kick()
293
294         def getPendingJobs(self):
295                 list = [ ]
296                 if self.active_job:
297                         list.append(self.active_job)
298                 list += self.active_jobs
299                 return list
300 # some examples:
301 #class PartitionExistsPostcondition:
302 #       def __init__(self, device):
303 #               self.device = device
304 #
305 #       def check(self, task):
306 #               import os
307 #               return os.access(self.device + "part1", os.F_OK)
308 #
309 #class CreatePartitionTask(Task):
310 #       def __init__(self, device):
311 #               Task.__init__(self, _("Create Partition"))
312 #               self.device = device
313 #               self.setTool("/sbin/sfdisk")
314 #               self.args += ["-f", self.device + "disc"]
315 #               self.initial_input = "0,\n;\n;\n;\ny\n"
316 #               self.postconditions.append(PartitionExistsPostcondition(self.device))
317 #
318 #class CreateFilesystemTask(Task):
319 #       def __init__(self, device, partition = 1, largefile = True):
320 #               Task.__init__(self, _("Create Filesystem"))
321 #               self.setTool("/sbin/mkfs.ext")
322 #               if largefile:
323 #                       self.args += ["-T", "largefile"]
324 #               self.args.append("-m0")
325 #               self.args.append(device + "part%d" % partition)
326 #
327 #class FilesystemMountTask(Task):
328 #       def __init__(self, device, partition = 1, filesystem = "ext3"):
329 #               Task.__init__(self, _("Mounting Filesystem"))
330 #               self.setTool("/bin/mount")
331 #               if filesystem is not None:
332 #                       self.args += ["-t", filesystem]
333 #               self.args.append(device + "part%d" % partition)
334
335 class Condition:
336         RECOVERABLE = False
337
338         def getErrorMessage(self, task):
339                 return _("An unknown error occured!") + " (%s @ task %s)" % (self.__class__.__name__, task.__class__.__name__)
340
341 class WorkspaceExistsPrecondition(Condition):
342         def check(self, task):
343                 return os.access(task.job.workspace, os.W_OK)
344
345 class DiskspacePrecondition(Condition):
346         def __init__(self, diskspace_required):
347                 self.diskspace_required = diskspace_required
348                 self.diskspace_available = 0
349
350         def check(self, task):
351                 import os
352                 try:
353                         s = os.statvfs(task.job.workspace)
354                         self.diskspace_available = s.f_bsize * s.f_bavail
355                         return self.diskspace_available >= self.diskspace_required
356                 except OSError:
357                         return False
358
359         def getErrorMessage(self, task):
360                 return _("Not enough diskspace. Please free up some diskspace and try again. (%d MB required, %d MB available)") % (self.diskspace_required / 1024 / 1024, self.diskspace_available / 1024 / 1024)
361
362 class ToolExistsPrecondition(Condition):
363         def check(self, task):
364                 import os
365                 if task.cmd[0]=='/':
366                         realpath = task.cmd
367                 else:
368                         realpath = task.cwd + '/' + task.cmd
369                 self.realpath = realpath
370                 return os.access(realpath, os.X_OK)
371
372         def getErrorMessage(self, task):
373                 return _("A required tool (%s) was not found.") % (self.realpath)
374
375 class AbortedPostcondition(Condition):
376         def getErrorMessage(self, task):
377                 return "Cancelled upon user request"
378
379 class ReturncodePostcondition(Condition):
380         def check(self, task):
381                 return task.returncode == 0
382
383 #class HDDInitJob(Job):
384 #       def __init__(self, device):
385 #               Job.__init__(self, _("Initialize Harddisk"))
386 #               self.device = device
387 #               self.fromDescription(self.createDescription())
388 #
389 #       def fromDescription(self, description):
390 #               self.device = description["device"]
391 #               self.addTask(CreatePartitionTask(self.device))
392 #               self.addTask(CreateFilesystemTask(self.device))
393 #               self.addTask(FilesystemMountTask(self.device))
394 #
395 #       def createDescription(self):
396 #               return {"device": self.device}
397
398 job_manager = JobManager()