models.py 11 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  status = Column(Enum(*Status))
  result = Column(Integer)

  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

  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

45
46
47
48
49
50
  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)

51
52
53
54
55
56
57
58
  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)
    status = "%s" % self.status + (" (%d)" % self.result if self.result is not None else "" )

    return format.format(job_id, self.job.queue_name, status)

59
60
61
62
63

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

64
65
66
  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
67
68
  queue_name = Column(String(20))              # The name of the queue
  grid_arguments = Column(String(255))         # The kwargs arguments for the job submission (e.g. in the grid)
69
70
71
  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)
72
  stop_on_failure = Column(Boolean)            # An indicator whether to stop depending jobs when this job finishes with an error
73
74
75
76

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

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


89
  def submit(self, new_queue = None):
90
91
92
    """Sets the status of this job to 'submitted'."""
    self.status = 'submitted'
    self.result = None
93
94
    if new_queue is not None:
      self.queue_name = new_queue
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    for array_job in self.array:
      array_job.status = 'submitted'
      array_job.result = None

  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():
115
      if job.status not in ('success', 'failure'):
116
        new_status = 'waiting'
117
118
      elif self.stop_on_failure and job.status == 'failure':
        new_status = 'failure'
119
120
121

    # reset the queued jobs that depend on us to waiting status
    for job in self.get_jobs_waiting_for_us():
122
123
      if job.status == 'queued':
        job.status = 'failure' if new_status == 'failure' else 'waiting'
124
125
126

    self.status = new_status
    for array_job in self.array:
127
128
      if array_job.status not in ('success', 'failure'):
        array_job.status = new_status
129
130
131
132
133
134
135
136
137
138


  def execute(self, array_id = None):
    """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'

139
140
141
142
143
144
145
    # 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)


146
147
148
149
150
151
152
153
154
155
156
157

  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
158
        if array_job.status not in ('success', 'failure'):
159
160
161
162
163
164
165
166
167
168
169
170
171
172
          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()

173
174

  def get_command_line(self):
175
176
177
178
    """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))
179

180
  def get_array(self):
181
182
183
184
    """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))
185

186
  def get_arguments(self):
187
188
189
190
    """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
    return loads(self.grid_arguments) if isinstance(self.grid_arguments, bytes) else loads(str(self.grid_arguments))
191

192
193
194
195
196
197
198
  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]


199
  def std_out_file(self, array_id = None):
200
    return os.path.join(self.log_dir, (self.name if self.name else 'job') + ".o" + str(self.id)) if self.log_dir else None
201
202

  def std_err_file(self, array_id = None):
203
    return os.path.join(self.log_dir, (self.name if self.name else 'job') + ".e" + str(self.id)) if self.log_dir else None
204
205
206


  def __str__(self):
207
    id = "%d" % self.id
208
209
210
211
    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
212
213
214
215
    if self.result is not None: r = "%s (%d)" % (self.status, self.result)
    else: r = "%s" % self.status
    return "%s : %s -- %s" % (n, r, " ".join(self.get_command_line()))

216
  def format(self, format, dependencies = 0, limit_command_line = None):
217
218
    """Formats the current job into a nicer string to fit into a table."""
    command_line = " ".join(self.get_command_line())
219
    if limit_command_line is not None and len(command_line) > limit_command_line:
220
221
222
223
224
      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 "" )

225
226
227
228
229
230
231
    if dependencies:
      deps = str([dep.id for dep in self.get_jobs_we_wait_for()])
      if dependencies < len(deps):
        deps = deps[:dependencies-3] + '...'
      return format.format(job_id, self.queue_name, status, self.name, deps, command_line)
    else:
      return format.format(job_id, self.queue_name, status, self.name, command_line)
232

233
234
235
236
237
238


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

242
243
244
245
  # 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
246

247
248
249
  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
250
251
252



253
def add_job(session, command_line, name = 'job', dependencies = [], array = None, log_dir = None, stop_on_failure = False, **kwargs):
254
  """Helper function to create a job, add the dependencies and the array jobs."""
255
  job = Job(command_line=command_line, name=name, log_dir=log_dir, array_string=array, stop_on_failure=stop_on_failure, kwargs=kwargs)
256
257
258
259
260

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

261
262
  # by default id and unique id are identical, but the id might be overwritten later on
  job.id = job.unique
263
264

  for d in dependencies:
265
266
267
268
269
270
    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)

271
272
273
274
  if array:
    (start, stop, step) = array
    # add array jobs
    for i in range(start, stop+1, step):
275
      session.add(ArrayJob(i, job.unique))
276
277
278

  session.commit()

279
  return job