models.py 13.5 KB
Newer Older
1
import sqlalchemy
2 3
from sqlalchemy import Table, Column, Integer, String, Boolean, ForeignKey
from sqlalchemy.orm import backref
4
from sqlalchemy.ext.declarative import declarative_base
5
from .tools import Enum, relationship
6 7

import os
8 9 10 11 12 13
import sys

if sys.version_info[0] >= 3:
  from pickle import dumps, loads
else:
  from cPickle import dumps, loads
14

15
from .tools import logger
16 17 18

Base = declarative_base()

19
Status = ('submitted', 'queued', 'waiting', 'executing', 'success', 'failure')
20 21 22 23 24 25 26

class ArrayJob(Base):
  """This class defines one element of an array job."""
  __tablename__ = 'ArrayJob'

  unique = Column(Integer, primary_key = True)
  id = Column(Integer)
27
  job_id = Column(Integer, ForeignKey('Job.unique'))
28 29
  status = Column(Enum(*Status))
  result = Column(Integer)
30
  machine_name = Column(String(10))
31 32 33 34 35 36 37 38

  job = relationship("Job", backref='array', order_by=id)

  def __init__(self, id, job_id):
    self.id = id
    self.job_id = job_id
    self.status = Status[0]
    self.result = None
39
    self.machine_name = None # will be set later, by the Job class
40 41 42 43 44 45 46

  def std_out_file(self):
    return self.job.std_out_file() + "." + str(self.id) if self.job.log_dir else None

  def std_err_file(self):
    return self.job.std_err_file() + "." + str(self.id) if self.job.log_dir else None

47 48 49 50 51 52
  def __str__(self):
    n = "<ArrayJob %d> of <Job %d>" % (self.id, self.job.id)
    if self.result is not None: r = "%s (%d)" % (self.status, self.result)
    else: r = "%s" % self.status
    return "%s : %s" % (n, r)

53 54 55 56
  def format(self, format):
    """Formats the current job into a nicer string to fit into a table."""

    job_id = "%d - %d" % (self.job.id, self.id)
57
    queue = self.job.queue_name if self.machine_name is None else self.machine_name
58 59
    status = "%s" % self.status + (" (%d)" % self.result if self.result is not None else "" )

60
    return format.format(job_id, queue, status)
61

62 63 64 65 66

class Job(Base):
  """This class defines one Job that was submitted to the Job Manager."""
  __tablename__ = 'Job'

67 68 69
  unique = Column(Integer, primary_key = True) # The unique ID of the job (not corresponding to the grid ID)
  command_line = Column(String(255))           # The command line to execute, converted to one string
  name = Column(String(20))                    # A hand-chosen name for the task
70
  queue_name = Column(String(20))              # The name of the queue
71
  machine_name = Column(String(10))            # The name of the machine in which the job is run
72
  grid_arguments = Column(String(255))         # The kwargs arguments for the job submission (e.g. in the grid)
73
  id = Column(Integer)                         # The ID of the job as given from the grid
74 75
  log_dir = Column(String(255))                # The directory where the log files will be put to
  array_string = Column(String(255))           # The array string (only needed for re-submission)
76
  stop_on_failure = Column(Boolean)            # An indicator whether to stop depending jobs when this job finishes with an error
77 78 79 80

  status = Column(Enum(*Status))
  result = Column(Integer)

81
  def __init__(self, command_line, name = None, log_dir = None, array_string = None, queue_name = 'local', machine_name = None, stop_on_failure = False, **kwargs):
82
    """Constructs a Job object without an ID (needs to be set later)."""
83 84
    self.command_line = dumps(command_line)
    self.name = name
85
    self.queue_name = queue_name   # will be set during the queue command later
86
    self.machine_name = machine_name   # will be set during the execute command later
87
    self.grid_arguments = dumps(kwargs)
88
    self.log_dir = log_dir
89
    self.stop_on_failure = stop_on_failure
90
    self.array_string = dumps(array_string)
91 92 93
    self.submit()


94
  def submit(self, new_queue = None):
95 96 97
    """Sets the status of this job to 'submitted'."""
    self.status = 'submitted'
    self.result = None
98
    self.machine_name = None
99 100
    if new_queue is not None:
      self.queue_name = new_queue
101 102 103
    for array_job in self.array:
      array_job.status = 'submitted'
      array_job.result = None
104
      array_job.machine_name = None
105
    self.id = self.unique
106

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

  def queue(self, new_job_id = None, new_job_name = None, queue_name = None):
    """Sets the status of this job to 'queued' or 'waiting'."""
    # update the job id (i.e., when the job is executed in the grid)
    if new_job_id is not None:
      self.id = new_job_id

    if new_job_name is not None:
      self.name = new_job_name

    if queue_name is not None:
      self.queue_name = queue_name

    new_status = 'queued'
    self.result = None
    # check if we have to wait for another job to finish
    for job in self.get_jobs_we_wait_for():
124
      if job.status not in ('success', 'failure'):
125
        new_status = 'waiting'
126 127
      elif self.stop_on_failure and job.status == 'failure':
        new_status = 'failure'
128 129 130

    # reset the queued jobs that depend on us to waiting status
    for job in self.get_jobs_waiting_for_us():
131 132
      if job.status == 'queued':
        job.status = 'failure' if new_status == 'failure' else 'waiting'
133 134 135

    self.status = new_status
    for array_job in self.array:
136 137
      if array_job.status not in ('success', 'failure'):
        array_job.status = new_status
138 139


140
  def execute(self, array_id = None, machine_name = None):
141 142 143 144 145 146
    """Sets the status of this job to 'executing'."""
    self.status = 'executing'
    if array_id is not None:
      for array_job in self.array:
        if array_job.id == array_id:
          array_job.status = 'executing'
147 148 149 150
          if machine_name is not None:
            array_job.machine_name = machine_name
    elif machine_name is not None:
      self.machine_name = machine_name
151

152 153 154 155 156 157 158
    # sometimes, the 'finish' command did not work for array jobs,
    # so check if any old job still has the 'executing' flag set
    for job in self.get_jobs_we_wait_for():
      if job.array and job.status == 'executing':
        job.finish(0, -1)


159 160 161 162 163 164 165 166 167 168 169
  def finish(self, result, array_id = None):
    """Sets the status of this job to 'success' or 'failure'."""
    # check if there is any array job still running
    new_status = 'success' if result == 0 else 'failure'
    new_result = result
    finished = True
    if array_id is not None:
      for array_job in self.array:
        if array_job.id == array_id:
          array_job.status = new_status
          array_job.result = result
170
        if array_job.status not in ('success', 'failure'):
171 172 173 174 175 176 177 178 179 180 181 182 183 184
          finished = False
        elif new_result == 0:
          new_result = array_job.result

    if finished:
      # There was no array job, or all array jobs finished
      self.status = 'success' if new_result == 0 else 'failure'
      self.result = new_result

      # update all waiting jobs
      for job in self.get_jobs_waiting_for_us():
        if job.status == 'waiting':
          job.queue()

185

186 187 188 189 190 191 192 193 194 195 196 197 198 199
  def refresh(self):
    """Refreshes the status information."""
    if self.status == 'executing' and self.array:
      new_result = 0
      for array_job in self.array:
        if array_job.status == 'failure' and new_result is not None:
          new_result = array_job.result
        elif array_job.status not in ('success', 'failure'):
          new_result = None
      if new_result is not None:
        self.status = 'success' if new_result == 0 else 'failure'
        self.result = new_result


200
  def get_command_line(self):
201 202 203 204
    """Returns the command line for the job."""
    # In python 2, the command line is unicode, which needs to be converted to string before pickling;
    # In python 3, the command line is bytes, which can be pickled directly
    return loads(self.command_line) if isinstance(self.command_line, bytes) else loads(str(self.command_line))
205

206
  def get_array(self):
207 208 209 210
    """Returns the array arguments for the job; usually a string."""
    # In python 2, the command line is unicode, which needs to be converted to string before pickling;
    # In python 3, the command line is bytes, which can be pickled directly
    return loads(self.array_string) if isinstance(self.array_string, bytes) else loads(str(self.array_string))
211

212

213
  def get_arguments(self):
214 215 216
    """Returns the additional options for the grid (such as the queue, memory requirements, ...)."""
    # In python 2, the command line is unicode, which needs to be converted to string before pickling;
    # In python 3, the command line is bytes, which can be pickled directly
217
    args = loads(self.grid_arguments)['kwargs'] if isinstance(self.grid_arguments, bytes) else loads(str(self.grid_arguments))['kwargs']
218
    # in any case, the commands have to be converted to str
219 220 221 222 223 224 225 226 227 228 229 230
    retval = {}
    if 'pe_opt' in args:
      retval['pe_opt'] = args['pe_opt']
    if 'memfree' in args and args['memfree'] is not None:
      retval['memfree'] = args['memfree']
    if 'hvmem' in args and args['hvmem'] is not None:
      retval['hvmem'] = args['hvmem']
    if 'env' in args and len(args['env']) > 0:
      retval['env'] = args['env']
    if 'io_big' in args and args['io_big']:
      retval['io_big'] = True

231 232 233 234
    # also add the queue
    if self.queue_name is not None:
      retval['queue'] = str(self.queue_name)

235 236
    return retval

237 238
  def set_arguments(self, **kwargs):
    self.grid_arguments = dumps(kwargs)
239

240 241 242 243 244 245 246
  def get_jobs_we_wait_for(self):
    return [j.waited_for_job for j in self.jobs_we_have_to_wait_for if j.waited_for_job is not None]

  def get_jobs_waiting_for_us(self):
    return [j.waiting_job for j in self.jobs_that_wait_for_us if j.waiting_job is not None]


247
  def std_out_file(self, array_id = None):
248
    return os.path.join(self.log_dir, (self.name if self.name else 'job') + ".o" + str(self.id)) if self.log_dir else None
249 250

  def std_err_file(self, array_id = None):
251
    return os.path.join(self.log_dir, (self.name if self.name else 'job') + ".e" + str(self.id)) if self.log_dir else None
252 253


254 255 256 257 258 259 260 261 262 263
  def _cmdline(self):
    cmdline = self.get_command_line()
    c = ""
    for cmd in cmdline:
      if cmd[0] == '-':
        c += "%s " % cmd
      else:
        c += "'%s' " % cmd
    return c

264
  def __str__(self):
265
    id = "%d (%d)" % (self.unique, self.id)
266 267
    if self.machine_name: m = "%s - %s" % (self.queue_name, self.machine_name)
    else: m = self.queue_name
268 269 270 271
    if self.array: a = "[%d-%d:%d]" % self.get_array()
    else: a = ""
    if self.name is not None: n = "<Job: %s %s - '%s'>" % (id, a, self.name)
    else: n = "<Job: %s>" % id
272 273
    if self.result is not None: r = "%s (%d)" % (self.status, self.result)
    else: r = "%s" % self.status
274
    return "%s | %s : %s -- %s" % (n, m, r, self._cmdline())
275

276
  def format(self, format, dependencies = 0, limit_command_line = None):
277
    """Formats the current job into a nicer string to fit into a table."""
278
    command_line = self._cmdline()
279
    if limit_command_line is not None and len(command_line) > limit_command_line:
280 281 282 283
      command_line = command_line[:limit_command_line-3] + '...'

    job_id = "%d" % self.id + (" [%d-%d:%d]" % self.get_array() if self.array else "")
    status = "%s" % self.status + (" (%d)" % self.result if self.result is not None else "" )
284
    queue = self.queue_name if self.machine_name is None else self.machine_name
285 286 287 288 289
    if limit_command_line is None:
      grid_opt = self.get_arguments()
      if grid_opt:
        # add additional information about the job at the end
        command_line = "<" + ",".join(["%s=%s" % (key,value) for key,value in grid_opt.iteritems()]) + ">: " + command_line
290

291
    if dependencies:
292
      deps = str(sorted(list(set([dep.id for dep in self.get_jobs_we_wait_for()]))))
293 294
      if dependencies < len(deps):
        deps = deps[:dependencies-3] + '...'
295
      return format.format(self.unique, job_id, queue, status, self.name, deps, command_line)
296
    else:
297
      return format.format(self.unique, job_id, queue, status, self.name, command_line)
298

299 300 301 302 303 304


class JobDependence(Base):
  """This table defines a many-to-many relationship between Jobs."""
  __tablename__ = 'JobDependence'
  id = Column(Integer, primary_key=True)
305 306
  waiting_job_id = Column(Integer, ForeignKey('Job.unique')) # The ID of the waiting job
  waited_for_job_id = Column(Integer, ForeignKey('Job.unique')) # The ID of the job to wait for
307

308 309 310 311
  # This is twisted: The 'jobs_we_have_to_wait_for' field in the Job class needs to be joined with the waiting job id, so that jobs_we_have_to_wait_for.waiting_job is correct
  # Honestly, I am lost but it seems to work...
  waiting_job = relationship('Job', backref = 'jobs_we_have_to_wait_for', primaryjoin=(Job.unique == waiting_job_id), order_by=id) # The job that is waited for
  waited_for_job = relationship('Job', backref = 'jobs_that_wait_for_us', primaryjoin=(Job.unique == waited_for_job_id), order_by=id) # The job that waits
312

313 314 315
  def __init__(self, waiting_job_id, waited_for_job_id):
    self.waiting_job_id = waiting_job_id
    self.waited_for_job_id = waited_for_job_id
316 317 318



319
def add_job(session, command_line, name = 'job', dependencies = [], array = None, log_dir = None, stop_on_failure = False, **kwargs):
320
  """Helper function to create a job, add the dependencies and the array jobs."""
321
  job = Job(command_line=command_line, name=name, log_dir=log_dir, array_string=array, stop_on_failure=stop_on_failure, kwargs=kwargs)
322 323 324 325 326

  session.add(job)
  session.flush()
  session.refresh(job)

327 328
  # by default id and unique id are identical, but the id might be overwritten later on
  job.id = job.unique
329 330

  for d in dependencies:
331 332 333 334 335 336
    depending = list(session.query(Job).filter(Job.id == d))
    if len(depending):
      session.add(JobDependence(job.unique, depending[0].unique))
    else:
      logger.warn("Could not find dependent job with id %d in database" % d)

337 338 339 340
  if array:
    (start, stop, step) = array
    # add array jobs
    for i in range(start, stop+1, step):
341
      session.add(ArrayJob(i, job.unique))
342 343 344

  session.commit()

345
  return job