qdo revision 1930
1#! /usr/bin/env python
2
3# Copyright (c) 2004-2005 The Regents of The University of Michigan
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met: redistributions of source code must retain the above copyright
9# notice, this list of conditions and the following disclaimer;
10# redistributions in binary form must reproduce the above copyright
11# notice, this list of conditions and the following disclaimer in the
12# documentation and/or other materials provided with the distribution;
13# neither the name of the copyright holders nor the names of its
14# contributors may be used to endorse or promote products derived from
15# this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29import sys
30import os
31import re
32import time
33import optparse
34
35import pexpect
36
37progname = os.path.basename(sys.argv[0])
38
39usage = "%prog [options] command [command arguments]"
40optparser = optparse.OptionParser(usage=usage)
41optparser.allow_interspersed_args=False
42optparser.add_option('-e', dest='stderr_file',
43                     help='command stderr output file')
44optparser.add_option('-o', dest='stdout_file',
45                     help='command stdout output file')
46optparser.add_option('-l', dest='save_log', action='store_true',
47                     help='save qsub output log file')
48optparser.add_option('-N', dest='job_name',
49                     help='qsub job name')
50optparser.add_option('-q', dest='dest_queue',
51                     help='qsub destination queue')
52optparser.add_option('--qwait', dest='qsub_timeout', type='int',
53                     help='qsub queue wait timeout', default=30*60)
54optparser.add_option('-t', dest='cmd_timeout', type='int',
55                     help='command execution timeout', default=600*60)
56
57(options, cmd) = optparser.parse_args()
58
59if cmd == []:
60    print >>sys.stderr, "%s: missing command" % progname
61    sys.exit(1)
62
63if not options.job_name:
64    options.job_name = cmd[0]
65
66cwd = os.getcwd()
67
68# Deal with systems where /n is a symlink to /.automount
69if cwd.startswith('/.automount/'):
70    cwd = cwd.replace('/.automount/', '/n/', 1)
71
72if not cwd.startswith('/n/poolfs/'):
73    print >>sys.stderr, "Error: current directory must be under /n/poolfs."
74    sys.exit(1)
75
76# The Shell class wraps pexpect.spawn with some handy functions that
77# assume the thing on the other end is a Bourne/bash shell.
78class Shell(pexpect.spawn):
79    # Regexp to match the shell prompt.  We change the prompt to
80    # something fixed and distinctive to make it easier to match
81    # reliably.
82    prompt_re = re.compile('qdo\$ ')
83
84    def __init__(self, cmd):
85        # initialize base pexpect.spawn object
86	try:
87            pexpect.spawn.__init__(self, cmd)
88	except pexpect.ExceptionPexpect, exc:
89	    print "%s:" % progname, exc
90	    sys.exit(1)
91        # full_output accumulates the full output of the session
92        self.full_output = ""
93        self.quick_timeout = 15
94        # wait for a prompt, then change it
95        try:
96            self.expect('\$ ', options.qsub_timeout)
97        except pexpect.TIMEOUT:
98            print >>sys.stderr, "%s: qsub timed out." % progname
99            self.kill(15)
100            self.close(wait=True)
101            sys.exit(1)
102        self.do_command('unset PROMPT_COMMAND; PS1="qdo$ "')
103
104    # version of expect that updates full_output too
105    def expect(self, regexp, timeout = -1):
106        pexpect.spawn.expect(self, regexp, timeout)
107        self.full_output += self.before + self.after
108
109    # Just issue a command and wait for the next prompt.
110    # Returns a string containing the output of the command.
111    def do_bare_command(self, cmd, timeout = -1):
112        global full_output
113        self.sendline(cmd)
114        # read back the echo of the command
115        self.readline()
116        # wait for the next prompt
117        self.expect(self.prompt_re, timeout)
118        output = self.before.rstrip()
119        return output
120
121    # Issue a command, then query its exit status.
122    # Returns a (string, int) tuple with the command output and the status.
123    def do_command(self, cmd, timeout = -1):
124        # do the command itself
125        output = self.do_bare_command(cmd, timeout)
126        # collect status
127        status = int(self.do_bare_command("echo $?", self.quick_timeout))
128        return (output, status)
129
130    # Check to see if the given directory exists.
131    def dir_exists(self, dirname):
132        (output, status) = shell.do_command('[ -d %s ]' % dirname,
133                                            self.quick_timeout)
134        return status == 0
135
136
137# Spawn the interactive pool job.
138
139# Hack to do link on poolfs... disabled for now since
140# compiler/linker/library versioning problems between poolfs and
141# nodes.  May never work since poolfs is x86-64 and nodes are 32-bit.
142if False and len(cmd) > 50:
143    shell_cmd = 'ssh -t poolfs /bin/sh -l'
144    print "%s: running %s on poolfs" % (progname, cmd[0])
145else:
146    shell_cmd = 'qsub -I -S /bin/sh'
147    shell_cmd += ' -N "%s"' % options.job_name
148    if options.dest_queue:
149        shell_cmd += ' -q ' + options.dest_queue
150
151shell = Shell(shell_cmd)
152
153try:
154    # chdir to cwd
155    (output, status) = shell.do_command('cd ' + cwd)
156
157    if status != 0:
158        raise OSError, "Can't chdir to %s" % cwd
159
160    # wacky hack: sometimes scons will create an output directory then
161    # fork a job to generate files in that directory, and the job will
162    # get run before the directory creation propagates through NFS.
163    # This hack looks for a '-o' option indicating an output file and
164    # waits for the corresponding directory to appear if necessary.
165    try:
166        if 'cc' in cmd[0] or 'g++' in cmd[0]:
167            output_dir = os.path.dirname(cmd[cmd.index('-o')+1])
168        elif 'm5' in cmd[0]:
169            output_dir = cmd[cmd.index('-d')+1]
170        else:
171            output_dir = None
172    except (ValueError, IndexError):
173        # no big deal if there's no '-o'/'-d' or if it's the final argument
174        output_dir = None
175
176    if output_dir:
177        secs_waited = 0
178        while not shell.dir_exists(output_dir) and secs_waited < 45:
179            time.sleep(5)
180            secs_waited += 5
181        if secs_waited > 10:
182            print "waited", secs_waited, "seconds for", output_dir
183
184    # run command
185    if options.stdout_file:
186        cmd += ['>', options.stdout_file]
187    if options.stderr_file:
188        cmd += ['2>', options.stderr_file]
189    try:
190        (output, status) = shell.do_command(' '.join(cmd), options.cmd_timeout)
191    except pexpect.TIMEOUT:
192            print >>sys.stderr, "%s: command timed out after %d seconds." \
193                  % (progname, options.cmd_timeout)
194            shell.sendline('~.') # qsub/ssh termination escape sequence
195            shell.close(wait=True)
196            status = 3
197    if output:
198        print output
199
200finally:
201    # end job
202    if shell.isalive():
203        shell.sendline('exit')
204        shell.expect('qsub: job .* completed\r\n')
205        shell.close(wait=True)
206
207    # if there was an error, log the output even if not requested
208    if status != 0 or options.save_log:
209        log = file('qdo-log.' + str(os.getpid()), 'w')
210        log.write(shell.full_output)
211        log.close()
212
213del shell
214
215sys.exit(status)
216