Statistics
| Branch: | Tag: | Revision:

root / lib / jqueue.py @ 75d81fc8

History | View | Annotate | Download (70.8 kB)

1 498ae1cc Iustin Pop
#
2 498ae1cc Iustin Pop
#
3 498ae1cc Iustin Pop
4 b95479a5 Michael Hanselmann
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
5 498ae1cc Iustin Pop
#
6 498ae1cc Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 498ae1cc Iustin Pop
# it under the terms of the GNU General Public License as published by
8 498ae1cc Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 498ae1cc Iustin Pop
# (at your option) any later version.
10 498ae1cc Iustin Pop
#
11 498ae1cc Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 498ae1cc Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 498ae1cc Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 498ae1cc Iustin Pop
# General Public License for more details.
15 498ae1cc Iustin Pop
#
16 498ae1cc Iustin Pop
# You should have received a copy of the GNU General Public License
17 498ae1cc Iustin Pop
# along with this program; if not, write to the Free Software
18 498ae1cc Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 498ae1cc Iustin Pop
# 02110-1301, USA.
20 498ae1cc Iustin Pop
21 498ae1cc Iustin Pop
22 6c5a7090 Michael Hanselmann
"""Module implementing the job queue handling.
23 6c5a7090 Michael Hanselmann

24 ea03467c Iustin Pop
Locking: there's a single, large lock in the L{JobQueue} class. It's
25 ea03467c Iustin Pop
used by all other classes in this module.
26 ea03467c Iustin Pop

27 ea03467c Iustin Pop
@var JOBQUEUE_THREADS: the number of worker threads we start for
28 ea03467c Iustin Pop
    processing jobs
29 6c5a7090 Michael Hanselmann

30 6c5a7090 Michael Hanselmann
"""
31 498ae1cc Iustin Pop
32 e2715f69 Michael Hanselmann
import logging
33 f1da30e6 Michael Hanselmann
import errno
34 f1da30e6 Michael Hanselmann
import re
35 f1048938 Iustin Pop
import time
36 5685c1a5 Michael Hanselmann
import weakref
37 b95479a5 Michael Hanselmann
import threading
38 498ae1cc Iustin Pop
39 6c2549d6 Guido Trotter
try:
40 6c2549d6 Guido Trotter
  # pylint: disable-msg=E0611
41 6c2549d6 Guido Trotter
  from pyinotify import pyinotify
42 6c2549d6 Guido Trotter
except ImportError:
43 6c2549d6 Guido Trotter
  import pyinotify
44 6c2549d6 Guido Trotter
45 6c2549d6 Guido Trotter
from ganeti import asyncnotifier
46 e2715f69 Michael Hanselmann
from ganeti import constants
47 f1da30e6 Michael Hanselmann
from ganeti import serializer
48 e2715f69 Michael Hanselmann
from ganeti import workerpool
49 99bd4f0a Guido Trotter
from ganeti import locking
50 f1da30e6 Michael Hanselmann
from ganeti import opcodes
51 7a1ecaed Iustin Pop
from ganeti import errors
52 e2715f69 Michael Hanselmann
from ganeti import mcpu
53 7996a135 Iustin Pop
from ganeti import utils
54 04ab05ce Michael Hanselmann
from ganeti import jstore
55 c3f0a12f Iustin Pop
from ganeti import rpc
56 82b22e19 René Nussbaumer
from ganeti import runtime
57 a744b676 Manuel Franceschini
from ganeti import netutils
58 989a8bee Michael Hanselmann
from ganeti import compat
59 b95479a5 Michael Hanselmann
from ganeti import ht
60 e2715f69 Michael Hanselmann
61 fbf0262f Michael Hanselmann
62 1daae384 Iustin Pop
JOBQUEUE_THREADS = 25
63 58b22b6e Michael Hanselmann
JOBS_PER_ARCHIVE_DIRECTORY = 10000
64 e2715f69 Michael Hanselmann
65 ebb80afa Guido Trotter
# member lock names to be passed to @ssynchronized decorator
66 ebb80afa Guido Trotter
_LOCK = "_lock"
67 ebb80afa Guido Trotter
_QUEUE = "_queue"
68 99bd4f0a Guido Trotter
69 498ae1cc Iustin Pop
70 9728ae5d Iustin Pop
class CancelJob(Exception):
71 fbf0262f Michael Hanselmann
  """Special exception to cancel a job.
72 fbf0262f Michael Hanselmann

73 fbf0262f Michael Hanselmann
  """
74 fbf0262f Michael Hanselmann
75 fbf0262f Michael Hanselmann
76 70552c46 Michael Hanselmann
def TimeStampNow():
77 ea03467c Iustin Pop
  """Returns the current timestamp.
78 ea03467c Iustin Pop

79 ea03467c Iustin Pop
  @rtype: tuple
80 ea03467c Iustin Pop
  @return: the current time in the (seconds, microseconds) format
81 ea03467c Iustin Pop

82 ea03467c Iustin Pop
  """
83 70552c46 Michael Hanselmann
  return utils.SplitTime(time.time())
84 70552c46 Michael Hanselmann
85 70552c46 Michael Hanselmann
86 e2715f69 Michael Hanselmann
class _QueuedOpCode(object):
87 5bbd3f7f Michael Hanselmann
  """Encapsulates an opcode object.
88 e2715f69 Michael Hanselmann

89 ea03467c Iustin Pop
  @ivar log: holds the execution log and consists of tuples
90 ea03467c Iustin Pop
  of the form C{(log_serial, timestamp, level, message)}
91 ea03467c Iustin Pop
  @ivar input: the OpCode we encapsulate
92 ea03467c Iustin Pop
  @ivar status: the current status
93 ea03467c Iustin Pop
  @ivar result: the result of the LU execution
94 ea03467c Iustin Pop
  @ivar start_timestamp: timestamp for the start of the execution
95 b9b5abcb Iustin Pop
  @ivar exec_timestamp: timestamp for the actual LU Exec() function invocation
96 ea03467c Iustin Pop
  @ivar stop_timestamp: timestamp for the end of the execution
97 f1048938 Iustin Pop

98 e2715f69 Michael Hanselmann
  """
99 8f5c488d Michael Hanselmann
  __slots__ = ["input", "status", "result", "log", "priority",
100 b9b5abcb Iustin Pop
               "start_timestamp", "exec_timestamp", "end_timestamp",
101 66d895a8 Iustin Pop
               "__weakref__"]
102 66d895a8 Iustin Pop
103 85f03e0d Michael Hanselmann
  def __init__(self, op):
104 ea03467c Iustin Pop
    """Constructor for the _QuededOpCode.
105 ea03467c Iustin Pop

106 ea03467c Iustin Pop
    @type op: L{opcodes.OpCode}
107 ea03467c Iustin Pop
    @param op: the opcode we encapsulate
108 ea03467c Iustin Pop

109 ea03467c Iustin Pop
    """
110 85f03e0d Michael Hanselmann
    self.input = op
111 85f03e0d Michael Hanselmann
    self.status = constants.OP_STATUS_QUEUED
112 85f03e0d Michael Hanselmann
    self.result = None
113 85f03e0d Michael Hanselmann
    self.log = []
114 70552c46 Michael Hanselmann
    self.start_timestamp = None
115 b9b5abcb Iustin Pop
    self.exec_timestamp = None
116 70552c46 Michael Hanselmann
    self.end_timestamp = None
117 f1da30e6 Michael Hanselmann
118 8f5c488d Michael Hanselmann
    # Get initial priority (it might change during the lifetime of this opcode)
119 8f5c488d Michael Hanselmann
    self.priority = getattr(op, "priority", constants.OP_PRIO_DEFAULT)
120 8f5c488d Michael Hanselmann
121 f1da30e6 Michael Hanselmann
  @classmethod
122 f1da30e6 Michael Hanselmann
  def Restore(cls, state):
123 ea03467c Iustin Pop
    """Restore the _QueuedOpCode from the serialized form.
124 ea03467c Iustin Pop

125 ea03467c Iustin Pop
    @type state: dict
126 ea03467c Iustin Pop
    @param state: the serialized state
127 ea03467c Iustin Pop
    @rtype: _QueuedOpCode
128 ea03467c Iustin Pop
    @return: a new _QueuedOpCode instance
129 ea03467c Iustin Pop

130 ea03467c Iustin Pop
    """
131 85f03e0d Michael Hanselmann
    obj = _QueuedOpCode.__new__(cls)
132 85f03e0d Michael Hanselmann
    obj.input = opcodes.OpCode.LoadOpCode(state["input"])
133 85f03e0d Michael Hanselmann
    obj.status = state["status"]
134 85f03e0d Michael Hanselmann
    obj.result = state["result"]
135 85f03e0d Michael Hanselmann
    obj.log = state["log"]
136 70552c46 Michael Hanselmann
    obj.start_timestamp = state.get("start_timestamp", None)
137 b9b5abcb Iustin Pop
    obj.exec_timestamp = state.get("exec_timestamp", None)
138 70552c46 Michael Hanselmann
    obj.end_timestamp = state.get("end_timestamp", None)
139 8f5c488d Michael Hanselmann
    obj.priority = state.get("priority", constants.OP_PRIO_DEFAULT)
140 f1da30e6 Michael Hanselmann
    return obj
141 f1da30e6 Michael Hanselmann
142 f1da30e6 Michael Hanselmann
  def Serialize(self):
143 ea03467c Iustin Pop
    """Serializes this _QueuedOpCode.
144 ea03467c Iustin Pop

145 ea03467c Iustin Pop
    @rtype: dict
146 ea03467c Iustin Pop
    @return: the dictionary holding the serialized state
147 ea03467c Iustin Pop

148 ea03467c Iustin Pop
    """
149 6c5a7090 Michael Hanselmann
    return {
150 6c5a7090 Michael Hanselmann
      "input": self.input.__getstate__(),
151 6c5a7090 Michael Hanselmann
      "status": self.status,
152 6c5a7090 Michael Hanselmann
      "result": self.result,
153 6c5a7090 Michael Hanselmann
      "log": self.log,
154 70552c46 Michael Hanselmann
      "start_timestamp": self.start_timestamp,
155 b9b5abcb Iustin Pop
      "exec_timestamp": self.exec_timestamp,
156 70552c46 Michael Hanselmann
      "end_timestamp": self.end_timestamp,
157 8f5c488d Michael Hanselmann
      "priority": self.priority,
158 6c5a7090 Michael Hanselmann
      }
159 f1048938 Iustin Pop
160 e2715f69 Michael Hanselmann
161 e2715f69 Michael Hanselmann
class _QueuedJob(object):
162 e2715f69 Michael Hanselmann
  """In-memory job representation.
163 e2715f69 Michael Hanselmann

164 ea03467c Iustin Pop
  This is what we use to track the user-submitted jobs. Locking must
165 ea03467c Iustin Pop
  be taken care of by users of this class.
166 ea03467c Iustin Pop

167 ea03467c Iustin Pop
  @type queue: L{JobQueue}
168 ea03467c Iustin Pop
  @ivar queue: the parent queue
169 ea03467c Iustin Pop
  @ivar id: the job ID
170 ea03467c Iustin Pop
  @type ops: list
171 ea03467c Iustin Pop
  @ivar ops: the list of _QueuedOpCode that constitute the job
172 ea03467c Iustin Pop
  @type log_serial: int
173 ea03467c Iustin Pop
  @ivar log_serial: holds the index for the next log entry
174 ea03467c Iustin Pop
  @ivar received_timestamp: the timestamp for when the job was received
175 ea03467c Iustin Pop
  @ivar start_timestmap: the timestamp for start of execution
176 ea03467c Iustin Pop
  @ivar end_timestamp: the timestamp for end of execution
177 c0f6d0d8 Michael Hanselmann
  @ivar writable: Whether the job is allowed to be modified
178 e2715f69 Michael Hanselmann

179 e2715f69 Michael Hanselmann
  """
180 7260cfbe Iustin Pop
  # pylint: disable-msg=W0212
181 26d3fd2f Michael Hanselmann
  __slots__ = ["queue", "id", "ops", "log_serial", "ops_iter", "cur_opctx",
182 66d895a8 Iustin Pop
               "received_timestamp", "start_timestamp", "end_timestamp",
183 c0f6d0d8 Michael Hanselmann
               "__weakref__", "processor_lock", "writable"]
184 66d895a8 Iustin Pop
185 c0f6d0d8 Michael Hanselmann
  def __init__(self, queue, job_id, ops, writable):
186 ea03467c Iustin Pop
    """Constructor for the _QueuedJob.
187 ea03467c Iustin Pop

188 ea03467c Iustin Pop
    @type queue: L{JobQueue}
189 ea03467c Iustin Pop
    @param queue: our parent queue
190 ea03467c Iustin Pop
    @type job_id: job_id
191 ea03467c Iustin Pop
    @param job_id: our job id
192 ea03467c Iustin Pop
    @type ops: list
193 ea03467c Iustin Pop
    @param ops: the list of opcodes we hold, which will be encapsulated
194 ea03467c Iustin Pop
        in _QueuedOpCodes
195 c0f6d0d8 Michael Hanselmann
    @type writable: bool
196 c0f6d0d8 Michael Hanselmann
    @param writable: Whether job can be modified
197 ea03467c Iustin Pop

198 ea03467c Iustin Pop
    """
199 e2715f69 Michael Hanselmann
    if not ops:
200 c910bccb Guido Trotter
      raise errors.GenericError("A job needs at least one opcode")
201 e2715f69 Michael Hanselmann
202 85f03e0d Michael Hanselmann
    self.queue = queue
203 f1da30e6 Michael Hanselmann
    self.id = job_id
204 85f03e0d Michael Hanselmann
    self.ops = [_QueuedOpCode(op) for op in ops]
205 6c5a7090 Michael Hanselmann
    self.log_serial = 0
206 c56ec146 Iustin Pop
    self.received_timestamp = TimeStampNow()
207 c56ec146 Iustin Pop
    self.start_timestamp = None
208 c56ec146 Iustin Pop
    self.end_timestamp = None
209 6c5a7090 Michael Hanselmann
210 c0f6d0d8 Michael Hanselmann
    self._InitInMemory(self, writable)
211 fa4aa6b4 Michael Hanselmann
212 fa4aa6b4 Michael Hanselmann
  @staticmethod
213 c0f6d0d8 Michael Hanselmann
  def _InitInMemory(obj, writable):
214 fa4aa6b4 Michael Hanselmann
    """Initializes in-memory variables.
215 fa4aa6b4 Michael Hanselmann

216 fa4aa6b4 Michael Hanselmann
    """
217 c0f6d0d8 Michael Hanselmann
    obj.writable = writable
218 03b63608 Michael Hanselmann
    obj.ops_iter = None
219 26d3fd2f Michael Hanselmann
    obj.cur_opctx = None
220 f8a4adfa Michael Hanselmann
221 f8a4adfa Michael Hanselmann
    # Read-only jobs are not processed and therefore don't need a lock
222 f8a4adfa Michael Hanselmann
    if writable:
223 f8a4adfa Michael Hanselmann
      obj.processor_lock = threading.Lock()
224 f8a4adfa Michael Hanselmann
    else:
225 f8a4adfa Michael Hanselmann
      obj.processor_lock = None
226 be760ba8 Michael Hanselmann
227 9fa2e150 Michael Hanselmann
  def __repr__(self):
228 9fa2e150 Michael Hanselmann
    status = ["%s.%s" % (self.__class__.__module__, self.__class__.__name__),
229 9fa2e150 Michael Hanselmann
              "id=%s" % self.id,
230 9fa2e150 Michael Hanselmann
              "ops=%s" % ",".join([op.input.Summary() for op in self.ops])]
231 9fa2e150 Michael Hanselmann
232 9fa2e150 Michael Hanselmann
    return "<%s at %#x>" % (" ".join(status), id(self))
233 9fa2e150 Michael Hanselmann
234 f1da30e6 Michael Hanselmann
  @classmethod
235 c0f6d0d8 Michael Hanselmann
  def Restore(cls, queue, state, writable):
236 ea03467c Iustin Pop
    """Restore a _QueuedJob from serialized state:
237 ea03467c Iustin Pop

238 ea03467c Iustin Pop
    @type queue: L{JobQueue}
239 ea03467c Iustin Pop
    @param queue: to which queue the restored job belongs
240 ea03467c Iustin Pop
    @type state: dict
241 ea03467c Iustin Pop
    @param state: the serialized state
242 c0f6d0d8 Michael Hanselmann
    @type writable: bool
243 c0f6d0d8 Michael Hanselmann
    @param writable: Whether job can be modified
244 ea03467c Iustin Pop
    @rtype: _JobQueue
245 ea03467c Iustin Pop
    @return: the restored _JobQueue instance
246 ea03467c Iustin Pop

247 ea03467c Iustin Pop
    """
248 85f03e0d Michael Hanselmann
    obj = _QueuedJob.__new__(cls)
249 85f03e0d Michael Hanselmann
    obj.queue = queue
250 85f03e0d Michael Hanselmann
    obj.id = state["id"]
251 c56ec146 Iustin Pop
    obj.received_timestamp = state.get("received_timestamp", None)
252 c56ec146 Iustin Pop
    obj.start_timestamp = state.get("start_timestamp", None)
253 c56ec146 Iustin Pop
    obj.end_timestamp = state.get("end_timestamp", None)
254 6c5a7090 Michael Hanselmann
255 6c5a7090 Michael Hanselmann
    obj.ops = []
256 6c5a7090 Michael Hanselmann
    obj.log_serial = 0
257 6c5a7090 Michael Hanselmann
    for op_state in state["ops"]:
258 6c5a7090 Michael Hanselmann
      op = _QueuedOpCode.Restore(op_state)
259 6c5a7090 Michael Hanselmann
      for log_entry in op.log:
260 6c5a7090 Michael Hanselmann
        obj.log_serial = max(obj.log_serial, log_entry[0])
261 6c5a7090 Michael Hanselmann
      obj.ops.append(op)
262 6c5a7090 Michael Hanselmann
263 c0f6d0d8 Michael Hanselmann
    cls._InitInMemory(obj, writable)
264 be760ba8 Michael Hanselmann
265 f1da30e6 Michael Hanselmann
    return obj
266 f1da30e6 Michael Hanselmann
267 f1da30e6 Michael Hanselmann
  def Serialize(self):
268 ea03467c Iustin Pop
    """Serialize the _JobQueue instance.
269 ea03467c Iustin Pop

270 ea03467c Iustin Pop
    @rtype: dict
271 ea03467c Iustin Pop
    @return: the serialized state
272 ea03467c Iustin Pop

273 ea03467c Iustin Pop
    """
274 f1da30e6 Michael Hanselmann
    return {
275 f1da30e6 Michael Hanselmann
      "id": self.id,
276 85f03e0d Michael Hanselmann
      "ops": [op.Serialize() for op in self.ops],
277 c56ec146 Iustin Pop
      "start_timestamp": self.start_timestamp,
278 c56ec146 Iustin Pop
      "end_timestamp": self.end_timestamp,
279 c56ec146 Iustin Pop
      "received_timestamp": self.received_timestamp,
280 f1da30e6 Michael Hanselmann
      }
281 f1da30e6 Michael Hanselmann
282 85f03e0d Michael Hanselmann
  def CalcStatus(self):
283 ea03467c Iustin Pop
    """Compute the status of this job.
284 ea03467c Iustin Pop

285 ea03467c Iustin Pop
    This function iterates over all the _QueuedOpCodes in the job and
286 ea03467c Iustin Pop
    based on their status, computes the job status.
287 ea03467c Iustin Pop

288 ea03467c Iustin Pop
    The algorithm is:
289 ea03467c Iustin Pop
      - if we find a cancelled, or finished with error, the job
290 ea03467c Iustin Pop
        status will be the same
291 ea03467c Iustin Pop
      - otherwise, the last opcode with the status one of:
292 ea03467c Iustin Pop
          - waitlock
293 fbf0262f Michael Hanselmann
          - canceling
294 ea03467c Iustin Pop
          - running
295 ea03467c Iustin Pop

296 ea03467c Iustin Pop
        will determine the job status
297 ea03467c Iustin Pop

298 ea03467c Iustin Pop
      - otherwise, it means either all opcodes are queued, or success,
299 ea03467c Iustin Pop
        and the job status will be the same
300 ea03467c Iustin Pop

301 ea03467c Iustin Pop
    @return: the job status
302 ea03467c Iustin Pop

303 ea03467c Iustin Pop
    """
304 e2715f69 Michael Hanselmann
    status = constants.JOB_STATUS_QUEUED
305 e2715f69 Michael Hanselmann
306 e2715f69 Michael Hanselmann
    all_success = True
307 85f03e0d Michael Hanselmann
    for op in self.ops:
308 85f03e0d Michael Hanselmann
      if op.status == constants.OP_STATUS_SUCCESS:
309 e2715f69 Michael Hanselmann
        continue
310 e2715f69 Michael Hanselmann
311 e2715f69 Michael Hanselmann
      all_success = False
312 e2715f69 Michael Hanselmann
313 85f03e0d Michael Hanselmann
      if op.status == constants.OP_STATUS_QUEUED:
314 e2715f69 Michael Hanselmann
        pass
315 e92376d7 Iustin Pop
      elif op.status == constants.OP_STATUS_WAITLOCK:
316 e92376d7 Iustin Pop
        status = constants.JOB_STATUS_WAITLOCK
317 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_RUNNING:
318 e2715f69 Michael Hanselmann
        status = constants.JOB_STATUS_RUNNING
319 fbf0262f Michael Hanselmann
      elif op.status == constants.OP_STATUS_CANCELING:
320 fbf0262f Michael Hanselmann
        status = constants.JOB_STATUS_CANCELING
321 fbf0262f Michael Hanselmann
        break
322 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_ERROR:
323 f1da30e6 Michael Hanselmann
        status = constants.JOB_STATUS_ERROR
324 f1da30e6 Michael Hanselmann
        # The whole job fails if one opcode failed
325 f1da30e6 Michael Hanselmann
        break
326 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_CANCELED:
327 4cb1d919 Michael Hanselmann
        status = constants.OP_STATUS_CANCELED
328 4cb1d919 Michael Hanselmann
        break
329 e2715f69 Michael Hanselmann
330 e2715f69 Michael Hanselmann
    if all_success:
331 e2715f69 Michael Hanselmann
      status = constants.JOB_STATUS_SUCCESS
332 e2715f69 Michael Hanselmann
333 e2715f69 Michael Hanselmann
    return status
334 e2715f69 Michael Hanselmann
335 8f5c488d Michael Hanselmann
  def CalcPriority(self):
336 8f5c488d Michael Hanselmann
    """Gets the current priority for this job.
337 8f5c488d Michael Hanselmann

338 8f5c488d Michael Hanselmann
    Only unfinished opcodes are considered. When all are done, the default
339 8f5c488d Michael Hanselmann
    priority is used.
340 8f5c488d Michael Hanselmann

341 8f5c488d Michael Hanselmann
    @rtype: int
342 8f5c488d Michael Hanselmann

343 8f5c488d Michael Hanselmann
    """
344 8f5c488d Michael Hanselmann
    priorities = [op.priority for op in self.ops
345 8f5c488d Michael Hanselmann
                  if op.status not in constants.OPS_FINALIZED]
346 8f5c488d Michael Hanselmann
347 8f5c488d Michael Hanselmann
    if not priorities:
348 8f5c488d Michael Hanselmann
      # All opcodes are done, assume default priority
349 8f5c488d Michael Hanselmann
      return constants.OP_PRIO_DEFAULT
350 8f5c488d Michael Hanselmann
351 8f5c488d Michael Hanselmann
    return min(priorities)
352 8f5c488d Michael Hanselmann
353 6c5a7090 Michael Hanselmann
  def GetLogEntries(self, newer_than):
354 ea03467c Iustin Pop
    """Selectively returns the log entries.
355 ea03467c Iustin Pop

356 ea03467c Iustin Pop
    @type newer_than: None or int
357 5bbd3f7f Michael Hanselmann
    @param newer_than: if this is None, return all log entries,
358 ea03467c Iustin Pop
        otherwise return only the log entries with serial higher
359 ea03467c Iustin Pop
        than this value
360 ea03467c Iustin Pop
    @rtype: list
361 ea03467c Iustin Pop
    @return: the list of the log entries selected
362 ea03467c Iustin Pop

363 ea03467c Iustin Pop
    """
364 6c5a7090 Michael Hanselmann
    if newer_than is None:
365 6c5a7090 Michael Hanselmann
      serial = -1
366 6c5a7090 Michael Hanselmann
    else:
367 6c5a7090 Michael Hanselmann
      serial = newer_than
368 6c5a7090 Michael Hanselmann
369 6c5a7090 Michael Hanselmann
    entries = []
370 6c5a7090 Michael Hanselmann
    for op in self.ops:
371 63712a09 Iustin Pop
      entries.extend(filter(lambda entry: entry[0] > serial, op.log))
372 6c5a7090 Michael Hanselmann
373 6c5a7090 Michael Hanselmann
    return entries
374 6c5a7090 Michael Hanselmann
375 6a290889 Guido Trotter
  def GetInfo(self, fields):
376 6a290889 Guido Trotter
    """Returns information about a job.
377 6a290889 Guido Trotter

378 6a290889 Guido Trotter
    @type fields: list
379 6a290889 Guido Trotter
    @param fields: names of fields to return
380 6a290889 Guido Trotter
    @rtype: list
381 6a290889 Guido Trotter
    @return: list with one element for each field
382 6a290889 Guido Trotter
    @raise errors.OpExecError: when an invalid field
383 6a290889 Guido Trotter
        has been passed
384 6a290889 Guido Trotter

385 6a290889 Guido Trotter
    """
386 6a290889 Guido Trotter
    row = []
387 6a290889 Guido Trotter
    for fname in fields:
388 6a290889 Guido Trotter
      if fname == "id":
389 6a290889 Guido Trotter
        row.append(self.id)
390 6a290889 Guido Trotter
      elif fname == "status":
391 6a290889 Guido Trotter
        row.append(self.CalcStatus())
392 b8802cc4 Michael Hanselmann
      elif fname == "priority":
393 b8802cc4 Michael Hanselmann
        row.append(self.CalcPriority())
394 6a290889 Guido Trotter
      elif fname == "ops":
395 6a290889 Guido Trotter
        row.append([op.input.__getstate__() for op in self.ops])
396 6a290889 Guido Trotter
      elif fname == "opresult":
397 6a290889 Guido Trotter
        row.append([op.result for op in self.ops])
398 6a290889 Guido Trotter
      elif fname == "opstatus":
399 6a290889 Guido Trotter
        row.append([op.status for op in self.ops])
400 6a290889 Guido Trotter
      elif fname == "oplog":
401 6a290889 Guido Trotter
        row.append([op.log for op in self.ops])
402 6a290889 Guido Trotter
      elif fname == "opstart":
403 6a290889 Guido Trotter
        row.append([op.start_timestamp for op in self.ops])
404 6a290889 Guido Trotter
      elif fname == "opexec":
405 6a290889 Guido Trotter
        row.append([op.exec_timestamp for op in self.ops])
406 6a290889 Guido Trotter
      elif fname == "opend":
407 6a290889 Guido Trotter
        row.append([op.end_timestamp for op in self.ops])
408 b8802cc4 Michael Hanselmann
      elif fname == "oppriority":
409 b8802cc4 Michael Hanselmann
        row.append([op.priority for op in self.ops])
410 6a290889 Guido Trotter
      elif fname == "received_ts":
411 6a290889 Guido Trotter
        row.append(self.received_timestamp)
412 6a290889 Guido Trotter
      elif fname == "start_ts":
413 6a290889 Guido Trotter
        row.append(self.start_timestamp)
414 6a290889 Guido Trotter
      elif fname == "end_ts":
415 6a290889 Guido Trotter
        row.append(self.end_timestamp)
416 6a290889 Guido Trotter
      elif fname == "summary":
417 6a290889 Guido Trotter
        row.append([op.input.Summary() for op in self.ops])
418 6a290889 Guido Trotter
      else:
419 6a290889 Guido Trotter
        raise errors.OpExecError("Invalid self query field '%s'" % fname)
420 6a290889 Guido Trotter
    return row
421 6a290889 Guido Trotter
422 34327f51 Iustin Pop
  def MarkUnfinishedOps(self, status, result):
423 34327f51 Iustin Pop
    """Mark unfinished opcodes with a given status and result.
424 34327f51 Iustin Pop

425 34327f51 Iustin Pop
    This is an utility function for marking all running or waiting to
426 34327f51 Iustin Pop
    be run opcodes with a given status. Opcodes which are already
427 34327f51 Iustin Pop
    finalised are not changed.
428 34327f51 Iustin Pop

429 34327f51 Iustin Pop
    @param status: a given opcode status
430 34327f51 Iustin Pop
    @param result: the opcode result
431 34327f51 Iustin Pop

432 34327f51 Iustin Pop
    """
433 747f6113 Michael Hanselmann
    not_marked = True
434 747f6113 Michael Hanselmann
    for op in self.ops:
435 747f6113 Michael Hanselmann
      if op.status in constants.OPS_FINALIZED:
436 747f6113 Michael Hanselmann
        assert not_marked, "Finalized opcodes found after non-finalized ones"
437 747f6113 Michael Hanselmann
        continue
438 747f6113 Michael Hanselmann
      op.status = status
439 747f6113 Michael Hanselmann
      op.result = result
440 747f6113 Michael Hanselmann
      not_marked = False
441 34327f51 Iustin Pop
442 66bd7445 Michael Hanselmann
  def Finalize(self):
443 66bd7445 Michael Hanselmann
    """Marks the job as finalized.
444 66bd7445 Michael Hanselmann

445 66bd7445 Michael Hanselmann
    """
446 66bd7445 Michael Hanselmann
    self.end_timestamp = TimeStampNow()
447 66bd7445 Michael Hanselmann
448 099b2870 Michael Hanselmann
  def Cancel(self):
449 a0d2fe2c Michael Hanselmann
    """Marks job as canceled/-ing if possible.
450 a0d2fe2c Michael Hanselmann

451 a0d2fe2c Michael Hanselmann
    @rtype: tuple; (bool, string)
452 a0d2fe2c Michael Hanselmann
    @return: Boolean describing whether job was successfully canceled or marked
453 a0d2fe2c Michael Hanselmann
      as canceling and a text message
454 a0d2fe2c Michael Hanselmann

455 a0d2fe2c Michael Hanselmann
    """
456 099b2870 Michael Hanselmann
    status = self.CalcStatus()
457 099b2870 Michael Hanselmann
458 099b2870 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED:
459 099b2870 Michael Hanselmann
      self.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
460 099b2870 Michael Hanselmann
                             "Job canceled by request")
461 66bd7445 Michael Hanselmann
      self.Finalize()
462 86b16e9d Michael Hanselmann
      return (True, "Job %s canceled" % self.id)
463 099b2870 Michael Hanselmann
464 099b2870 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITLOCK:
465 099b2870 Michael Hanselmann
      # The worker will notice the new status and cancel the job
466 099b2870 Michael Hanselmann
      self.MarkUnfinishedOps(constants.OP_STATUS_CANCELING, None)
467 86b16e9d Michael Hanselmann
      return (True, "Job %s will be canceled" % self.id)
468 099b2870 Michael Hanselmann
469 86b16e9d Michael Hanselmann
    else:
470 86b16e9d Michael Hanselmann
      logging.debug("Job %s is no longer waiting in the queue", self.id)
471 86b16e9d Michael Hanselmann
      return (False, "Job %s is no longer waiting in the queue" % self.id)
472 099b2870 Michael Hanselmann
473 f1048938 Iustin Pop
474 ef2df7d3 Michael Hanselmann
class _OpExecCallbacks(mcpu.OpExecCbBase):
475 031a3e57 Michael Hanselmann
  def __init__(self, queue, job, op):
476 031a3e57 Michael Hanselmann
    """Initializes this class.
477 ea03467c Iustin Pop

478 031a3e57 Michael Hanselmann
    @type queue: L{JobQueue}
479 031a3e57 Michael Hanselmann
    @param queue: Job queue
480 031a3e57 Michael Hanselmann
    @type job: L{_QueuedJob}
481 031a3e57 Michael Hanselmann
    @param job: Job object
482 031a3e57 Michael Hanselmann
    @type op: L{_QueuedOpCode}
483 031a3e57 Michael Hanselmann
    @param op: OpCode
484 031a3e57 Michael Hanselmann

485 031a3e57 Michael Hanselmann
    """
486 031a3e57 Michael Hanselmann
    assert queue, "Queue is missing"
487 031a3e57 Michael Hanselmann
    assert job, "Job is missing"
488 031a3e57 Michael Hanselmann
    assert op, "Opcode is missing"
489 031a3e57 Michael Hanselmann
490 031a3e57 Michael Hanselmann
    self._queue = queue
491 031a3e57 Michael Hanselmann
    self._job = job
492 031a3e57 Michael Hanselmann
    self._op = op
493 031a3e57 Michael Hanselmann
494 dc1e2262 Michael Hanselmann
  def _CheckCancel(self):
495 dc1e2262 Michael Hanselmann
    """Raises an exception to cancel the job if asked to.
496 dc1e2262 Michael Hanselmann

497 dc1e2262 Michael Hanselmann
    """
498 dc1e2262 Michael Hanselmann
    # Cancel here if we were asked to
499 dc1e2262 Michael Hanselmann
    if self._op.status == constants.OP_STATUS_CANCELING:
500 dc1e2262 Michael Hanselmann
      logging.debug("Canceling opcode")
501 dc1e2262 Michael Hanselmann
      raise CancelJob()
502 dc1e2262 Michael Hanselmann
503 271daef8 Iustin Pop
  @locking.ssynchronized(_QUEUE, shared=1)
504 031a3e57 Michael Hanselmann
  def NotifyStart(self):
505 e92376d7 Iustin Pop
    """Mark the opcode as running, not lock-waiting.
506 e92376d7 Iustin Pop

507 031a3e57 Michael Hanselmann
    This is called from the mcpu code as a notifier function, when the LU is
508 031a3e57 Michael Hanselmann
    finally about to start the Exec() method. Of course, to have end-user
509 031a3e57 Michael Hanselmann
    visible results, the opcode must be initially (before calling into
510 031a3e57 Michael Hanselmann
    Processor.ExecOpCode) set to OP_STATUS_WAITLOCK.
511 e92376d7 Iustin Pop

512 e92376d7 Iustin Pop
    """
513 9bdab621 Michael Hanselmann
    assert self._op in self._job.ops
514 271daef8 Iustin Pop
    assert self._op.status in (constants.OP_STATUS_WAITLOCK,
515 271daef8 Iustin Pop
                               constants.OP_STATUS_CANCELING)
516 fbf0262f Michael Hanselmann
517 271daef8 Iustin Pop
    # Cancel here if we were asked to
518 dc1e2262 Michael Hanselmann
    self._CheckCancel()
519 fbf0262f Michael Hanselmann
520 e35344b4 Michael Hanselmann
    logging.debug("Opcode is now running")
521 9bdab621 Michael Hanselmann
522 271daef8 Iustin Pop
    self._op.status = constants.OP_STATUS_RUNNING
523 271daef8 Iustin Pop
    self._op.exec_timestamp = TimeStampNow()
524 271daef8 Iustin Pop
525 271daef8 Iustin Pop
    # And finally replicate the job status
526 271daef8 Iustin Pop
    self._queue.UpdateJobUnlocked(self._job)
527 031a3e57 Michael Hanselmann
528 ebb80afa Guido Trotter
  @locking.ssynchronized(_QUEUE, shared=1)
529 9bf5e01f Guido Trotter
  def _AppendFeedback(self, timestamp, log_type, log_msg):
530 9bf5e01f Guido Trotter
    """Internal feedback append function, with locks
531 9bf5e01f Guido Trotter

532 9bf5e01f Guido Trotter
    """
533 9bf5e01f Guido Trotter
    self._job.log_serial += 1
534 9bf5e01f Guido Trotter
    self._op.log.append((self._job.log_serial, timestamp, log_type, log_msg))
535 9bf5e01f Guido Trotter
    self._queue.UpdateJobUnlocked(self._job, replicate=False)
536 9bf5e01f Guido Trotter
537 031a3e57 Michael Hanselmann
  def Feedback(self, *args):
538 031a3e57 Michael Hanselmann
    """Append a log entry.
539 031a3e57 Michael Hanselmann

540 031a3e57 Michael Hanselmann
    """
541 031a3e57 Michael Hanselmann
    assert len(args) < 3
542 031a3e57 Michael Hanselmann
543 031a3e57 Michael Hanselmann
    if len(args) == 1:
544 031a3e57 Michael Hanselmann
      log_type = constants.ELOG_MESSAGE
545 031a3e57 Michael Hanselmann
      log_msg = args[0]
546 031a3e57 Michael Hanselmann
    else:
547 031a3e57 Michael Hanselmann
      (log_type, log_msg) = args
548 031a3e57 Michael Hanselmann
549 031a3e57 Michael Hanselmann
    # The time is split to make serialization easier and not lose
550 031a3e57 Michael Hanselmann
    # precision.
551 031a3e57 Michael Hanselmann
    timestamp = utils.SplitTime(time.time())
552 9bf5e01f Guido Trotter
    self._AppendFeedback(timestamp, log_type, log_msg)
553 031a3e57 Michael Hanselmann
554 acf931b7 Michael Hanselmann
  def CheckCancel(self):
555 acf931b7 Michael Hanselmann
    """Check whether job has been cancelled.
556 ef2df7d3 Michael Hanselmann

557 ef2df7d3 Michael Hanselmann
    """
558 dc1e2262 Michael Hanselmann
    assert self._op.status in (constants.OP_STATUS_WAITLOCK,
559 dc1e2262 Michael Hanselmann
                               constants.OP_STATUS_CANCELING)
560 dc1e2262 Michael Hanselmann
561 dc1e2262 Michael Hanselmann
    # Cancel here if we were asked to
562 dc1e2262 Michael Hanselmann
    self._CheckCancel()
563 dc1e2262 Michael Hanselmann
564 6a373640 Michael Hanselmann
  def SubmitManyJobs(self, jobs):
565 6a373640 Michael Hanselmann
    """Submits jobs for processing.
566 6a373640 Michael Hanselmann

567 6a373640 Michael Hanselmann
    See L{JobQueue.SubmitManyJobs}.
568 6a373640 Michael Hanselmann

569 6a373640 Michael Hanselmann
    """
570 6a373640 Michael Hanselmann
    # Locking is done in job queue
571 6a373640 Michael Hanselmann
    return self._queue.SubmitManyJobs(jobs)
572 6a373640 Michael Hanselmann
573 031a3e57 Michael Hanselmann
574 989a8bee Michael Hanselmann
class _JobChangesChecker(object):
575 989a8bee Michael Hanselmann
  def __init__(self, fields, prev_job_info, prev_log_serial):
576 989a8bee Michael Hanselmann
    """Initializes this class.
577 6c2549d6 Guido Trotter

578 989a8bee Michael Hanselmann
    @type fields: list of strings
579 989a8bee Michael Hanselmann
    @param fields: Fields requested by LUXI client
580 989a8bee Michael Hanselmann
    @type prev_job_info: string
581 989a8bee Michael Hanselmann
    @param prev_job_info: previous job info, as passed by the LUXI client
582 989a8bee Michael Hanselmann
    @type prev_log_serial: string
583 989a8bee Michael Hanselmann
    @param prev_log_serial: previous job serial, as passed by the LUXI client
584 6c2549d6 Guido Trotter

585 989a8bee Michael Hanselmann
    """
586 989a8bee Michael Hanselmann
    self._fields = fields
587 989a8bee Michael Hanselmann
    self._prev_job_info = prev_job_info
588 989a8bee Michael Hanselmann
    self._prev_log_serial = prev_log_serial
589 6c2549d6 Guido Trotter
590 989a8bee Michael Hanselmann
  def __call__(self, job):
591 989a8bee Michael Hanselmann
    """Checks whether job has changed.
592 6c2549d6 Guido Trotter

593 989a8bee Michael Hanselmann
    @type job: L{_QueuedJob}
594 989a8bee Michael Hanselmann
    @param job: Job object
595 6c2549d6 Guido Trotter

596 6c2549d6 Guido Trotter
    """
597 c0f6d0d8 Michael Hanselmann
    assert not job.writable, "Expected read-only job"
598 c0f6d0d8 Michael Hanselmann
599 989a8bee Michael Hanselmann
    status = job.CalcStatus()
600 989a8bee Michael Hanselmann
    job_info = job.GetInfo(self._fields)
601 989a8bee Michael Hanselmann
    log_entries = job.GetLogEntries(self._prev_log_serial)
602 6c2549d6 Guido Trotter
603 6c2549d6 Guido Trotter
    # Serializing and deserializing data can cause type changes (e.g. from
604 6c2549d6 Guido Trotter
    # tuple to list) or precision loss. We're doing it here so that we get
605 6c2549d6 Guido Trotter
    # the same modifications as the data received from the client. Without
606 6c2549d6 Guido Trotter
    # this, the comparison afterwards might fail without the data being
607 6c2549d6 Guido Trotter
    # significantly different.
608 6c2549d6 Guido Trotter
    # TODO: we just deserialized from disk, investigate how to make sure that
609 6c2549d6 Guido Trotter
    # the job info and log entries are compatible to avoid this further step.
610 989a8bee Michael Hanselmann
    # TODO: Doing something like in testutils.py:UnifyValueType might be more
611 989a8bee Michael Hanselmann
    # efficient, though floats will be tricky
612 989a8bee Michael Hanselmann
    job_info = serializer.LoadJson(serializer.DumpJson(job_info))
613 989a8bee Michael Hanselmann
    log_entries = serializer.LoadJson(serializer.DumpJson(log_entries))
614 6c2549d6 Guido Trotter
615 6c2549d6 Guido Trotter
    # Don't even try to wait if the job is no longer running, there will be
616 6c2549d6 Guido Trotter
    # no changes.
617 989a8bee Michael Hanselmann
    if (status not in (constants.JOB_STATUS_QUEUED,
618 989a8bee Michael Hanselmann
                       constants.JOB_STATUS_RUNNING,
619 989a8bee Michael Hanselmann
                       constants.JOB_STATUS_WAITLOCK) or
620 989a8bee Michael Hanselmann
        job_info != self._prev_job_info or
621 989a8bee Michael Hanselmann
        (log_entries and self._prev_log_serial != log_entries[0][0])):
622 989a8bee Michael Hanselmann
      logging.debug("Job %s changed", job.id)
623 989a8bee Michael Hanselmann
      return (job_info, log_entries)
624 6c2549d6 Guido Trotter
625 989a8bee Michael Hanselmann
    return None
626 989a8bee Michael Hanselmann
627 989a8bee Michael Hanselmann
628 989a8bee Michael Hanselmann
class _JobFileChangesWaiter(object):
629 989a8bee Michael Hanselmann
  def __init__(self, filename):
630 989a8bee Michael Hanselmann
    """Initializes this class.
631 989a8bee Michael Hanselmann

632 989a8bee Michael Hanselmann
    @type filename: string
633 989a8bee Michael Hanselmann
    @param filename: Path to job file
634 989a8bee Michael Hanselmann
    @raises errors.InotifyError: if the notifier cannot be setup
635 6c2549d6 Guido Trotter

636 989a8bee Michael Hanselmann
    """
637 989a8bee Michael Hanselmann
    self._wm = pyinotify.WatchManager()
638 989a8bee Michael Hanselmann
    self._inotify_handler = \
639 989a8bee Michael Hanselmann
      asyncnotifier.SingleFileEventHandler(self._wm, self._OnInotify, filename)
640 989a8bee Michael Hanselmann
    self._notifier = \
641 989a8bee Michael Hanselmann
      pyinotify.Notifier(self._wm, default_proc_fun=self._inotify_handler)
642 989a8bee Michael Hanselmann
    try:
643 989a8bee Michael Hanselmann
      self._inotify_handler.enable()
644 989a8bee Michael Hanselmann
    except Exception:
645 989a8bee Michael Hanselmann
      # pyinotify doesn't close file descriptors automatically
646 989a8bee Michael Hanselmann
      self._notifier.stop()
647 989a8bee Michael Hanselmann
      raise
648 989a8bee Michael Hanselmann
649 989a8bee Michael Hanselmann
  def _OnInotify(self, notifier_enabled):
650 989a8bee Michael Hanselmann
    """Callback for inotify.
651 989a8bee Michael Hanselmann

652 989a8bee Michael Hanselmann
    """
653 6c2549d6 Guido Trotter
    if not notifier_enabled:
654 989a8bee Michael Hanselmann
      self._inotify_handler.enable()
655 989a8bee Michael Hanselmann
656 989a8bee Michael Hanselmann
  def Wait(self, timeout):
657 989a8bee Michael Hanselmann
    """Waits for the job file to change.
658 989a8bee Michael Hanselmann

659 989a8bee Michael Hanselmann
    @type timeout: float
660 989a8bee Michael Hanselmann
    @param timeout: Timeout in seconds
661 989a8bee Michael Hanselmann
    @return: Whether there have been events
662 989a8bee Michael Hanselmann

663 989a8bee Michael Hanselmann
    """
664 989a8bee Michael Hanselmann
    assert timeout >= 0
665 989a8bee Michael Hanselmann
    have_events = self._notifier.check_events(timeout * 1000)
666 989a8bee Michael Hanselmann
    if have_events:
667 989a8bee Michael Hanselmann
      self._notifier.read_events()
668 989a8bee Michael Hanselmann
    self._notifier.process_events()
669 989a8bee Michael Hanselmann
    return have_events
670 989a8bee Michael Hanselmann
671 989a8bee Michael Hanselmann
  def Close(self):
672 989a8bee Michael Hanselmann
    """Closes underlying notifier and its file descriptor.
673 989a8bee Michael Hanselmann

674 989a8bee Michael Hanselmann
    """
675 989a8bee Michael Hanselmann
    self._notifier.stop()
676 989a8bee Michael Hanselmann
677 989a8bee Michael Hanselmann
678 989a8bee Michael Hanselmann
class _JobChangesWaiter(object):
679 989a8bee Michael Hanselmann
  def __init__(self, filename):
680 989a8bee Michael Hanselmann
    """Initializes this class.
681 989a8bee Michael Hanselmann

682 989a8bee Michael Hanselmann
    @type filename: string
683 989a8bee Michael Hanselmann
    @param filename: Path to job file
684 989a8bee Michael Hanselmann

685 989a8bee Michael Hanselmann
    """
686 989a8bee Michael Hanselmann
    self._filewaiter = None
687 989a8bee Michael Hanselmann
    self._filename = filename
688 6c2549d6 Guido Trotter
689 989a8bee Michael Hanselmann
  def Wait(self, timeout):
690 989a8bee Michael Hanselmann
    """Waits for a job to change.
691 6c2549d6 Guido Trotter

692 989a8bee Michael Hanselmann
    @type timeout: float
693 989a8bee Michael Hanselmann
    @param timeout: Timeout in seconds
694 989a8bee Michael Hanselmann
    @return: Whether there have been events
695 989a8bee Michael Hanselmann

696 989a8bee Michael Hanselmann
    """
697 989a8bee Michael Hanselmann
    if self._filewaiter:
698 989a8bee Michael Hanselmann
      return self._filewaiter.Wait(timeout)
699 989a8bee Michael Hanselmann
700 989a8bee Michael Hanselmann
    # Lazy setup: Avoid inotify setup cost when job file has already changed.
701 989a8bee Michael Hanselmann
    # If this point is reached, return immediately and let caller check the job
702 989a8bee Michael Hanselmann
    # file again in case there were changes since the last check. This avoids a
703 989a8bee Michael Hanselmann
    # race condition.
704 989a8bee Michael Hanselmann
    self._filewaiter = _JobFileChangesWaiter(self._filename)
705 989a8bee Michael Hanselmann
706 989a8bee Michael Hanselmann
    return True
707 989a8bee Michael Hanselmann
708 989a8bee Michael Hanselmann
  def Close(self):
709 989a8bee Michael Hanselmann
    """Closes underlying waiter.
710 989a8bee Michael Hanselmann

711 989a8bee Michael Hanselmann
    """
712 989a8bee Michael Hanselmann
    if self._filewaiter:
713 989a8bee Michael Hanselmann
      self._filewaiter.Close()
714 989a8bee Michael Hanselmann
715 989a8bee Michael Hanselmann
716 989a8bee Michael Hanselmann
class _WaitForJobChangesHelper(object):
717 989a8bee Michael Hanselmann
  """Helper class using inotify to wait for changes in a job file.
718 989a8bee Michael Hanselmann

719 989a8bee Michael Hanselmann
  This class takes a previous job status and serial, and alerts the client when
720 989a8bee Michael Hanselmann
  the current job status has changed.
721 989a8bee Michael Hanselmann

722 989a8bee Michael Hanselmann
  """
723 989a8bee Michael Hanselmann
  @staticmethod
724 989a8bee Michael Hanselmann
  def _CheckForChanges(job_load_fn, check_fn):
725 989a8bee Michael Hanselmann
    job = job_load_fn()
726 989a8bee Michael Hanselmann
    if not job:
727 989a8bee Michael Hanselmann
      raise errors.JobLost()
728 989a8bee Michael Hanselmann
729 989a8bee Michael Hanselmann
    result = check_fn(job)
730 989a8bee Michael Hanselmann
    if result is None:
731 989a8bee Michael Hanselmann
      raise utils.RetryAgain()
732 989a8bee Michael Hanselmann
733 989a8bee Michael Hanselmann
    return result
734 989a8bee Michael Hanselmann
735 989a8bee Michael Hanselmann
  def __call__(self, filename, job_load_fn,
736 989a8bee Michael Hanselmann
               fields, prev_job_info, prev_log_serial, timeout):
737 989a8bee Michael Hanselmann
    """Waits for changes on a job.
738 989a8bee Michael Hanselmann

739 989a8bee Michael Hanselmann
    @type filename: string
740 989a8bee Michael Hanselmann
    @param filename: File on which to wait for changes
741 989a8bee Michael Hanselmann
    @type job_load_fn: callable
742 989a8bee Michael Hanselmann
    @param job_load_fn: Function to load job
743 989a8bee Michael Hanselmann
    @type fields: list of strings
744 989a8bee Michael Hanselmann
    @param fields: Which fields to check for changes
745 989a8bee Michael Hanselmann
    @type prev_job_info: list or None
746 989a8bee Michael Hanselmann
    @param prev_job_info: Last job information returned
747 989a8bee Michael Hanselmann
    @type prev_log_serial: int
748 989a8bee Michael Hanselmann
    @param prev_log_serial: Last job message serial number
749 989a8bee Michael Hanselmann
    @type timeout: float
750 989a8bee Michael Hanselmann
    @param timeout: maximum time to wait in seconds
751 989a8bee Michael Hanselmann

752 989a8bee Michael Hanselmann
    """
753 6c2549d6 Guido Trotter
    try:
754 989a8bee Michael Hanselmann
      check_fn = _JobChangesChecker(fields, prev_job_info, prev_log_serial)
755 989a8bee Michael Hanselmann
      waiter = _JobChangesWaiter(filename)
756 989a8bee Michael Hanselmann
      try:
757 989a8bee Michael Hanselmann
        return utils.Retry(compat.partial(self._CheckForChanges,
758 989a8bee Michael Hanselmann
                                          job_load_fn, check_fn),
759 989a8bee Michael Hanselmann
                           utils.RETRY_REMAINING_TIME, timeout,
760 989a8bee Michael Hanselmann
                           wait_fn=waiter.Wait)
761 989a8bee Michael Hanselmann
      finally:
762 989a8bee Michael Hanselmann
        waiter.Close()
763 6c2549d6 Guido Trotter
    except (errors.InotifyError, errors.JobLost):
764 6c2549d6 Guido Trotter
      return None
765 6c2549d6 Guido Trotter
    except utils.RetryTimeout:
766 6c2549d6 Guido Trotter
      return constants.JOB_NOTCHANGED
767 6c2549d6 Guido Trotter
768 6c2549d6 Guido Trotter
769 6760e4ed Michael Hanselmann
def _EncodeOpError(err):
770 6760e4ed Michael Hanselmann
  """Encodes an error which occurred while processing an opcode.
771 6760e4ed Michael Hanselmann

772 6760e4ed Michael Hanselmann
  """
773 6760e4ed Michael Hanselmann
  if isinstance(err, errors.GenericError):
774 6760e4ed Michael Hanselmann
    to_encode = err
775 6760e4ed Michael Hanselmann
  else:
776 6760e4ed Michael Hanselmann
    to_encode = errors.OpExecError(str(err))
777 6760e4ed Michael Hanselmann
778 6760e4ed Michael Hanselmann
  return errors.EncodeException(to_encode)
779 6760e4ed Michael Hanselmann
780 6760e4ed Michael Hanselmann
781 26d3fd2f Michael Hanselmann
class _TimeoutStrategyWrapper:
782 26d3fd2f Michael Hanselmann
  def __init__(self, fn):
783 26d3fd2f Michael Hanselmann
    """Initializes this class.
784 26d3fd2f Michael Hanselmann

785 26d3fd2f Michael Hanselmann
    """
786 26d3fd2f Michael Hanselmann
    self._fn = fn
787 26d3fd2f Michael Hanselmann
    self._next = None
788 26d3fd2f Michael Hanselmann
789 26d3fd2f Michael Hanselmann
  def _Advance(self):
790 26d3fd2f Michael Hanselmann
    """Gets the next timeout if necessary.
791 26d3fd2f Michael Hanselmann

792 26d3fd2f Michael Hanselmann
    """
793 26d3fd2f Michael Hanselmann
    if self._next is None:
794 26d3fd2f Michael Hanselmann
      self._next = self._fn()
795 26d3fd2f Michael Hanselmann
796 26d3fd2f Michael Hanselmann
  def Peek(self):
797 26d3fd2f Michael Hanselmann
    """Returns the next timeout.
798 26d3fd2f Michael Hanselmann

799 26d3fd2f Michael Hanselmann
    """
800 26d3fd2f Michael Hanselmann
    self._Advance()
801 26d3fd2f Michael Hanselmann
    return self._next
802 26d3fd2f Michael Hanselmann
803 26d3fd2f Michael Hanselmann
  def Next(self):
804 26d3fd2f Michael Hanselmann
    """Returns the current timeout and advances the internal state.
805 26d3fd2f Michael Hanselmann

806 26d3fd2f Michael Hanselmann
    """
807 26d3fd2f Michael Hanselmann
    self._Advance()
808 26d3fd2f Michael Hanselmann
    result = self._next
809 26d3fd2f Michael Hanselmann
    self._next = None
810 26d3fd2f Michael Hanselmann
    return result
811 26d3fd2f Michael Hanselmann
812 26d3fd2f Michael Hanselmann
813 b80cc518 Michael Hanselmann
class _OpExecContext:
814 26d3fd2f Michael Hanselmann
  def __init__(self, op, index, log_prefix, timeout_strategy_factory):
815 b80cc518 Michael Hanselmann
    """Initializes this class.
816 b80cc518 Michael Hanselmann

817 b80cc518 Michael Hanselmann
    """
818 b80cc518 Michael Hanselmann
    self.op = op
819 b80cc518 Michael Hanselmann
    self.index = index
820 b80cc518 Michael Hanselmann
    self.log_prefix = log_prefix
821 b80cc518 Michael Hanselmann
    self.summary = op.input.Summary()
822 b80cc518 Michael Hanselmann
823 b95479a5 Michael Hanselmann
    # Create local copy to modify
824 b95479a5 Michael Hanselmann
    if getattr(op.input, opcodes.DEPEND_ATTR, None):
825 b95479a5 Michael Hanselmann
      self.jobdeps = op.input.depends[:]
826 b95479a5 Michael Hanselmann
    else:
827 b95479a5 Michael Hanselmann
      self.jobdeps = None
828 b95479a5 Michael Hanselmann
829 26d3fd2f Michael Hanselmann
    self._timeout_strategy_factory = timeout_strategy_factory
830 26d3fd2f Michael Hanselmann
    self._ResetTimeoutStrategy()
831 26d3fd2f Michael Hanselmann
832 26d3fd2f Michael Hanselmann
  def _ResetTimeoutStrategy(self):
833 26d3fd2f Michael Hanselmann
    """Creates a new timeout strategy.
834 26d3fd2f Michael Hanselmann

835 26d3fd2f Michael Hanselmann
    """
836 26d3fd2f Michael Hanselmann
    self._timeout_strategy = \
837 26d3fd2f Michael Hanselmann
      _TimeoutStrategyWrapper(self._timeout_strategy_factory().NextAttempt)
838 26d3fd2f Michael Hanselmann
839 26d3fd2f Michael Hanselmann
  def CheckPriorityIncrease(self):
840 26d3fd2f Michael Hanselmann
    """Checks whether priority can and should be increased.
841 26d3fd2f Michael Hanselmann

842 26d3fd2f Michael Hanselmann
    Called when locks couldn't be acquired.
843 26d3fd2f Michael Hanselmann

844 26d3fd2f Michael Hanselmann
    """
845 26d3fd2f Michael Hanselmann
    op = self.op
846 26d3fd2f Michael Hanselmann
847 26d3fd2f Michael Hanselmann
    # Exhausted all retries and next round should not use blocking acquire
848 26d3fd2f Michael Hanselmann
    # for locks?
849 26d3fd2f Michael Hanselmann
    if (self._timeout_strategy.Peek() is None and
850 26d3fd2f Michael Hanselmann
        op.priority > constants.OP_PRIO_HIGHEST):
851 26d3fd2f Michael Hanselmann
      logging.debug("Increasing priority")
852 26d3fd2f Michael Hanselmann
      op.priority -= 1
853 26d3fd2f Michael Hanselmann
      self._ResetTimeoutStrategy()
854 26d3fd2f Michael Hanselmann
      return True
855 26d3fd2f Michael Hanselmann
856 26d3fd2f Michael Hanselmann
    return False
857 26d3fd2f Michael Hanselmann
858 26d3fd2f Michael Hanselmann
  def GetNextLockTimeout(self):
859 26d3fd2f Michael Hanselmann
    """Returns the next lock acquire timeout.
860 26d3fd2f Michael Hanselmann

861 26d3fd2f Michael Hanselmann
    """
862 26d3fd2f Michael Hanselmann
    return self._timeout_strategy.Next()
863 26d3fd2f Michael Hanselmann
864 b80cc518 Michael Hanselmann
865 be760ba8 Michael Hanselmann
class _JobProcessor(object):
866 75d81fc8 Michael Hanselmann
  (DEFER,
867 75d81fc8 Michael Hanselmann
   WAITDEP,
868 75d81fc8 Michael Hanselmann
   FINISHED) = range(1, 4)
869 75d81fc8 Michael Hanselmann
870 26d3fd2f Michael Hanselmann
  def __init__(self, queue, opexec_fn, job,
871 26d3fd2f Michael Hanselmann
               _timeout_strategy_factory=mcpu.LockAttemptTimeoutStrategy):
872 be760ba8 Michael Hanselmann
    """Initializes this class.
873 be760ba8 Michael Hanselmann

874 be760ba8 Michael Hanselmann
    """
875 be760ba8 Michael Hanselmann
    self.queue = queue
876 be760ba8 Michael Hanselmann
    self.opexec_fn = opexec_fn
877 be760ba8 Michael Hanselmann
    self.job = job
878 26d3fd2f Michael Hanselmann
    self._timeout_strategy_factory = _timeout_strategy_factory
879 be760ba8 Michael Hanselmann
880 be760ba8 Michael Hanselmann
  @staticmethod
881 26d3fd2f Michael Hanselmann
  def _FindNextOpcode(job, timeout_strategy_factory):
882 be760ba8 Michael Hanselmann
    """Locates the next opcode to run.
883 be760ba8 Michael Hanselmann

884 be760ba8 Michael Hanselmann
    @type job: L{_QueuedJob}
885 be760ba8 Michael Hanselmann
    @param job: Job object
886 26d3fd2f Michael Hanselmann
    @param timeout_strategy_factory: Callable to create new timeout strategy
887 be760ba8 Michael Hanselmann

888 be760ba8 Michael Hanselmann
    """
889 be760ba8 Michael Hanselmann
    # Create some sort of a cache to speed up locating next opcode for future
890 be760ba8 Michael Hanselmann
    # lookups
891 be760ba8 Michael Hanselmann
    # TODO: Consider splitting _QueuedJob.ops into two separate lists, one for
892 be760ba8 Michael Hanselmann
    # pending and one for processed ops.
893 03b63608 Michael Hanselmann
    if job.ops_iter is None:
894 03b63608 Michael Hanselmann
      job.ops_iter = enumerate(job.ops)
895 be760ba8 Michael Hanselmann
896 be760ba8 Michael Hanselmann
    # Find next opcode to run
897 be760ba8 Michael Hanselmann
    while True:
898 be760ba8 Michael Hanselmann
      try:
899 03b63608 Michael Hanselmann
        (idx, op) = job.ops_iter.next()
900 be760ba8 Michael Hanselmann
      except StopIteration:
901 be760ba8 Michael Hanselmann
        raise errors.ProgrammerError("Called for a finished job")
902 be760ba8 Michael Hanselmann
903 be760ba8 Michael Hanselmann
      if op.status == constants.OP_STATUS_RUNNING:
904 be760ba8 Michael Hanselmann
        # Found an opcode already marked as running
905 be760ba8 Michael Hanselmann
        raise errors.ProgrammerError("Called for job marked as running")
906 be760ba8 Michael Hanselmann
907 26d3fd2f Michael Hanselmann
      opctx = _OpExecContext(op, idx, "Op %s/%s" % (idx + 1, len(job.ops)),
908 26d3fd2f Michael Hanselmann
                             timeout_strategy_factory)
909 be760ba8 Michael Hanselmann
910 66bd7445 Michael Hanselmann
      if op.status not in constants.OPS_FINALIZED:
911 66bd7445 Michael Hanselmann
        return opctx
912 be760ba8 Michael Hanselmann
913 66bd7445 Michael Hanselmann
      # This is a job that was partially completed before master daemon
914 66bd7445 Michael Hanselmann
      # shutdown, so it can be expected that some opcodes are already
915 66bd7445 Michael Hanselmann
      # completed successfully (if any did error out, then the whole job
916 66bd7445 Michael Hanselmann
      # should have been aborted and not resubmitted for processing).
917 66bd7445 Michael Hanselmann
      logging.info("%s: opcode %s already processed, skipping",
918 66bd7445 Michael Hanselmann
                   opctx.log_prefix, opctx.summary)
919 be760ba8 Michael Hanselmann
920 be760ba8 Michael Hanselmann
  @staticmethod
921 be760ba8 Michael Hanselmann
  def _MarkWaitlock(job, op):
922 be760ba8 Michael Hanselmann
    """Marks an opcode as waiting for locks.
923 be760ba8 Michael Hanselmann

924 be760ba8 Michael Hanselmann
    The job's start timestamp is also set if necessary.
925 be760ba8 Michael Hanselmann

926 be760ba8 Michael Hanselmann
    @type job: L{_QueuedJob}
927 be760ba8 Michael Hanselmann
    @param job: Job object
928 a38e8674 Michael Hanselmann
    @type op: L{_QueuedOpCode}
929 a38e8674 Michael Hanselmann
    @param op: Opcode object
930 be760ba8 Michael Hanselmann

931 be760ba8 Michael Hanselmann
    """
932 be760ba8 Michael Hanselmann
    assert op in job.ops
933 5fd6b694 Michael Hanselmann
    assert op.status in (constants.OP_STATUS_QUEUED,
934 5fd6b694 Michael Hanselmann
                         constants.OP_STATUS_WAITLOCK)
935 5fd6b694 Michael Hanselmann
936 5fd6b694 Michael Hanselmann
    update = False
937 be760ba8 Michael Hanselmann
938 be760ba8 Michael Hanselmann
    op.result = None
939 5fd6b694 Michael Hanselmann
940 5fd6b694 Michael Hanselmann
    if op.status == constants.OP_STATUS_QUEUED:
941 5fd6b694 Michael Hanselmann
      op.status = constants.OP_STATUS_WAITLOCK
942 5fd6b694 Michael Hanselmann
      update = True
943 5fd6b694 Michael Hanselmann
944 5fd6b694 Michael Hanselmann
    if op.start_timestamp is None:
945 5fd6b694 Michael Hanselmann
      op.start_timestamp = TimeStampNow()
946 5fd6b694 Michael Hanselmann
      update = True
947 be760ba8 Michael Hanselmann
948 be760ba8 Michael Hanselmann
    if job.start_timestamp is None:
949 be760ba8 Michael Hanselmann
      job.start_timestamp = op.start_timestamp
950 5fd6b694 Michael Hanselmann
      update = True
951 5fd6b694 Michael Hanselmann
952 5fd6b694 Michael Hanselmann
    assert op.status == constants.OP_STATUS_WAITLOCK
953 5fd6b694 Michael Hanselmann
954 5fd6b694 Michael Hanselmann
    return update
955 be760ba8 Michael Hanselmann
956 b95479a5 Michael Hanselmann
  @staticmethod
957 b95479a5 Michael Hanselmann
  def _CheckDependencies(queue, job, opctx):
958 b95479a5 Michael Hanselmann
    """Checks if an opcode has dependencies and if so, processes them.
959 b95479a5 Michael Hanselmann

960 b95479a5 Michael Hanselmann
    @type queue: L{JobQueue}
961 b95479a5 Michael Hanselmann
    @param queue: Queue object
962 b95479a5 Michael Hanselmann
    @type job: L{_QueuedJob}
963 b95479a5 Michael Hanselmann
    @param job: Job object
964 b95479a5 Michael Hanselmann
    @type opctx: L{_OpExecContext}
965 b95479a5 Michael Hanselmann
    @param opctx: Opcode execution context
966 b95479a5 Michael Hanselmann
    @rtype: bool
967 b95479a5 Michael Hanselmann
    @return: Whether opcode will be re-scheduled by dependency tracker
968 b95479a5 Michael Hanselmann

969 b95479a5 Michael Hanselmann
    """
970 b95479a5 Michael Hanselmann
    op = opctx.op
971 b95479a5 Michael Hanselmann
972 b95479a5 Michael Hanselmann
    result = False
973 b95479a5 Michael Hanselmann
974 b95479a5 Michael Hanselmann
    while opctx.jobdeps:
975 b95479a5 Michael Hanselmann
      (dep_job_id, dep_status) = opctx.jobdeps[0]
976 b95479a5 Michael Hanselmann
977 b95479a5 Michael Hanselmann
      (depresult, depmsg) = queue.depmgr.CheckAndRegister(job, dep_job_id,
978 b95479a5 Michael Hanselmann
                                                          dep_status)
979 b95479a5 Michael Hanselmann
      assert ht.TNonEmptyString(depmsg), "No dependency message"
980 b95479a5 Michael Hanselmann
981 b95479a5 Michael Hanselmann
      logging.info("%s: %s", opctx.log_prefix, depmsg)
982 b95479a5 Michael Hanselmann
983 b95479a5 Michael Hanselmann
      if depresult == _JobDependencyManager.CONTINUE:
984 b95479a5 Michael Hanselmann
        # Remove dependency and continue
985 b95479a5 Michael Hanselmann
        opctx.jobdeps.pop(0)
986 b95479a5 Michael Hanselmann
987 b95479a5 Michael Hanselmann
      elif depresult == _JobDependencyManager.WAIT:
988 b95479a5 Michael Hanselmann
        # Need to wait for notification, dependency tracker will re-add job
989 b95479a5 Michael Hanselmann
        # to workerpool
990 b95479a5 Michael Hanselmann
        result = True
991 b95479a5 Michael Hanselmann
        break
992 b95479a5 Michael Hanselmann
993 b95479a5 Michael Hanselmann
      elif depresult == _JobDependencyManager.CANCEL:
994 b95479a5 Michael Hanselmann
        # Job was cancelled, cancel this job as well
995 b95479a5 Michael Hanselmann
        job.Cancel()
996 b95479a5 Michael Hanselmann
        assert op.status == constants.OP_STATUS_CANCELING
997 b95479a5 Michael Hanselmann
        break
998 b95479a5 Michael Hanselmann
999 b95479a5 Michael Hanselmann
      elif depresult in (_JobDependencyManager.WRONGSTATUS,
1000 b95479a5 Michael Hanselmann
                         _JobDependencyManager.ERROR):
1001 b95479a5 Michael Hanselmann
        # Job failed or there was an error, this job must fail
1002 b95479a5 Michael Hanselmann
        op.status = constants.OP_STATUS_ERROR
1003 b95479a5 Michael Hanselmann
        op.result = _EncodeOpError(errors.OpExecError(depmsg))
1004 b95479a5 Michael Hanselmann
        break
1005 b95479a5 Michael Hanselmann
1006 b95479a5 Michael Hanselmann
      else:
1007 b95479a5 Michael Hanselmann
        raise errors.ProgrammerError("Unknown dependency result '%s'" %
1008 b95479a5 Michael Hanselmann
                                     depresult)
1009 b95479a5 Michael Hanselmann
1010 b95479a5 Michael Hanselmann
    return result
1011 b95479a5 Michael Hanselmann
1012 b80cc518 Michael Hanselmann
  def _ExecOpCodeUnlocked(self, opctx):
1013 be760ba8 Michael Hanselmann
    """Processes one opcode and returns the result.
1014 be760ba8 Michael Hanselmann

1015 be760ba8 Michael Hanselmann
    """
1016 b80cc518 Michael Hanselmann
    op = opctx.op
1017 b80cc518 Michael Hanselmann
1018 be760ba8 Michael Hanselmann
    assert op.status == constants.OP_STATUS_WAITLOCK
1019 be760ba8 Michael Hanselmann
1020 26d3fd2f Michael Hanselmann
    timeout = opctx.GetNextLockTimeout()
1021 26d3fd2f Michael Hanselmann
1022 be760ba8 Michael Hanselmann
    try:
1023 be760ba8 Michael Hanselmann
      # Make sure not to hold queue lock while calling ExecOpCode
1024 be760ba8 Michael Hanselmann
      result = self.opexec_fn(op.input,
1025 26d3fd2f Michael Hanselmann
                              _OpExecCallbacks(self.queue, self.job, op),
1026 f23db633 Michael Hanselmann
                              timeout=timeout, priority=op.priority)
1027 26d3fd2f Michael Hanselmann
    except mcpu.LockAcquireTimeout:
1028 26d3fd2f Michael Hanselmann
      assert timeout is not None, "Received timeout for blocking acquire"
1029 26d3fd2f Michael Hanselmann
      logging.debug("Couldn't acquire locks in %0.6fs", timeout)
1030 9e49dfc5 Michael Hanselmann
1031 9e49dfc5 Michael Hanselmann
      assert op.status in (constants.OP_STATUS_WAITLOCK,
1032 9e49dfc5 Michael Hanselmann
                           constants.OP_STATUS_CANCELING)
1033 9e49dfc5 Michael Hanselmann
1034 9e49dfc5 Michael Hanselmann
      # Was job cancelled while we were waiting for the lock?
1035 9e49dfc5 Michael Hanselmann
      if op.status == constants.OP_STATUS_CANCELING:
1036 9e49dfc5 Michael Hanselmann
        return (constants.OP_STATUS_CANCELING, None)
1037 9e49dfc5 Michael Hanselmann
1038 5fd6b694 Michael Hanselmann
      # Stay in waitlock while trying to re-acquire lock
1039 5fd6b694 Michael Hanselmann
      return (constants.OP_STATUS_WAITLOCK, None)
1040 be760ba8 Michael Hanselmann
    except CancelJob:
1041 b80cc518 Michael Hanselmann
      logging.exception("%s: Canceling job", opctx.log_prefix)
1042 be760ba8 Michael Hanselmann
      assert op.status == constants.OP_STATUS_CANCELING
1043 be760ba8 Michael Hanselmann
      return (constants.OP_STATUS_CANCELING, None)
1044 be760ba8 Michael Hanselmann
    except Exception, err: # pylint: disable-msg=W0703
1045 b80cc518 Michael Hanselmann
      logging.exception("%s: Caught exception in %s",
1046 b80cc518 Michael Hanselmann
                        opctx.log_prefix, opctx.summary)
1047 be760ba8 Michael Hanselmann
      return (constants.OP_STATUS_ERROR, _EncodeOpError(err))
1048 be760ba8 Michael Hanselmann
    else:
1049 b80cc518 Michael Hanselmann
      logging.debug("%s: %s successful",
1050 b80cc518 Michael Hanselmann
                    opctx.log_prefix, opctx.summary)
1051 be760ba8 Michael Hanselmann
      return (constants.OP_STATUS_SUCCESS, result)
1052 be760ba8 Michael Hanselmann
1053 26d3fd2f Michael Hanselmann
  def __call__(self, _nextop_fn=None):
1054 be760ba8 Michael Hanselmann
    """Continues execution of a job.
1055 be760ba8 Michael Hanselmann

1056 26d3fd2f Michael Hanselmann
    @param _nextop_fn: Callback function for tests
1057 75d81fc8 Michael Hanselmann
    @return: C{FINISHED} if job is fully processed, C{DEFER} if the job should
1058 75d81fc8 Michael Hanselmann
      be deferred and C{WAITDEP} if the dependency manager
1059 75d81fc8 Michael Hanselmann
      (L{_JobDependencyManager}) will re-schedule the job when appropriate
1060 be760ba8 Michael Hanselmann

1061 be760ba8 Michael Hanselmann
    """
1062 be760ba8 Michael Hanselmann
    queue = self.queue
1063 be760ba8 Michael Hanselmann
    job = self.job
1064 be760ba8 Michael Hanselmann
1065 be760ba8 Michael Hanselmann
    logging.debug("Processing job %s", job.id)
1066 be760ba8 Michael Hanselmann
1067 be760ba8 Michael Hanselmann
    queue.acquire(shared=1)
1068 be760ba8 Michael Hanselmann
    try:
1069 be760ba8 Michael Hanselmann
      opcount = len(job.ops)
1070 be760ba8 Michael Hanselmann
1071 c0f6d0d8 Michael Hanselmann
      assert job.writable, "Expected writable job"
1072 c0f6d0d8 Michael Hanselmann
1073 66bd7445 Michael Hanselmann
      # Don't do anything for finalized jobs
1074 66bd7445 Michael Hanselmann
      if job.CalcStatus() in constants.JOBS_FINALIZED:
1075 75d81fc8 Michael Hanselmann
        return self.FINISHED
1076 66bd7445 Michael Hanselmann
1077 26d3fd2f Michael Hanselmann
      # Is a previous opcode still pending?
1078 26d3fd2f Michael Hanselmann
      if job.cur_opctx:
1079 26d3fd2f Michael Hanselmann
        opctx = job.cur_opctx
1080 5fd6b694 Michael Hanselmann
        job.cur_opctx = None
1081 26d3fd2f Michael Hanselmann
      else:
1082 26d3fd2f Michael Hanselmann
        if __debug__ and _nextop_fn:
1083 26d3fd2f Michael Hanselmann
          _nextop_fn()
1084 26d3fd2f Michael Hanselmann
        opctx = self._FindNextOpcode(job, self._timeout_strategy_factory)
1085 26d3fd2f Michael Hanselmann
1086 b80cc518 Michael Hanselmann
      op = opctx.op
1087 be760ba8 Michael Hanselmann
1088 be760ba8 Michael Hanselmann
      # Consistency check
1089 be760ba8 Michael Hanselmann
      assert compat.all(i.status in (constants.OP_STATUS_QUEUED,
1090 66bd7445 Michael Hanselmann
                                     constants.OP_STATUS_CANCELING)
1091 5fd6b694 Michael Hanselmann
                        for i in job.ops[opctx.index + 1:])
1092 be760ba8 Michael Hanselmann
1093 be760ba8 Michael Hanselmann
      assert op.status in (constants.OP_STATUS_QUEUED,
1094 be760ba8 Michael Hanselmann
                           constants.OP_STATUS_WAITLOCK,
1095 66bd7445 Michael Hanselmann
                           constants.OP_STATUS_CANCELING)
1096 be760ba8 Michael Hanselmann
1097 26d3fd2f Michael Hanselmann
      assert (op.priority <= constants.OP_PRIO_LOWEST and
1098 26d3fd2f Michael Hanselmann
              op.priority >= constants.OP_PRIO_HIGHEST)
1099 26d3fd2f Michael Hanselmann
1100 b95479a5 Michael Hanselmann
      waitjob = None
1101 b95479a5 Michael Hanselmann
1102 66bd7445 Michael Hanselmann
      if op.status != constants.OP_STATUS_CANCELING:
1103 30c945d0 Michael Hanselmann
        assert op.status in (constants.OP_STATUS_QUEUED,
1104 30c945d0 Michael Hanselmann
                             constants.OP_STATUS_WAITLOCK)
1105 30c945d0 Michael Hanselmann
1106 be760ba8 Michael Hanselmann
        # Prepare to start opcode
1107 5fd6b694 Michael Hanselmann
        if self._MarkWaitlock(job, op):
1108 5fd6b694 Michael Hanselmann
          # Write to disk
1109 5fd6b694 Michael Hanselmann
          queue.UpdateJobUnlocked(job)
1110 be760ba8 Michael Hanselmann
1111 be760ba8 Michael Hanselmann
        assert op.status == constants.OP_STATUS_WAITLOCK
1112 be760ba8 Michael Hanselmann
        assert job.CalcStatus() == constants.JOB_STATUS_WAITLOCK
1113 5fd6b694 Michael Hanselmann
        assert job.start_timestamp and op.start_timestamp
1114 b95479a5 Michael Hanselmann
        assert waitjob is None
1115 b95479a5 Michael Hanselmann
1116 b95479a5 Michael Hanselmann
        # Check if waiting for a job is necessary
1117 b95479a5 Michael Hanselmann
        waitjob = self._CheckDependencies(queue, job, opctx)
1118 be760ba8 Michael Hanselmann
1119 b95479a5 Michael Hanselmann
        assert op.status in (constants.OP_STATUS_WAITLOCK,
1120 b95479a5 Michael Hanselmann
                             constants.OP_STATUS_CANCELING,
1121 b95479a5 Michael Hanselmann
                             constants.OP_STATUS_ERROR)
1122 be760ba8 Michael Hanselmann
1123 b95479a5 Michael Hanselmann
        if not (waitjob or op.status in (constants.OP_STATUS_CANCELING,
1124 b95479a5 Michael Hanselmann
                                         constants.OP_STATUS_ERROR)):
1125 b95479a5 Michael Hanselmann
          logging.info("%s: opcode %s waiting for locks",
1126 b95479a5 Michael Hanselmann
                       opctx.log_prefix, opctx.summary)
1127 be760ba8 Michael Hanselmann
1128 b95479a5 Michael Hanselmann
          assert not opctx.jobdeps, "Not all dependencies were removed"
1129 b95479a5 Michael Hanselmann
1130 b95479a5 Michael Hanselmann
          queue.release()
1131 b95479a5 Michael Hanselmann
          try:
1132 b95479a5 Michael Hanselmann
            (op_status, op_result) = self._ExecOpCodeUnlocked(opctx)
1133 b95479a5 Michael Hanselmann
          finally:
1134 b95479a5 Michael Hanselmann
            queue.acquire(shared=1)
1135 b95479a5 Michael Hanselmann
1136 b95479a5 Michael Hanselmann
          op.status = op_status
1137 b95479a5 Michael Hanselmann
          op.result = op_result
1138 b95479a5 Michael Hanselmann
1139 b95479a5 Michael Hanselmann
          assert not waitjob
1140 be760ba8 Michael Hanselmann
1141 5fd6b694 Michael Hanselmann
        if op.status == constants.OP_STATUS_WAITLOCK:
1142 26d3fd2f Michael Hanselmann
          # Couldn't get locks in time
1143 26d3fd2f Michael Hanselmann
          assert not op.end_timestamp
1144 be760ba8 Michael Hanselmann
        else:
1145 26d3fd2f Michael Hanselmann
          # Finalize opcode
1146 26d3fd2f Michael Hanselmann
          op.end_timestamp = TimeStampNow()
1147 be760ba8 Michael Hanselmann
1148 26d3fd2f Michael Hanselmann
          if op.status == constants.OP_STATUS_CANCELING:
1149 26d3fd2f Michael Hanselmann
            assert not compat.any(i.status != constants.OP_STATUS_CANCELING
1150 26d3fd2f Michael Hanselmann
                                  for i in job.ops[opctx.index:])
1151 26d3fd2f Michael Hanselmann
          else:
1152 26d3fd2f Michael Hanselmann
            assert op.status in constants.OPS_FINALIZED
1153 be760ba8 Michael Hanselmann
1154 b95479a5 Michael Hanselmann
      if op.status == constants.OP_STATUS_WAITLOCK or waitjob:
1155 be760ba8 Michael Hanselmann
        finalize = False
1156 be760ba8 Michael Hanselmann
1157 b95479a5 Michael Hanselmann
        if not waitjob and opctx.CheckPriorityIncrease():
1158 5fd6b694 Michael Hanselmann
          # Priority was changed, need to update on-disk file
1159 5fd6b694 Michael Hanselmann
          queue.UpdateJobUnlocked(job)
1160 be760ba8 Michael Hanselmann
1161 26d3fd2f Michael Hanselmann
        # Keep around for another round
1162 26d3fd2f Michael Hanselmann
        job.cur_opctx = opctx
1163 be760ba8 Michael Hanselmann
1164 26d3fd2f Michael Hanselmann
        assert (op.priority <= constants.OP_PRIO_LOWEST and
1165 26d3fd2f Michael Hanselmann
                op.priority >= constants.OP_PRIO_HIGHEST)
1166 be760ba8 Michael Hanselmann
1167 26d3fd2f Michael Hanselmann
        # In no case must the status be finalized here
1168 5fd6b694 Michael Hanselmann
        assert job.CalcStatus() == constants.JOB_STATUS_WAITLOCK
1169 be760ba8 Michael Hanselmann
1170 be760ba8 Michael Hanselmann
      else:
1171 26d3fd2f Michael Hanselmann
        # Ensure all opcodes so far have been successful
1172 26d3fd2f Michael Hanselmann
        assert (opctx.index == 0 or
1173 26d3fd2f Michael Hanselmann
                compat.all(i.status == constants.OP_STATUS_SUCCESS
1174 26d3fd2f Michael Hanselmann
                           for i in job.ops[:opctx.index]))
1175 26d3fd2f Michael Hanselmann
1176 26d3fd2f Michael Hanselmann
        # Reset context
1177 26d3fd2f Michael Hanselmann
        job.cur_opctx = None
1178 26d3fd2f Michael Hanselmann
1179 26d3fd2f Michael Hanselmann
        if op.status == constants.OP_STATUS_SUCCESS:
1180 26d3fd2f Michael Hanselmann
          finalize = False
1181 26d3fd2f Michael Hanselmann
1182 26d3fd2f Michael Hanselmann
        elif op.status == constants.OP_STATUS_ERROR:
1183 26d3fd2f Michael Hanselmann
          # Ensure failed opcode has an exception as its result
1184 26d3fd2f Michael Hanselmann
          assert errors.GetEncodedError(job.ops[opctx.index].result)
1185 26d3fd2f Michael Hanselmann
1186 26d3fd2f Michael Hanselmann
          to_encode = errors.OpExecError("Preceding opcode failed")
1187 26d3fd2f Michael Hanselmann
          job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
1188 26d3fd2f Michael Hanselmann
                                _EncodeOpError(to_encode))
1189 26d3fd2f Michael Hanselmann
          finalize = True
1190 be760ba8 Michael Hanselmann
1191 26d3fd2f Michael Hanselmann
          # Consistency check
1192 26d3fd2f Michael Hanselmann
          assert compat.all(i.status == constants.OP_STATUS_ERROR and
1193 26d3fd2f Michael Hanselmann
                            errors.GetEncodedError(i.result)
1194 26d3fd2f Michael Hanselmann
                            for i in job.ops[opctx.index:])
1195 be760ba8 Michael Hanselmann
1196 26d3fd2f Michael Hanselmann
        elif op.status == constants.OP_STATUS_CANCELING:
1197 26d3fd2f Michael Hanselmann
          job.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
1198 26d3fd2f Michael Hanselmann
                                "Job canceled by request")
1199 26d3fd2f Michael Hanselmann
          finalize = True
1200 26d3fd2f Michael Hanselmann
1201 26d3fd2f Michael Hanselmann
        else:
1202 26d3fd2f Michael Hanselmann
          raise errors.ProgrammerError("Unknown status '%s'" % op.status)
1203 26d3fd2f Michael Hanselmann
1204 66bd7445 Michael Hanselmann
        if opctx.index == (opcount - 1):
1205 66bd7445 Michael Hanselmann
          # Finalize on last opcode
1206 66bd7445 Michael Hanselmann
          finalize = True
1207 66bd7445 Michael Hanselmann
1208 66bd7445 Michael Hanselmann
        if finalize:
1209 26d3fd2f Michael Hanselmann
          # All opcodes have been run, finalize job
1210 66bd7445 Michael Hanselmann
          job.Finalize()
1211 26d3fd2f Michael Hanselmann
1212 26d3fd2f Michael Hanselmann
        # Write to disk. If the job status is final, this is the final write
1213 26d3fd2f Michael Hanselmann
        # allowed. Once the file has been written, it can be archived anytime.
1214 26d3fd2f Michael Hanselmann
        queue.UpdateJobUnlocked(job)
1215 be760ba8 Michael Hanselmann
1216 b95479a5 Michael Hanselmann
        assert not waitjob
1217 b95479a5 Michael Hanselmann
1218 66bd7445 Michael Hanselmann
        if finalize:
1219 26d3fd2f Michael Hanselmann
          logging.info("Finished job %s, status = %s", job.id, job.CalcStatus())
1220 75d81fc8 Michael Hanselmann
          return self.FINISHED
1221 be760ba8 Michael Hanselmann
1222 b95479a5 Michael Hanselmann
      assert not waitjob or queue.depmgr.JobWaiting(job)
1223 b95479a5 Michael Hanselmann
1224 75d81fc8 Michael Hanselmann
      if waitjob:
1225 75d81fc8 Michael Hanselmann
        return self.WAITDEP
1226 75d81fc8 Michael Hanselmann
      else:
1227 75d81fc8 Michael Hanselmann
        return self.DEFER
1228 be760ba8 Michael Hanselmann
    finally:
1229 c0f6d0d8 Michael Hanselmann
      assert job.writable, "Job became read-only while being processed"
1230 be760ba8 Michael Hanselmann
      queue.release()
1231 be760ba8 Michael Hanselmann
1232 be760ba8 Michael Hanselmann
1233 031a3e57 Michael Hanselmann
class _JobQueueWorker(workerpool.BaseWorker):
1234 031a3e57 Michael Hanselmann
  """The actual job workers.
1235 031a3e57 Michael Hanselmann

1236 031a3e57 Michael Hanselmann
  """
1237 7260cfbe Iustin Pop
  def RunTask(self, job): # pylint: disable-msg=W0221
1238 e2715f69 Michael Hanselmann
    """Job executor.
1239 e2715f69 Michael Hanselmann

1240 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
1241 ea03467c Iustin Pop
    @param job: the job to be processed
1242 ea03467c Iustin Pop

1243 e2715f69 Michael Hanselmann
    """
1244 f8a4adfa Michael Hanselmann
    assert job.writable, "Expected writable job"
1245 f8a4adfa Michael Hanselmann
1246 b95479a5 Michael Hanselmann
    # Ensure only one worker is active on a single job. If a job registers for
1247 b95479a5 Michael Hanselmann
    # a dependency job, and the other job notifies before the first worker is
1248 b95479a5 Michael Hanselmann
    # done, the job can end up in the tasklist more than once.
1249 b95479a5 Michael Hanselmann
    job.processor_lock.acquire()
1250 b95479a5 Michael Hanselmann
    try:
1251 b95479a5 Michael Hanselmann
      return self._RunTaskInner(job)
1252 b95479a5 Michael Hanselmann
    finally:
1253 b95479a5 Michael Hanselmann
      job.processor_lock.release()
1254 b95479a5 Michael Hanselmann
1255 b95479a5 Michael Hanselmann
  def _RunTaskInner(self, job):
1256 b95479a5 Michael Hanselmann
    """Executes a job.
1257 b95479a5 Michael Hanselmann

1258 b95479a5 Michael Hanselmann
    Must be called with per-job lock acquired.
1259 b95479a5 Michael Hanselmann

1260 b95479a5 Michael Hanselmann
    """
1261 be760ba8 Michael Hanselmann
    queue = job.queue
1262 be760ba8 Michael Hanselmann
    assert queue == self.pool.queue
1263 be760ba8 Michael Hanselmann
1264 0aeeb6e3 Michael Hanselmann
    setname_fn = lambda op: self.SetTaskName(self._GetWorkerName(job, op))
1265 0aeeb6e3 Michael Hanselmann
    setname_fn(None)
1266 daba67c7 Michael Hanselmann
1267 be760ba8 Michael Hanselmann
    proc = mcpu.Processor(queue.context, job.id)
1268 be760ba8 Michael Hanselmann
1269 0aeeb6e3 Michael Hanselmann
    # Create wrapper for setting thread name
1270 0aeeb6e3 Michael Hanselmann
    wrap_execop_fn = compat.partial(self._WrapExecOpCode, setname_fn,
1271 0aeeb6e3 Michael Hanselmann
                                    proc.ExecOpCode)
1272 0aeeb6e3 Michael Hanselmann
1273 75d81fc8 Michael Hanselmann
    result = _JobProcessor(queue, wrap_execop_fn, job)()
1274 75d81fc8 Michael Hanselmann
1275 75d81fc8 Michael Hanselmann
    if result == _JobProcessor.FINISHED:
1276 75d81fc8 Michael Hanselmann
      # Notify waiting jobs
1277 75d81fc8 Michael Hanselmann
      queue.depmgr.NotifyWaiters(job.id)
1278 75d81fc8 Michael Hanselmann
1279 75d81fc8 Michael Hanselmann
    elif result == _JobProcessor.DEFER:
1280 be760ba8 Michael Hanselmann
      # Schedule again
1281 26d3fd2f Michael Hanselmann
      raise workerpool.DeferTask(priority=job.CalcPriority())
1282 e2715f69 Michael Hanselmann
1283 75d81fc8 Michael Hanselmann
    elif result == _JobProcessor.WAITDEP:
1284 75d81fc8 Michael Hanselmann
      # No-op, dependency manager will re-schedule
1285 75d81fc8 Michael Hanselmann
      pass
1286 75d81fc8 Michael Hanselmann
1287 75d81fc8 Michael Hanselmann
    else:
1288 75d81fc8 Michael Hanselmann
      raise errors.ProgrammerError("Job processor returned unknown status %s" %
1289 75d81fc8 Michael Hanselmann
                                   (result, ))
1290 75d81fc8 Michael Hanselmann
1291 0aeeb6e3 Michael Hanselmann
  @staticmethod
1292 0aeeb6e3 Michael Hanselmann
  def _WrapExecOpCode(setname_fn, execop_fn, op, *args, **kwargs):
1293 0aeeb6e3 Michael Hanselmann
    """Updates the worker thread name to include a short summary of the opcode.
1294 0aeeb6e3 Michael Hanselmann

1295 0aeeb6e3 Michael Hanselmann
    @param setname_fn: Callable setting worker thread name
1296 0aeeb6e3 Michael Hanselmann
    @param execop_fn: Callable for executing opcode (usually
1297 0aeeb6e3 Michael Hanselmann
                      L{mcpu.Processor.ExecOpCode})
1298 0aeeb6e3 Michael Hanselmann

1299 0aeeb6e3 Michael Hanselmann
    """
1300 0aeeb6e3 Michael Hanselmann
    setname_fn(op)
1301 0aeeb6e3 Michael Hanselmann
    try:
1302 0aeeb6e3 Michael Hanselmann
      return execop_fn(op, *args, **kwargs)
1303 0aeeb6e3 Michael Hanselmann
    finally:
1304 0aeeb6e3 Michael Hanselmann
      setname_fn(None)
1305 0aeeb6e3 Michael Hanselmann
1306 0aeeb6e3 Michael Hanselmann
  @staticmethod
1307 0aeeb6e3 Michael Hanselmann
  def _GetWorkerName(job, op):
1308 0aeeb6e3 Michael Hanselmann
    """Sets the worker thread name.
1309 0aeeb6e3 Michael Hanselmann

1310 0aeeb6e3 Michael Hanselmann
    @type job: L{_QueuedJob}
1311 0aeeb6e3 Michael Hanselmann
    @type op: L{opcodes.OpCode}
1312 0aeeb6e3 Michael Hanselmann

1313 0aeeb6e3 Michael Hanselmann
    """
1314 0aeeb6e3 Michael Hanselmann
    parts = ["Job%s" % job.id]
1315 0aeeb6e3 Michael Hanselmann
1316 0aeeb6e3 Michael Hanselmann
    if op:
1317 0aeeb6e3 Michael Hanselmann
      parts.append(op.TinySummary())
1318 0aeeb6e3 Michael Hanselmann
1319 0aeeb6e3 Michael Hanselmann
    return "/".join(parts)
1320 0aeeb6e3 Michael Hanselmann
1321 e2715f69 Michael Hanselmann
1322 e2715f69 Michael Hanselmann
class _JobQueueWorkerPool(workerpool.WorkerPool):
1323 ea03467c Iustin Pop
  """Simple class implementing a job-processing workerpool.
1324 ea03467c Iustin Pop

1325 ea03467c Iustin Pop
  """
1326 5bdce580 Michael Hanselmann
  def __init__(self, queue):
1327 0aeeb6e3 Michael Hanselmann
    super(_JobQueueWorkerPool, self).__init__("Jq",
1328 89e2b4d2 Michael Hanselmann
                                              JOBQUEUE_THREADS,
1329 e2715f69 Michael Hanselmann
                                              _JobQueueWorker)
1330 5bdce580 Michael Hanselmann
    self.queue = queue
1331 e2715f69 Michael Hanselmann
1332 e2715f69 Michael Hanselmann
1333 b95479a5 Michael Hanselmann
class _JobDependencyManager:
1334 b95479a5 Michael Hanselmann
  """Keeps track of job dependencies.
1335 b95479a5 Michael Hanselmann

1336 b95479a5 Michael Hanselmann
  """
1337 b95479a5 Michael Hanselmann
  (WAIT,
1338 b95479a5 Michael Hanselmann
   ERROR,
1339 b95479a5 Michael Hanselmann
   CANCEL,
1340 b95479a5 Michael Hanselmann
   CONTINUE,
1341 b95479a5 Michael Hanselmann
   WRONGSTATUS) = range(1, 6)
1342 b95479a5 Michael Hanselmann
1343 b95479a5 Michael Hanselmann
  # TODO: Export waiter information to lock monitor
1344 b95479a5 Michael Hanselmann
1345 b95479a5 Michael Hanselmann
  def __init__(self, getstatus_fn, enqueue_fn):
1346 b95479a5 Michael Hanselmann
    """Initializes this class.
1347 b95479a5 Michael Hanselmann

1348 b95479a5 Michael Hanselmann
    """
1349 b95479a5 Michael Hanselmann
    self._getstatus_fn = getstatus_fn
1350 b95479a5 Michael Hanselmann
    self._enqueue_fn = enqueue_fn
1351 b95479a5 Michael Hanselmann
1352 b95479a5 Michael Hanselmann
    self._waiters = {}
1353 b95479a5 Michael Hanselmann
    self._lock = locking.SharedLock("JobDepMgr")
1354 b95479a5 Michael Hanselmann
1355 b95479a5 Michael Hanselmann
  @locking.ssynchronized(_LOCK, shared=1)
1356 b95479a5 Michael Hanselmann
  def JobWaiting(self, job):
1357 b95479a5 Michael Hanselmann
    """Checks if a job is waiting.
1358 b95479a5 Michael Hanselmann

1359 b95479a5 Michael Hanselmann
    """
1360 b95479a5 Michael Hanselmann
    return compat.any(job in jobs
1361 b95479a5 Michael Hanselmann
                      for jobs in self._waiters.values())
1362 b95479a5 Michael Hanselmann
1363 b95479a5 Michael Hanselmann
  @locking.ssynchronized(_LOCK)
1364 b95479a5 Michael Hanselmann
  def CheckAndRegister(self, job, dep_job_id, dep_status):
1365 b95479a5 Michael Hanselmann
    """Checks if a dependency job has the requested status.
1366 b95479a5 Michael Hanselmann

1367 b95479a5 Michael Hanselmann
    If the other job is not yet in a finalized status, the calling job will be
1368 b95479a5 Michael Hanselmann
    notified (re-added to the workerpool) at a later point.
1369 b95479a5 Michael Hanselmann

1370 b95479a5 Michael Hanselmann
    @type job: L{_QueuedJob}
1371 b95479a5 Michael Hanselmann
    @param job: Job object
1372 b95479a5 Michael Hanselmann
    @type dep_job_id: string
1373 b95479a5 Michael Hanselmann
    @param dep_job_id: ID of dependency job
1374 b95479a5 Michael Hanselmann
    @type dep_status: list
1375 b95479a5 Michael Hanselmann
    @param dep_status: Required status
1376 b95479a5 Michael Hanselmann

1377 b95479a5 Michael Hanselmann
    """
1378 b95479a5 Michael Hanselmann
    assert ht.TString(job.id)
1379 b95479a5 Michael Hanselmann
    assert ht.TString(dep_job_id)
1380 b95479a5 Michael Hanselmann
    assert ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))(dep_status)
1381 b95479a5 Michael Hanselmann
1382 b95479a5 Michael Hanselmann
    if job.id == dep_job_id:
1383 b95479a5 Michael Hanselmann
      return (self.ERROR, "Job can't depend on itself")
1384 b95479a5 Michael Hanselmann
1385 b95479a5 Michael Hanselmann
    # Get status of dependency job
1386 b95479a5 Michael Hanselmann
    try:
1387 b95479a5 Michael Hanselmann
      status = self._getstatus_fn(dep_job_id)
1388 b95479a5 Michael Hanselmann
    except errors.JobLost, err:
1389 b95479a5 Michael Hanselmann
      return (self.ERROR, "Dependency error: %s" % err)
1390 b95479a5 Michael Hanselmann
1391 b95479a5 Michael Hanselmann
    assert status in constants.JOB_STATUS_ALL
1392 b95479a5 Michael Hanselmann
1393 b95479a5 Michael Hanselmann
    job_id_waiters = self._waiters.setdefault(dep_job_id, set())
1394 b95479a5 Michael Hanselmann
1395 b95479a5 Michael Hanselmann
    if status not in constants.JOBS_FINALIZED:
1396 b95479a5 Michael Hanselmann
      # Register for notification and wait for job to finish
1397 b95479a5 Michael Hanselmann
      job_id_waiters.add(job)
1398 b95479a5 Michael Hanselmann
      return (self.WAIT,
1399 b95479a5 Michael Hanselmann
              "Need to wait for job %s, wanted status '%s'" %
1400 b95479a5 Michael Hanselmann
              (dep_job_id, dep_status))
1401 b95479a5 Michael Hanselmann
1402 b95479a5 Michael Hanselmann
    # Remove from waiters list
1403 b95479a5 Michael Hanselmann
    if job in job_id_waiters:
1404 b95479a5 Michael Hanselmann
      job_id_waiters.remove(job)
1405 b95479a5 Michael Hanselmann
1406 b95479a5 Michael Hanselmann
    if (status == constants.JOB_STATUS_CANCELED and
1407 b95479a5 Michael Hanselmann
        constants.JOB_STATUS_CANCELED not in dep_status):
1408 b95479a5 Michael Hanselmann
      return (self.CANCEL, "Dependency job %s was cancelled" % dep_job_id)
1409 b95479a5 Michael Hanselmann
1410 b95479a5 Michael Hanselmann
    elif not dep_status or status in dep_status:
1411 b95479a5 Michael Hanselmann
      return (self.CONTINUE,
1412 b95479a5 Michael Hanselmann
              "Dependency job %s finished with status '%s'" %
1413 b95479a5 Michael Hanselmann
              (dep_job_id, status))
1414 b95479a5 Michael Hanselmann
1415 b95479a5 Michael Hanselmann
    else:
1416 b95479a5 Michael Hanselmann
      return (self.WRONGSTATUS,
1417 b95479a5 Michael Hanselmann
              "Dependency job %s finished with status '%s',"
1418 b95479a5 Michael Hanselmann
              " not one of '%s' as required" %
1419 b95479a5 Michael Hanselmann
              (dep_job_id, status, utils.CommaJoin(dep_status)))
1420 b95479a5 Michael Hanselmann
1421 b95479a5 Michael Hanselmann
  @locking.ssynchronized(_LOCK)
1422 b95479a5 Michael Hanselmann
  def NotifyWaiters(self, job_id):
1423 b95479a5 Michael Hanselmann
    """Notifies all jobs waiting for a certain job ID.
1424 b95479a5 Michael Hanselmann

1425 b95479a5 Michael Hanselmann
    @type job_id: string
1426 b95479a5 Michael Hanselmann
    @param job_id: Job ID
1427 b95479a5 Michael Hanselmann

1428 b95479a5 Michael Hanselmann
    """
1429 b95479a5 Michael Hanselmann
    assert ht.TString(job_id)
1430 b95479a5 Michael Hanselmann
1431 b95479a5 Michael Hanselmann
    jobs = self._waiters.pop(job_id, None)
1432 b95479a5 Michael Hanselmann
    if jobs:
1433 b95479a5 Michael Hanselmann
      # Re-add jobs to workerpool
1434 b95479a5 Michael Hanselmann
      logging.debug("Re-adding %s jobs which were waiting for job %s",
1435 b95479a5 Michael Hanselmann
                    len(jobs), job_id)
1436 b95479a5 Michael Hanselmann
      self._enqueue_fn(jobs)
1437 b95479a5 Michael Hanselmann
1438 b95479a5 Michael Hanselmann
    # Remove all jobs without actual waiters
1439 b95479a5 Michael Hanselmann
    for job_id in [job_id for (job_id, waiters) in self._waiters.items()
1440 b95479a5 Michael Hanselmann
                   if not waiters]:
1441 b95479a5 Michael Hanselmann
      del self._waiters[job_id]
1442 b95479a5 Michael Hanselmann
1443 b95479a5 Michael Hanselmann
1444 6c881c52 Iustin Pop
def _RequireOpenQueue(fn):
1445 6c881c52 Iustin Pop
  """Decorator for "public" functions.
1446 ea03467c Iustin Pop

1447 6c881c52 Iustin Pop
  This function should be used for all 'public' functions. That is,
1448 6c881c52 Iustin Pop
  functions usually called from other classes. Note that this should
1449 6c881c52 Iustin Pop
  be applied only to methods (not plain functions), since it expects
1450 6c881c52 Iustin Pop
  that the decorated function is called with a first argument that has
1451 a71f9c7d Guido Trotter
  a '_queue_filelock' argument.
1452 ea03467c Iustin Pop

1453 99bd4f0a Guido Trotter
  @warning: Use this decorator only after locking.ssynchronized
1454 f1da30e6 Michael Hanselmann

1455 6c881c52 Iustin Pop
  Example::
1456 ebb80afa Guido Trotter
    @locking.ssynchronized(_LOCK)
1457 6c881c52 Iustin Pop
    @_RequireOpenQueue
1458 6c881c52 Iustin Pop
    def Example(self):
1459 6c881c52 Iustin Pop
      pass
1460 db37da70 Michael Hanselmann

1461 6c881c52 Iustin Pop
  """
1462 6c881c52 Iustin Pop
  def wrapper(self, *args, **kwargs):
1463 7260cfbe Iustin Pop
    # pylint: disable-msg=W0212
1464 a71f9c7d Guido Trotter
    assert self._queue_filelock is not None, "Queue should be open"
1465 6c881c52 Iustin Pop
    return fn(self, *args, **kwargs)
1466 6c881c52 Iustin Pop
  return wrapper
1467 db37da70 Michael Hanselmann
1468 db37da70 Michael Hanselmann
1469 6c881c52 Iustin Pop
class JobQueue(object):
1470 6c881c52 Iustin Pop
  """Queue used to manage the jobs.
1471 db37da70 Michael Hanselmann

1472 6c881c52 Iustin Pop
  @cvar _RE_JOB_FILE: regex matching the valid job file names
1473 6c881c52 Iustin Pop

1474 6c881c52 Iustin Pop
  """
1475 6c881c52 Iustin Pop
  _RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
1476 db37da70 Michael Hanselmann
1477 85f03e0d Michael Hanselmann
  def __init__(self, context):
1478 ea03467c Iustin Pop
    """Constructor for JobQueue.
1479 ea03467c Iustin Pop

1480 ea03467c Iustin Pop
    The constructor will initialize the job queue object and then
1481 ea03467c Iustin Pop
    start loading the current jobs from disk, either for starting them
1482 ea03467c Iustin Pop
    (if they were queue) or for aborting them (if they were already
1483 ea03467c Iustin Pop
    running).
1484 ea03467c Iustin Pop

1485 ea03467c Iustin Pop
    @type context: GanetiContext
1486 ea03467c Iustin Pop
    @param context: the context object for access to the configuration
1487 ea03467c Iustin Pop
        data and other ganeti objects
1488 ea03467c Iustin Pop

1489 ea03467c Iustin Pop
    """
1490 5bdce580 Michael Hanselmann
    self.context = context
1491 5685c1a5 Michael Hanselmann
    self._memcache = weakref.WeakValueDictionary()
1492 b705c7a6 Manuel Franceschini
    self._my_hostname = netutils.Hostname.GetSysName()
1493 f1da30e6 Michael Hanselmann
1494 ebb80afa Guido Trotter
    # The Big JobQueue lock. If a code block or method acquires it in shared
1495 ebb80afa Guido Trotter
    # mode safe it must guarantee concurrency with all the code acquiring it in
1496 ebb80afa Guido Trotter
    # shared mode, including itself. In order not to acquire it at all
1497 ebb80afa Guido Trotter
    # concurrency must be guaranteed with all code acquiring it in shared mode
1498 ebb80afa Guido Trotter
    # and all code acquiring it exclusively.
1499 7f93570a Iustin Pop
    self._lock = locking.SharedLock("JobQueue")
1500 ebb80afa Guido Trotter
1501 ebb80afa Guido Trotter
    self.acquire = self._lock.acquire
1502 ebb80afa Guido Trotter
    self.release = self._lock.release
1503 85f03e0d Michael Hanselmann
1504 a71f9c7d Guido Trotter
    # Initialize the queue, and acquire the filelock.
1505 a71f9c7d Guido Trotter
    # This ensures no other process is working on the job queue.
1506 a71f9c7d Guido Trotter
    self._queue_filelock = jstore.InitAndVerifyQueue(must_lock=True)
1507 f1da30e6 Michael Hanselmann
1508 04ab05ce Michael Hanselmann
    # Read serial file
1509 04ab05ce Michael Hanselmann
    self._last_serial = jstore.ReadSerial()
1510 04ab05ce Michael Hanselmann
    assert self._last_serial is not None, ("Serial file was modified between"
1511 04ab05ce Michael Hanselmann
                                           " check in jstore and here")
1512 c4beba1c Iustin Pop
1513 23752136 Michael Hanselmann
    # Get initial list of nodes
1514 99aabbed Iustin Pop
    self._nodes = dict((n.name, n.primary_ip)
1515 59303563 Iustin Pop
                       for n in self.context.cfg.GetAllNodesInfo().values()
1516 59303563 Iustin Pop
                       if n.master_candidate)
1517 8e00939c Michael Hanselmann
1518 8e00939c Michael Hanselmann
    # Remove master node
1519 d8e0dc17 Guido Trotter
    self._nodes.pop(self._my_hostname, None)
1520 23752136 Michael Hanselmann
1521 23752136 Michael Hanselmann
    # TODO: Check consistency across nodes
1522 23752136 Michael Hanselmann
1523 20571a26 Guido Trotter
    self._queue_size = 0
1524 20571a26 Guido Trotter
    self._UpdateQueueSizeUnlocked()
1525 ff699aa9 Michael Hanselmann
    self._drained = jstore.CheckDrainFlag()
1526 20571a26 Guido Trotter
1527 b95479a5 Michael Hanselmann
    # Job dependencies
1528 b95479a5 Michael Hanselmann
    self.depmgr = _JobDependencyManager(self._GetJobStatusForDependencies,
1529 b95479a5 Michael Hanselmann
                                        self._EnqueueJobs)
1530 b95479a5 Michael Hanselmann
1531 85f03e0d Michael Hanselmann
    # Setup worker pool
1532 5bdce580 Michael Hanselmann
    self._wpool = _JobQueueWorkerPool(self)
1533 85f03e0d Michael Hanselmann
    try:
1534 de9d02c7 Michael Hanselmann
      self._InspectQueue()
1535 de9d02c7 Michael Hanselmann
    except:
1536 de9d02c7 Michael Hanselmann
      self._wpool.TerminateWorkers()
1537 de9d02c7 Michael Hanselmann
      raise
1538 711b5124 Michael Hanselmann
1539 de9d02c7 Michael Hanselmann
  @locking.ssynchronized(_LOCK)
1540 de9d02c7 Michael Hanselmann
  @_RequireOpenQueue
1541 de9d02c7 Michael Hanselmann
  def _InspectQueue(self):
1542 de9d02c7 Michael Hanselmann
    """Loads the whole job queue and resumes unfinished jobs.
1543 de9d02c7 Michael Hanselmann

1544 de9d02c7 Michael Hanselmann
    This function needs the lock here because WorkerPool.AddTask() may start a
1545 de9d02c7 Michael Hanselmann
    job while we're still doing our work.
1546 711b5124 Michael Hanselmann

1547 de9d02c7 Michael Hanselmann
    """
1548 de9d02c7 Michael Hanselmann
    logging.info("Inspecting job queue")
1549 de9d02c7 Michael Hanselmann
1550 7b5c4a69 Michael Hanselmann
    restartjobs = []
1551 7b5c4a69 Michael Hanselmann
1552 de9d02c7 Michael Hanselmann
    all_job_ids = self._GetJobIDsUnlocked()
1553 de9d02c7 Michael Hanselmann
    jobs_count = len(all_job_ids)
1554 de9d02c7 Michael Hanselmann
    lastinfo = time.time()
1555 de9d02c7 Michael Hanselmann
    for idx, job_id in enumerate(all_job_ids):
1556 de9d02c7 Michael Hanselmann
      # Give an update every 1000 jobs or 10 seconds
1557 de9d02c7 Michael Hanselmann
      if (idx % 1000 == 0 or time.time() >= (lastinfo + 10.0) or
1558 de9d02c7 Michael Hanselmann
          idx == (jobs_count - 1)):
1559 de9d02c7 Michael Hanselmann
        logging.info("Job queue inspection: %d/%d (%0.1f %%)",
1560 de9d02c7 Michael Hanselmann
                     idx, jobs_count - 1, 100.0 * (idx + 1) / jobs_count)
1561 711b5124 Michael Hanselmann
        lastinfo = time.time()
1562 94ed59a5 Iustin Pop
1563 de9d02c7 Michael Hanselmann
      job = self._LoadJobUnlocked(job_id)
1564 85f03e0d Michael Hanselmann
1565 de9d02c7 Michael Hanselmann
      # a failure in loading the job can cause 'None' to be returned
1566 de9d02c7 Michael Hanselmann
      if job is None:
1567 de9d02c7 Michael Hanselmann
        continue
1568 85f03e0d Michael Hanselmann
1569 de9d02c7 Michael Hanselmann
      status = job.CalcStatus()
1570 711b5124 Michael Hanselmann
1571 320d1daf Michael Hanselmann
      if status == constants.JOB_STATUS_QUEUED:
1572 7b5c4a69 Michael Hanselmann
        restartjobs.append(job)
1573 de9d02c7 Michael Hanselmann
1574 de9d02c7 Michael Hanselmann
      elif status in (constants.JOB_STATUS_RUNNING,
1575 5ef699a0 Michael Hanselmann
                      constants.JOB_STATUS_WAITLOCK,
1576 de9d02c7 Michael Hanselmann
                      constants.JOB_STATUS_CANCELING):
1577 de9d02c7 Michael Hanselmann
        logging.warning("Unfinished job %s found: %s", job.id, job)
1578 320d1daf Michael Hanselmann
1579 320d1daf Michael Hanselmann
        if status == constants.JOB_STATUS_WAITLOCK:
1580 320d1daf Michael Hanselmann
          # Restart job
1581 320d1daf Michael Hanselmann
          job.MarkUnfinishedOps(constants.OP_STATUS_QUEUED, None)
1582 320d1daf Michael Hanselmann
          restartjobs.append(job)
1583 320d1daf Michael Hanselmann
        else:
1584 320d1daf Michael Hanselmann
          job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
1585 320d1daf Michael Hanselmann
                                "Unclean master daemon shutdown")
1586 45df0793 Michael Hanselmann
          job.Finalize()
1587 320d1daf Michael Hanselmann
1588 de9d02c7 Michael Hanselmann
        self.UpdateJobUnlocked(job)
1589 de9d02c7 Michael Hanselmann
1590 7b5c4a69 Michael Hanselmann
    if restartjobs:
1591 7b5c4a69 Michael Hanselmann
      logging.info("Restarting %s jobs", len(restartjobs))
1592 75d81fc8 Michael Hanselmann
      self._EnqueueJobsUnlocked(restartjobs)
1593 7b5c4a69 Michael Hanselmann
1594 de9d02c7 Michael Hanselmann
    logging.info("Job queue inspection finished")
1595 85f03e0d Michael Hanselmann
1596 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1597 d2e03a33 Michael Hanselmann
  @_RequireOpenQueue
1598 99aabbed Iustin Pop
  def AddNode(self, node):
1599 99aabbed Iustin Pop
    """Register a new node with the queue.
1600 99aabbed Iustin Pop

1601 99aabbed Iustin Pop
    @type node: L{objects.Node}
1602 99aabbed Iustin Pop
    @param node: the node object to be added
1603 99aabbed Iustin Pop

1604 99aabbed Iustin Pop
    """
1605 99aabbed Iustin Pop
    node_name = node.name
1606 d2e03a33 Michael Hanselmann
    assert node_name != self._my_hostname
1607 23752136 Michael Hanselmann
1608 9f774ee8 Michael Hanselmann
    # Clean queue directory on added node
1609 c8457ce7 Iustin Pop
    result = rpc.RpcRunner.call_jobqueue_purge(node_name)
1610 3cebe102 Michael Hanselmann
    msg = result.fail_msg
1611 c8457ce7 Iustin Pop
    if msg:
1612 c8457ce7 Iustin Pop
      logging.warning("Cannot cleanup queue directory on node %s: %s",
1613 c8457ce7 Iustin Pop
                      node_name, msg)
1614 23752136 Michael Hanselmann
1615 59303563 Iustin Pop
    if not node.master_candidate:
1616 59303563 Iustin Pop
      # remove if existing, ignoring errors
1617 59303563 Iustin Pop
      self._nodes.pop(node_name, None)
1618 59303563 Iustin Pop
      # and skip the replication of the job ids
1619 59303563 Iustin Pop
      return
1620 59303563 Iustin Pop
1621 d2e03a33 Michael Hanselmann
    # Upload the whole queue excluding archived jobs
1622 d2e03a33 Michael Hanselmann
    files = [self._GetJobPath(job_id) for job_id in self._GetJobIDsUnlocked()]
1623 23752136 Michael Hanselmann
1624 d2e03a33 Michael Hanselmann
    # Upload current serial file
1625 d2e03a33 Michael Hanselmann
    files.append(constants.JOB_QUEUE_SERIAL_FILE)
1626 d2e03a33 Michael Hanselmann
1627 d2e03a33 Michael Hanselmann
    for file_name in files:
1628 9f774ee8 Michael Hanselmann
      # Read file content
1629 13998ef2 Michael Hanselmann
      content = utils.ReadFile(file_name)
1630 9f774ee8 Michael Hanselmann
1631 a3811745 Michael Hanselmann
      result = rpc.RpcRunner.call_jobqueue_update([node_name],
1632 a3811745 Michael Hanselmann
                                                  [node.primary_ip],
1633 a3811745 Michael Hanselmann
                                                  file_name, content)
1634 3cebe102 Michael Hanselmann
      msg = result[node_name].fail_msg
1635 c8457ce7 Iustin Pop
      if msg:
1636 c8457ce7 Iustin Pop
        logging.error("Failed to upload file %s to node %s: %s",
1637 c8457ce7 Iustin Pop
                      file_name, node_name, msg)
1638 d2e03a33 Michael Hanselmann
1639 99aabbed Iustin Pop
    self._nodes[node_name] = node.primary_ip
1640 d2e03a33 Michael Hanselmann
1641 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1642 d2e03a33 Michael Hanselmann
  @_RequireOpenQueue
1643 d2e03a33 Michael Hanselmann
  def RemoveNode(self, node_name):
1644 ea03467c Iustin Pop
    """Callback called when removing nodes from the cluster.
1645 ea03467c Iustin Pop

1646 ea03467c Iustin Pop
    @type node_name: str
1647 ea03467c Iustin Pop
    @param node_name: the name of the node to remove
1648 ea03467c Iustin Pop

1649 ea03467c Iustin Pop
    """
1650 d8e0dc17 Guido Trotter
    self._nodes.pop(node_name, None)
1651 23752136 Michael Hanselmann
1652 7e950d31 Iustin Pop
  @staticmethod
1653 7e950d31 Iustin Pop
  def _CheckRpcResult(result, nodes, failmsg):
1654 ea03467c Iustin Pop
    """Verifies the status of an RPC call.
1655 ea03467c Iustin Pop

1656 ea03467c Iustin Pop
    Since we aim to keep consistency should this node (the current
1657 ea03467c Iustin Pop
    master) fail, we will log errors if our rpc fail, and especially
1658 5bbd3f7f Michael Hanselmann
    log the case when more than half of the nodes fails.
1659 ea03467c Iustin Pop

1660 ea03467c Iustin Pop
    @param result: the data as returned from the rpc call
1661 ea03467c Iustin Pop
    @type nodes: list
1662 ea03467c Iustin Pop
    @param nodes: the list of nodes we made the call to
1663 ea03467c Iustin Pop
    @type failmsg: str
1664 ea03467c Iustin Pop
    @param failmsg: the identifier to be used for logging
1665 ea03467c Iustin Pop

1666 ea03467c Iustin Pop
    """
1667 e74798c1 Michael Hanselmann
    failed = []
1668 e74798c1 Michael Hanselmann
    success = []
1669 e74798c1 Michael Hanselmann
1670 e74798c1 Michael Hanselmann
    for node in nodes:
1671 3cebe102 Michael Hanselmann
      msg = result[node].fail_msg
1672 c8457ce7 Iustin Pop
      if msg:
1673 e74798c1 Michael Hanselmann
        failed.append(node)
1674 45e0d704 Iustin Pop
        logging.error("RPC call %s (%s) failed on node %s: %s",
1675 45e0d704 Iustin Pop
                      result[node].call, failmsg, node, msg)
1676 c8457ce7 Iustin Pop
      else:
1677 c8457ce7 Iustin Pop
        success.append(node)
1678 e74798c1 Michael Hanselmann
1679 e74798c1 Michael Hanselmann
    # +1 for the master node
1680 e74798c1 Michael Hanselmann
    if (len(success) + 1) < len(failed):
1681 e74798c1 Michael Hanselmann
      # TODO: Handle failing nodes
1682 e74798c1 Michael Hanselmann
      logging.error("More than half of the nodes failed")
1683 e74798c1 Michael Hanselmann
1684 99aabbed Iustin Pop
  def _GetNodeIp(self):
1685 99aabbed Iustin Pop
    """Helper for returning the node name/ip list.
1686 99aabbed Iustin Pop

1687 ea03467c Iustin Pop
    @rtype: (list, list)
1688 ea03467c Iustin Pop
    @return: a tuple of two lists, the first one with the node
1689 ea03467c Iustin Pop
        names and the second one with the node addresses
1690 ea03467c Iustin Pop

1691 99aabbed Iustin Pop
    """
1692 e35344b4 Michael Hanselmann
    # TODO: Change to "tuple(map(list, zip(*self._nodes.items())))"?
1693 99aabbed Iustin Pop
    name_list = self._nodes.keys()
1694 99aabbed Iustin Pop
    addr_list = [self._nodes[name] for name in name_list]
1695 99aabbed Iustin Pop
    return name_list, addr_list
1696 99aabbed Iustin Pop
1697 4c36bdf5 Guido Trotter
  def _UpdateJobQueueFile(self, file_name, data, replicate):
1698 8e00939c Michael Hanselmann
    """Writes a file locally and then replicates it to all nodes.
1699 8e00939c Michael Hanselmann

1700 ea03467c Iustin Pop
    This function will replace the contents of a file on the local
1701 ea03467c Iustin Pop
    node and then replicate it to all the other nodes we have.
1702 ea03467c Iustin Pop

1703 ea03467c Iustin Pop
    @type file_name: str
1704 ea03467c Iustin Pop
    @param file_name: the path of the file to be replicated
1705 ea03467c Iustin Pop
    @type data: str
1706 ea03467c Iustin Pop
    @param data: the new contents of the file
1707 4c36bdf5 Guido Trotter
    @type replicate: boolean
1708 4c36bdf5 Guido Trotter
    @param replicate: whether to spread the changes to the remote nodes
1709 ea03467c Iustin Pop

1710 8e00939c Michael Hanselmann
    """
1711 82b22e19 René Nussbaumer
    getents = runtime.GetEnts()
1712 82b22e19 René Nussbaumer
    utils.WriteFile(file_name, data=data, uid=getents.masterd_uid,
1713 82b22e19 René Nussbaumer
                    gid=getents.masterd_gid)
1714 8e00939c Michael Hanselmann
1715 4c36bdf5 Guido Trotter
    if replicate:
1716 4c36bdf5 Guido Trotter
      names, addrs = self._GetNodeIp()
1717 4c36bdf5 Guido Trotter
      result = rpc.RpcRunner.call_jobqueue_update(names, addrs, file_name, data)
1718 4c36bdf5 Guido Trotter
      self._CheckRpcResult(result, self._nodes, "Updating %s" % file_name)
1719 23752136 Michael Hanselmann
1720 d7fd1f28 Michael Hanselmann
  def _RenameFilesUnlocked(self, rename):
1721 ea03467c Iustin Pop
    """Renames a file locally and then replicate the change.
1722 ea03467c Iustin Pop

1723 ea03467c Iustin Pop
    This function will rename a file in the local queue directory
1724 ea03467c Iustin Pop
    and then replicate this rename to all the other nodes we have.
1725 ea03467c Iustin Pop

1726 d7fd1f28 Michael Hanselmann
    @type rename: list of (old, new)
1727 d7fd1f28 Michael Hanselmann
    @param rename: List containing tuples mapping old to new names
1728 ea03467c Iustin Pop

1729 ea03467c Iustin Pop
    """
1730 dd875d32 Michael Hanselmann
    # Rename them locally
1731 d7fd1f28 Michael Hanselmann
    for old, new in rename:
1732 d7fd1f28 Michael Hanselmann
      utils.RenameFile(old, new, mkdir=True)
1733 abc1f2ce Michael Hanselmann
1734 dd875d32 Michael Hanselmann
    # ... and on all nodes
1735 dd875d32 Michael Hanselmann
    names, addrs = self._GetNodeIp()
1736 dd875d32 Michael Hanselmann
    result = rpc.RpcRunner.call_jobqueue_rename(names, addrs, rename)
1737 dd875d32 Michael Hanselmann
    self._CheckRpcResult(result, self._nodes, "Renaming files (%r)" % rename)
1738 abc1f2ce Michael Hanselmann
1739 7e950d31 Iustin Pop
  @staticmethod
1740 7e950d31 Iustin Pop
  def _FormatJobID(job_id):
1741 ea03467c Iustin Pop
    """Convert a job ID to string format.
1742 ea03467c Iustin Pop

1743 ea03467c Iustin Pop
    Currently this just does C{str(job_id)} after performing some
1744 ea03467c Iustin Pop
    checks, but if we want to change the job id format this will
1745 ea03467c Iustin Pop
    abstract this change.
1746 ea03467c Iustin Pop

1747 ea03467c Iustin Pop
    @type job_id: int or long
1748 ea03467c Iustin Pop
    @param job_id: the numeric job id
1749 ea03467c Iustin Pop
    @rtype: str
1750 ea03467c Iustin Pop
    @return: the formatted job id
1751 ea03467c Iustin Pop

1752 ea03467c Iustin Pop
    """
1753 85f03e0d Michael Hanselmann
    if not isinstance(job_id, (int, long)):
1754 85f03e0d Michael Hanselmann
      raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id)
1755 85f03e0d Michael Hanselmann
    if job_id < 0:
1756 85f03e0d Michael Hanselmann
      raise errors.ProgrammerError("Job ID %s is negative" % job_id)
1757 85f03e0d Michael Hanselmann
1758 85f03e0d Michael Hanselmann
    return str(job_id)
1759 85f03e0d Michael Hanselmann
1760 58b22b6e Michael Hanselmann
  @classmethod
1761 58b22b6e Michael Hanselmann
  def _GetArchiveDirectory(cls, job_id):
1762 58b22b6e Michael Hanselmann
    """Returns the archive directory for a job.
1763 58b22b6e Michael Hanselmann

1764 58b22b6e Michael Hanselmann
    @type job_id: str
1765 58b22b6e Michael Hanselmann
    @param job_id: Job identifier
1766 58b22b6e Michael Hanselmann
    @rtype: str
1767 58b22b6e Michael Hanselmann
    @return: Directory name
1768 58b22b6e Michael Hanselmann

1769 58b22b6e Michael Hanselmann
    """
1770 58b22b6e Michael Hanselmann
    return str(int(job_id) / JOBS_PER_ARCHIVE_DIRECTORY)
1771 58b22b6e Michael Hanselmann
1772 009e73d0 Iustin Pop
  def _NewSerialsUnlocked(self, count):
1773 f1da30e6 Michael Hanselmann
    """Generates a new job identifier.
1774 f1da30e6 Michael Hanselmann

1775 f1da30e6 Michael Hanselmann
    Job identifiers are unique during the lifetime of a cluster.
1776 f1da30e6 Michael Hanselmann

1777 009e73d0 Iustin Pop
    @type count: integer
1778 009e73d0 Iustin Pop
    @param count: how many serials to return
1779 ea03467c Iustin Pop
    @rtype: str
1780 ea03467c Iustin Pop
    @return: a string representing the job identifier.
1781 f1da30e6 Michael Hanselmann

1782 f1da30e6 Michael Hanselmann
    """
1783 009e73d0 Iustin Pop
    assert count > 0
1784 f1da30e6 Michael Hanselmann
    # New number
1785 009e73d0 Iustin Pop
    serial = self._last_serial + count
1786 f1da30e6 Michael Hanselmann
1787 f1da30e6 Michael Hanselmann
    # Write to file
1788 4c36bdf5 Guido Trotter
    self._UpdateJobQueueFile(constants.JOB_QUEUE_SERIAL_FILE,
1789 4c36bdf5 Guido Trotter
                             "%s\n" % serial, True)
1790 f1da30e6 Michael Hanselmann
1791 009e73d0 Iustin Pop
    result = [self._FormatJobID(v)
1792 3c88bf36 Michael Hanselmann
              for v in range(self._last_serial + 1, serial + 1)]
1793 3c88bf36 Michael Hanselmann
1794 f1da30e6 Michael Hanselmann
    # Keep it only if we were able to write the file
1795 f1da30e6 Michael Hanselmann
    self._last_serial = serial
1796 f1da30e6 Michael Hanselmann
1797 3c88bf36 Michael Hanselmann
    assert len(result) == count
1798 3c88bf36 Michael Hanselmann
1799 009e73d0 Iustin Pop
    return result
1800 f1da30e6 Michael Hanselmann
1801 85f03e0d Michael Hanselmann
  @staticmethod
1802 85f03e0d Michael Hanselmann
  def _GetJobPath(job_id):
1803 ea03467c Iustin Pop
    """Returns the job file for a given job id.
1804 ea03467c Iustin Pop

1805 ea03467c Iustin Pop
    @type job_id: str
1806 ea03467c Iustin Pop
    @param job_id: the job identifier
1807 ea03467c Iustin Pop
    @rtype: str
1808 ea03467c Iustin Pop
    @return: the path to the job file
1809 ea03467c Iustin Pop

1810 ea03467c Iustin Pop
    """
1811 c4feafe8 Iustin Pop
    return utils.PathJoin(constants.QUEUE_DIR, "job-%s" % job_id)
1812 f1da30e6 Michael Hanselmann
1813 58b22b6e Michael Hanselmann
  @classmethod
1814 58b22b6e Michael Hanselmann
  def _GetArchivedJobPath(cls, job_id):
1815 ea03467c Iustin Pop
    """Returns the archived job file for a give job id.
1816 ea03467c Iustin Pop

1817 ea03467c Iustin Pop
    @type job_id: str
1818 ea03467c Iustin Pop
    @param job_id: the job identifier
1819 ea03467c Iustin Pop
    @rtype: str
1820 ea03467c Iustin Pop
    @return: the path to the archived job file
1821 ea03467c Iustin Pop

1822 ea03467c Iustin Pop
    """
1823 0411c011 Iustin Pop
    return utils.PathJoin(constants.JOB_QUEUE_ARCHIVE_DIR,
1824 0411c011 Iustin Pop
                          cls._GetArchiveDirectory(job_id), "job-%s" % job_id)
1825 0cb94105 Michael Hanselmann
1826 85a1c57d Guido Trotter
  def _GetJobIDsUnlocked(self, sort=True):
1827 911a495b Iustin Pop
    """Return all known job IDs.
1828 911a495b Iustin Pop

1829 ac0930b9 Iustin Pop
    The method only looks at disk because it's a requirement that all
1830 ac0930b9 Iustin Pop
    jobs are present on disk (so in the _memcache we don't have any
1831 ac0930b9 Iustin Pop
    extra IDs).
1832 ac0930b9 Iustin Pop

1833 85a1c57d Guido Trotter
    @type sort: boolean
1834 85a1c57d Guido Trotter
    @param sort: perform sorting on the returned job ids
1835 ea03467c Iustin Pop
    @rtype: list
1836 ea03467c Iustin Pop
    @return: the list of job IDs
1837 ea03467c Iustin Pop

1838 911a495b Iustin Pop
    """
1839 85a1c57d Guido Trotter
    jlist = []
1840 b5b8309d Guido Trotter
    for filename in utils.ListVisibleFiles(constants.QUEUE_DIR):
1841 85a1c57d Guido Trotter
      m = self._RE_JOB_FILE.match(filename)
1842 85a1c57d Guido Trotter
      if m:
1843 85a1c57d Guido Trotter
        jlist.append(m.group(1))
1844 85a1c57d Guido Trotter
    if sort:
1845 85a1c57d Guido Trotter
      jlist = utils.NiceSort(jlist)
1846 f0d874fe Iustin Pop
    return jlist
1847 911a495b Iustin Pop
1848 911a495b Iustin Pop
  def _LoadJobUnlocked(self, job_id):
1849 ea03467c Iustin Pop
    """Loads a job from the disk or memory.
1850 ea03467c Iustin Pop

1851 ea03467c Iustin Pop
    Given a job id, this will return the cached job object if
1852 ea03467c Iustin Pop
    existing, or try to load the job from the disk. If loading from
1853 ea03467c Iustin Pop
    disk, it will also add the job to the cache.
1854 ea03467c Iustin Pop

1855 ea03467c Iustin Pop
    @param job_id: the job id
1856 ea03467c Iustin Pop
    @rtype: L{_QueuedJob} or None
1857 ea03467c Iustin Pop
    @return: either None or the job object
1858 ea03467c Iustin Pop

1859 ea03467c Iustin Pop
    """
1860 5685c1a5 Michael Hanselmann
    job = self._memcache.get(job_id, None)
1861 5685c1a5 Michael Hanselmann
    if job:
1862 205d71fd Michael Hanselmann
      logging.debug("Found job %s in memcache", job_id)
1863 c0f6d0d8 Michael Hanselmann
      assert job.writable, "Found read-only job in memcache"
1864 5685c1a5 Michael Hanselmann
      return job
1865 ac0930b9 Iustin Pop
1866 3d6c5566 Guido Trotter
    try:
1867 194c8ca4 Michael Hanselmann
      job = self._LoadJobFromDisk(job_id, False)
1868 aa9f8167 Iustin Pop
      if job is None:
1869 aa9f8167 Iustin Pop
        return job
1870 3d6c5566 Guido Trotter
    except errors.JobFileCorrupted:
1871 3d6c5566 Guido Trotter
      old_path = self._GetJobPath(job_id)
1872 3d6c5566 Guido Trotter
      new_path = self._GetArchivedJobPath(job_id)
1873 3d6c5566 Guido Trotter
      if old_path == new_path:
1874 3d6c5566 Guido Trotter
        # job already archived (future case)
1875 3d6c5566 Guido Trotter
        logging.exception("Can't parse job %s", job_id)
1876 3d6c5566 Guido Trotter
      else:
1877 3d6c5566 Guido Trotter
        # non-archived case
1878 3d6c5566 Guido Trotter
        logging.exception("Can't parse job %s, will archive.", job_id)
1879 3d6c5566 Guido Trotter
        self._RenameFilesUnlocked([(old_path, new_path)])
1880 3d6c5566 Guido Trotter
      return None
1881 162c8636 Guido Trotter
1882 c0f6d0d8 Michael Hanselmann
    assert job.writable, "Job just loaded is not writable"
1883 c0f6d0d8 Michael Hanselmann
1884 162c8636 Guido Trotter
    self._memcache[job_id] = job
1885 162c8636 Guido Trotter
    logging.debug("Added job %s to the cache", job_id)
1886 162c8636 Guido Trotter
    return job
1887 162c8636 Guido Trotter
1888 c0f6d0d8 Michael Hanselmann
  def _LoadJobFromDisk(self, job_id, try_archived, writable=None):
1889 162c8636 Guido Trotter
    """Load the given job file from disk.
1890 162c8636 Guido Trotter

1891 162c8636 Guido Trotter
    Given a job file, read, load and restore it in a _QueuedJob format.
1892 162c8636 Guido Trotter

1893 162c8636 Guido Trotter
    @type job_id: string
1894 162c8636 Guido Trotter
    @param job_id: job identifier
1895 194c8ca4 Michael Hanselmann
    @type try_archived: bool
1896 194c8ca4 Michael Hanselmann
    @param try_archived: Whether to try loading an archived job
1897 162c8636 Guido Trotter
    @rtype: L{_QueuedJob} or None
1898 162c8636 Guido Trotter
    @return: either None or the job object
1899 162c8636 Guido Trotter

1900 162c8636 Guido Trotter
    """
1901 c0f6d0d8 Michael Hanselmann
    path_functions = [(self._GetJobPath, True)]
1902 194c8ca4 Michael Hanselmann
1903 194c8ca4 Michael Hanselmann
    if try_archived:
1904 c0f6d0d8 Michael Hanselmann
      path_functions.append((self._GetArchivedJobPath, False))
1905 194c8ca4 Michael Hanselmann
1906 194c8ca4 Michael Hanselmann
    raw_data = None
1907 c0f6d0d8 Michael Hanselmann
    writable_default = None
1908 194c8ca4 Michael Hanselmann
1909 c0f6d0d8 Michael Hanselmann
    for (fn, writable_default) in path_functions:
1910 194c8ca4 Michael Hanselmann
      filepath = fn(job_id)
1911 194c8ca4 Michael Hanselmann
      logging.debug("Loading job from %s", filepath)
1912 194c8ca4 Michael Hanselmann
      try:
1913 194c8ca4 Michael Hanselmann
        raw_data = utils.ReadFile(filepath)
1914 194c8ca4 Michael Hanselmann
      except EnvironmentError, err:
1915 194c8ca4 Michael Hanselmann
        if err.errno != errno.ENOENT:
1916 194c8ca4 Michael Hanselmann
          raise
1917 194c8ca4 Michael Hanselmann
      else:
1918 194c8ca4 Michael Hanselmann
        break
1919 194c8ca4 Michael Hanselmann
1920 194c8ca4 Michael Hanselmann
    if not raw_data:
1921 194c8ca4 Michael Hanselmann
      return None
1922 13998ef2 Michael Hanselmann
1923 c0f6d0d8 Michael Hanselmann
    if writable is None:
1924 c0f6d0d8 Michael Hanselmann
      writable = writable_default
1925 c0f6d0d8 Michael Hanselmann
1926 94ed59a5 Iustin Pop
    try:
1927 162c8636 Guido Trotter
      data = serializer.LoadJson(raw_data)
1928 c0f6d0d8 Michael Hanselmann
      job = _QueuedJob.Restore(self, data, writable)
1929 7260cfbe Iustin Pop
    except Exception, err: # pylint: disable-msg=W0703
1930 3d6c5566 Guido Trotter
      raise errors.JobFileCorrupted(err)
1931 94ed59a5 Iustin Pop
1932 ac0930b9 Iustin Pop
    return job
1933 f1da30e6 Michael Hanselmann
1934 c0f6d0d8 Michael Hanselmann
  def SafeLoadJobFromDisk(self, job_id, try_archived, writable=None):
1935 0f9c08dc Guido Trotter
    """Load the given job file from disk.
1936 0f9c08dc Guido Trotter

1937 0f9c08dc Guido Trotter
    Given a job file, read, load and restore it in a _QueuedJob format.
1938 0f9c08dc Guido Trotter
    In case of error reading the job, it gets returned as None, and the
1939 0f9c08dc Guido Trotter
    exception is logged.
1940 0f9c08dc Guido Trotter

1941 0f9c08dc Guido Trotter
    @type job_id: string
1942 0f9c08dc Guido Trotter
    @param job_id: job identifier
1943 194c8ca4 Michael Hanselmann
    @type try_archived: bool
1944 194c8ca4 Michael Hanselmann
    @param try_archived: Whether to try loading an archived job
1945 0f9c08dc Guido Trotter
    @rtype: L{_QueuedJob} or None
1946 0f9c08dc Guido Trotter
    @return: either None or the job object
1947 0f9c08dc Guido Trotter

1948 0f9c08dc Guido Trotter
    """
1949 0f9c08dc Guido Trotter
    try:
1950 c0f6d0d8 Michael Hanselmann
      return self._LoadJobFromDisk(job_id, try_archived, writable=writable)
1951 0f9c08dc Guido Trotter
    except (errors.JobFileCorrupted, EnvironmentError):
1952 0f9c08dc Guido Trotter
      logging.exception("Can't load/parse job %s", job_id)
1953 0f9c08dc Guido Trotter
      return None
1954 0f9c08dc Guido Trotter
1955 20571a26 Guido Trotter
  def _UpdateQueueSizeUnlocked(self):
1956 20571a26 Guido Trotter
    """Update the queue size.
1957 20571a26 Guido Trotter

1958 20571a26 Guido Trotter
    """
1959 20571a26 Guido Trotter
    self._queue_size = len(self._GetJobIDsUnlocked(sort=False))
1960 20571a26 Guido Trotter
1961 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1962 20571a26 Guido Trotter
  @_RequireOpenQueue
1963 20571a26 Guido Trotter
  def SetDrainFlag(self, drain_flag):
1964 3ccafd0e Iustin Pop
    """Sets the drain flag for the queue.
1965 3ccafd0e Iustin Pop

1966 ea03467c Iustin Pop
    @type drain_flag: boolean
1967 5bbd3f7f Michael Hanselmann
    @param drain_flag: Whether to set or unset the drain flag
1968 ea03467c Iustin Pop

1969 3ccafd0e Iustin Pop
    """
1970 ff699aa9 Michael Hanselmann
    jstore.SetDrainFlag(drain_flag)
1971 20571a26 Guido Trotter
1972 20571a26 Guido Trotter
    self._drained = drain_flag
1973 20571a26 Guido Trotter
1974 3ccafd0e Iustin Pop
    return True
1975 3ccafd0e Iustin Pop
1976 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1977 009e73d0 Iustin Pop
  def _SubmitJobUnlocked(self, job_id, ops):
1978 85f03e0d Michael Hanselmann
    """Create and store a new job.
1979 f1da30e6 Michael Hanselmann

1980 85f03e0d Michael Hanselmann
    This enters the job into our job queue and also puts it on the new
1981 85f03e0d Michael Hanselmann
    queue, in order for it to be picked up by the queue processors.
1982 c3f0a12f Iustin Pop

1983 009e73d0 Iustin Pop
    @type job_id: job ID
1984 69b99987 Michael Hanselmann
    @param job_id: the job ID for the new job
1985 c3f0a12f Iustin Pop
    @type ops: list
1986 205d71fd Michael Hanselmann
    @param ops: The list of OpCodes that will become the new job.
1987 7beb1e53 Guido Trotter
    @rtype: L{_QueuedJob}
1988 7beb1e53 Guido Trotter
    @return: the job object to be queued
1989 7beb1e53 Guido Trotter
    @raise errors.JobQueueDrainError: if the job queue is marked for draining
1990 7beb1e53 Guido Trotter
    @raise errors.JobQueueFull: if the job queue has too many jobs in it
1991 e71c8147 Michael Hanselmann
    @raise errors.GenericError: If an opcode is not valid
1992 c3f0a12f Iustin Pop

1993 c3f0a12f Iustin Pop
    """
1994 20571a26 Guido Trotter
    # Ok when sharing the big job queue lock, as the drain file is created when
1995 20571a26 Guido Trotter
    # the lock is exclusive.
1996 20571a26 Guido Trotter
    if self._drained:
1997 2971c913 Iustin Pop
      raise errors.JobQueueDrainError("Job queue is drained, refusing job")
1998 f87b405e Michael Hanselmann
1999 20571a26 Guido Trotter
    if self._queue_size >= constants.JOB_QUEUE_SIZE_HARD_LIMIT:
2000 f87b405e Michael Hanselmann
      raise errors.JobQueueFull()
2001 f87b405e Michael Hanselmann
2002 c0f6d0d8 Michael Hanselmann
    job = _QueuedJob(self, job_id, ops, True)
2003 f1da30e6 Michael Hanselmann
2004 e71c8147 Michael Hanselmann
    # Check priority
2005 e71c8147 Michael Hanselmann
    for idx, op in enumerate(job.ops):
2006 e71c8147 Michael Hanselmann
      if op.priority not in constants.OP_PRIO_SUBMIT_VALID:
2007 e71c8147 Michael Hanselmann
        allowed = utils.CommaJoin(constants.OP_PRIO_SUBMIT_VALID)
2008 e71c8147 Michael Hanselmann
        raise errors.GenericError("Opcode %s has invalid priority %s, allowed"
2009 e71c8147 Michael Hanselmann
                                  " are %s" % (idx, op.priority, allowed))
2010 e71c8147 Michael Hanselmann
2011 b247c6fc Michael Hanselmann
      dependencies = getattr(op.input, opcodes.DEPEND_ATTR, None)
2012 b247c6fc Michael Hanselmann
      if not opcodes.TNoRelativeJobDependencies(dependencies):
2013 b247c6fc Michael Hanselmann
        raise errors.GenericError("Opcode %s has invalid dependencies, must"
2014 b247c6fc Michael Hanselmann
                                  " match %s: %s" %
2015 b247c6fc Michael Hanselmann
                                  (idx, opcodes.TNoRelativeJobDependencies,
2016 b247c6fc Michael Hanselmann
                                   dependencies))
2017 b247c6fc Michael Hanselmann
2018 f1da30e6 Michael Hanselmann
    # Write to disk
2019 85f03e0d Michael Hanselmann
    self.UpdateJobUnlocked(job)
2020 f1da30e6 Michael Hanselmann
2021 20571a26 Guido Trotter
    self._queue_size += 1
2022 20571a26 Guido Trotter
2023 5685c1a5 Michael Hanselmann
    logging.debug("Adding new job %s to the cache", job_id)
2024 ac0930b9 Iustin Pop
    self._memcache[job_id] = job
2025 ac0930b9 Iustin Pop
2026 7beb1e53 Guido Trotter
    return job
2027 f1da30e6 Michael Hanselmann
2028 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
2029 2971c913 Iustin Pop
  @_RequireOpenQueue
2030 2971c913 Iustin Pop
  def SubmitJob(self, ops):
2031 2971c913 Iustin Pop
    """Create and store a new job.
2032 2971c913 Iustin Pop

2033 2971c913 Iustin Pop
    @see: L{_SubmitJobUnlocked}
2034 2971c913 Iustin Pop

2035 2971c913 Iustin Pop
    """
2036 b247c6fc Michael Hanselmann
    (job_id, ) = self._NewSerialsUnlocked(1)
2037 75d81fc8 Michael Hanselmann
    self._EnqueueJobsUnlocked([self._SubmitJobUnlocked(job_id, ops)])
2038 7beb1e53 Guido Trotter
    return job_id
2039 2971c913 Iustin Pop
2040 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
2041 2971c913 Iustin Pop
  @_RequireOpenQueue
2042 2971c913 Iustin Pop
  def SubmitManyJobs(self, jobs):
2043 2971c913 Iustin Pop
    """Create and store multiple jobs.
2044 2971c913 Iustin Pop

2045 2971c913 Iustin Pop
    @see: L{_SubmitJobUnlocked}
2046 2971c913 Iustin Pop

2047 2971c913 Iustin Pop
    """
2048 009e73d0 Iustin Pop
    all_job_ids = self._NewSerialsUnlocked(len(jobs))
2049 b247c6fc Michael Hanselmann
2050 b247c6fc Michael Hanselmann
    (results, added_jobs) = \
2051 b247c6fc Michael Hanselmann
      self._SubmitManyJobsUnlocked(jobs, all_job_ids, [])
2052 7b5c4a69 Michael Hanselmann
2053 75d81fc8 Michael Hanselmann
    self._EnqueueJobsUnlocked(added_jobs)
2054 2971c913 Iustin Pop
2055 2971c913 Iustin Pop
    return results
2056 2971c913 Iustin Pop
2057 b247c6fc Michael Hanselmann
  @staticmethod
2058 b247c6fc Michael Hanselmann
  def _FormatSubmitError(msg, ops):
2059 b247c6fc Michael Hanselmann
    """Formats errors which occurred while submitting a job.
2060 b247c6fc Michael Hanselmann

2061 b247c6fc Michael Hanselmann
    """
2062 b247c6fc Michael Hanselmann
    return ("%s; opcodes %s" %
2063 b247c6fc Michael Hanselmann
            (msg, utils.CommaJoin(op.Summary() for op in ops)))
2064 b247c6fc Michael Hanselmann
2065 b247c6fc Michael Hanselmann
  @staticmethod
2066 b247c6fc Michael Hanselmann
  def _ResolveJobDependencies(resolve_fn, deps):
2067 b247c6fc Michael Hanselmann
    """Resolves relative job IDs in dependencies.
2068 b247c6fc Michael Hanselmann

2069 b247c6fc Michael Hanselmann
    @type resolve_fn: callable
2070 b247c6fc Michael Hanselmann
    @param resolve_fn: Function to resolve a relative job ID
2071 b247c6fc Michael Hanselmann
    @type deps: list
2072 b247c6fc Michael Hanselmann
    @param deps: Dependencies
2073 b247c6fc Michael Hanselmann
    @rtype: list
2074 b247c6fc Michael Hanselmann
    @return: Resolved dependencies
2075 b247c6fc Michael Hanselmann

2076 b247c6fc Michael Hanselmann
    """
2077 b247c6fc Michael Hanselmann
    result = []
2078 b247c6fc Michael Hanselmann
2079 b247c6fc Michael Hanselmann
    for (dep_job_id, dep_status) in deps:
2080 b247c6fc Michael Hanselmann
      if ht.TRelativeJobId(dep_job_id):
2081 b247c6fc Michael Hanselmann
        assert ht.TInt(dep_job_id) and dep_job_id < 0
2082 b247c6fc Michael Hanselmann
        try:
2083 b247c6fc Michael Hanselmann
          job_id = resolve_fn(dep_job_id)
2084 b247c6fc Michael Hanselmann
        except IndexError:
2085 b247c6fc Michael Hanselmann
          # Abort
2086 b247c6fc Michael Hanselmann
          return (False, "Unable to resolve relative job ID %s" % dep_job_id)
2087 b247c6fc Michael Hanselmann
      else:
2088 b247c6fc Michael Hanselmann
        job_id = dep_job_id
2089 b247c6fc Michael Hanselmann
2090 b247c6fc Michael Hanselmann
      result.append((job_id, dep_status))
2091 b247c6fc Michael Hanselmann
2092 b247c6fc Michael Hanselmann
    return (True, result)
2093 b247c6fc Michael Hanselmann
2094 b247c6fc Michael Hanselmann
  def _SubmitManyJobsUnlocked(self, jobs, job_ids, previous_job_ids):
2095 b247c6fc Michael Hanselmann
    """Create and store multiple jobs.
2096 b247c6fc Michael Hanselmann

2097 b247c6fc Michael Hanselmann
    @see: L{_SubmitJobUnlocked}
2098 b247c6fc Michael Hanselmann

2099 b247c6fc Michael Hanselmann
    """
2100 b247c6fc Michael Hanselmann
    results = []
2101 b247c6fc Michael Hanselmann
    added_jobs = []
2102 b247c6fc Michael Hanselmann
2103 b247c6fc Michael Hanselmann
    def resolve_fn(job_idx, reljobid):
2104 b247c6fc Michael Hanselmann
      assert reljobid < 0
2105 b247c6fc Michael Hanselmann
      return (previous_job_ids + job_ids[:job_idx])[reljobid]
2106 b247c6fc Michael Hanselmann
2107 b247c6fc Michael Hanselmann
    for (idx, (job_id, ops)) in enumerate(zip(job_ids, jobs)):
2108 b247c6fc Michael Hanselmann
      for op in ops:
2109 b247c6fc Michael Hanselmann
        if getattr(op, opcodes.DEPEND_ATTR, None):
2110 b247c6fc Michael Hanselmann
          (status, data) = \
2111 b247c6fc Michael Hanselmann
            self._ResolveJobDependencies(compat.partial(resolve_fn, idx),
2112 b247c6fc Michael Hanselmann
                                         op.depends)
2113 b247c6fc Michael Hanselmann
          if not status:
2114 b247c6fc Michael Hanselmann
            # Abort resolving dependencies
2115 b247c6fc Michael Hanselmann
            assert ht.TNonEmptyString(data), "No error message"
2116 b247c6fc Michael Hanselmann
            break
2117 b247c6fc Michael Hanselmann
          # Use resolved dependencies
2118 b247c6fc Michael Hanselmann
          op.depends = data
2119 b247c6fc Michael Hanselmann
      else:
2120 b247c6fc Michael Hanselmann
        try:
2121 b247c6fc Michael Hanselmann
          job = self._SubmitJobUnlocked(job_id, ops)
2122 b247c6fc Michael Hanselmann
        except errors.GenericError, err:
2123 b247c6fc Michael Hanselmann
          status = False
2124 b247c6fc Michael Hanselmann
          data = self._FormatSubmitError(str(err), ops)
2125 b247c6fc Michael Hanselmann
        else:
2126 b247c6fc Michael Hanselmann
          status = True
2127 b247c6fc Michael Hanselmann
          data = job_id
2128 b247c6fc Michael Hanselmann
          added_jobs.append(job)
2129 b247c6fc Michael Hanselmann
2130 b247c6fc Michael Hanselmann
      results.append((status, data))
2131 b247c6fc Michael Hanselmann
2132 b247c6fc Michael Hanselmann
    return (results, added_jobs)
2133 b247c6fc Michael Hanselmann
2134 75d81fc8 Michael Hanselmann
  @locking.ssynchronized(_LOCK)
2135 7b5c4a69 Michael Hanselmann
  def _EnqueueJobs(self, jobs):
2136 7b5c4a69 Michael Hanselmann
    """Helper function to add jobs to worker pool's queue.
2137 7b5c4a69 Michael Hanselmann

2138 7b5c4a69 Michael Hanselmann
    @type jobs: list
2139 7b5c4a69 Michael Hanselmann
    @param jobs: List of all jobs
2140 7b5c4a69 Michael Hanselmann

2141 7b5c4a69 Michael Hanselmann
    """
2142 75d81fc8 Michael Hanselmann
    return self._EnqueueJobsUnlocked(jobs)
2143 75d81fc8 Michael Hanselmann
2144 75d81fc8 Michael Hanselmann
  def _EnqueueJobsUnlocked(self, jobs):
2145 75d81fc8 Michael Hanselmann
    """Helper function to add jobs to worker pool's queue.
2146 75d81fc8 Michael Hanselmann

2147 75d81fc8 Michael Hanselmann
    @type jobs: list
2148 75d81fc8 Michael Hanselmann
    @param jobs: List of all jobs
2149 75d81fc8 Michael Hanselmann

2150 75d81fc8 Michael Hanselmann
    """
2151 75d81fc8 Michael Hanselmann
    assert self._lock.is_owned(shared=0), "Must own lock in exclusive mode"
2152 7b5c4a69 Michael Hanselmann
    self._wpool.AddManyTasks([(job, ) for job in jobs],
2153 7b5c4a69 Michael Hanselmann
                             priority=[job.CalcPriority() for job in jobs])
2154 7b5c4a69 Michael Hanselmann
2155 b95479a5 Michael Hanselmann
  def _GetJobStatusForDependencies(self, job_id):
2156 b95479a5 Michael Hanselmann
    """Gets the status of a job for dependencies.
2157 b95479a5 Michael Hanselmann

2158 b95479a5 Michael Hanselmann
    @type job_id: string
2159 b95479a5 Michael Hanselmann
    @param job_id: Job ID
2160 b95479a5 Michael Hanselmann
    @raise errors.JobLost: If job can't be found
2161 b95479a5 Michael Hanselmann

2162 b95479a5 Michael Hanselmann
    """
2163 b95479a5 Michael Hanselmann
    if not isinstance(job_id, basestring):
2164 b95479a5 Michael Hanselmann
      job_id = self._FormatJobID(job_id)
2165 b95479a5 Michael Hanselmann
2166 b95479a5 Michael Hanselmann
    # Not using in-memory cache as doing so would require an exclusive lock
2167 b95479a5 Michael Hanselmann
2168 b95479a5 Michael Hanselmann
    # Try to load from disk
2169 c0f6d0d8 Michael Hanselmann
    job = self.SafeLoadJobFromDisk(job_id, True, writable=False)
2170 c0f6d0d8 Michael Hanselmann
2171 c0f6d0d8 Michael Hanselmann
    assert not job.writable, "Got writable job"
2172 b95479a5 Michael Hanselmann
2173 b95479a5 Michael Hanselmann
    if job:
2174 b95479a5 Michael Hanselmann
      return job.CalcStatus()
2175 b95479a5 Michael Hanselmann
2176 b95479a5 Michael Hanselmann
    raise errors.JobLost("Job %s not found" % job_id)
2177 b95479a5 Michael Hanselmann
2178 db37da70 Michael Hanselmann
  @_RequireOpenQueue
2179 4c36bdf5 Guido Trotter
  def UpdateJobUnlocked(self, job, replicate=True):
2180 ea03467c Iustin Pop
    """Update a job's on disk storage.
2181 ea03467c Iustin Pop

2182 ea03467c Iustin Pop
    After a job has been modified, this function needs to be called in
2183 ea03467c Iustin Pop
    order to write the changes to disk and replicate them to the other
2184 ea03467c Iustin Pop
    nodes.
2185 ea03467c Iustin Pop

2186 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
2187 ea03467c Iustin Pop
    @param job: the changed job
2188 4c36bdf5 Guido Trotter
    @type replicate: boolean
2189 4c36bdf5 Guido Trotter
    @param replicate: whether to replicate the change to remote nodes
2190 ea03467c Iustin Pop

2191 ea03467c Iustin Pop
    """
2192 66bd7445 Michael Hanselmann
    if __debug__:
2193 66bd7445 Michael Hanselmann
      finalized = job.CalcStatus() in constants.JOBS_FINALIZED
2194 66bd7445 Michael Hanselmann
      assert (finalized ^ (job.end_timestamp is None))
2195 c0f6d0d8 Michael Hanselmann
      assert job.writable, "Can't update read-only job"
2196 66bd7445 Michael Hanselmann
2197 f1da30e6 Michael Hanselmann
    filename = self._GetJobPath(job.id)
2198 23752136 Michael Hanselmann
    data = serializer.DumpJson(job.Serialize(), indent=False)
2199 f1da30e6 Michael Hanselmann
    logging.debug("Writing job %s to %s", job.id, filename)
2200 4c36bdf5 Guido Trotter
    self._UpdateJobQueueFile(filename, data, replicate)
2201 ac0930b9 Iustin Pop
2202 5c735209 Iustin Pop
  def WaitForJobChanges(self, job_id, fields, prev_job_info, prev_log_serial,
2203 5c735209 Iustin Pop
                        timeout):
2204 6c5a7090 Michael Hanselmann
    """Waits for changes in a job.
2205 6c5a7090 Michael Hanselmann

2206 6c5a7090 Michael Hanselmann
    @type job_id: string
2207 6c5a7090 Michael Hanselmann
    @param job_id: Job identifier
2208 6c5a7090 Michael Hanselmann
    @type fields: list of strings
2209 6c5a7090 Michael Hanselmann
    @param fields: Which fields to check for changes
2210 6c5a7090 Michael Hanselmann
    @type prev_job_info: list or None
2211 6c5a7090 Michael Hanselmann
    @param prev_job_info: Last job information returned
2212 6c5a7090 Michael Hanselmann
    @type prev_log_serial: int
2213 6c5a7090 Michael Hanselmann
    @param prev_log_serial: Last job message serial number
2214 5c735209 Iustin Pop
    @type timeout: float
2215 989a8bee Michael Hanselmann
    @param timeout: maximum time to wait in seconds
2216 ea03467c Iustin Pop
    @rtype: tuple (job info, log entries)
2217 ea03467c Iustin Pop
    @return: a tuple of the job information as required via
2218 ea03467c Iustin Pop
        the fields parameter, and the log entries as a list
2219 ea03467c Iustin Pop

2220 ea03467c Iustin Pop
        if the job has not changed and the timeout has expired,
2221 ea03467c Iustin Pop
        we instead return a special value,
2222 ea03467c Iustin Pop
        L{constants.JOB_NOTCHANGED}, which should be interpreted
2223 ea03467c Iustin Pop
        as such by the clients
2224 6c5a7090 Michael Hanselmann

2225 6c5a7090 Michael Hanselmann
    """
2226 c0f6d0d8 Michael Hanselmann
    load_fn = compat.partial(self.SafeLoadJobFromDisk, job_id, False,
2227 c0f6d0d8 Michael Hanselmann
                             writable=False)
2228 989a8bee Michael Hanselmann
2229 989a8bee Michael Hanselmann
    helper = _WaitForJobChangesHelper()
2230 989a8bee Michael Hanselmann
2231 989a8bee Michael Hanselmann
    return helper(self._GetJobPath(job_id), load_fn,
2232 989a8bee Michael Hanselmann
                  fields, prev_job_info, prev_log_serial, timeout)
2233 dfe57c22 Michael Hanselmann
2234 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
2235 db37da70 Michael Hanselmann
  @_RequireOpenQueue
2236 188c5e0a Michael Hanselmann
  def CancelJob(self, job_id):
2237 188c5e0a Michael Hanselmann
    """Cancels a job.
2238 188c5e0a Michael Hanselmann

2239 ea03467c Iustin Pop
    This will only succeed if the job has not started yet.
2240 ea03467c Iustin Pop

2241 188c5e0a Michael Hanselmann
    @type job_id: string
2242 ea03467c Iustin Pop
    @param job_id: job ID of job to be cancelled.
2243 188c5e0a Michael Hanselmann

2244 188c5e0a Michael Hanselmann
    """
2245 fbf0262f Michael Hanselmann
    logging.info("Cancelling job %s", job_id)
2246 188c5e0a Michael Hanselmann
2247 85f03e0d Michael Hanselmann
    job = self._LoadJobUnlocked(job_id)
2248 188c5e0a Michael Hanselmann
    if not job:
2249 188c5e0a Michael Hanselmann
      logging.debug("Job %s not found", job_id)
2250 fbf0262f Michael Hanselmann
      return (False, "Job %s not found" % job_id)
2251 fbf0262f Michael Hanselmann
2252 c0f6d0d8 Michael Hanselmann
    assert job.writable, "Can't cancel read-only job"
2253 c0f6d0d8 Michael Hanselmann
2254 099b2870 Michael Hanselmann
    (success, msg) = job.Cancel()
2255 188c5e0a Michael Hanselmann
2256 099b2870 Michael Hanselmann
    if success:
2257 66bd7445 Michael Hanselmann
      # If the job was finalized (e.g. cancelled), this is the final write
2258 66bd7445 Michael Hanselmann
      # allowed. The job can be archived anytime.
2259 099b2870 Michael Hanselmann
      self.UpdateJobUnlocked(job)
2260 fbf0262f Michael Hanselmann
2261 099b2870 Michael Hanselmann
    return (success, msg)
2262 fbf0262f Michael Hanselmann
2263 fbf0262f Michael Hanselmann
  @_RequireOpenQueue
2264 d7fd1f28 Michael Hanselmann
  def _ArchiveJobsUnlocked(self, jobs):
2265 d7fd1f28 Michael Hanselmann
    """Archives jobs.
2266 c609f802 Michael Hanselmann

2267 d7fd1f28 Michael Hanselmann
    @type jobs: list of L{_QueuedJob}
2268 25e7b43f Iustin Pop
    @param jobs: Job objects
2269 d7fd1f28 Michael Hanselmann
    @rtype: int
2270 d7fd1f28 Michael Hanselmann
    @return: Number of archived jobs
2271 c609f802 Michael Hanselmann

2272 c609f802 Michael Hanselmann
    """
2273 d7fd1f28 Michael Hanselmann
    archive_jobs = []
2274 d7fd1f28 Michael Hanselmann
    rename_files = []
2275 d7fd1f28 Michael Hanselmann
    for job in jobs:
2276 c0f6d0d8 Michael Hanselmann
      assert job.writable, "Can't archive read-only job"
2277 c0f6d0d8 Michael Hanselmann
2278 989a8bee Michael Hanselmann
      if job.CalcStatus() not in constants.JOBS_FINALIZED:
2279 d7fd1f28 Michael Hanselmann
        logging.debug("Job %s is not yet done", job.id)
2280 d7fd1f28 Michael Hanselmann
        continue
2281 c609f802 Michael Hanselmann
2282 d7fd1f28 Michael Hanselmann
      archive_jobs.append(job)
2283 c609f802 Michael Hanselmann
2284 d7fd1f28 Michael Hanselmann
      old = self._GetJobPath(job.id)
2285 d7fd1f28 Michael Hanselmann
      new = self._GetArchivedJobPath(job.id)
2286 d7fd1f28 Michael Hanselmann
      rename_files.append((old, new))
2287 c609f802 Michael Hanselmann
2288 d7fd1f28 Michael Hanselmann
    # TODO: What if 1..n files fail to rename?
2289 d7fd1f28 Michael Hanselmann
    self._RenameFilesUnlocked(rename_files)
2290 f1da30e6 Michael Hanselmann
2291 d7fd1f28 Michael Hanselmann
    logging.debug("Successfully archived job(s) %s",
2292 1f864b60 Iustin Pop
                  utils.CommaJoin(job.id for job in archive_jobs))
2293 d7fd1f28 Michael Hanselmann
2294 20571a26 Guido Trotter
    # Since we haven't quite checked, above, if we succeeded or failed renaming
2295 20571a26 Guido Trotter
    # the files, we update the cached queue size from the filesystem. When we
2296 20571a26 Guido Trotter
    # get around to fix the TODO: above, we can use the number of actually
2297 20571a26 Guido Trotter
    # archived jobs to fix this.
2298 20571a26 Guido Trotter
    self._UpdateQueueSizeUnlocked()
2299 d7fd1f28 Michael Hanselmann
    return len(archive_jobs)
2300 78d12585 Michael Hanselmann
2301 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
2302 07cd723a Iustin Pop
  @_RequireOpenQueue
2303 07cd723a Iustin Pop
  def ArchiveJob(self, job_id):
2304 07cd723a Iustin Pop
    """Archives a job.
2305 07cd723a Iustin Pop

2306 25e7b43f Iustin Pop
    This is just a wrapper over L{_ArchiveJobsUnlocked}.
2307 ea03467c Iustin Pop

2308 07cd723a Iustin Pop
    @type job_id: string
2309 07cd723a Iustin Pop
    @param job_id: Job ID of job to be archived.
2310 78d12585 Michael Hanselmann
    @rtype: bool
2311 78d12585 Michael Hanselmann
    @return: Whether job was archived
2312 07cd723a Iustin Pop

2313 07cd723a Iustin Pop
    """
2314 78d12585 Michael Hanselmann
    logging.info("Archiving job %s", job_id)
2315 78d12585 Michael Hanselmann
2316 78d12585 Michael Hanselmann
    job = self._LoadJobUnlocked(job_id)
2317 78d12585 Michael Hanselmann
    if not job:
2318 78d12585 Michael Hanselmann
      logging.debug("Job %s not found", job_id)
2319 78d12585 Michael Hanselmann
      return False
2320 78d12585 Michael Hanselmann
2321 5278185a Iustin Pop
    return self._ArchiveJobsUnlocked([job]) == 1
2322 07cd723a Iustin Pop
2323 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
2324 07cd723a Iustin Pop
  @_RequireOpenQueue
2325 f8ad5591 Michael Hanselmann
  def AutoArchiveJobs(self, age, timeout):
2326 07cd723a Iustin Pop
    """Archives all jobs based on age.
2327 07cd723a Iustin Pop

2328 07cd723a Iustin Pop
    The method will archive all jobs which are older than the age
2329 07cd723a Iustin Pop
    parameter. For jobs that don't have an end timestamp, the start
2330 07cd723a Iustin Pop
    timestamp will be considered. The special '-1' age will cause
2331 07cd723a Iustin Pop
    archival of all jobs (that are not running or queued).
2332 07cd723a Iustin Pop

2333 07cd723a Iustin Pop
    @type age: int
2334 07cd723a Iustin Pop
    @param age: the minimum age in seconds
2335 07cd723a Iustin Pop

2336 07cd723a Iustin Pop
    """
2337 07cd723a Iustin Pop
    logging.info("Archiving jobs with age more than %s seconds", age)
2338 07cd723a Iustin Pop
2339 07cd723a Iustin Pop
    now = time.time()
2340 f8ad5591 Michael Hanselmann
    end_time = now + timeout
2341 f8ad5591 Michael Hanselmann
    archived_count = 0
2342 f8ad5591 Michael Hanselmann
    last_touched = 0
2343 f8ad5591 Michael Hanselmann
2344 69b03fd7 Guido Trotter
    all_job_ids = self._GetJobIDsUnlocked()
2345 d7fd1f28 Michael Hanselmann
    pending = []
2346 f8ad5591 Michael Hanselmann
    for idx, job_id in enumerate(all_job_ids):
2347 d2c8afb1 Michael Hanselmann
      last_touched = idx + 1
2348 f8ad5591 Michael Hanselmann
2349 d7fd1f28 Michael Hanselmann
      # Not optimal because jobs could be pending
2350 d7fd1f28 Michael Hanselmann
      # TODO: Measure average duration for job archival and take number of
2351 d7fd1f28 Michael Hanselmann
      # pending jobs into account.
2352 f8ad5591 Michael Hanselmann
      if time.time() > end_time:
2353 f8ad5591 Michael Hanselmann
        break
2354 f8ad5591 Michael Hanselmann
2355 78d12585 Michael Hanselmann
      # Returns None if the job failed to load
2356 78d12585 Michael Hanselmann
      job = self._LoadJobUnlocked(job_id)
2357 f8ad5591 Michael Hanselmann
      if job:
2358 f8ad5591 Michael Hanselmann
        if job.end_timestamp is None:
2359 f8ad5591 Michael Hanselmann
          if job.start_timestamp is None:
2360 f8ad5591 Michael Hanselmann
            job_age = job.received_timestamp
2361 f8ad5591 Michael Hanselmann
          else:
2362 f8ad5591 Michael Hanselmann
            job_age = job.start_timestamp
2363 07cd723a Iustin Pop
        else:
2364 f8ad5591 Michael Hanselmann
          job_age = job.end_timestamp
2365 f8ad5591 Michael Hanselmann
2366 f8ad5591 Michael Hanselmann
        if age == -1 or now - job_age[0] > age:
2367 d7fd1f28 Michael Hanselmann
          pending.append(job)
2368 d7fd1f28 Michael Hanselmann
2369 d7fd1f28 Michael Hanselmann
          # Archive 10 jobs at a time
2370 d7fd1f28 Michael Hanselmann
          if len(pending) >= 10:
2371 d7fd1f28 Michael Hanselmann
            archived_count += self._ArchiveJobsUnlocked(pending)
2372 d7fd1f28 Michael Hanselmann
            pending = []
2373 f8ad5591 Michael Hanselmann
2374 d7fd1f28 Michael Hanselmann
    if pending:
2375 d7fd1f28 Michael Hanselmann
      archived_count += self._ArchiveJobsUnlocked(pending)
2376 07cd723a Iustin Pop
2377 d2c8afb1 Michael Hanselmann
    return (archived_count, len(all_job_ids) - last_touched)
2378 07cd723a Iustin Pop
2379 e2715f69 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2380 e2715f69 Michael Hanselmann
    """Returns a list of jobs in queue.
2381 e2715f69 Michael Hanselmann

2382 ea03467c Iustin Pop
    @type job_ids: list
2383 ea03467c Iustin Pop
    @param job_ids: sequence of job identifiers or None for all
2384 ea03467c Iustin Pop
    @type fields: list
2385 ea03467c Iustin Pop
    @param fields: names of fields to return
2386 ea03467c Iustin Pop
    @rtype: list
2387 ea03467c Iustin Pop
    @return: list one element per job, each element being list with
2388 ea03467c Iustin Pop
        the requested fields
2389 e2715f69 Michael Hanselmann

2390 e2715f69 Michael Hanselmann
    """
2391 85f03e0d Michael Hanselmann
    jobs = []
2392 9f7b4967 Guido Trotter
    list_all = False
2393 9f7b4967 Guido Trotter
    if not job_ids:
2394 9f7b4967 Guido Trotter
      # Since files are added to/removed from the queue atomically, there's no
2395 9f7b4967 Guido Trotter
      # risk of getting the job ids in an inconsistent state.
2396 9f7b4967 Guido Trotter
      job_ids = self._GetJobIDsUnlocked()
2397 9f7b4967 Guido Trotter
      list_all = True
2398 e2715f69 Michael Hanselmann
2399 9f7b4967 Guido Trotter
    for job_id in job_ids:
2400 194c8ca4 Michael Hanselmann
      job = self.SafeLoadJobFromDisk(job_id, True)
2401 9f7b4967 Guido Trotter
      if job is not None:
2402 6a290889 Guido Trotter
        jobs.append(job.GetInfo(fields))
2403 9f7b4967 Guido Trotter
      elif not list_all:
2404 9f7b4967 Guido Trotter
        jobs.append(None)
2405 e2715f69 Michael Hanselmann
2406 85f03e0d Michael Hanselmann
    return jobs
2407 e2715f69 Michael Hanselmann
2408 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
2409 db37da70 Michael Hanselmann
  @_RequireOpenQueue
2410 e2715f69 Michael Hanselmann
  def Shutdown(self):
2411 e2715f69 Michael Hanselmann
    """Stops the job queue.
2412 e2715f69 Michael Hanselmann

2413 ea03467c Iustin Pop
    This shutdowns all the worker threads an closes the queue.
2414 ea03467c Iustin Pop

2415 e2715f69 Michael Hanselmann
    """
2416 e2715f69 Michael Hanselmann
    self._wpool.TerminateWorkers()
2417 85f03e0d Michael Hanselmann
2418 a71f9c7d Guido Trotter
    self._queue_filelock.Close()
2419 a71f9c7d Guido Trotter
    self._queue_filelock = None