04e5c9385948e0e4426619787ada2fa3199b8bb4
[vuplus_dvbapp] / 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.cmdline = None
131                 self.task_progress_changed = None
132                 self.output_line = ""
133                 job.addTask(self)
134
135         def setCommandline(self, cmd, args):
136                 self.cmd = cmd
137                 self.args = args
138
139         def setTool(self, tool):
140                 self.cmd = tool
141                 self.args = [tool]
142                 self.global_preconditions.append(ToolExistsPrecondition())
143                 self.postconditions.append(ReturncodePostcondition())
144
145         def setCmdline(self, cmdline):
146                 self.cmdline = cmdline
147
148         def checkPreconditions(self, immediate = False):
149                 not_met = [ ]
150                 if immediate:
151                         preconditions = self.immediate_preconditions
152                 else:
153                         preconditions = self.global_preconditions
154                 for precondition in preconditions:
155                         if not precondition.check(self):
156                                 not_met.append(precondition)
157                 return not_met
158
159         def run(self, callback):
160                 failed_preconditions = self.checkPreconditions(True) + self.checkPreconditions(False)
161                 if len(failed_preconditions):
162                         callback(self, failed_preconditions)
163                         return
164                 self.prepare()
165
166                 self.callback = callback
167                 from enigma import eConsoleAppContainer
168                 self.container = eConsoleAppContainer()
169                 self.container.appClosed.append(self.processFinished)
170                 self.container.stdoutAvail.append(self.processStdout)
171                 self.container.stderrAvail.append(self.processStderr)
172
173                 if self.cwd is not None:
174                         self.container.setCWD(self.cwd)
175
176                 if not self.cmd and self.cmdline:
177                         print "execute:", self.container.execute(self.cmdline), self.cmdline
178                 else:
179                         assert self.cmd is not None
180                         assert len(self.args) >= 1
181                         print "execute:", self.container.execute(self.cmd, *self.args), ' '.join(self.args)
182                 if self.initial_input:
183                         self.writeInput(self.initial_input)
184
185         def prepare(self):
186                 pass
187
188         def cleanup(self, failed):
189                 pass
190         
191         def processStdout(self, data):
192                 self.processOutput(data)
193                 
194         def processStderr(self, data):
195                 self.processOutput(data)
196
197         def processOutput(self, data):
198                 self.output_line += data
199                 while True:
200                         i = self.output_line.find('\n')
201                         if i == -1:
202                                 break
203                         self.processOutputLine(self.output_line[:i+1])
204                         self.output_line = self.output_line[i+1:]
205
206         def processOutputLine(self, line):
207                 pass
208
209         def processFinished(self, returncode):
210                 self.returncode = returncode
211                 self.finish()
212
213         def abort(self):
214                 self.container.kill()
215                 self.finish(aborted = True)
216
217         def finish(self, aborted = False):
218                 self.afterRun()
219                 not_met = [ ]
220                 if aborted:
221                         not_met.append(AbortedPostcondition())
222                 else:
223                         for postcondition in self.postconditions:
224                                 if not postcondition.check(self):
225                                         not_met.append(postcondition)
226                 self.cleanup(not_met)
227                 self.callback(self, not_met)
228
229         def afterRun(self):
230                 pass
231
232         def writeInput(self, input):
233                 self.container.write(input)
234
235         def getProgress(self):
236                 return self.__progress
237
238         def setProgress(self, progress):
239                 if progress > self.end:
240                         progress = self.end
241                 if progress < 0:
242                         progress = 0
243                 self.__progress = progress
244                 if self.task_progress_changed:
245                         self.task_progress_changed()
246
247         progress = property(getProgress, setProgress)
248
249 # The jobmanager will execute multiple jobs, each after another.
250 # later, it will also support suspending jobs (and continuing them after reboot etc)
251 # It also supports a notification when some error occured, and possibly a retry.
252 class JobManager:
253         def __init__(self):
254                 self.active_jobs = [ ]
255                 self.failed_jobs = [ ]
256                 self.job_classes = [ ]
257                 self.in_background = False
258                 self.active_job = None
259
260         def AddJob(self, job):
261                 self.active_jobs.append(job)
262                 self.kick()
263
264         def kick(self):
265                 if self.active_job is None:
266                         if len(self.active_jobs):
267                                 self.active_job = self.active_jobs.pop(0)
268                                 self.active_job.start(self.jobDone)
269
270         def jobDone(self, job, task, problems):
271                 print "job", job, "completed with", problems, "in", task
272                 from Tools import Notifications
273                 if self.in_background:
274                         from Screens.TaskView import JobView
275                         self.in_background = False
276                         Notifications.AddNotification(JobView, self.active_job)
277                 if problems:
278                         from Screens.MessageBox import MessageBox
279                         if problems[0].RECOVERABLE:
280                                 Notifications.AddNotificationWithCallback(self.errorCB, MessageBox, _("Error: %s\nRetry?") % (problems[0].getErrorMessage(task)))
281                         else:
282                                 Notifications.AddNotification(MessageBox, _("Error") + (': %s') % (problems[0].getErrorMessage(task)), type = MessageBox.TYPE_ERROR )
283                                 self.errorCB(False)
284                         return
285                         #self.failed_jobs.append(self.active_job)
286
287                 self.active_job = None
288                 self.kick()
289
290         def errorCB(self, answer):
291                 if answer:
292                         print "retrying job"
293                         self.active_job.retry()
294                 else:
295                         print "not retrying job."
296                         self.failed_jobs.append(self.active_job)
297                         self.active_job = None
298                         self.kick()
299
300         def getPendingJobs(self):
301                 list = [ ]
302                 if self.active_job:
303                         list.append(self.active_job)
304                 list += self.active_jobs
305                 return list
306 # some examples:
307 #class PartitionExistsPostcondition:
308 #       def __init__(self, device):
309 #               self.device = device
310 #
311 #       def check(self, task):
312 #               import os
313 #               return os.access(self.device + "part1", os.F_OK)
314 #
315 #class CreatePartitionTask(Task):
316 #       def __init__(self, device):
317 #               Task.__init__(self, _("Create Partition"))
318 #               self.device = device
319 #               self.setTool("/sbin/sfdisk")
320 #               self.args += ["-f", self.device + "disc"]
321 #               self.initial_input = "0,\n;\n;\n;\ny\n"
322 #               self.postconditions.append(PartitionExistsPostcondition(self.device))
323 #
324 #class CreateFilesystemTask(Task):
325 #       def __init__(self, device, partition = 1, largefile = True):
326 #               Task.__init__(self, _("Create Filesystem"))
327 #               self.setTool("/sbin/mkfs.ext")
328 #               if largefile:
329 #                       self.args += ["-T", "largefile"]
330 #               self.args.append("-m0")
331 #               self.args.append(device + "part%d" % partition)
332 #
333 #class FilesystemMountTask(Task):
334 #       def __init__(self, device, partition = 1, filesystem = "ext3"):
335 #               Task.__init__(self, _("Mounting Filesystem"))
336 #               self.setTool("/bin/mount")
337 #               if filesystem is not None:
338 #                       self.args += ["-t", filesystem]
339 #               self.args.append(device + "part%d" % partition)
340
341 class Condition:
342         RECOVERABLE = False
343
344         def getErrorMessage(self, task):
345                 return _("An unknown error occured!") + " (%s @ task %s)" % (self.__class__.__name__, task.__class__.__name__)
346
347 class WorkspaceExistsPrecondition(Condition):
348         def check(self, task):
349                 return os.access(task.job.workspace, os.W_OK)
350
351 class DiskspacePrecondition(Condition):
352         def __init__(self, diskspace_required):
353                 self.diskspace_required = diskspace_required
354                 self.diskspace_available = 0
355
356         def check(self, task):
357                 import os
358                 try:
359                         s = os.statvfs(task.job.workspace)
360                         self.diskspace_available = s.f_bsize * s.f_bavail
361                         return self.diskspace_available >= self.diskspace_required
362                 except OSError:
363                         return False
364
365         def getErrorMessage(self, task):
366                 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)
367
368 class ToolExistsPrecondition(Condition):
369         def check(self, task):
370                 import os
371                 if task.cmd[0]=='/':
372                         realpath = task.cmd
373                 else:
374                         realpath = task.cwd + '/' + task.cmd
375                 self.realpath = realpath
376                 return os.access(realpath, os.X_OK)
377
378         def getErrorMessage(self, task):
379                 return _("A required tool (%s) was not found.") % (self.realpath)
380
381 class AbortedPostcondition(Condition):
382         def getErrorMessage(self, task):
383                 return "Cancelled upon user request"
384
385 class ReturncodePostcondition(Condition):
386         def check(self, task):
387                 return task.returncode == 0
388
389 #class HDDInitJob(Job):
390 #       def __init__(self, device):
391 #               Job.__init__(self, _("Initialize Harddisk"))
392 #               self.device = device
393 #               self.fromDescription(self.createDescription())
394 #
395 #       def fromDescription(self, description):
396 #               self.device = description["device"]
397 #               self.addTask(CreatePartitionTask(self.device))
398 #               self.addTask(CreateFilesystemTask(self.device))
399 #               self.addTask(FilesystemMountTask(self.device))
400 #
401 #       def createDescription(self):
402 #               return {"device": self.device}
403
404 job_manager = JobManager()