0c342920590079a561130465af81b3eefa8f1a98
[htsworkflow.git] / gaworkflow / util / queuecommands.py
1 """
2 Run up to N simultanous jobs from provided of commands 
3 """
4
5 import logging
6 from subprocess import PIPE
7 import subprocess
8 import select
9 import sys
10
11 class QueueCommands(object):
12     """
13     Queue up N commands from cmd_list, launching more jobs as the first
14     finish.
15     """
16
17     def __init__(self, cmd_list, N=0, cwd=None):
18         """
19         cmd_list is a list of elements suitable for subprocess
20         N is the  number of simultanious processes to run. 
21         0 is all of them.
22         
23         WARNING: this will not work on windows
24         (It depends on being able to pass local file descriptors to the 
25         select call with isn't supported by the Win32 API)
26         """
27         self.to_run = cmd_list[:]
28         self.running = {}
29         self.N = N
30         self.cwd = cwd
31
32     def under_process_limit(self):
33         """
34         are we still under the total number of allowable jobs?
35         """
36         if self.N == 0:
37             return True
38
39         if len(self.running) < self.N:
40             return True
41
42         return False
43
44     def start_jobs(self):
45         """
46         Launch jobs until we have the maximum allowable running
47         (or have run out of jobs)
48         """
49         queue_log = logging.getLogger('queue')
50         queue_log.info('using %s as cwd' % (self.cwd,))
51
52         while (len(self.to_run) > 0) and self.under_process_limit():
53             cmd = self.to_run.pop(0)
54             p = subprocess.Popen(cmd, stdout=PIPE, cwd=self.cwd, shell=True)
55             self.running[p.stdout] = p
56             queue_log.info("Created process %d from %s" % (p.pid, str(cmd)))
57
58     def run(self):
59         """
60         run up to N jobs until we run out of jobs
61         """
62         queue_log = logging.getLogger('queue')
63
64         # to_run slowly gets consumed by start_jobs
65         while len(self.to_run) > 0 or len(self.running) > 0:
66             # fill any empty spots in our job queue
67             self.start_jobs()
68
69             # build a list of file descriptors
70             # fds=file desciptors
71             fds = [ x.stdout for x in self.running.values()]
72
73             # wait for something to finish
74             # wl= write list, xl=exception list (not used so get bad names)
75             read_list, wl, xl = select.select(fds, [], fds)
76         
77             # for everything that might have finished...
78             for pending_fd in read_list:
79                 pending = self.running[pending_fd]
80                 # if it really did finish, remove it from running jobs
81                 if pending.poll() is not None:
82                     queue_log.info("Process %d finished" % (pending.pid,))
83                     del self.running[pending_fd]
84