tools.py 6.77 KB
Newer Older
André Anjos's avatar
André Anjos committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Wed 24 Aug 2011 09:26:46 CEST 

"""Functions that replace the shell based utilities for the grid submission and
probing.
"""

import os
import re
import logging

# Constant regular expressions
WHITE_SPACE = re.compile('\s+')

def makedirs_safe(fulldir):
  """Creates a directory if it does not exists. Takes into consideration
  concurrent access support. Works like the shell's 'mkdir -p'.
  """

  try:
    if not os.path.exists(fulldir): os.makedirs(fulldir)
  except OSError as exc: # Python >2.5
    if exc.errno == errno.EEXIST: pass
    else: raise

def qsub(command, queue='all.q', cwd=True, name=None, deps=[], stdout='',
    stderr='', env=[], context='grid'):
  """Submits a shell job to a given grid queue
  
  Keyword parameters:

  command
    The command to be submitted to the grid

  queue
    A valid queue name

  cwd
    If the job should change to the current working directory before starting

  name
    An optional name to set for the job. If not given, defaults to the script
    name being launched.

  deps
    Job ids to which this job will be dependent on

  stdout
    The standard output directory. If not given, defaults to what qsub has as a
    default.

  stderr
    The standard error directory (if not given, defaults to the stdout
    directory).

  env
    This is a list of extra variables that will be set on the environment
    running the command of your choice.

  context
    The setshell context in which we should try a 'qsub'. Normally you don't
    need to change the default. This variable can also be set to a context
    dictionary in which case we just setup using that context instead of
    probing for a new one, what can be fast.

  Returns a list of job ids assigned to this job (integers)
  """

  scmd = ['qsub', '-l', 'qname=%s' % queue]

  if cwd: scmd += ['-cwd']

  if name: scmd += ['-N', name]

  if deps: scmd += ['-hold_jid', ','.join(['%d' % k for k in deps])]

  if stdout:
    
    if not cwd:
      # pivot, temporarily, to home directory
      curdir = os.path.realpath(os.curdir)
      os.chdir(os.environ['HOME'])
    
    if not os.path.exists(stdout): makedirs_safe(stdout)

    if not cwd:
      # go back
      os.chdir(os.path.realpath(curdir))

    scmd += ['-o', stdout]

  if stderr:
    if not os.path.exists(stdout): makedirs_safe(stdout)
    scmd += ['-e', stderr]
  elif stdout: #just re-use the stdout settings
    scmd += ['-e', stdout]

  scmd += ['-terse'] # simplified job identifiers returned by the command line

  for k in env: scmd += ['-v', k]

  if not isinstance(command, (list, tuple)): command = [command]
  scmd += command

  logging.debug("Qsub command '%s'", ' '.join(scmd))
  from .setshell import sexec
  jobid = sexec(context, scmd)
  return int(jobid.split('.',1)[0])

def make_shell(shell, command, kwargs):
  """Returns a single command given a shell and a command to be qsub'ed
  
  Keyword parameters: (please read the help of qsub())
    (read the help of qsub() for details on extra arguments that may be
    supplied)

  shell
    The path to the shell to use when submitting the job.

  command
    The script path to be submitted

  Returns the args and kwargs parameters to be supplied to qsub()
  """

  return (['-S', shell] + command, kwargs)

def make_python_wrapper(wrapper, command, kwargs):
  """Returns a single command given a python wrapper and a command to be
  qsub'ed by that wrapper.
  
  Keyword parameters: (please read the help of qsub())
    (read the help of qsub() for details on extra arguments that may be
    supplied)

  wrapper
    This is the python wrapper to be used for prefixing the environment in
    which the **command** will execute. This parameter must be either a path to
    the wrapper or a list with the wrapper and **wrapper** command options.

  command
    The script path to be submitted

  Returns the args and kwargs parameters to be supplied to qsub()
  """

  if not isinstance(wrapper, (list, tuple)): wrapper = [wrapper]
  if not isinstance(command, (list, tuple)): command = [command]
  return make_shell('/usr/bin/python', wrapper + ['--'] + command, kwargs)

def make_torch_wrapper(torch, debug, command, kwargs):
  """Submits a command using the Torch python wrapper so the **command**
  executes in a valid Torch context.
  
  Keyword parameters: (please read the help of qsub())
    (read the help of qsub() for details on extra arguments that may be
    supplied)

  torch
    This is the root directory for the torch installation you would like to use
    for wrapping the execution of **command**.

  debug
    If set, this flag will switch the torch libraries to debug versions with
    symbols loaded.

  command
    The script path to be submitted

  Returns the args and kwargs parameters to be supplied to qsub()
  """
  binroot = os.path.join(torch, 'bin')
  shell = os.path.join(binroot, 'shell.py')
  if not os.path.exists(shell):
    raise RuntimeError, 'Cannot locate wrapper "%s"' % shell

  wrapper = [shell]

  if debug: wrapper += ['--debug']

  # adds OVERWRITE_TORCH5SPRO_ROOT to the execution environment
  if not kwargs.has_key('env'): kwargs['env'] = {}
  kwargs['env'].append('OVERWRITE_TORCH5SPRO_BINROOT=%s' % binroot)

  return make_python_wrapper(wrapper, command, kwargs)

def qstat(jobid, context='grid'):
  """Queries status of a given job.
  
  Keyword parameters:

  jobid
    The job identifier as returned by qsub()
  
  context
    The setshell context in which we should try a 'qsub'. Normally you don't
    need to change the default. This variable can also be set to a context
    dictionary in which case we just setup using that context instead of
    probing for a new one, what can be fast.

  Returns a dictionary with the specific job properties
  """

  scmd = ['qstat', '-j', '%d' % jobid, '-f']

  logging.debug("Qstat command '%s'", ' '.join(scmd))

  from .setshell import sexec
  data = sexec(context, scmd, error_on_nonzero=False)

  # some parsing:
  retval = {}
  for line in data.split('\n'):
    s = line.strip()
    if s.lower().find('do not exist') != -1: return {}
    if not s or s.find(10*'=') != -1: continue
    key, value = WHITE_SPACE.split(s, 1)
    key = key.rstrip(':')
    retval[key] = value

  return retval

def qdel(jobid, context='grid'):
  """Halts a given job.
  
  Keyword parameters:

  jobid
    The job identifier as returned by qsub()
  
  context
    The setshell context in which we should try a 'qsub'. Normally you don't
    need to change the default. This variable can also be set to a context
    dictionary in which case we just setup using that context instead of
    probing for a new one, what can be fast.
  """

  scmd = ['qdel', '%d' % jobid]

  logging.debug("Qdel command '%s'", ' '.join(scmd))

  from .setshell import sexec
  sexec(context, scmd, error_on_nonzero=False)