models.py 13 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 74 75
  id = Column(Integer, unique = True)          # The ID of the job as given from the grid
  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 105
      array_job.machine_name = None

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

  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():
123
      if job.status not in ('success', 'failure'):
124
        new_status = 'waiting'
125 126
      elif self.stop_on_failure and job.status == 'failure':
        new_status = 'failure'
127 128 129

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

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


139
  def execute(self, array_id = None, machine_name = None):
140 141 142 143 144 145
    """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'
146 147 148 149
          if machine_name is not None:
            array_job.machine_name = machine_name
    elif machine_name is not None:
      self.machine_name = machine_name
150

151 152 153 154 155 156 157
    # 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)


158 159 160 161 162 163 164 165 166 167 168
  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
169
        if array_job.status not in ('success', 'failure'):
170 171 172 173 174 175 176 177 178 179 180 181 182 183
          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()

184

185 186 187 188 189 190 191 192 193 194 195 196 197 198
  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


199
  def get_command_line(self):
200 201 202 203
    """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))
204

205
  def get_array(self):
206 207 208 209
    """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))
210

211

212
  def get_arguments(self):
213 214 215
    """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
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    args = loads(self.grid_arguments)['kwargs'] if isinstance(self.grid_arguments, bytes) else loads(str(self.grid_arguments))['kwargs']
    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

    return retval

231

232 233 234 235 236 237 238
  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]


239
  def std_out_file(self, array_id = None):
240
    return os.path.join(self.log_dir, (self.name if self.name else 'job') + ".o" + str(self.id)) if self.log_dir else None
241 242

  def std_err_file(self, array_id = None):
243
    return os.path.join(self.log_dir, (self.name if self.name else 'job') + ".e" + str(self.id)) if self.log_dir else None
244 245 246


  def __str__(self):
247
    id = "%d" % self.id
248 249
    if self.machine_name: m = "%s - %s" % (self.queue_name, self.machine_name)
    else: m = self.queue_name
250 251 252 253
    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
254 255
    if self.result is not None: r = "%s (%d)" % (self.status, self.result)
    else: r = "%s" % self.status
256
    return "%s | %s : %s -- %s" % (n, m, r, " ".join(self.get_command_line()))
257

258
  def format(self, format, dependencies = 0, limit_command_line = None):
259 260
    """Formats the current job into a nicer string to fit into a table."""
    command_line = " ".join(self.get_command_line())
261
    if limit_command_line is not None and len(command_line) > limit_command_line:
262 263 264 265
      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 "" )
266
    queue = self.queue_name if self.machine_name is None else self.machine_name
267 268 269 270 271
    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
272

273 274 275 276
    if dependencies:
      deps = str([dep.id for dep in self.get_jobs_we_wait_for()])
      if dependencies < len(deps):
        deps = deps[:dependencies-3] + '...'
277
      return format.format(job_id, queue, status, self.name, deps, command_line)
278
    else:
279
      return format.format(job_id, queue, status, self.name, command_line)
280

281 282 283 284 285 286


class JobDependence(Base):
  """This table defines a many-to-many relationship between Jobs."""
  __tablename__ = 'JobDependence'
  id = Column(Integer, primary_key=True)
287 288
  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
289

290 291 292 293
  # 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
294

295 296 297
  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
298 299 300



301
def add_job(session, command_line, name = 'job', dependencies = [], array = None, log_dir = None, stop_on_failure = False, **kwargs):
302
  """Helper function to create a job, add the dependencies and the array jobs."""
303
  job = Job(command_line=command_line, name=name, log_dir=log_dir, array_string=array, stop_on_failure=stop_on_failure, kwargs=kwargs)
304 305 306 307 308

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

309 310
  # by default id and unique id are identical, but the id might be overwritten later on
  job.id = job.unique
311 312

  for d in dependencies:
313 314 315 316 317 318
    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)

319 320 321 322
  if array:
    (start, stop, step) = array
    # add array jobs
    for i in range(start, stop+1, step):
323
      session.add(ArrayJob(i, job.unique))
324 325 326

  session.commit()

327
  return job