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