Statistics
| Branch: | Tag: | Revision:

root / lib / jqueue.py @ ff699aa9

History | View | Annotate | Download (57.9 kB)

1 498ae1cc Iustin Pop
#
2 498ae1cc Iustin Pop
#
3 498ae1cc Iustin Pop
4 7f93570a Iustin Pop
# Copyright (C) 2006, 2007, 2008, 2009, 2010 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 498ae1cc Iustin Pop
38 6c2549d6 Guido Trotter
try:
39 6c2549d6 Guido Trotter
  # pylint: disable-msg=E0611
40 6c2549d6 Guido Trotter
  from pyinotify import pyinotify
41 6c2549d6 Guido Trotter
except ImportError:
42 6c2549d6 Guido Trotter
  import pyinotify
43 6c2549d6 Guido Trotter
44 6c2549d6 Guido Trotter
from ganeti import asyncnotifier
45 e2715f69 Michael Hanselmann
from ganeti import constants
46 f1da30e6 Michael Hanselmann
from ganeti import serializer
47 e2715f69 Michael Hanselmann
from ganeti import workerpool
48 99bd4f0a Guido Trotter
from ganeti import locking
49 f1da30e6 Michael Hanselmann
from ganeti import opcodes
50 7a1ecaed Iustin Pop
from ganeti import errors
51 e2715f69 Michael Hanselmann
from ganeti import mcpu
52 7996a135 Iustin Pop
from ganeti import utils
53 04ab05ce Michael Hanselmann
from ganeti import jstore
54 c3f0a12f Iustin Pop
from ganeti import rpc
55 82b22e19 René Nussbaumer
from ganeti import runtime
56 a744b676 Manuel Franceschini
from ganeti import netutils
57 989a8bee Michael Hanselmann
from ganeti import compat
58 e2715f69 Michael Hanselmann
59 fbf0262f Michael Hanselmann
60 1daae384 Iustin Pop
JOBQUEUE_THREADS = 25
61 58b22b6e Michael Hanselmann
JOBS_PER_ARCHIVE_DIRECTORY = 10000
62 e2715f69 Michael Hanselmann
63 ebb80afa Guido Trotter
# member lock names to be passed to @ssynchronized decorator
64 ebb80afa Guido Trotter
_LOCK = "_lock"
65 ebb80afa Guido Trotter
_QUEUE = "_queue"
66 99bd4f0a Guido Trotter
67 498ae1cc Iustin Pop
68 9728ae5d Iustin Pop
class CancelJob(Exception):
69 fbf0262f Michael Hanselmann
  """Special exception to cancel a job.
70 fbf0262f Michael Hanselmann

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

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

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

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

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

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

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

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

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

143 ea03467c Iustin Pop
    @rtype: dict
144 ea03467c Iustin Pop
    @return: the dictionary holding the serialized state
145 ea03467c Iustin Pop

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

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

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

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

185 ea03467c Iustin Pop
    @type queue: L{JobQueue}
186 ea03467c Iustin Pop
    @param queue: our parent queue
187 ea03467c Iustin Pop
    @type job_id: job_id
188 ea03467c Iustin Pop
    @param job_id: our job id
189 ea03467c Iustin Pop
    @type ops: list
190 ea03467c Iustin Pop
    @param ops: the list of opcodes we hold, which will be encapsulated
191 ea03467c Iustin Pop
        in _QueuedOpCodes
192 ea03467c Iustin Pop

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

211 fa4aa6b4 Michael Hanselmann
    """
212 03b63608 Michael Hanselmann
    obj.ops_iter = None
213 26d3fd2f Michael Hanselmann
    obj.cur_opctx = None
214 be760ba8 Michael Hanselmann
215 9fa2e150 Michael Hanselmann
  def __repr__(self):
216 9fa2e150 Michael Hanselmann
    status = ["%s.%s" % (self.__class__.__module__, self.__class__.__name__),
217 9fa2e150 Michael Hanselmann
              "id=%s" % self.id,
218 9fa2e150 Michael Hanselmann
              "ops=%s" % ",".join([op.input.Summary() for op in self.ops])]
219 9fa2e150 Michael Hanselmann
220 9fa2e150 Michael Hanselmann
    return "<%s at %#x>" % (" ".join(status), id(self))
221 9fa2e150 Michael Hanselmann
222 f1da30e6 Michael Hanselmann
  @classmethod
223 85f03e0d Michael Hanselmann
  def Restore(cls, queue, state):
224 ea03467c Iustin Pop
    """Restore a _QueuedJob from serialized state:
225 ea03467c Iustin Pop

226 ea03467c Iustin Pop
    @type queue: L{JobQueue}
227 ea03467c Iustin Pop
    @param queue: to which queue the restored job belongs
228 ea03467c Iustin Pop
    @type state: dict
229 ea03467c Iustin Pop
    @param state: the serialized state
230 ea03467c Iustin Pop
    @rtype: _JobQueue
231 ea03467c Iustin Pop
    @return: the restored _JobQueue instance
232 ea03467c Iustin Pop

233 ea03467c Iustin Pop
    """
234 85f03e0d Michael Hanselmann
    obj = _QueuedJob.__new__(cls)
235 85f03e0d Michael Hanselmann
    obj.queue = queue
236 85f03e0d Michael Hanselmann
    obj.id = state["id"]
237 c56ec146 Iustin Pop
    obj.received_timestamp = state.get("received_timestamp", None)
238 c56ec146 Iustin Pop
    obj.start_timestamp = state.get("start_timestamp", None)
239 c56ec146 Iustin Pop
    obj.end_timestamp = state.get("end_timestamp", None)
240 6c5a7090 Michael Hanselmann
241 6c5a7090 Michael Hanselmann
    obj.ops = []
242 6c5a7090 Michael Hanselmann
    obj.log_serial = 0
243 6c5a7090 Michael Hanselmann
    for op_state in state["ops"]:
244 6c5a7090 Michael Hanselmann
      op = _QueuedOpCode.Restore(op_state)
245 6c5a7090 Michael Hanselmann
      for log_entry in op.log:
246 6c5a7090 Michael Hanselmann
        obj.log_serial = max(obj.log_serial, log_entry[0])
247 6c5a7090 Michael Hanselmann
      obj.ops.append(op)
248 6c5a7090 Michael Hanselmann
249 fa4aa6b4 Michael Hanselmann
    cls._InitInMemory(obj)
250 be760ba8 Michael Hanselmann
251 f1da30e6 Michael Hanselmann
    return obj
252 f1da30e6 Michael Hanselmann
253 f1da30e6 Michael Hanselmann
  def Serialize(self):
254 ea03467c Iustin Pop
    """Serialize the _JobQueue instance.
255 ea03467c Iustin Pop

256 ea03467c Iustin Pop
    @rtype: dict
257 ea03467c Iustin Pop
    @return: the serialized state
258 ea03467c Iustin Pop

259 ea03467c Iustin Pop
    """
260 f1da30e6 Michael Hanselmann
    return {
261 f1da30e6 Michael Hanselmann
      "id": self.id,
262 85f03e0d Michael Hanselmann
      "ops": [op.Serialize() for op in self.ops],
263 c56ec146 Iustin Pop
      "start_timestamp": self.start_timestamp,
264 c56ec146 Iustin Pop
      "end_timestamp": self.end_timestamp,
265 c56ec146 Iustin Pop
      "received_timestamp": self.received_timestamp,
266 f1da30e6 Michael Hanselmann
      }
267 f1da30e6 Michael Hanselmann
268 85f03e0d Michael Hanselmann
  def CalcStatus(self):
269 ea03467c Iustin Pop
    """Compute the status of this job.
270 ea03467c Iustin Pop

271 ea03467c Iustin Pop
    This function iterates over all the _QueuedOpCodes in the job and
272 ea03467c Iustin Pop
    based on their status, computes the job status.
273 ea03467c Iustin Pop

274 ea03467c Iustin Pop
    The algorithm is:
275 ea03467c Iustin Pop
      - if we find a cancelled, or finished with error, the job
276 ea03467c Iustin Pop
        status will be the same
277 ea03467c Iustin Pop
      - otherwise, the last opcode with the status one of:
278 ea03467c Iustin Pop
          - waitlock
279 fbf0262f Michael Hanselmann
          - canceling
280 ea03467c Iustin Pop
          - running
281 ea03467c Iustin Pop

282 ea03467c Iustin Pop
        will determine the job status
283 ea03467c Iustin Pop

284 ea03467c Iustin Pop
      - otherwise, it means either all opcodes are queued, or success,
285 ea03467c Iustin Pop
        and the job status will be the same
286 ea03467c Iustin Pop

287 ea03467c Iustin Pop
    @return: the job status
288 ea03467c Iustin Pop

289 ea03467c Iustin Pop
    """
290 e2715f69 Michael Hanselmann
    status = constants.JOB_STATUS_QUEUED
291 e2715f69 Michael Hanselmann
292 e2715f69 Michael Hanselmann
    all_success = True
293 85f03e0d Michael Hanselmann
    for op in self.ops:
294 85f03e0d Michael Hanselmann
      if op.status == constants.OP_STATUS_SUCCESS:
295 e2715f69 Michael Hanselmann
        continue
296 e2715f69 Michael Hanselmann
297 e2715f69 Michael Hanselmann
      all_success = False
298 e2715f69 Michael Hanselmann
299 85f03e0d Michael Hanselmann
      if op.status == constants.OP_STATUS_QUEUED:
300 e2715f69 Michael Hanselmann
        pass
301 e92376d7 Iustin Pop
      elif op.status == constants.OP_STATUS_WAITLOCK:
302 e92376d7 Iustin Pop
        status = constants.JOB_STATUS_WAITLOCK
303 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_RUNNING:
304 e2715f69 Michael Hanselmann
        status = constants.JOB_STATUS_RUNNING
305 fbf0262f Michael Hanselmann
      elif op.status == constants.OP_STATUS_CANCELING:
306 fbf0262f Michael Hanselmann
        status = constants.JOB_STATUS_CANCELING
307 fbf0262f Michael Hanselmann
        break
308 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_ERROR:
309 f1da30e6 Michael Hanselmann
        status = constants.JOB_STATUS_ERROR
310 f1da30e6 Michael Hanselmann
        # The whole job fails if one opcode failed
311 f1da30e6 Michael Hanselmann
        break
312 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_CANCELED:
313 4cb1d919 Michael Hanselmann
        status = constants.OP_STATUS_CANCELED
314 4cb1d919 Michael Hanselmann
        break
315 e2715f69 Michael Hanselmann
316 e2715f69 Michael Hanselmann
    if all_success:
317 e2715f69 Michael Hanselmann
      status = constants.JOB_STATUS_SUCCESS
318 e2715f69 Michael Hanselmann
319 e2715f69 Michael Hanselmann
    return status
320 e2715f69 Michael Hanselmann
321 8f5c488d Michael Hanselmann
  def CalcPriority(self):
322 8f5c488d Michael Hanselmann
    """Gets the current priority for this job.
323 8f5c488d Michael Hanselmann

324 8f5c488d Michael Hanselmann
    Only unfinished opcodes are considered. When all are done, the default
325 8f5c488d Michael Hanselmann
    priority is used.
326 8f5c488d Michael Hanselmann

327 8f5c488d Michael Hanselmann
    @rtype: int
328 8f5c488d Michael Hanselmann

329 8f5c488d Michael Hanselmann
    """
330 8f5c488d Michael Hanselmann
    priorities = [op.priority for op in self.ops
331 8f5c488d Michael Hanselmann
                  if op.status not in constants.OPS_FINALIZED]
332 8f5c488d Michael Hanselmann
333 8f5c488d Michael Hanselmann
    if not priorities:
334 8f5c488d Michael Hanselmann
      # All opcodes are done, assume default priority
335 8f5c488d Michael Hanselmann
      return constants.OP_PRIO_DEFAULT
336 8f5c488d Michael Hanselmann
337 8f5c488d Michael Hanselmann
    return min(priorities)
338 8f5c488d Michael Hanselmann
339 6c5a7090 Michael Hanselmann
  def GetLogEntries(self, newer_than):
340 ea03467c Iustin Pop
    """Selectively returns the log entries.
341 ea03467c Iustin Pop

342 ea03467c Iustin Pop
    @type newer_than: None or int
343 5bbd3f7f Michael Hanselmann
    @param newer_than: if this is None, return all log entries,
344 ea03467c Iustin Pop
        otherwise return only the log entries with serial higher
345 ea03467c Iustin Pop
        than this value
346 ea03467c Iustin Pop
    @rtype: list
347 ea03467c Iustin Pop
    @return: the list of the log entries selected
348 ea03467c Iustin Pop

349 ea03467c Iustin Pop
    """
350 6c5a7090 Michael Hanselmann
    if newer_than is None:
351 6c5a7090 Michael Hanselmann
      serial = -1
352 6c5a7090 Michael Hanselmann
    else:
353 6c5a7090 Michael Hanselmann
      serial = newer_than
354 6c5a7090 Michael Hanselmann
355 6c5a7090 Michael Hanselmann
    entries = []
356 6c5a7090 Michael Hanselmann
    for op in self.ops:
357 63712a09 Iustin Pop
      entries.extend(filter(lambda entry: entry[0] > serial, op.log))
358 6c5a7090 Michael Hanselmann
359 6c5a7090 Michael Hanselmann
    return entries
360 6c5a7090 Michael Hanselmann
361 6a290889 Guido Trotter
  def GetInfo(self, fields):
362 6a290889 Guido Trotter
    """Returns information about a job.
363 6a290889 Guido Trotter

364 6a290889 Guido Trotter
    @type fields: list
365 6a290889 Guido Trotter
    @param fields: names of fields to return
366 6a290889 Guido Trotter
    @rtype: list
367 6a290889 Guido Trotter
    @return: list with one element for each field
368 6a290889 Guido Trotter
    @raise errors.OpExecError: when an invalid field
369 6a290889 Guido Trotter
        has been passed
370 6a290889 Guido Trotter

371 6a290889 Guido Trotter
    """
372 6a290889 Guido Trotter
    row = []
373 6a290889 Guido Trotter
    for fname in fields:
374 6a290889 Guido Trotter
      if fname == "id":
375 6a290889 Guido Trotter
        row.append(self.id)
376 6a290889 Guido Trotter
      elif fname == "status":
377 6a290889 Guido Trotter
        row.append(self.CalcStatus())
378 b8802cc4 Michael Hanselmann
      elif fname == "priority":
379 b8802cc4 Michael Hanselmann
        row.append(self.CalcPriority())
380 6a290889 Guido Trotter
      elif fname == "ops":
381 6a290889 Guido Trotter
        row.append([op.input.__getstate__() for op in self.ops])
382 6a290889 Guido Trotter
      elif fname == "opresult":
383 6a290889 Guido Trotter
        row.append([op.result for op in self.ops])
384 6a290889 Guido Trotter
      elif fname == "opstatus":
385 6a290889 Guido Trotter
        row.append([op.status for op in self.ops])
386 6a290889 Guido Trotter
      elif fname == "oplog":
387 6a290889 Guido Trotter
        row.append([op.log for op in self.ops])
388 6a290889 Guido Trotter
      elif fname == "opstart":
389 6a290889 Guido Trotter
        row.append([op.start_timestamp for op in self.ops])
390 6a290889 Guido Trotter
      elif fname == "opexec":
391 6a290889 Guido Trotter
        row.append([op.exec_timestamp for op in self.ops])
392 6a290889 Guido Trotter
      elif fname == "opend":
393 6a290889 Guido Trotter
        row.append([op.end_timestamp for op in self.ops])
394 b8802cc4 Michael Hanselmann
      elif fname == "oppriority":
395 b8802cc4 Michael Hanselmann
        row.append([op.priority for op in self.ops])
396 6a290889 Guido Trotter
      elif fname == "received_ts":
397 6a290889 Guido Trotter
        row.append(self.received_timestamp)
398 6a290889 Guido Trotter
      elif fname == "start_ts":
399 6a290889 Guido Trotter
        row.append(self.start_timestamp)
400 6a290889 Guido Trotter
      elif fname == "end_ts":
401 6a290889 Guido Trotter
        row.append(self.end_timestamp)
402 6a290889 Guido Trotter
      elif fname == "summary":
403 6a290889 Guido Trotter
        row.append([op.input.Summary() for op in self.ops])
404 6a290889 Guido Trotter
      else:
405 6a290889 Guido Trotter
        raise errors.OpExecError("Invalid self query field '%s'" % fname)
406 6a290889 Guido Trotter
    return row
407 6a290889 Guido Trotter
408 34327f51 Iustin Pop
  def MarkUnfinishedOps(self, status, result):
409 34327f51 Iustin Pop
    """Mark unfinished opcodes with a given status and result.
410 34327f51 Iustin Pop

411 34327f51 Iustin Pop
    This is an utility function for marking all running or waiting to
412 34327f51 Iustin Pop
    be run opcodes with a given status. Opcodes which are already
413 34327f51 Iustin Pop
    finalised are not changed.
414 34327f51 Iustin Pop

415 34327f51 Iustin Pop
    @param status: a given opcode status
416 34327f51 Iustin Pop
    @param result: the opcode result
417 34327f51 Iustin Pop

418 34327f51 Iustin Pop
    """
419 747f6113 Michael Hanselmann
    not_marked = True
420 747f6113 Michael Hanselmann
    for op in self.ops:
421 747f6113 Michael Hanselmann
      if op.status in constants.OPS_FINALIZED:
422 747f6113 Michael Hanselmann
        assert not_marked, "Finalized opcodes found after non-finalized ones"
423 747f6113 Michael Hanselmann
        continue
424 747f6113 Michael Hanselmann
      op.status = status
425 747f6113 Michael Hanselmann
      op.result = result
426 747f6113 Michael Hanselmann
      not_marked = False
427 34327f51 Iustin Pop
428 099b2870 Michael Hanselmann
  def Cancel(self):
429 a0d2fe2c Michael Hanselmann
    """Marks job as canceled/-ing if possible.
430 a0d2fe2c Michael Hanselmann

431 a0d2fe2c Michael Hanselmann
    @rtype: tuple; (bool, string)
432 a0d2fe2c Michael Hanselmann
    @return: Boolean describing whether job was successfully canceled or marked
433 a0d2fe2c Michael Hanselmann
      as canceling and a text message
434 a0d2fe2c Michael Hanselmann

435 a0d2fe2c Michael Hanselmann
    """
436 099b2870 Michael Hanselmann
    status = self.CalcStatus()
437 099b2870 Michael Hanselmann
438 099b2870 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED:
439 099b2870 Michael Hanselmann
      self.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
440 099b2870 Michael Hanselmann
                             "Job canceled by request")
441 86b16e9d Michael Hanselmann
      return (True, "Job %s canceled" % self.id)
442 099b2870 Michael Hanselmann
443 099b2870 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITLOCK:
444 099b2870 Michael Hanselmann
      # The worker will notice the new status and cancel the job
445 099b2870 Michael Hanselmann
      self.MarkUnfinishedOps(constants.OP_STATUS_CANCELING, None)
446 86b16e9d Michael Hanselmann
      return (True, "Job %s will be canceled" % self.id)
447 099b2870 Michael Hanselmann
448 86b16e9d Michael Hanselmann
    else:
449 86b16e9d Michael Hanselmann
      logging.debug("Job %s is no longer waiting in the queue", self.id)
450 86b16e9d Michael Hanselmann
      return (False, "Job %s is no longer waiting in the queue" % self.id)
451 099b2870 Michael Hanselmann
452 f1048938 Iustin Pop
453 ef2df7d3 Michael Hanselmann
class _OpExecCallbacks(mcpu.OpExecCbBase):
454 031a3e57 Michael Hanselmann
  def __init__(self, queue, job, op):
455 031a3e57 Michael Hanselmann
    """Initializes this class.
456 ea03467c Iustin Pop

457 031a3e57 Michael Hanselmann
    @type queue: L{JobQueue}
458 031a3e57 Michael Hanselmann
    @param queue: Job queue
459 031a3e57 Michael Hanselmann
    @type job: L{_QueuedJob}
460 031a3e57 Michael Hanselmann
    @param job: Job object
461 031a3e57 Michael Hanselmann
    @type op: L{_QueuedOpCode}
462 031a3e57 Michael Hanselmann
    @param op: OpCode
463 031a3e57 Michael Hanselmann

464 031a3e57 Michael Hanselmann
    """
465 031a3e57 Michael Hanselmann
    assert queue, "Queue is missing"
466 031a3e57 Michael Hanselmann
    assert job, "Job is missing"
467 031a3e57 Michael Hanselmann
    assert op, "Opcode is missing"
468 031a3e57 Michael Hanselmann
469 031a3e57 Michael Hanselmann
    self._queue = queue
470 031a3e57 Michael Hanselmann
    self._job = job
471 031a3e57 Michael Hanselmann
    self._op = op
472 031a3e57 Michael Hanselmann
473 dc1e2262 Michael Hanselmann
  def _CheckCancel(self):
474 dc1e2262 Michael Hanselmann
    """Raises an exception to cancel the job if asked to.
475 dc1e2262 Michael Hanselmann

476 dc1e2262 Michael Hanselmann
    """
477 dc1e2262 Michael Hanselmann
    # Cancel here if we were asked to
478 dc1e2262 Michael Hanselmann
    if self._op.status == constants.OP_STATUS_CANCELING:
479 dc1e2262 Michael Hanselmann
      logging.debug("Canceling opcode")
480 dc1e2262 Michael Hanselmann
      raise CancelJob()
481 dc1e2262 Michael Hanselmann
482 271daef8 Iustin Pop
  @locking.ssynchronized(_QUEUE, shared=1)
483 031a3e57 Michael Hanselmann
  def NotifyStart(self):
484 e92376d7 Iustin Pop
    """Mark the opcode as running, not lock-waiting.
485 e92376d7 Iustin Pop

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

491 e92376d7 Iustin Pop
    """
492 9bdab621 Michael Hanselmann
    assert self._op in self._job.ops
493 271daef8 Iustin Pop
    assert self._op.status in (constants.OP_STATUS_WAITLOCK,
494 271daef8 Iustin Pop
                               constants.OP_STATUS_CANCELING)
495 fbf0262f Michael Hanselmann
496 271daef8 Iustin Pop
    # Cancel here if we were asked to
497 dc1e2262 Michael Hanselmann
    self._CheckCancel()
498 fbf0262f Michael Hanselmann
499 e35344b4 Michael Hanselmann
    logging.debug("Opcode is now running")
500 9bdab621 Michael Hanselmann
501 271daef8 Iustin Pop
    self._op.status = constants.OP_STATUS_RUNNING
502 271daef8 Iustin Pop
    self._op.exec_timestamp = TimeStampNow()
503 271daef8 Iustin Pop
504 271daef8 Iustin Pop
    # And finally replicate the job status
505 271daef8 Iustin Pop
    self._queue.UpdateJobUnlocked(self._job)
506 031a3e57 Michael Hanselmann
507 ebb80afa Guido Trotter
  @locking.ssynchronized(_QUEUE, shared=1)
508 9bf5e01f Guido Trotter
  def _AppendFeedback(self, timestamp, log_type, log_msg):
509 9bf5e01f Guido Trotter
    """Internal feedback append function, with locks
510 9bf5e01f Guido Trotter

511 9bf5e01f Guido Trotter
    """
512 9bf5e01f Guido Trotter
    self._job.log_serial += 1
513 9bf5e01f Guido Trotter
    self._op.log.append((self._job.log_serial, timestamp, log_type, log_msg))
514 9bf5e01f Guido Trotter
    self._queue.UpdateJobUnlocked(self._job, replicate=False)
515 9bf5e01f Guido Trotter
516 031a3e57 Michael Hanselmann
  def Feedback(self, *args):
517 031a3e57 Michael Hanselmann
    """Append a log entry.
518 031a3e57 Michael Hanselmann

519 031a3e57 Michael Hanselmann
    """
520 031a3e57 Michael Hanselmann
    assert len(args) < 3
521 031a3e57 Michael Hanselmann
522 031a3e57 Michael Hanselmann
    if len(args) == 1:
523 031a3e57 Michael Hanselmann
      log_type = constants.ELOG_MESSAGE
524 031a3e57 Michael Hanselmann
      log_msg = args[0]
525 031a3e57 Michael Hanselmann
    else:
526 031a3e57 Michael Hanselmann
      (log_type, log_msg) = args
527 031a3e57 Michael Hanselmann
528 031a3e57 Michael Hanselmann
    # The time is split to make serialization easier and not lose
529 031a3e57 Michael Hanselmann
    # precision.
530 031a3e57 Michael Hanselmann
    timestamp = utils.SplitTime(time.time())
531 9bf5e01f Guido Trotter
    self._AppendFeedback(timestamp, log_type, log_msg)
532 031a3e57 Michael Hanselmann
533 acf931b7 Michael Hanselmann
  def CheckCancel(self):
534 acf931b7 Michael Hanselmann
    """Check whether job has been cancelled.
535 ef2df7d3 Michael Hanselmann

536 ef2df7d3 Michael Hanselmann
    """
537 dc1e2262 Michael Hanselmann
    assert self._op.status in (constants.OP_STATUS_WAITLOCK,
538 dc1e2262 Michael Hanselmann
                               constants.OP_STATUS_CANCELING)
539 dc1e2262 Michael Hanselmann
540 dc1e2262 Michael Hanselmann
    # Cancel here if we were asked to
541 dc1e2262 Michael Hanselmann
    self._CheckCancel()
542 dc1e2262 Michael Hanselmann
543 031a3e57 Michael Hanselmann
544 989a8bee Michael Hanselmann
class _JobChangesChecker(object):
545 989a8bee Michael Hanselmann
  def __init__(self, fields, prev_job_info, prev_log_serial):
546 989a8bee Michael Hanselmann
    """Initializes this class.
547 6c2549d6 Guido Trotter

548 989a8bee Michael Hanselmann
    @type fields: list of strings
549 989a8bee Michael Hanselmann
    @param fields: Fields requested by LUXI client
550 989a8bee Michael Hanselmann
    @type prev_job_info: string
551 989a8bee Michael Hanselmann
    @param prev_job_info: previous job info, as passed by the LUXI client
552 989a8bee Michael Hanselmann
    @type prev_log_serial: string
553 989a8bee Michael Hanselmann
    @param prev_log_serial: previous job serial, as passed by the LUXI client
554 6c2549d6 Guido Trotter

555 989a8bee Michael Hanselmann
    """
556 989a8bee Michael Hanselmann
    self._fields = fields
557 989a8bee Michael Hanselmann
    self._prev_job_info = prev_job_info
558 989a8bee Michael Hanselmann
    self._prev_log_serial = prev_log_serial
559 6c2549d6 Guido Trotter
560 989a8bee Michael Hanselmann
  def __call__(self, job):
561 989a8bee Michael Hanselmann
    """Checks whether job has changed.
562 6c2549d6 Guido Trotter

563 989a8bee Michael Hanselmann
    @type job: L{_QueuedJob}
564 989a8bee Michael Hanselmann
    @param job: Job object
565 6c2549d6 Guido Trotter

566 6c2549d6 Guido Trotter
    """
567 989a8bee Michael Hanselmann
    status = job.CalcStatus()
568 989a8bee Michael Hanselmann
    job_info = job.GetInfo(self._fields)
569 989a8bee Michael Hanselmann
    log_entries = job.GetLogEntries(self._prev_log_serial)
570 6c2549d6 Guido Trotter
571 6c2549d6 Guido Trotter
    # Serializing and deserializing data can cause type changes (e.g. from
572 6c2549d6 Guido Trotter
    # tuple to list) or precision loss. We're doing it here so that we get
573 6c2549d6 Guido Trotter
    # the same modifications as the data received from the client. Without
574 6c2549d6 Guido Trotter
    # this, the comparison afterwards might fail without the data being
575 6c2549d6 Guido Trotter
    # significantly different.
576 6c2549d6 Guido Trotter
    # TODO: we just deserialized from disk, investigate how to make sure that
577 6c2549d6 Guido Trotter
    # the job info and log entries are compatible to avoid this further step.
578 989a8bee Michael Hanselmann
    # TODO: Doing something like in testutils.py:UnifyValueType might be more
579 989a8bee Michael Hanselmann
    # efficient, though floats will be tricky
580 989a8bee Michael Hanselmann
    job_info = serializer.LoadJson(serializer.DumpJson(job_info))
581 989a8bee Michael Hanselmann
    log_entries = serializer.LoadJson(serializer.DumpJson(log_entries))
582 6c2549d6 Guido Trotter
583 6c2549d6 Guido Trotter
    # Don't even try to wait if the job is no longer running, there will be
584 6c2549d6 Guido Trotter
    # no changes.
585 989a8bee Michael Hanselmann
    if (status not in (constants.JOB_STATUS_QUEUED,
586 989a8bee Michael Hanselmann
                       constants.JOB_STATUS_RUNNING,
587 989a8bee Michael Hanselmann
                       constants.JOB_STATUS_WAITLOCK) or
588 989a8bee Michael Hanselmann
        job_info != self._prev_job_info or
589 989a8bee Michael Hanselmann
        (log_entries and self._prev_log_serial != log_entries[0][0])):
590 989a8bee Michael Hanselmann
      logging.debug("Job %s changed", job.id)
591 989a8bee Michael Hanselmann
      return (job_info, log_entries)
592 6c2549d6 Guido Trotter
593 989a8bee Michael Hanselmann
    return None
594 989a8bee Michael Hanselmann
595 989a8bee Michael Hanselmann
596 989a8bee Michael Hanselmann
class _JobFileChangesWaiter(object):
597 989a8bee Michael Hanselmann
  def __init__(self, filename):
598 989a8bee Michael Hanselmann
    """Initializes this class.
599 989a8bee Michael Hanselmann

600 989a8bee Michael Hanselmann
    @type filename: string
601 989a8bee Michael Hanselmann
    @param filename: Path to job file
602 989a8bee Michael Hanselmann
    @raises errors.InotifyError: if the notifier cannot be setup
603 6c2549d6 Guido Trotter

604 989a8bee Michael Hanselmann
    """
605 989a8bee Michael Hanselmann
    self._wm = pyinotify.WatchManager()
606 989a8bee Michael Hanselmann
    self._inotify_handler = \
607 989a8bee Michael Hanselmann
      asyncnotifier.SingleFileEventHandler(self._wm, self._OnInotify, filename)
608 989a8bee Michael Hanselmann
    self._notifier = \
609 989a8bee Michael Hanselmann
      pyinotify.Notifier(self._wm, default_proc_fun=self._inotify_handler)
610 989a8bee Michael Hanselmann
    try:
611 989a8bee Michael Hanselmann
      self._inotify_handler.enable()
612 989a8bee Michael Hanselmann
    except Exception:
613 989a8bee Michael Hanselmann
      # pyinotify doesn't close file descriptors automatically
614 989a8bee Michael Hanselmann
      self._notifier.stop()
615 989a8bee Michael Hanselmann
      raise
616 989a8bee Michael Hanselmann
617 989a8bee Michael Hanselmann
  def _OnInotify(self, notifier_enabled):
618 989a8bee Michael Hanselmann
    """Callback for inotify.
619 989a8bee Michael Hanselmann

620 989a8bee Michael Hanselmann
    """
621 6c2549d6 Guido Trotter
    if not notifier_enabled:
622 989a8bee Michael Hanselmann
      self._inotify_handler.enable()
623 989a8bee Michael Hanselmann
624 989a8bee Michael Hanselmann
  def Wait(self, timeout):
625 989a8bee Michael Hanselmann
    """Waits for the job file to change.
626 989a8bee Michael Hanselmann

627 989a8bee Michael Hanselmann
    @type timeout: float
628 989a8bee Michael Hanselmann
    @param timeout: Timeout in seconds
629 989a8bee Michael Hanselmann
    @return: Whether there have been events
630 989a8bee Michael Hanselmann

631 989a8bee Michael Hanselmann
    """
632 989a8bee Michael Hanselmann
    assert timeout >= 0
633 989a8bee Michael Hanselmann
    have_events = self._notifier.check_events(timeout * 1000)
634 989a8bee Michael Hanselmann
    if have_events:
635 989a8bee Michael Hanselmann
      self._notifier.read_events()
636 989a8bee Michael Hanselmann
    self._notifier.process_events()
637 989a8bee Michael Hanselmann
    return have_events
638 989a8bee Michael Hanselmann
639 989a8bee Michael Hanselmann
  def Close(self):
640 989a8bee Michael Hanselmann
    """Closes underlying notifier and its file descriptor.
641 989a8bee Michael Hanselmann

642 989a8bee Michael Hanselmann
    """
643 989a8bee Michael Hanselmann
    self._notifier.stop()
644 989a8bee Michael Hanselmann
645 989a8bee Michael Hanselmann
646 989a8bee Michael Hanselmann
class _JobChangesWaiter(object):
647 989a8bee Michael Hanselmann
  def __init__(self, filename):
648 989a8bee Michael Hanselmann
    """Initializes this class.
649 989a8bee Michael Hanselmann

650 989a8bee Michael Hanselmann
    @type filename: string
651 989a8bee Michael Hanselmann
    @param filename: Path to job file
652 989a8bee Michael Hanselmann

653 989a8bee Michael Hanselmann
    """
654 989a8bee Michael Hanselmann
    self._filewaiter = None
655 989a8bee Michael Hanselmann
    self._filename = filename
656 6c2549d6 Guido Trotter
657 989a8bee Michael Hanselmann
  def Wait(self, timeout):
658 989a8bee Michael Hanselmann
    """Waits for a job to change.
659 6c2549d6 Guido Trotter

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

664 989a8bee Michael Hanselmann
    """
665 989a8bee Michael Hanselmann
    if self._filewaiter:
666 989a8bee Michael Hanselmann
      return self._filewaiter.Wait(timeout)
667 989a8bee Michael Hanselmann
668 989a8bee Michael Hanselmann
    # Lazy setup: Avoid inotify setup cost when job file has already changed.
669 989a8bee Michael Hanselmann
    # If this point is reached, return immediately and let caller check the job
670 989a8bee Michael Hanselmann
    # file again in case there were changes since the last check. This avoids a
671 989a8bee Michael Hanselmann
    # race condition.
672 989a8bee Michael Hanselmann
    self._filewaiter = _JobFileChangesWaiter(self._filename)
673 989a8bee Michael Hanselmann
674 989a8bee Michael Hanselmann
    return True
675 989a8bee Michael Hanselmann
676 989a8bee Michael Hanselmann
  def Close(self):
677 989a8bee Michael Hanselmann
    """Closes underlying waiter.
678 989a8bee Michael Hanselmann

679 989a8bee Michael Hanselmann
    """
680 989a8bee Michael Hanselmann
    if self._filewaiter:
681 989a8bee Michael Hanselmann
      self._filewaiter.Close()
682 989a8bee Michael Hanselmann
683 989a8bee Michael Hanselmann
684 989a8bee Michael Hanselmann
class _WaitForJobChangesHelper(object):
685 989a8bee Michael Hanselmann
  """Helper class using inotify to wait for changes in a job file.
686 989a8bee Michael Hanselmann

687 989a8bee Michael Hanselmann
  This class takes a previous job status and serial, and alerts the client when
688 989a8bee Michael Hanselmann
  the current job status has changed.
689 989a8bee Michael Hanselmann

690 989a8bee Michael Hanselmann
  """
691 989a8bee Michael Hanselmann
  @staticmethod
692 989a8bee Michael Hanselmann
  def _CheckForChanges(job_load_fn, check_fn):
693 989a8bee Michael Hanselmann
    job = job_load_fn()
694 989a8bee Michael Hanselmann
    if not job:
695 989a8bee Michael Hanselmann
      raise errors.JobLost()
696 989a8bee Michael Hanselmann
697 989a8bee Michael Hanselmann
    result = check_fn(job)
698 989a8bee Michael Hanselmann
    if result is None:
699 989a8bee Michael Hanselmann
      raise utils.RetryAgain()
700 989a8bee Michael Hanselmann
701 989a8bee Michael Hanselmann
    return result
702 989a8bee Michael Hanselmann
703 989a8bee Michael Hanselmann
  def __call__(self, filename, job_load_fn,
704 989a8bee Michael Hanselmann
               fields, prev_job_info, prev_log_serial, timeout):
705 989a8bee Michael Hanselmann
    """Waits for changes on a job.
706 989a8bee Michael Hanselmann

707 989a8bee Michael Hanselmann
    @type filename: string
708 989a8bee Michael Hanselmann
    @param filename: File on which to wait for changes
709 989a8bee Michael Hanselmann
    @type job_load_fn: callable
710 989a8bee Michael Hanselmann
    @param job_load_fn: Function to load job
711 989a8bee Michael Hanselmann
    @type fields: list of strings
712 989a8bee Michael Hanselmann
    @param fields: Which fields to check for changes
713 989a8bee Michael Hanselmann
    @type prev_job_info: list or None
714 989a8bee Michael Hanselmann
    @param prev_job_info: Last job information returned
715 989a8bee Michael Hanselmann
    @type prev_log_serial: int
716 989a8bee Michael Hanselmann
    @param prev_log_serial: Last job message serial number
717 989a8bee Michael Hanselmann
    @type timeout: float
718 989a8bee Michael Hanselmann
    @param timeout: maximum time to wait in seconds
719 989a8bee Michael Hanselmann

720 989a8bee Michael Hanselmann
    """
721 6c2549d6 Guido Trotter
    try:
722 989a8bee Michael Hanselmann
      check_fn = _JobChangesChecker(fields, prev_job_info, prev_log_serial)
723 989a8bee Michael Hanselmann
      waiter = _JobChangesWaiter(filename)
724 989a8bee Michael Hanselmann
      try:
725 989a8bee Michael Hanselmann
        return utils.Retry(compat.partial(self._CheckForChanges,
726 989a8bee Michael Hanselmann
                                          job_load_fn, check_fn),
727 989a8bee Michael Hanselmann
                           utils.RETRY_REMAINING_TIME, timeout,
728 989a8bee Michael Hanselmann
                           wait_fn=waiter.Wait)
729 989a8bee Michael Hanselmann
      finally:
730 989a8bee Michael Hanselmann
        waiter.Close()
731 6c2549d6 Guido Trotter
    except (errors.InotifyError, errors.JobLost):
732 6c2549d6 Guido Trotter
      return None
733 6c2549d6 Guido Trotter
    except utils.RetryTimeout:
734 6c2549d6 Guido Trotter
      return constants.JOB_NOTCHANGED
735 6c2549d6 Guido Trotter
736 6c2549d6 Guido Trotter
737 6760e4ed Michael Hanselmann
def _EncodeOpError(err):
738 6760e4ed Michael Hanselmann
  """Encodes an error which occurred while processing an opcode.
739 6760e4ed Michael Hanselmann

740 6760e4ed Michael Hanselmann
  """
741 6760e4ed Michael Hanselmann
  if isinstance(err, errors.GenericError):
742 6760e4ed Michael Hanselmann
    to_encode = err
743 6760e4ed Michael Hanselmann
  else:
744 6760e4ed Michael Hanselmann
    to_encode = errors.OpExecError(str(err))
745 6760e4ed Michael Hanselmann
746 6760e4ed Michael Hanselmann
  return errors.EncodeException(to_encode)
747 6760e4ed Michael Hanselmann
748 6760e4ed Michael Hanselmann
749 26d3fd2f Michael Hanselmann
class _TimeoutStrategyWrapper:
750 26d3fd2f Michael Hanselmann
  def __init__(self, fn):
751 26d3fd2f Michael Hanselmann
    """Initializes this class.
752 26d3fd2f Michael Hanselmann

753 26d3fd2f Michael Hanselmann
    """
754 26d3fd2f Michael Hanselmann
    self._fn = fn
755 26d3fd2f Michael Hanselmann
    self._next = None
756 26d3fd2f Michael Hanselmann
757 26d3fd2f Michael Hanselmann
  def _Advance(self):
758 26d3fd2f Michael Hanselmann
    """Gets the next timeout if necessary.
759 26d3fd2f Michael Hanselmann

760 26d3fd2f Michael Hanselmann
    """
761 26d3fd2f Michael Hanselmann
    if self._next is None:
762 26d3fd2f Michael Hanselmann
      self._next = self._fn()
763 26d3fd2f Michael Hanselmann
764 26d3fd2f Michael Hanselmann
  def Peek(self):
765 26d3fd2f Michael Hanselmann
    """Returns the next timeout.
766 26d3fd2f Michael Hanselmann

767 26d3fd2f Michael Hanselmann
    """
768 26d3fd2f Michael Hanselmann
    self._Advance()
769 26d3fd2f Michael Hanselmann
    return self._next
770 26d3fd2f Michael Hanselmann
771 26d3fd2f Michael Hanselmann
  def Next(self):
772 26d3fd2f Michael Hanselmann
    """Returns the current timeout and advances the internal state.
773 26d3fd2f Michael Hanselmann

774 26d3fd2f Michael Hanselmann
    """
775 26d3fd2f Michael Hanselmann
    self._Advance()
776 26d3fd2f Michael Hanselmann
    result = self._next
777 26d3fd2f Michael Hanselmann
    self._next = None
778 26d3fd2f Michael Hanselmann
    return result
779 26d3fd2f Michael Hanselmann
780 26d3fd2f Michael Hanselmann
781 b80cc518 Michael Hanselmann
class _OpExecContext:
782 26d3fd2f Michael Hanselmann
  def __init__(self, op, index, log_prefix, timeout_strategy_factory):
783 b80cc518 Michael Hanselmann
    """Initializes this class.
784 b80cc518 Michael Hanselmann

785 b80cc518 Michael Hanselmann
    """
786 b80cc518 Michael Hanselmann
    self.op = op
787 b80cc518 Michael Hanselmann
    self.index = index
788 b80cc518 Michael Hanselmann
    self.log_prefix = log_prefix
789 b80cc518 Michael Hanselmann
    self.summary = op.input.Summary()
790 b80cc518 Michael Hanselmann
791 26d3fd2f Michael Hanselmann
    self._timeout_strategy_factory = timeout_strategy_factory
792 26d3fd2f Michael Hanselmann
    self._ResetTimeoutStrategy()
793 26d3fd2f Michael Hanselmann
794 26d3fd2f Michael Hanselmann
  def _ResetTimeoutStrategy(self):
795 26d3fd2f Michael Hanselmann
    """Creates a new timeout strategy.
796 26d3fd2f Michael Hanselmann

797 26d3fd2f Michael Hanselmann
    """
798 26d3fd2f Michael Hanselmann
    self._timeout_strategy = \
799 26d3fd2f Michael Hanselmann
      _TimeoutStrategyWrapper(self._timeout_strategy_factory().NextAttempt)
800 26d3fd2f Michael Hanselmann
801 26d3fd2f Michael Hanselmann
  def CheckPriorityIncrease(self):
802 26d3fd2f Michael Hanselmann
    """Checks whether priority can and should be increased.
803 26d3fd2f Michael Hanselmann

804 26d3fd2f Michael Hanselmann
    Called when locks couldn't be acquired.
805 26d3fd2f Michael Hanselmann

806 26d3fd2f Michael Hanselmann
    """
807 26d3fd2f Michael Hanselmann
    op = self.op
808 26d3fd2f Michael Hanselmann
809 26d3fd2f Michael Hanselmann
    # Exhausted all retries and next round should not use blocking acquire
810 26d3fd2f Michael Hanselmann
    # for locks?
811 26d3fd2f Michael Hanselmann
    if (self._timeout_strategy.Peek() is None and
812 26d3fd2f Michael Hanselmann
        op.priority > constants.OP_PRIO_HIGHEST):
813 26d3fd2f Michael Hanselmann
      logging.debug("Increasing priority")
814 26d3fd2f Michael Hanselmann
      op.priority -= 1
815 26d3fd2f Michael Hanselmann
      self._ResetTimeoutStrategy()
816 26d3fd2f Michael Hanselmann
      return True
817 26d3fd2f Michael Hanselmann
818 26d3fd2f Michael Hanselmann
    return False
819 26d3fd2f Michael Hanselmann
820 26d3fd2f Michael Hanselmann
  def GetNextLockTimeout(self):
821 26d3fd2f Michael Hanselmann
    """Returns the next lock acquire timeout.
822 26d3fd2f Michael Hanselmann

823 26d3fd2f Michael Hanselmann
    """
824 26d3fd2f Michael Hanselmann
    return self._timeout_strategy.Next()
825 26d3fd2f Michael Hanselmann
826 b80cc518 Michael Hanselmann
827 be760ba8 Michael Hanselmann
class _JobProcessor(object):
828 26d3fd2f Michael Hanselmann
  def __init__(self, queue, opexec_fn, job,
829 26d3fd2f Michael Hanselmann
               _timeout_strategy_factory=mcpu.LockAttemptTimeoutStrategy):
830 be760ba8 Michael Hanselmann
    """Initializes this class.
831 be760ba8 Michael Hanselmann

832 be760ba8 Michael Hanselmann
    """
833 be760ba8 Michael Hanselmann
    self.queue = queue
834 be760ba8 Michael Hanselmann
    self.opexec_fn = opexec_fn
835 be760ba8 Michael Hanselmann
    self.job = job
836 26d3fd2f Michael Hanselmann
    self._timeout_strategy_factory = _timeout_strategy_factory
837 be760ba8 Michael Hanselmann
838 be760ba8 Michael Hanselmann
  @staticmethod
839 26d3fd2f Michael Hanselmann
  def _FindNextOpcode(job, timeout_strategy_factory):
840 be760ba8 Michael Hanselmann
    """Locates the next opcode to run.
841 be760ba8 Michael Hanselmann

842 be760ba8 Michael Hanselmann
    @type job: L{_QueuedJob}
843 be760ba8 Michael Hanselmann
    @param job: Job object
844 26d3fd2f Michael Hanselmann
    @param timeout_strategy_factory: Callable to create new timeout strategy
845 be760ba8 Michael Hanselmann

846 be760ba8 Michael Hanselmann
    """
847 be760ba8 Michael Hanselmann
    # Create some sort of a cache to speed up locating next opcode for future
848 be760ba8 Michael Hanselmann
    # lookups
849 be760ba8 Michael Hanselmann
    # TODO: Consider splitting _QueuedJob.ops into two separate lists, one for
850 be760ba8 Michael Hanselmann
    # pending and one for processed ops.
851 03b63608 Michael Hanselmann
    if job.ops_iter is None:
852 03b63608 Michael Hanselmann
      job.ops_iter = enumerate(job.ops)
853 be760ba8 Michael Hanselmann
854 be760ba8 Michael Hanselmann
    # Find next opcode to run
855 be760ba8 Michael Hanselmann
    while True:
856 be760ba8 Michael Hanselmann
      try:
857 03b63608 Michael Hanselmann
        (idx, op) = job.ops_iter.next()
858 be760ba8 Michael Hanselmann
      except StopIteration:
859 be760ba8 Michael Hanselmann
        raise errors.ProgrammerError("Called for a finished job")
860 be760ba8 Michael Hanselmann
861 be760ba8 Michael Hanselmann
      if op.status == constants.OP_STATUS_RUNNING:
862 be760ba8 Michael Hanselmann
        # Found an opcode already marked as running
863 be760ba8 Michael Hanselmann
        raise errors.ProgrammerError("Called for job marked as running")
864 be760ba8 Michael Hanselmann
865 26d3fd2f Michael Hanselmann
      opctx = _OpExecContext(op, idx, "Op %s/%s" % (idx + 1, len(job.ops)),
866 26d3fd2f Michael Hanselmann
                             timeout_strategy_factory)
867 be760ba8 Michael Hanselmann
868 be760ba8 Michael Hanselmann
      if op.status == constants.OP_STATUS_CANCELED:
869 be760ba8 Michael Hanselmann
        # Cancelled jobs are handled by the caller
870 be760ba8 Michael Hanselmann
        assert not compat.any(i.status != constants.OP_STATUS_CANCELED
871 be760ba8 Michael Hanselmann
                              for i in job.ops[idx:])
872 be760ba8 Michael Hanselmann
873 be760ba8 Michael Hanselmann
      elif op.status in constants.OPS_FINALIZED:
874 be760ba8 Michael Hanselmann
        # This is a job that was partially completed before master daemon
875 be760ba8 Michael Hanselmann
        # shutdown, so it can be expected that some opcodes are already
876 be760ba8 Michael Hanselmann
        # completed successfully (if any did error out, then the whole job
877 be760ba8 Michael Hanselmann
        # should have been aborted and not resubmitted for processing).
878 be760ba8 Michael Hanselmann
        logging.info("%s: opcode %s already processed, skipping",
879 b80cc518 Michael Hanselmann
                     opctx.log_prefix, opctx.summary)
880 be760ba8 Michael Hanselmann
        continue
881 be760ba8 Michael Hanselmann
882 b80cc518 Michael Hanselmann
      return opctx
883 be760ba8 Michael Hanselmann
884 be760ba8 Michael Hanselmann
  @staticmethod
885 be760ba8 Michael Hanselmann
  def _MarkWaitlock(job, op):
886 be760ba8 Michael Hanselmann
    """Marks an opcode as waiting for locks.
887 be760ba8 Michael Hanselmann

888 be760ba8 Michael Hanselmann
    The job's start timestamp is also set if necessary.
889 be760ba8 Michael Hanselmann

890 be760ba8 Michael Hanselmann
    @type job: L{_QueuedJob}
891 be760ba8 Michael Hanselmann
    @param job: Job object
892 a38e8674 Michael Hanselmann
    @type op: L{_QueuedOpCode}
893 a38e8674 Michael Hanselmann
    @param op: Opcode object
894 be760ba8 Michael Hanselmann

895 be760ba8 Michael Hanselmann
    """
896 be760ba8 Michael Hanselmann
    assert op in job.ops
897 5fd6b694 Michael Hanselmann
    assert op.status in (constants.OP_STATUS_QUEUED,
898 5fd6b694 Michael Hanselmann
                         constants.OP_STATUS_WAITLOCK)
899 5fd6b694 Michael Hanselmann
900 5fd6b694 Michael Hanselmann
    update = False
901 be760ba8 Michael Hanselmann
902 be760ba8 Michael Hanselmann
    op.result = None
903 5fd6b694 Michael Hanselmann
904 5fd6b694 Michael Hanselmann
    if op.status == constants.OP_STATUS_QUEUED:
905 5fd6b694 Michael Hanselmann
      op.status = constants.OP_STATUS_WAITLOCK
906 5fd6b694 Michael Hanselmann
      update = True
907 5fd6b694 Michael Hanselmann
908 5fd6b694 Michael Hanselmann
    if op.start_timestamp is None:
909 5fd6b694 Michael Hanselmann
      op.start_timestamp = TimeStampNow()
910 5fd6b694 Michael Hanselmann
      update = True
911 be760ba8 Michael Hanselmann
912 be760ba8 Michael Hanselmann
    if job.start_timestamp is None:
913 be760ba8 Michael Hanselmann
      job.start_timestamp = op.start_timestamp
914 5fd6b694 Michael Hanselmann
      update = True
915 5fd6b694 Michael Hanselmann
916 5fd6b694 Michael Hanselmann
    assert op.status == constants.OP_STATUS_WAITLOCK
917 5fd6b694 Michael Hanselmann
918 5fd6b694 Michael Hanselmann
    return update
919 be760ba8 Michael Hanselmann
920 b80cc518 Michael Hanselmann
  def _ExecOpCodeUnlocked(self, opctx):
921 be760ba8 Michael Hanselmann
    """Processes one opcode and returns the result.
922 be760ba8 Michael Hanselmann

923 be760ba8 Michael Hanselmann
    """
924 b80cc518 Michael Hanselmann
    op = opctx.op
925 b80cc518 Michael Hanselmann
926 be760ba8 Michael Hanselmann
    assert op.status == constants.OP_STATUS_WAITLOCK
927 be760ba8 Michael Hanselmann
928 26d3fd2f Michael Hanselmann
    timeout = opctx.GetNextLockTimeout()
929 26d3fd2f Michael Hanselmann
930 be760ba8 Michael Hanselmann
    try:
931 be760ba8 Michael Hanselmann
      # Make sure not to hold queue lock while calling ExecOpCode
932 be760ba8 Michael Hanselmann
      result = self.opexec_fn(op.input,
933 26d3fd2f Michael Hanselmann
                              _OpExecCallbacks(self.queue, self.job, op),
934 f23db633 Michael Hanselmann
                              timeout=timeout, priority=op.priority)
935 26d3fd2f Michael Hanselmann
    except mcpu.LockAcquireTimeout:
936 26d3fd2f Michael Hanselmann
      assert timeout is not None, "Received timeout for blocking acquire"
937 26d3fd2f Michael Hanselmann
      logging.debug("Couldn't acquire locks in %0.6fs", timeout)
938 9e49dfc5 Michael Hanselmann
939 9e49dfc5 Michael Hanselmann
      assert op.status in (constants.OP_STATUS_WAITLOCK,
940 9e49dfc5 Michael Hanselmann
                           constants.OP_STATUS_CANCELING)
941 9e49dfc5 Michael Hanselmann
942 9e49dfc5 Michael Hanselmann
      # Was job cancelled while we were waiting for the lock?
943 9e49dfc5 Michael Hanselmann
      if op.status == constants.OP_STATUS_CANCELING:
944 9e49dfc5 Michael Hanselmann
        return (constants.OP_STATUS_CANCELING, None)
945 9e49dfc5 Michael Hanselmann
946 5fd6b694 Michael Hanselmann
      # Stay in waitlock while trying to re-acquire lock
947 5fd6b694 Michael Hanselmann
      return (constants.OP_STATUS_WAITLOCK, None)
948 be760ba8 Michael Hanselmann
    except CancelJob:
949 b80cc518 Michael Hanselmann
      logging.exception("%s: Canceling job", opctx.log_prefix)
950 be760ba8 Michael Hanselmann
      assert op.status == constants.OP_STATUS_CANCELING
951 be760ba8 Michael Hanselmann
      return (constants.OP_STATUS_CANCELING, None)
952 be760ba8 Michael Hanselmann
    except Exception, err: # pylint: disable-msg=W0703
953 b80cc518 Michael Hanselmann
      logging.exception("%s: Caught exception in %s",
954 b80cc518 Michael Hanselmann
                        opctx.log_prefix, opctx.summary)
955 be760ba8 Michael Hanselmann
      return (constants.OP_STATUS_ERROR, _EncodeOpError(err))
956 be760ba8 Michael Hanselmann
    else:
957 b80cc518 Michael Hanselmann
      logging.debug("%s: %s successful",
958 b80cc518 Michael Hanselmann
                    opctx.log_prefix, opctx.summary)
959 be760ba8 Michael Hanselmann
      return (constants.OP_STATUS_SUCCESS, result)
960 be760ba8 Michael Hanselmann
961 26d3fd2f Michael Hanselmann
  def __call__(self, _nextop_fn=None):
962 be760ba8 Michael Hanselmann
    """Continues execution of a job.
963 be760ba8 Michael Hanselmann

964 26d3fd2f Michael Hanselmann
    @param _nextop_fn: Callback function for tests
965 be760ba8 Michael Hanselmann
    @rtype: bool
966 be760ba8 Michael Hanselmann
    @return: True if job is finished, False if processor needs to be called
967 be760ba8 Michael Hanselmann
             again
968 be760ba8 Michael Hanselmann

969 be760ba8 Michael Hanselmann
    """
970 be760ba8 Michael Hanselmann
    queue = self.queue
971 be760ba8 Michael Hanselmann
    job = self.job
972 be760ba8 Michael Hanselmann
973 be760ba8 Michael Hanselmann
    logging.debug("Processing job %s", job.id)
974 be760ba8 Michael Hanselmann
975 be760ba8 Michael Hanselmann
    queue.acquire(shared=1)
976 be760ba8 Michael Hanselmann
    try:
977 be760ba8 Michael Hanselmann
      opcount = len(job.ops)
978 be760ba8 Michael Hanselmann
979 26d3fd2f Michael Hanselmann
      # Is a previous opcode still pending?
980 26d3fd2f Michael Hanselmann
      if job.cur_opctx:
981 26d3fd2f Michael Hanselmann
        opctx = job.cur_opctx
982 5fd6b694 Michael Hanselmann
        job.cur_opctx = None
983 26d3fd2f Michael Hanselmann
      else:
984 26d3fd2f Michael Hanselmann
        if __debug__ and _nextop_fn:
985 26d3fd2f Michael Hanselmann
          _nextop_fn()
986 26d3fd2f Michael Hanselmann
        opctx = self._FindNextOpcode(job, self._timeout_strategy_factory)
987 26d3fd2f Michael Hanselmann
988 b80cc518 Michael Hanselmann
      op = opctx.op
989 be760ba8 Michael Hanselmann
990 be760ba8 Michael Hanselmann
      # Consistency check
991 be760ba8 Michael Hanselmann
      assert compat.all(i.status in (constants.OP_STATUS_QUEUED,
992 30c945d0 Michael Hanselmann
                                     constants.OP_STATUS_CANCELING,
993 be760ba8 Michael Hanselmann
                                     constants.OP_STATUS_CANCELED)
994 5fd6b694 Michael Hanselmann
                        for i in job.ops[opctx.index + 1:])
995 be760ba8 Michael Hanselmann
996 be760ba8 Michael Hanselmann
      assert op.status in (constants.OP_STATUS_QUEUED,
997 be760ba8 Michael Hanselmann
                           constants.OP_STATUS_WAITLOCK,
998 30c945d0 Michael Hanselmann
                           constants.OP_STATUS_CANCELING,
999 be760ba8 Michael Hanselmann
                           constants.OP_STATUS_CANCELED)
1000 be760ba8 Michael Hanselmann
1001 26d3fd2f Michael Hanselmann
      assert (op.priority <= constants.OP_PRIO_LOWEST and
1002 26d3fd2f Michael Hanselmann
              op.priority >= constants.OP_PRIO_HIGHEST)
1003 26d3fd2f Michael Hanselmann
1004 30c945d0 Michael Hanselmann
      if op.status not in (constants.OP_STATUS_CANCELING,
1005 30c945d0 Michael Hanselmann
                           constants.OP_STATUS_CANCELED):
1006 30c945d0 Michael Hanselmann
        assert op.status in (constants.OP_STATUS_QUEUED,
1007 30c945d0 Michael Hanselmann
                             constants.OP_STATUS_WAITLOCK)
1008 30c945d0 Michael Hanselmann
1009 be760ba8 Michael Hanselmann
        # Prepare to start opcode
1010 5fd6b694 Michael Hanselmann
        if self._MarkWaitlock(job, op):
1011 5fd6b694 Michael Hanselmann
          # Write to disk
1012 5fd6b694 Michael Hanselmann
          queue.UpdateJobUnlocked(job)
1013 be760ba8 Michael Hanselmann
1014 be760ba8 Michael Hanselmann
        assert op.status == constants.OP_STATUS_WAITLOCK
1015 be760ba8 Michael Hanselmann
        assert job.CalcStatus() == constants.JOB_STATUS_WAITLOCK
1016 5fd6b694 Michael Hanselmann
        assert job.start_timestamp and op.start_timestamp
1017 be760ba8 Michael Hanselmann
1018 b80cc518 Michael Hanselmann
        logging.info("%s: opcode %s waiting for locks",
1019 b80cc518 Michael Hanselmann
                     opctx.log_prefix, opctx.summary)
1020 be760ba8 Michael Hanselmann
1021 be760ba8 Michael Hanselmann
        queue.release()
1022 be760ba8 Michael Hanselmann
        try:
1023 b80cc518 Michael Hanselmann
          (op_status, op_result) = self._ExecOpCodeUnlocked(opctx)
1024 be760ba8 Michael Hanselmann
        finally:
1025 be760ba8 Michael Hanselmann
          queue.acquire(shared=1)
1026 be760ba8 Michael Hanselmann
1027 be760ba8 Michael Hanselmann
        op.status = op_status
1028 be760ba8 Michael Hanselmann
        op.result = op_result
1029 be760ba8 Michael Hanselmann
1030 5fd6b694 Michael Hanselmann
        if op.status == constants.OP_STATUS_WAITLOCK:
1031 26d3fd2f Michael Hanselmann
          # Couldn't get locks in time
1032 26d3fd2f Michael Hanselmann
          assert not op.end_timestamp
1033 be760ba8 Michael Hanselmann
        else:
1034 26d3fd2f Michael Hanselmann
          # Finalize opcode
1035 26d3fd2f Michael Hanselmann
          op.end_timestamp = TimeStampNow()
1036 be760ba8 Michael Hanselmann
1037 26d3fd2f Michael Hanselmann
          if op.status == constants.OP_STATUS_CANCELING:
1038 26d3fd2f Michael Hanselmann
            assert not compat.any(i.status != constants.OP_STATUS_CANCELING
1039 26d3fd2f Michael Hanselmann
                                  for i in job.ops[opctx.index:])
1040 26d3fd2f Michael Hanselmann
          else:
1041 26d3fd2f Michael Hanselmann
            assert op.status in constants.OPS_FINALIZED
1042 be760ba8 Michael Hanselmann
1043 5fd6b694 Michael Hanselmann
      if op.status == constants.OP_STATUS_WAITLOCK:
1044 be760ba8 Michael Hanselmann
        finalize = False
1045 be760ba8 Michael Hanselmann
1046 5fd6b694 Michael Hanselmann
        if opctx.CheckPriorityIncrease():
1047 5fd6b694 Michael Hanselmann
          # Priority was changed, need to update on-disk file
1048 5fd6b694 Michael Hanselmann
          queue.UpdateJobUnlocked(job)
1049 be760ba8 Michael Hanselmann
1050 26d3fd2f Michael Hanselmann
        # Keep around for another round
1051 26d3fd2f Michael Hanselmann
        job.cur_opctx = opctx
1052 be760ba8 Michael Hanselmann
1053 26d3fd2f Michael Hanselmann
        assert (op.priority <= constants.OP_PRIO_LOWEST and
1054 26d3fd2f Michael Hanselmann
                op.priority >= constants.OP_PRIO_HIGHEST)
1055 be760ba8 Michael Hanselmann
1056 26d3fd2f Michael Hanselmann
        # In no case must the status be finalized here
1057 5fd6b694 Michael Hanselmann
        assert job.CalcStatus() == constants.JOB_STATUS_WAITLOCK
1058 be760ba8 Michael Hanselmann
1059 be760ba8 Michael Hanselmann
      else:
1060 26d3fd2f Michael Hanselmann
        # Ensure all opcodes so far have been successful
1061 26d3fd2f Michael Hanselmann
        assert (opctx.index == 0 or
1062 26d3fd2f Michael Hanselmann
                compat.all(i.status == constants.OP_STATUS_SUCCESS
1063 26d3fd2f Michael Hanselmann
                           for i in job.ops[:opctx.index]))
1064 26d3fd2f Michael Hanselmann
1065 26d3fd2f Michael Hanselmann
        # Reset context
1066 26d3fd2f Michael Hanselmann
        job.cur_opctx = None
1067 26d3fd2f Michael Hanselmann
1068 26d3fd2f Michael Hanselmann
        if op.status == constants.OP_STATUS_SUCCESS:
1069 26d3fd2f Michael Hanselmann
          finalize = False
1070 26d3fd2f Michael Hanselmann
1071 26d3fd2f Michael Hanselmann
        elif op.status == constants.OP_STATUS_ERROR:
1072 26d3fd2f Michael Hanselmann
          # Ensure failed opcode has an exception as its result
1073 26d3fd2f Michael Hanselmann
          assert errors.GetEncodedError(job.ops[opctx.index].result)
1074 26d3fd2f Michael Hanselmann
1075 26d3fd2f Michael Hanselmann
          to_encode = errors.OpExecError("Preceding opcode failed")
1076 26d3fd2f Michael Hanselmann
          job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
1077 26d3fd2f Michael Hanselmann
                                _EncodeOpError(to_encode))
1078 26d3fd2f Michael Hanselmann
          finalize = True
1079 be760ba8 Michael Hanselmann
1080 26d3fd2f Michael Hanselmann
          # Consistency check
1081 26d3fd2f Michael Hanselmann
          assert compat.all(i.status == constants.OP_STATUS_ERROR and
1082 26d3fd2f Michael Hanselmann
                            errors.GetEncodedError(i.result)
1083 26d3fd2f Michael Hanselmann
                            for i in job.ops[opctx.index:])
1084 be760ba8 Michael Hanselmann
1085 26d3fd2f Michael Hanselmann
        elif op.status == constants.OP_STATUS_CANCELING:
1086 26d3fd2f Michael Hanselmann
          job.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
1087 26d3fd2f Michael Hanselmann
                                "Job canceled by request")
1088 26d3fd2f Michael Hanselmann
          finalize = True
1089 26d3fd2f Michael Hanselmann
1090 26d3fd2f Michael Hanselmann
        elif op.status == constants.OP_STATUS_CANCELED:
1091 26d3fd2f Michael Hanselmann
          finalize = True
1092 26d3fd2f Michael Hanselmann
1093 26d3fd2f Michael Hanselmann
        else:
1094 26d3fd2f Michael Hanselmann
          raise errors.ProgrammerError("Unknown status '%s'" % op.status)
1095 26d3fd2f Michael Hanselmann
1096 26d3fd2f Michael Hanselmann
        # Finalizing or last opcode?
1097 26d3fd2f Michael Hanselmann
        if finalize or opctx.index == (opcount - 1):
1098 26d3fd2f Michael Hanselmann
          # All opcodes have been run, finalize job
1099 26d3fd2f Michael Hanselmann
          job.end_timestamp = TimeStampNow()
1100 26d3fd2f Michael Hanselmann
1101 26d3fd2f Michael Hanselmann
        # Write to disk. If the job status is final, this is the final write
1102 26d3fd2f Michael Hanselmann
        # allowed. Once the file has been written, it can be archived anytime.
1103 26d3fd2f Michael Hanselmann
        queue.UpdateJobUnlocked(job)
1104 be760ba8 Michael Hanselmann
1105 26d3fd2f Michael Hanselmann
        if finalize or opctx.index == (opcount - 1):
1106 26d3fd2f Michael Hanselmann
          logging.info("Finished job %s, status = %s", job.id, job.CalcStatus())
1107 26d3fd2f Michael Hanselmann
          return True
1108 be760ba8 Michael Hanselmann
1109 be760ba8 Michael Hanselmann
      return False
1110 be760ba8 Michael Hanselmann
    finally:
1111 be760ba8 Michael Hanselmann
      queue.release()
1112 be760ba8 Michael Hanselmann
1113 be760ba8 Michael Hanselmann
1114 031a3e57 Michael Hanselmann
class _JobQueueWorker(workerpool.BaseWorker):
1115 031a3e57 Michael Hanselmann
  """The actual job workers.
1116 031a3e57 Michael Hanselmann

1117 031a3e57 Michael Hanselmann
  """
1118 7260cfbe Iustin Pop
  def RunTask(self, job): # pylint: disable-msg=W0221
1119 e2715f69 Michael Hanselmann
    """Job executor.
1120 e2715f69 Michael Hanselmann

1121 be760ba8 Michael Hanselmann
    This functions processes a job. It is closely tied to the L{_QueuedJob} and
1122 be760ba8 Michael Hanselmann
    L{_QueuedOpCode} classes.
1123 e2715f69 Michael Hanselmann

1124 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
1125 ea03467c Iustin Pop
    @param job: the job to be processed
1126 ea03467c Iustin Pop

1127 e2715f69 Michael Hanselmann
    """
1128 be760ba8 Michael Hanselmann
    queue = job.queue
1129 be760ba8 Michael Hanselmann
    assert queue == self.pool.queue
1130 be760ba8 Michael Hanselmann
1131 daba67c7 Michael Hanselmann
    self.SetTaskName("Job%s" % job.id)
1132 daba67c7 Michael Hanselmann
1133 be760ba8 Michael Hanselmann
    proc = mcpu.Processor(queue.context, job.id)
1134 be760ba8 Michael Hanselmann
1135 be760ba8 Michael Hanselmann
    if not _JobProcessor(queue, proc.ExecOpCode, job)():
1136 be760ba8 Michael Hanselmann
      # Schedule again
1137 26d3fd2f Michael Hanselmann
      raise workerpool.DeferTask(priority=job.CalcPriority())
1138 e2715f69 Michael Hanselmann
1139 e2715f69 Michael Hanselmann
1140 e2715f69 Michael Hanselmann
class _JobQueueWorkerPool(workerpool.WorkerPool):
1141 ea03467c Iustin Pop
  """Simple class implementing a job-processing workerpool.
1142 ea03467c Iustin Pop

1143 ea03467c Iustin Pop
  """
1144 5bdce580 Michael Hanselmann
  def __init__(self, queue):
1145 89e2b4d2 Michael Hanselmann
    super(_JobQueueWorkerPool, self).__init__("JobQueue",
1146 89e2b4d2 Michael Hanselmann
                                              JOBQUEUE_THREADS,
1147 e2715f69 Michael Hanselmann
                                              _JobQueueWorker)
1148 5bdce580 Michael Hanselmann
    self.queue = queue
1149 e2715f69 Michael Hanselmann
1150 e2715f69 Michael Hanselmann
1151 6c881c52 Iustin Pop
def _RequireOpenQueue(fn):
1152 6c881c52 Iustin Pop
  """Decorator for "public" functions.
1153 ea03467c Iustin Pop

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

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

1162 6c881c52 Iustin Pop
  Example::
1163 ebb80afa Guido Trotter
    @locking.ssynchronized(_LOCK)
1164 6c881c52 Iustin Pop
    @_RequireOpenQueue
1165 6c881c52 Iustin Pop
    def Example(self):
1166 6c881c52 Iustin Pop
      pass
1167 db37da70 Michael Hanselmann

1168 6c881c52 Iustin Pop
  """
1169 6c881c52 Iustin Pop
  def wrapper(self, *args, **kwargs):
1170 7260cfbe Iustin Pop
    # pylint: disable-msg=W0212
1171 a71f9c7d Guido Trotter
    assert self._queue_filelock is not None, "Queue should be open"
1172 6c881c52 Iustin Pop
    return fn(self, *args, **kwargs)
1173 6c881c52 Iustin Pop
  return wrapper
1174 db37da70 Michael Hanselmann
1175 db37da70 Michael Hanselmann
1176 6c881c52 Iustin Pop
class JobQueue(object):
1177 6c881c52 Iustin Pop
  """Queue used to manage the jobs.
1178 db37da70 Michael Hanselmann

1179 6c881c52 Iustin Pop
  @cvar _RE_JOB_FILE: regex matching the valid job file names
1180 6c881c52 Iustin Pop

1181 6c881c52 Iustin Pop
  """
1182 6c881c52 Iustin Pop
  _RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
1183 db37da70 Michael Hanselmann
1184 85f03e0d Michael Hanselmann
  def __init__(self, context):
1185 ea03467c Iustin Pop
    """Constructor for JobQueue.
1186 ea03467c Iustin Pop

1187 ea03467c Iustin Pop
    The constructor will initialize the job queue object and then
1188 ea03467c Iustin Pop
    start loading the current jobs from disk, either for starting them
1189 ea03467c Iustin Pop
    (if they were queue) or for aborting them (if they were already
1190 ea03467c Iustin Pop
    running).
1191 ea03467c Iustin Pop

1192 ea03467c Iustin Pop
    @type context: GanetiContext
1193 ea03467c Iustin Pop
    @param context: the context object for access to the configuration
1194 ea03467c Iustin Pop
        data and other ganeti objects
1195 ea03467c Iustin Pop

1196 ea03467c Iustin Pop
    """
1197 5bdce580 Michael Hanselmann
    self.context = context
1198 5685c1a5 Michael Hanselmann
    self._memcache = weakref.WeakValueDictionary()
1199 b705c7a6 Manuel Franceschini
    self._my_hostname = netutils.Hostname.GetSysName()
1200 f1da30e6 Michael Hanselmann
1201 ebb80afa Guido Trotter
    # The Big JobQueue lock. If a code block or method acquires it in shared
1202 ebb80afa Guido Trotter
    # mode safe it must guarantee concurrency with all the code acquiring it in
1203 ebb80afa Guido Trotter
    # shared mode, including itself. In order not to acquire it at all
1204 ebb80afa Guido Trotter
    # concurrency must be guaranteed with all code acquiring it in shared mode
1205 ebb80afa Guido Trotter
    # and all code acquiring it exclusively.
1206 7f93570a Iustin Pop
    self._lock = locking.SharedLock("JobQueue")
1207 ebb80afa Guido Trotter
1208 ebb80afa Guido Trotter
    self.acquire = self._lock.acquire
1209 ebb80afa Guido Trotter
    self.release = self._lock.release
1210 85f03e0d Michael Hanselmann
1211 a71f9c7d Guido Trotter
    # Initialize the queue, and acquire the filelock.
1212 a71f9c7d Guido Trotter
    # This ensures no other process is working on the job queue.
1213 a71f9c7d Guido Trotter
    self._queue_filelock = jstore.InitAndVerifyQueue(must_lock=True)
1214 f1da30e6 Michael Hanselmann
1215 04ab05ce Michael Hanselmann
    # Read serial file
1216 04ab05ce Michael Hanselmann
    self._last_serial = jstore.ReadSerial()
1217 04ab05ce Michael Hanselmann
    assert self._last_serial is not None, ("Serial file was modified between"
1218 04ab05ce Michael Hanselmann
                                           " check in jstore and here")
1219 c4beba1c Iustin Pop
1220 23752136 Michael Hanselmann
    # Get initial list of nodes
1221 99aabbed Iustin Pop
    self._nodes = dict((n.name, n.primary_ip)
1222 59303563 Iustin Pop
                       for n in self.context.cfg.GetAllNodesInfo().values()
1223 59303563 Iustin Pop
                       if n.master_candidate)
1224 8e00939c Michael Hanselmann
1225 8e00939c Michael Hanselmann
    # Remove master node
1226 d8e0dc17 Guido Trotter
    self._nodes.pop(self._my_hostname, None)
1227 23752136 Michael Hanselmann
1228 23752136 Michael Hanselmann
    # TODO: Check consistency across nodes
1229 23752136 Michael Hanselmann
1230 20571a26 Guido Trotter
    self._queue_size = 0
1231 20571a26 Guido Trotter
    self._UpdateQueueSizeUnlocked()
1232 ff699aa9 Michael Hanselmann
    self._drained = jstore.CheckDrainFlag()
1233 20571a26 Guido Trotter
1234 85f03e0d Michael Hanselmann
    # Setup worker pool
1235 5bdce580 Michael Hanselmann
    self._wpool = _JobQueueWorkerPool(self)
1236 85f03e0d Michael Hanselmann
    try:
1237 de9d02c7 Michael Hanselmann
      self._InspectQueue()
1238 de9d02c7 Michael Hanselmann
    except:
1239 de9d02c7 Michael Hanselmann
      self._wpool.TerminateWorkers()
1240 de9d02c7 Michael Hanselmann
      raise
1241 711b5124 Michael Hanselmann
1242 de9d02c7 Michael Hanselmann
  @locking.ssynchronized(_LOCK)
1243 de9d02c7 Michael Hanselmann
  @_RequireOpenQueue
1244 de9d02c7 Michael Hanselmann
  def _InspectQueue(self):
1245 de9d02c7 Michael Hanselmann
    """Loads the whole job queue and resumes unfinished jobs.
1246 de9d02c7 Michael Hanselmann

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

1250 de9d02c7 Michael Hanselmann
    """
1251 de9d02c7 Michael Hanselmann
    logging.info("Inspecting job queue")
1252 de9d02c7 Michael Hanselmann
1253 7b5c4a69 Michael Hanselmann
    restartjobs = []
1254 7b5c4a69 Michael Hanselmann
1255 de9d02c7 Michael Hanselmann
    all_job_ids = self._GetJobIDsUnlocked()
1256 de9d02c7 Michael Hanselmann
    jobs_count = len(all_job_ids)
1257 de9d02c7 Michael Hanselmann
    lastinfo = time.time()
1258 de9d02c7 Michael Hanselmann
    for idx, job_id in enumerate(all_job_ids):
1259 de9d02c7 Michael Hanselmann
      # Give an update every 1000 jobs or 10 seconds
1260 de9d02c7 Michael Hanselmann
      if (idx % 1000 == 0 or time.time() >= (lastinfo + 10.0) or
1261 de9d02c7 Michael Hanselmann
          idx == (jobs_count - 1)):
1262 de9d02c7 Michael Hanselmann
        logging.info("Job queue inspection: %d/%d (%0.1f %%)",
1263 de9d02c7 Michael Hanselmann
                     idx, jobs_count - 1, 100.0 * (idx + 1) / jobs_count)
1264 711b5124 Michael Hanselmann
        lastinfo = time.time()
1265 94ed59a5 Iustin Pop
1266 de9d02c7 Michael Hanselmann
      job = self._LoadJobUnlocked(job_id)
1267 85f03e0d Michael Hanselmann
1268 de9d02c7 Michael Hanselmann
      # a failure in loading the job can cause 'None' to be returned
1269 de9d02c7 Michael Hanselmann
      if job is None:
1270 de9d02c7 Michael Hanselmann
        continue
1271 85f03e0d Michael Hanselmann
1272 de9d02c7 Michael Hanselmann
      status = job.CalcStatus()
1273 711b5124 Michael Hanselmann
1274 320d1daf Michael Hanselmann
      if status == constants.JOB_STATUS_QUEUED:
1275 7b5c4a69 Michael Hanselmann
        restartjobs.append(job)
1276 de9d02c7 Michael Hanselmann
1277 de9d02c7 Michael Hanselmann
      elif status in (constants.JOB_STATUS_RUNNING,
1278 5ef699a0 Michael Hanselmann
                      constants.JOB_STATUS_WAITLOCK,
1279 de9d02c7 Michael Hanselmann
                      constants.JOB_STATUS_CANCELING):
1280 de9d02c7 Michael Hanselmann
        logging.warning("Unfinished job %s found: %s", job.id, job)
1281 320d1daf Michael Hanselmann
1282 320d1daf Michael Hanselmann
        if status == constants.JOB_STATUS_WAITLOCK:
1283 320d1daf Michael Hanselmann
          # Restart job
1284 320d1daf Michael Hanselmann
          job.MarkUnfinishedOps(constants.OP_STATUS_QUEUED, None)
1285 320d1daf Michael Hanselmann
          restartjobs.append(job)
1286 320d1daf Michael Hanselmann
        else:
1287 320d1daf Michael Hanselmann
          job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
1288 320d1daf Michael Hanselmann
                                "Unclean master daemon shutdown")
1289 320d1daf Michael Hanselmann
1290 de9d02c7 Michael Hanselmann
        self.UpdateJobUnlocked(job)
1291 de9d02c7 Michael Hanselmann
1292 7b5c4a69 Michael Hanselmann
    if restartjobs:
1293 7b5c4a69 Michael Hanselmann
      logging.info("Restarting %s jobs", len(restartjobs))
1294 7b5c4a69 Michael Hanselmann
      self._EnqueueJobs(restartjobs)
1295 7b5c4a69 Michael Hanselmann
1296 de9d02c7 Michael Hanselmann
    logging.info("Job queue inspection finished")
1297 85f03e0d Michael Hanselmann
1298 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1299 d2e03a33 Michael Hanselmann
  @_RequireOpenQueue
1300 99aabbed Iustin Pop
  def AddNode(self, node):
1301 99aabbed Iustin Pop
    """Register a new node with the queue.
1302 99aabbed Iustin Pop

1303 99aabbed Iustin Pop
    @type node: L{objects.Node}
1304 99aabbed Iustin Pop
    @param node: the node object to be added
1305 99aabbed Iustin Pop

1306 99aabbed Iustin Pop
    """
1307 99aabbed Iustin Pop
    node_name = node.name
1308 d2e03a33 Michael Hanselmann
    assert node_name != self._my_hostname
1309 23752136 Michael Hanselmann
1310 9f774ee8 Michael Hanselmann
    # Clean queue directory on added node
1311 c8457ce7 Iustin Pop
    result = rpc.RpcRunner.call_jobqueue_purge(node_name)
1312 3cebe102 Michael Hanselmann
    msg = result.fail_msg
1313 c8457ce7 Iustin Pop
    if msg:
1314 c8457ce7 Iustin Pop
      logging.warning("Cannot cleanup queue directory on node %s: %s",
1315 c8457ce7 Iustin Pop
                      node_name, msg)
1316 23752136 Michael Hanselmann
1317 59303563 Iustin Pop
    if not node.master_candidate:
1318 59303563 Iustin Pop
      # remove if existing, ignoring errors
1319 59303563 Iustin Pop
      self._nodes.pop(node_name, None)
1320 59303563 Iustin Pop
      # and skip the replication of the job ids
1321 59303563 Iustin Pop
      return
1322 59303563 Iustin Pop
1323 d2e03a33 Michael Hanselmann
    # Upload the whole queue excluding archived jobs
1324 d2e03a33 Michael Hanselmann
    files = [self._GetJobPath(job_id) for job_id in self._GetJobIDsUnlocked()]
1325 23752136 Michael Hanselmann
1326 d2e03a33 Michael Hanselmann
    # Upload current serial file
1327 d2e03a33 Michael Hanselmann
    files.append(constants.JOB_QUEUE_SERIAL_FILE)
1328 d2e03a33 Michael Hanselmann
1329 d2e03a33 Michael Hanselmann
    for file_name in files:
1330 9f774ee8 Michael Hanselmann
      # Read file content
1331 13998ef2 Michael Hanselmann
      content = utils.ReadFile(file_name)
1332 9f774ee8 Michael Hanselmann
1333 a3811745 Michael Hanselmann
      result = rpc.RpcRunner.call_jobqueue_update([node_name],
1334 a3811745 Michael Hanselmann
                                                  [node.primary_ip],
1335 a3811745 Michael Hanselmann
                                                  file_name, content)
1336 3cebe102 Michael Hanselmann
      msg = result[node_name].fail_msg
1337 c8457ce7 Iustin Pop
      if msg:
1338 c8457ce7 Iustin Pop
        logging.error("Failed to upload file %s to node %s: %s",
1339 c8457ce7 Iustin Pop
                      file_name, node_name, msg)
1340 d2e03a33 Michael Hanselmann
1341 99aabbed Iustin Pop
    self._nodes[node_name] = node.primary_ip
1342 d2e03a33 Michael Hanselmann
1343 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1344 d2e03a33 Michael Hanselmann
  @_RequireOpenQueue
1345 d2e03a33 Michael Hanselmann
  def RemoveNode(self, node_name):
1346 ea03467c Iustin Pop
    """Callback called when removing nodes from the cluster.
1347 ea03467c Iustin Pop

1348 ea03467c Iustin Pop
    @type node_name: str
1349 ea03467c Iustin Pop
    @param node_name: the name of the node to remove
1350 ea03467c Iustin Pop

1351 ea03467c Iustin Pop
    """
1352 d8e0dc17 Guido Trotter
    self._nodes.pop(node_name, None)
1353 23752136 Michael Hanselmann
1354 7e950d31 Iustin Pop
  @staticmethod
1355 7e950d31 Iustin Pop
  def _CheckRpcResult(result, nodes, failmsg):
1356 ea03467c Iustin Pop
    """Verifies the status of an RPC call.
1357 ea03467c Iustin Pop

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

1362 ea03467c Iustin Pop
    @param result: the data as returned from the rpc call
1363 ea03467c Iustin Pop
    @type nodes: list
1364 ea03467c Iustin Pop
    @param nodes: the list of nodes we made the call to
1365 ea03467c Iustin Pop
    @type failmsg: str
1366 ea03467c Iustin Pop
    @param failmsg: the identifier to be used for logging
1367 ea03467c Iustin Pop

1368 ea03467c Iustin Pop
    """
1369 e74798c1 Michael Hanselmann
    failed = []
1370 e74798c1 Michael Hanselmann
    success = []
1371 e74798c1 Michael Hanselmann
1372 e74798c1 Michael Hanselmann
    for node in nodes:
1373 3cebe102 Michael Hanselmann
      msg = result[node].fail_msg
1374 c8457ce7 Iustin Pop
      if msg:
1375 e74798c1 Michael Hanselmann
        failed.append(node)
1376 45e0d704 Iustin Pop
        logging.error("RPC call %s (%s) failed on node %s: %s",
1377 45e0d704 Iustin Pop
                      result[node].call, failmsg, node, msg)
1378 c8457ce7 Iustin Pop
      else:
1379 c8457ce7 Iustin Pop
        success.append(node)
1380 e74798c1 Michael Hanselmann
1381 e74798c1 Michael Hanselmann
    # +1 for the master node
1382 e74798c1 Michael Hanselmann
    if (len(success) + 1) < len(failed):
1383 e74798c1 Michael Hanselmann
      # TODO: Handle failing nodes
1384 e74798c1 Michael Hanselmann
      logging.error("More than half of the nodes failed")
1385 e74798c1 Michael Hanselmann
1386 99aabbed Iustin Pop
  def _GetNodeIp(self):
1387 99aabbed Iustin Pop
    """Helper for returning the node name/ip list.
1388 99aabbed Iustin Pop

1389 ea03467c Iustin Pop
    @rtype: (list, list)
1390 ea03467c Iustin Pop
    @return: a tuple of two lists, the first one with the node
1391 ea03467c Iustin Pop
        names and the second one with the node addresses
1392 ea03467c Iustin Pop

1393 99aabbed Iustin Pop
    """
1394 e35344b4 Michael Hanselmann
    # TODO: Change to "tuple(map(list, zip(*self._nodes.items())))"?
1395 99aabbed Iustin Pop
    name_list = self._nodes.keys()
1396 99aabbed Iustin Pop
    addr_list = [self._nodes[name] for name in name_list]
1397 99aabbed Iustin Pop
    return name_list, addr_list
1398 99aabbed Iustin Pop
1399 4c36bdf5 Guido Trotter
  def _UpdateJobQueueFile(self, file_name, data, replicate):
1400 8e00939c Michael Hanselmann
    """Writes a file locally and then replicates it to all nodes.
1401 8e00939c Michael Hanselmann

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

1405 ea03467c Iustin Pop
    @type file_name: str
1406 ea03467c Iustin Pop
    @param file_name: the path of the file to be replicated
1407 ea03467c Iustin Pop
    @type data: str
1408 ea03467c Iustin Pop
    @param data: the new contents of the file
1409 4c36bdf5 Guido Trotter
    @type replicate: boolean
1410 4c36bdf5 Guido Trotter
    @param replicate: whether to spread the changes to the remote nodes
1411 ea03467c Iustin Pop

1412 8e00939c Michael Hanselmann
    """
1413 82b22e19 René Nussbaumer
    getents = runtime.GetEnts()
1414 82b22e19 René Nussbaumer
    utils.WriteFile(file_name, data=data, uid=getents.masterd_uid,
1415 82b22e19 René Nussbaumer
                    gid=getents.masterd_gid)
1416 8e00939c Michael Hanselmann
1417 4c36bdf5 Guido Trotter
    if replicate:
1418 4c36bdf5 Guido Trotter
      names, addrs = self._GetNodeIp()
1419 4c36bdf5 Guido Trotter
      result = rpc.RpcRunner.call_jobqueue_update(names, addrs, file_name, data)
1420 4c36bdf5 Guido Trotter
      self._CheckRpcResult(result, self._nodes, "Updating %s" % file_name)
1421 23752136 Michael Hanselmann
1422 d7fd1f28 Michael Hanselmann
  def _RenameFilesUnlocked(self, rename):
1423 ea03467c Iustin Pop
    """Renames a file locally and then replicate the change.
1424 ea03467c Iustin Pop

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

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

1431 ea03467c Iustin Pop
    """
1432 dd875d32 Michael Hanselmann
    # Rename them locally
1433 d7fd1f28 Michael Hanselmann
    for old, new in rename:
1434 d7fd1f28 Michael Hanselmann
      utils.RenameFile(old, new, mkdir=True)
1435 abc1f2ce Michael Hanselmann
1436 dd875d32 Michael Hanselmann
    # ... and on all nodes
1437 dd875d32 Michael Hanselmann
    names, addrs = self._GetNodeIp()
1438 dd875d32 Michael Hanselmann
    result = rpc.RpcRunner.call_jobqueue_rename(names, addrs, rename)
1439 dd875d32 Michael Hanselmann
    self._CheckRpcResult(result, self._nodes, "Renaming files (%r)" % rename)
1440 abc1f2ce Michael Hanselmann
1441 7e950d31 Iustin Pop
  @staticmethod
1442 7e950d31 Iustin Pop
  def _FormatJobID(job_id):
1443 ea03467c Iustin Pop
    """Convert a job ID to string format.
1444 ea03467c Iustin Pop

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

1449 ea03467c Iustin Pop
    @type job_id: int or long
1450 ea03467c Iustin Pop
    @param job_id: the numeric job id
1451 ea03467c Iustin Pop
    @rtype: str
1452 ea03467c Iustin Pop
    @return: the formatted job id
1453 ea03467c Iustin Pop

1454 ea03467c Iustin Pop
    """
1455 85f03e0d Michael Hanselmann
    if not isinstance(job_id, (int, long)):
1456 85f03e0d Michael Hanselmann
      raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id)
1457 85f03e0d Michael Hanselmann
    if job_id < 0:
1458 85f03e0d Michael Hanselmann
      raise errors.ProgrammerError("Job ID %s is negative" % job_id)
1459 85f03e0d Michael Hanselmann
1460 85f03e0d Michael Hanselmann
    return str(job_id)
1461 85f03e0d Michael Hanselmann
1462 58b22b6e Michael Hanselmann
  @classmethod
1463 58b22b6e Michael Hanselmann
  def _GetArchiveDirectory(cls, job_id):
1464 58b22b6e Michael Hanselmann
    """Returns the archive directory for a job.
1465 58b22b6e Michael Hanselmann

1466 58b22b6e Michael Hanselmann
    @type job_id: str
1467 58b22b6e Michael Hanselmann
    @param job_id: Job identifier
1468 58b22b6e Michael Hanselmann
    @rtype: str
1469 58b22b6e Michael Hanselmann
    @return: Directory name
1470 58b22b6e Michael Hanselmann

1471 58b22b6e Michael Hanselmann
    """
1472 58b22b6e Michael Hanselmann
    return str(int(job_id) / JOBS_PER_ARCHIVE_DIRECTORY)
1473 58b22b6e Michael Hanselmann
1474 009e73d0 Iustin Pop
  def _NewSerialsUnlocked(self, count):
1475 f1da30e6 Michael Hanselmann
    """Generates a new job identifier.
1476 f1da30e6 Michael Hanselmann

1477 f1da30e6 Michael Hanselmann
    Job identifiers are unique during the lifetime of a cluster.
1478 f1da30e6 Michael Hanselmann

1479 009e73d0 Iustin Pop
    @type count: integer
1480 009e73d0 Iustin Pop
    @param count: how many serials to return
1481 ea03467c Iustin Pop
    @rtype: str
1482 ea03467c Iustin Pop
    @return: a string representing the job identifier.
1483 f1da30e6 Michael Hanselmann

1484 f1da30e6 Michael Hanselmann
    """
1485 009e73d0 Iustin Pop
    assert count > 0
1486 f1da30e6 Michael Hanselmann
    # New number
1487 009e73d0 Iustin Pop
    serial = self._last_serial + count
1488 f1da30e6 Michael Hanselmann
1489 f1da30e6 Michael Hanselmann
    # Write to file
1490 4c36bdf5 Guido Trotter
    self._UpdateJobQueueFile(constants.JOB_QUEUE_SERIAL_FILE,
1491 4c36bdf5 Guido Trotter
                             "%s\n" % serial, True)
1492 f1da30e6 Michael Hanselmann
1493 009e73d0 Iustin Pop
    result = [self._FormatJobID(v)
1494 009e73d0 Iustin Pop
              for v in range(self._last_serial, serial + 1)]
1495 f1da30e6 Michael Hanselmann
    # Keep it only if we were able to write the file
1496 f1da30e6 Michael Hanselmann
    self._last_serial = serial
1497 f1da30e6 Michael Hanselmann
1498 009e73d0 Iustin Pop
    return result
1499 f1da30e6 Michael Hanselmann
1500 85f03e0d Michael Hanselmann
  @staticmethod
1501 85f03e0d Michael Hanselmann
  def _GetJobPath(job_id):
1502 ea03467c Iustin Pop
    """Returns the job file for a given job id.
1503 ea03467c Iustin Pop

1504 ea03467c Iustin Pop
    @type job_id: str
1505 ea03467c Iustin Pop
    @param job_id: the job identifier
1506 ea03467c Iustin Pop
    @rtype: str
1507 ea03467c Iustin Pop
    @return: the path to the job file
1508 ea03467c Iustin Pop

1509 ea03467c Iustin Pop
    """
1510 c4feafe8 Iustin Pop
    return utils.PathJoin(constants.QUEUE_DIR, "job-%s" % job_id)
1511 f1da30e6 Michael Hanselmann
1512 58b22b6e Michael Hanselmann
  @classmethod
1513 58b22b6e Michael Hanselmann
  def _GetArchivedJobPath(cls, job_id):
1514 ea03467c Iustin Pop
    """Returns the archived job file for a give job id.
1515 ea03467c Iustin Pop

1516 ea03467c Iustin Pop
    @type job_id: str
1517 ea03467c Iustin Pop
    @param job_id: the job identifier
1518 ea03467c Iustin Pop
    @rtype: str
1519 ea03467c Iustin Pop
    @return: the path to the archived job file
1520 ea03467c Iustin Pop

1521 ea03467c Iustin Pop
    """
1522 0411c011 Iustin Pop
    return utils.PathJoin(constants.JOB_QUEUE_ARCHIVE_DIR,
1523 0411c011 Iustin Pop
                          cls._GetArchiveDirectory(job_id), "job-%s" % job_id)
1524 0cb94105 Michael Hanselmann
1525 85a1c57d Guido Trotter
  def _GetJobIDsUnlocked(self, sort=True):
1526 911a495b Iustin Pop
    """Return all known job IDs.
1527 911a495b Iustin Pop

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

1532 85a1c57d Guido Trotter
    @type sort: boolean
1533 85a1c57d Guido Trotter
    @param sort: perform sorting on the returned job ids
1534 ea03467c Iustin Pop
    @rtype: list
1535 ea03467c Iustin Pop
    @return: the list of job IDs
1536 ea03467c Iustin Pop

1537 911a495b Iustin Pop
    """
1538 85a1c57d Guido Trotter
    jlist = []
1539 b5b8309d Guido Trotter
    for filename in utils.ListVisibleFiles(constants.QUEUE_DIR):
1540 85a1c57d Guido Trotter
      m = self._RE_JOB_FILE.match(filename)
1541 85a1c57d Guido Trotter
      if m:
1542 85a1c57d Guido Trotter
        jlist.append(m.group(1))
1543 85a1c57d Guido Trotter
    if sort:
1544 85a1c57d Guido Trotter
      jlist = utils.NiceSort(jlist)
1545 f0d874fe Iustin Pop
    return jlist
1546 911a495b Iustin Pop
1547 911a495b Iustin Pop
  def _LoadJobUnlocked(self, job_id):
1548 ea03467c Iustin Pop
    """Loads a job from the disk or memory.
1549 ea03467c Iustin Pop

1550 ea03467c Iustin Pop
    Given a job id, this will return the cached job object if
1551 ea03467c Iustin Pop
    existing, or try to load the job from the disk. If loading from
1552 ea03467c Iustin Pop
    disk, it will also add the job to the cache.
1553 ea03467c Iustin Pop

1554 ea03467c Iustin Pop
    @param job_id: the job id
1555 ea03467c Iustin Pop
    @rtype: L{_QueuedJob} or None
1556 ea03467c Iustin Pop
    @return: either None or the job object
1557 ea03467c Iustin Pop

1558 ea03467c Iustin Pop
    """
1559 5685c1a5 Michael Hanselmann
    job = self._memcache.get(job_id, None)
1560 5685c1a5 Michael Hanselmann
    if job:
1561 205d71fd Michael Hanselmann
      logging.debug("Found job %s in memcache", job_id)
1562 5685c1a5 Michael Hanselmann
      return job
1563 ac0930b9 Iustin Pop
1564 3d6c5566 Guido Trotter
    try:
1565 3d6c5566 Guido Trotter
      job = self._LoadJobFromDisk(job_id)
1566 aa9f8167 Iustin Pop
      if job is None:
1567 aa9f8167 Iustin Pop
        return job
1568 3d6c5566 Guido Trotter
    except errors.JobFileCorrupted:
1569 3d6c5566 Guido Trotter
      old_path = self._GetJobPath(job_id)
1570 3d6c5566 Guido Trotter
      new_path = self._GetArchivedJobPath(job_id)
1571 3d6c5566 Guido Trotter
      if old_path == new_path:
1572 3d6c5566 Guido Trotter
        # job already archived (future case)
1573 3d6c5566 Guido Trotter
        logging.exception("Can't parse job %s", job_id)
1574 3d6c5566 Guido Trotter
      else:
1575 3d6c5566 Guido Trotter
        # non-archived case
1576 3d6c5566 Guido Trotter
        logging.exception("Can't parse job %s, will archive.", job_id)
1577 3d6c5566 Guido Trotter
        self._RenameFilesUnlocked([(old_path, new_path)])
1578 3d6c5566 Guido Trotter
      return None
1579 162c8636 Guido Trotter
1580 162c8636 Guido Trotter
    self._memcache[job_id] = job
1581 162c8636 Guido Trotter
    logging.debug("Added job %s to the cache", job_id)
1582 162c8636 Guido Trotter
    return job
1583 162c8636 Guido Trotter
1584 162c8636 Guido Trotter
  def _LoadJobFromDisk(self, job_id):
1585 162c8636 Guido Trotter
    """Load the given job file from disk.
1586 162c8636 Guido Trotter

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

1589 162c8636 Guido Trotter
    @type job_id: string
1590 162c8636 Guido Trotter
    @param job_id: job identifier
1591 162c8636 Guido Trotter
    @rtype: L{_QueuedJob} or None
1592 162c8636 Guido Trotter
    @return: either None or the job object
1593 162c8636 Guido Trotter

1594 162c8636 Guido Trotter
    """
1595 911a495b Iustin Pop
    filepath = self._GetJobPath(job_id)
1596 f1da30e6 Michael Hanselmann
    logging.debug("Loading job from %s", filepath)
1597 f1da30e6 Michael Hanselmann
    try:
1598 13998ef2 Michael Hanselmann
      raw_data = utils.ReadFile(filepath)
1599 162c8636 Guido Trotter
    except EnvironmentError, err:
1600 f1da30e6 Michael Hanselmann
      if err.errno in (errno.ENOENT, ):
1601 f1da30e6 Michael Hanselmann
        return None
1602 f1da30e6 Michael Hanselmann
      raise
1603 13998ef2 Michael Hanselmann
1604 94ed59a5 Iustin Pop
    try:
1605 162c8636 Guido Trotter
      data = serializer.LoadJson(raw_data)
1606 94ed59a5 Iustin Pop
      job = _QueuedJob.Restore(self, data)
1607 7260cfbe Iustin Pop
    except Exception, err: # pylint: disable-msg=W0703
1608 3d6c5566 Guido Trotter
      raise errors.JobFileCorrupted(err)
1609 94ed59a5 Iustin Pop
1610 ac0930b9 Iustin Pop
    return job
1611 f1da30e6 Michael Hanselmann
1612 0f9c08dc Guido Trotter
  def SafeLoadJobFromDisk(self, job_id):
1613 0f9c08dc Guido Trotter
    """Load the given job file from disk.
1614 0f9c08dc Guido Trotter

1615 0f9c08dc Guido Trotter
    Given a job file, read, load and restore it in a _QueuedJob format.
1616 0f9c08dc Guido Trotter
    In case of error reading the job, it gets returned as None, and the
1617 0f9c08dc Guido Trotter
    exception is logged.
1618 0f9c08dc Guido Trotter

1619 0f9c08dc Guido Trotter
    @type job_id: string
1620 0f9c08dc Guido Trotter
    @param job_id: job identifier
1621 0f9c08dc Guido Trotter
    @rtype: L{_QueuedJob} or None
1622 0f9c08dc Guido Trotter
    @return: either None or the job object
1623 0f9c08dc Guido Trotter

1624 0f9c08dc Guido Trotter
    """
1625 0f9c08dc Guido Trotter
    try:
1626 0f9c08dc Guido Trotter
      return self._LoadJobFromDisk(job_id)
1627 0f9c08dc Guido Trotter
    except (errors.JobFileCorrupted, EnvironmentError):
1628 0f9c08dc Guido Trotter
      logging.exception("Can't load/parse job %s", job_id)
1629 0f9c08dc Guido Trotter
      return None
1630 0f9c08dc Guido Trotter
1631 20571a26 Guido Trotter
  def _UpdateQueueSizeUnlocked(self):
1632 20571a26 Guido Trotter
    """Update the queue size.
1633 20571a26 Guido Trotter

1634 20571a26 Guido Trotter
    """
1635 20571a26 Guido Trotter
    self._queue_size = len(self._GetJobIDsUnlocked(sort=False))
1636 20571a26 Guido Trotter
1637 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1638 20571a26 Guido Trotter
  @_RequireOpenQueue
1639 20571a26 Guido Trotter
  def SetDrainFlag(self, drain_flag):
1640 3ccafd0e Iustin Pop
    """Sets the drain flag for the queue.
1641 3ccafd0e Iustin Pop

1642 ea03467c Iustin Pop
    @type drain_flag: boolean
1643 5bbd3f7f Michael Hanselmann
    @param drain_flag: Whether to set or unset the drain flag
1644 ea03467c Iustin Pop

1645 3ccafd0e Iustin Pop
    """
1646 ff699aa9 Michael Hanselmann
    jstore.SetDrainFlag(drain_flag)
1647 20571a26 Guido Trotter
1648 20571a26 Guido Trotter
    self._drained = drain_flag
1649 20571a26 Guido Trotter
1650 3ccafd0e Iustin Pop
    return True
1651 3ccafd0e Iustin Pop
1652 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1653 009e73d0 Iustin Pop
  def _SubmitJobUnlocked(self, job_id, ops):
1654 85f03e0d Michael Hanselmann
    """Create and store a new job.
1655 f1da30e6 Michael Hanselmann

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

1659 009e73d0 Iustin Pop
    @type job_id: job ID
1660 69b99987 Michael Hanselmann
    @param job_id: the job ID for the new job
1661 c3f0a12f Iustin Pop
    @type ops: list
1662 205d71fd Michael Hanselmann
    @param ops: The list of OpCodes that will become the new job.
1663 7beb1e53 Guido Trotter
    @rtype: L{_QueuedJob}
1664 7beb1e53 Guido Trotter
    @return: the job object to be queued
1665 7beb1e53 Guido Trotter
    @raise errors.JobQueueDrainError: if the job queue is marked for draining
1666 7beb1e53 Guido Trotter
    @raise errors.JobQueueFull: if the job queue has too many jobs in it
1667 e71c8147 Michael Hanselmann
    @raise errors.GenericError: If an opcode is not valid
1668 c3f0a12f Iustin Pop

1669 c3f0a12f Iustin Pop
    """
1670 20571a26 Guido Trotter
    # Ok when sharing the big job queue lock, as the drain file is created when
1671 20571a26 Guido Trotter
    # the lock is exclusive.
1672 20571a26 Guido Trotter
    if self._drained:
1673 2971c913 Iustin Pop
      raise errors.JobQueueDrainError("Job queue is drained, refusing job")
1674 f87b405e Michael Hanselmann
1675 20571a26 Guido Trotter
    if self._queue_size >= constants.JOB_QUEUE_SIZE_HARD_LIMIT:
1676 f87b405e Michael Hanselmann
      raise errors.JobQueueFull()
1677 f87b405e Michael Hanselmann
1678 f1da30e6 Michael Hanselmann
    job = _QueuedJob(self, job_id, ops)
1679 f1da30e6 Michael Hanselmann
1680 e71c8147 Michael Hanselmann
    # Check priority
1681 e71c8147 Michael Hanselmann
    for idx, op in enumerate(job.ops):
1682 e71c8147 Michael Hanselmann
      if op.priority not in constants.OP_PRIO_SUBMIT_VALID:
1683 e71c8147 Michael Hanselmann
        allowed = utils.CommaJoin(constants.OP_PRIO_SUBMIT_VALID)
1684 e71c8147 Michael Hanselmann
        raise errors.GenericError("Opcode %s has invalid priority %s, allowed"
1685 e71c8147 Michael Hanselmann
                                  " are %s" % (idx, op.priority, allowed))
1686 e71c8147 Michael Hanselmann
1687 f1da30e6 Michael Hanselmann
    # Write to disk
1688 85f03e0d Michael Hanselmann
    self.UpdateJobUnlocked(job)
1689 f1da30e6 Michael Hanselmann
1690 20571a26 Guido Trotter
    self._queue_size += 1
1691 20571a26 Guido Trotter
1692 5685c1a5 Michael Hanselmann
    logging.debug("Adding new job %s to the cache", job_id)
1693 ac0930b9 Iustin Pop
    self._memcache[job_id] = job
1694 ac0930b9 Iustin Pop
1695 7beb1e53 Guido Trotter
    return job
1696 f1da30e6 Michael Hanselmann
1697 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1698 2971c913 Iustin Pop
  @_RequireOpenQueue
1699 2971c913 Iustin Pop
  def SubmitJob(self, ops):
1700 2971c913 Iustin Pop
    """Create and store a new job.
1701 2971c913 Iustin Pop

1702 2971c913 Iustin Pop
    @see: L{_SubmitJobUnlocked}
1703 2971c913 Iustin Pop

1704 2971c913 Iustin Pop
    """
1705 009e73d0 Iustin Pop
    job_id = self._NewSerialsUnlocked(1)[0]
1706 7b5c4a69 Michael Hanselmann
    self._EnqueueJobs([self._SubmitJobUnlocked(job_id, ops)])
1707 7beb1e53 Guido Trotter
    return job_id
1708 2971c913 Iustin Pop
1709 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1710 2971c913 Iustin Pop
  @_RequireOpenQueue
1711 2971c913 Iustin Pop
  def SubmitManyJobs(self, jobs):
1712 2971c913 Iustin Pop
    """Create and store multiple jobs.
1713 2971c913 Iustin Pop

1714 2971c913 Iustin Pop
    @see: L{_SubmitJobUnlocked}
1715 2971c913 Iustin Pop

1716 2971c913 Iustin Pop
    """
1717 2971c913 Iustin Pop
    results = []
1718 7b5c4a69 Michael Hanselmann
    added_jobs = []
1719 009e73d0 Iustin Pop
    all_job_ids = self._NewSerialsUnlocked(len(jobs))
1720 009e73d0 Iustin Pop
    for job_id, ops in zip(all_job_ids, jobs):
1721 2971c913 Iustin Pop
      try:
1722 7b5c4a69 Michael Hanselmann
        added_jobs.append(self._SubmitJobUnlocked(job_id, ops))
1723 2971c913 Iustin Pop
        status = True
1724 7beb1e53 Guido Trotter
        data = job_id
1725 2971c913 Iustin Pop
      except errors.GenericError, err:
1726 2971c913 Iustin Pop
        data = str(err)
1727 2971c913 Iustin Pop
        status = False
1728 2971c913 Iustin Pop
      results.append((status, data))
1729 7b5c4a69 Michael Hanselmann
1730 7b5c4a69 Michael Hanselmann
    self._EnqueueJobs(added_jobs)
1731 2971c913 Iustin Pop
1732 2971c913 Iustin Pop
    return results
1733 2971c913 Iustin Pop
1734 7b5c4a69 Michael Hanselmann
  def _EnqueueJobs(self, jobs):
1735 7b5c4a69 Michael Hanselmann
    """Helper function to add jobs to worker pool's queue.
1736 7b5c4a69 Michael Hanselmann

1737 7b5c4a69 Michael Hanselmann
    @type jobs: list
1738 7b5c4a69 Michael Hanselmann
    @param jobs: List of all jobs
1739 7b5c4a69 Michael Hanselmann

1740 7b5c4a69 Michael Hanselmann
    """
1741 7b5c4a69 Michael Hanselmann
    self._wpool.AddManyTasks([(job, ) for job in jobs],
1742 7b5c4a69 Michael Hanselmann
                             priority=[job.CalcPriority() for job in jobs])
1743 7b5c4a69 Michael Hanselmann
1744 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1745 4c36bdf5 Guido Trotter
  def UpdateJobUnlocked(self, job, replicate=True):
1746 ea03467c Iustin Pop
    """Update a job's on disk storage.
1747 ea03467c Iustin Pop

1748 ea03467c Iustin Pop
    After a job has been modified, this function needs to be called in
1749 ea03467c Iustin Pop
    order to write the changes to disk and replicate them to the other
1750 ea03467c Iustin Pop
    nodes.
1751 ea03467c Iustin Pop

1752 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
1753 ea03467c Iustin Pop
    @param job: the changed job
1754 4c36bdf5 Guido Trotter
    @type replicate: boolean
1755 4c36bdf5 Guido Trotter
    @param replicate: whether to replicate the change to remote nodes
1756 ea03467c Iustin Pop

1757 ea03467c Iustin Pop
    """
1758 f1da30e6 Michael Hanselmann
    filename = self._GetJobPath(job.id)
1759 23752136 Michael Hanselmann
    data = serializer.DumpJson(job.Serialize(), indent=False)
1760 f1da30e6 Michael Hanselmann
    logging.debug("Writing job %s to %s", job.id, filename)
1761 4c36bdf5 Guido Trotter
    self._UpdateJobQueueFile(filename, data, replicate)
1762 ac0930b9 Iustin Pop
1763 5c735209 Iustin Pop
  def WaitForJobChanges(self, job_id, fields, prev_job_info, prev_log_serial,
1764 5c735209 Iustin Pop
                        timeout):
1765 6c5a7090 Michael Hanselmann
    """Waits for changes in a job.
1766 6c5a7090 Michael Hanselmann

1767 6c5a7090 Michael Hanselmann
    @type job_id: string
1768 6c5a7090 Michael Hanselmann
    @param job_id: Job identifier
1769 6c5a7090 Michael Hanselmann
    @type fields: list of strings
1770 6c5a7090 Michael Hanselmann
    @param fields: Which fields to check for changes
1771 6c5a7090 Michael Hanselmann
    @type prev_job_info: list or None
1772 6c5a7090 Michael Hanselmann
    @param prev_job_info: Last job information returned
1773 6c5a7090 Michael Hanselmann
    @type prev_log_serial: int
1774 6c5a7090 Michael Hanselmann
    @param prev_log_serial: Last job message serial number
1775 5c735209 Iustin Pop
    @type timeout: float
1776 989a8bee Michael Hanselmann
    @param timeout: maximum time to wait in seconds
1777 ea03467c Iustin Pop
    @rtype: tuple (job info, log entries)
1778 ea03467c Iustin Pop
    @return: a tuple of the job information as required via
1779 ea03467c Iustin Pop
        the fields parameter, and the log entries as a list
1780 ea03467c Iustin Pop

1781 ea03467c Iustin Pop
        if the job has not changed and the timeout has expired,
1782 ea03467c Iustin Pop
        we instead return a special value,
1783 ea03467c Iustin Pop
        L{constants.JOB_NOTCHANGED}, which should be interpreted
1784 ea03467c Iustin Pop
        as such by the clients
1785 6c5a7090 Michael Hanselmann

1786 6c5a7090 Michael Hanselmann
    """
1787 989a8bee Michael Hanselmann
    load_fn = compat.partial(self.SafeLoadJobFromDisk, job_id)
1788 989a8bee Michael Hanselmann
1789 989a8bee Michael Hanselmann
    helper = _WaitForJobChangesHelper()
1790 989a8bee Michael Hanselmann
1791 989a8bee Michael Hanselmann
    return helper(self._GetJobPath(job_id), load_fn,
1792 989a8bee Michael Hanselmann
                  fields, prev_job_info, prev_log_serial, timeout)
1793 dfe57c22 Michael Hanselmann
1794 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1795 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1796 188c5e0a Michael Hanselmann
  def CancelJob(self, job_id):
1797 188c5e0a Michael Hanselmann
    """Cancels a job.
1798 188c5e0a Michael Hanselmann

1799 ea03467c Iustin Pop
    This will only succeed if the job has not started yet.
1800 ea03467c Iustin Pop

1801 188c5e0a Michael Hanselmann
    @type job_id: string
1802 ea03467c Iustin Pop
    @param job_id: job ID of job to be cancelled.
1803 188c5e0a Michael Hanselmann

1804 188c5e0a Michael Hanselmann
    """
1805 fbf0262f Michael Hanselmann
    logging.info("Cancelling job %s", job_id)
1806 188c5e0a Michael Hanselmann
1807 85f03e0d Michael Hanselmann
    job = self._LoadJobUnlocked(job_id)
1808 188c5e0a Michael Hanselmann
    if not job:
1809 188c5e0a Michael Hanselmann
      logging.debug("Job %s not found", job_id)
1810 fbf0262f Michael Hanselmann
      return (False, "Job %s not found" % job_id)
1811 fbf0262f Michael Hanselmann
1812 099b2870 Michael Hanselmann
    (success, msg) = job.Cancel()
1813 188c5e0a Michael Hanselmann
1814 099b2870 Michael Hanselmann
    if success:
1815 099b2870 Michael Hanselmann
      self.UpdateJobUnlocked(job)
1816 fbf0262f Michael Hanselmann
1817 099b2870 Michael Hanselmann
    return (success, msg)
1818 fbf0262f Michael Hanselmann
1819 fbf0262f Michael Hanselmann
  @_RequireOpenQueue
1820 d7fd1f28 Michael Hanselmann
  def _ArchiveJobsUnlocked(self, jobs):
1821 d7fd1f28 Michael Hanselmann
    """Archives jobs.
1822 c609f802 Michael Hanselmann

1823 d7fd1f28 Michael Hanselmann
    @type jobs: list of L{_QueuedJob}
1824 25e7b43f Iustin Pop
    @param jobs: Job objects
1825 d7fd1f28 Michael Hanselmann
    @rtype: int
1826 d7fd1f28 Michael Hanselmann
    @return: Number of archived jobs
1827 c609f802 Michael Hanselmann

1828 c609f802 Michael Hanselmann
    """
1829 d7fd1f28 Michael Hanselmann
    archive_jobs = []
1830 d7fd1f28 Michael Hanselmann
    rename_files = []
1831 d7fd1f28 Michael Hanselmann
    for job in jobs:
1832 989a8bee Michael Hanselmann
      if job.CalcStatus() not in constants.JOBS_FINALIZED:
1833 d7fd1f28 Michael Hanselmann
        logging.debug("Job %s is not yet done", job.id)
1834 d7fd1f28 Michael Hanselmann
        continue
1835 c609f802 Michael Hanselmann
1836 d7fd1f28 Michael Hanselmann
      archive_jobs.append(job)
1837 c609f802 Michael Hanselmann
1838 d7fd1f28 Michael Hanselmann
      old = self._GetJobPath(job.id)
1839 d7fd1f28 Michael Hanselmann
      new = self._GetArchivedJobPath(job.id)
1840 d7fd1f28 Michael Hanselmann
      rename_files.append((old, new))
1841 c609f802 Michael Hanselmann
1842 d7fd1f28 Michael Hanselmann
    # TODO: What if 1..n files fail to rename?
1843 d7fd1f28 Michael Hanselmann
    self._RenameFilesUnlocked(rename_files)
1844 f1da30e6 Michael Hanselmann
1845 d7fd1f28 Michael Hanselmann
    logging.debug("Successfully archived job(s) %s",
1846 1f864b60 Iustin Pop
                  utils.CommaJoin(job.id for job in archive_jobs))
1847 d7fd1f28 Michael Hanselmann
1848 20571a26 Guido Trotter
    # Since we haven't quite checked, above, if we succeeded or failed renaming
1849 20571a26 Guido Trotter
    # the files, we update the cached queue size from the filesystem. When we
1850 20571a26 Guido Trotter
    # get around to fix the TODO: above, we can use the number of actually
1851 20571a26 Guido Trotter
    # archived jobs to fix this.
1852 20571a26 Guido Trotter
    self._UpdateQueueSizeUnlocked()
1853 d7fd1f28 Michael Hanselmann
    return len(archive_jobs)
1854 78d12585 Michael Hanselmann
1855 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1856 07cd723a Iustin Pop
  @_RequireOpenQueue
1857 07cd723a Iustin Pop
  def ArchiveJob(self, job_id):
1858 07cd723a Iustin Pop
    """Archives a job.
1859 07cd723a Iustin Pop

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

1862 07cd723a Iustin Pop
    @type job_id: string
1863 07cd723a Iustin Pop
    @param job_id: Job ID of job to be archived.
1864 78d12585 Michael Hanselmann
    @rtype: bool
1865 78d12585 Michael Hanselmann
    @return: Whether job was archived
1866 07cd723a Iustin Pop

1867 07cd723a Iustin Pop
    """
1868 78d12585 Michael Hanselmann
    logging.info("Archiving job %s", job_id)
1869 78d12585 Michael Hanselmann
1870 78d12585 Michael Hanselmann
    job = self._LoadJobUnlocked(job_id)
1871 78d12585 Michael Hanselmann
    if not job:
1872 78d12585 Michael Hanselmann
      logging.debug("Job %s not found", job_id)
1873 78d12585 Michael Hanselmann
      return False
1874 78d12585 Michael Hanselmann
1875 5278185a Iustin Pop
    return self._ArchiveJobsUnlocked([job]) == 1
1876 07cd723a Iustin Pop
1877 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1878 07cd723a Iustin Pop
  @_RequireOpenQueue
1879 f8ad5591 Michael Hanselmann
  def AutoArchiveJobs(self, age, timeout):
1880 07cd723a Iustin Pop
    """Archives all jobs based on age.
1881 07cd723a Iustin Pop

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

1887 07cd723a Iustin Pop
    @type age: int
1888 07cd723a Iustin Pop
    @param age: the minimum age in seconds
1889 07cd723a Iustin Pop

1890 07cd723a Iustin Pop
    """
1891 07cd723a Iustin Pop
    logging.info("Archiving jobs with age more than %s seconds", age)
1892 07cd723a Iustin Pop
1893 07cd723a Iustin Pop
    now = time.time()
1894 f8ad5591 Michael Hanselmann
    end_time = now + timeout
1895 f8ad5591 Michael Hanselmann
    archived_count = 0
1896 f8ad5591 Michael Hanselmann
    last_touched = 0
1897 f8ad5591 Michael Hanselmann
1898 69b03fd7 Guido Trotter
    all_job_ids = self._GetJobIDsUnlocked()
1899 d7fd1f28 Michael Hanselmann
    pending = []
1900 f8ad5591 Michael Hanselmann
    for idx, job_id in enumerate(all_job_ids):
1901 d2c8afb1 Michael Hanselmann
      last_touched = idx + 1
1902 f8ad5591 Michael Hanselmann
1903 d7fd1f28 Michael Hanselmann
      # Not optimal because jobs could be pending
1904 d7fd1f28 Michael Hanselmann
      # TODO: Measure average duration for job archival and take number of
1905 d7fd1f28 Michael Hanselmann
      # pending jobs into account.
1906 f8ad5591 Michael Hanselmann
      if time.time() > end_time:
1907 f8ad5591 Michael Hanselmann
        break
1908 f8ad5591 Michael Hanselmann
1909 78d12585 Michael Hanselmann
      # Returns None if the job failed to load
1910 78d12585 Michael Hanselmann
      job = self._LoadJobUnlocked(job_id)
1911 f8ad5591 Michael Hanselmann
      if job:
1912 f8ad5591 Michael Hanselmann
        if job.end_timestamp is None:
1913 f8ad5591 Michael Hanselmann
          if job.start_timestamp is None:
1914 f8ad5591 Michael Hanselmann
            job_age = job.received_timestamp
1915 f8ad5591 Michael Hanselmann
          else:
1916 f8ad5591 Michael Hanselmann
            job_age = job.start_timestamp
1917 07cd723a Iustin Pop
        else:
1918 f8ad5591 Michael Hanselmann
          job_age = job.end_timestamp
1919 f8ad5591 Michael Hanselmann
1920 f8ad5591 Michael Hanselmann
        if age == -1 or now - job_age[0] > age:
1921 d7fd1f28 Michael Hanselmann
          pending.append(job)
1922 d7fd1f28 Michael Hanselmann
1923 d7fd1f28 Michael Hanselmann
          # Archive 10 jobs at a time
1924 d7fd1f28 Michael Hanselmann
          if len(pending) >= 10:
1925 d7fd1f28 Michael Hanselmann
            archived_count += self._ArchiveJobsUnlocked(pending)
1926 d7fd1f28 Michael Hanselmann
            pending = []
1927 f8ad5591 Michael Hanselmann
1928 d7fd1f28 Michael Hanselmann
    if pending:
1929 d7fd1f28 Michael Hanselmann
      archived_count += self._ArchiveJobsUnlocked(pending)
1930 07cd723a Iustin Pop
1931 d2c8afb1 Michael Hanselmann
    return (archived_count, len(all_job_ids) - last_touched)
1932 07cd723a Iustin Pop
1933 e2715f69 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1934 e2715f69 Michael Hanselmann
    """Returns a list of jobs in queue.
1935 e2715f69 Michael Hanselmann

1936 ea03467c Iustin Pop
    @type job_ids: list
1937 ea03467c Iustin Pop
    @param job_ids: sequence of job identifiers or None for all
1938 ea03467c Iustin Pop
    @type fields: list
1939 ea03467c Iustin Pop
    @param fields: names of fields to return
1940 ea03467c Iustin Pop
    @rtype: list
1941 ea03467c Iustin Pop
    @return: list one element per job, each element being list with
1942 ea03467c Iustin Pop
        the requested fields
1943 e2715f69 Michael Hanselmann

1944 e2715f69 Michael Hanselmann
    """
1945 85f03e0d Michael Hanselmann
    jobs = []
1946 9f7b4967 Guido Trotter
    list_all = False
1947 9f7b4967 Guido Trotter
    if not job_ids:
1948 9f7b4967 Guido Trotter
      # Since files are added to/removed from the queue atomically, there's no
1949 9f7b4967 Guido Trotter
      # risk of getting the job ids in an inconsistent state.
1950 9f7b4967 Guido Trotter
      job_ids = self._GetJobIDsUnlocked()
1951 9f7b4967 Guido Trotter
      list_all = True
1952 e2715f69 Michael Hanselmann
1953 9f7b4967 Guido Trotter
    for job_id in job_ids:
1954 9f7b4967 Guido Trotter
      job = self.SafeLoadJobFromDisk(job_id)
1955 9f7b4967 Guido Trotter
      if job is not None:
1956 6a290889 Guido Trotter
        jobs.append(job.GetInfo(fields))
1957 9f7b4967 Guido Trotter
      elif not list_all:
1958 9f7b4967 Guido Trotter
        jobs.append(None)
1959 e2715f69 Michael Hanselmann
1960 85f03e0d Michael Hanselmann
    return jobs
1961 e2715f69 Michael Hanselmann
1962 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1963 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1964 e2715f69 Michael Hanselmann
  def Shutdown(self):
1965 e2715f69 Michael Hanselmann
    """Stops the job queue.
1966 e2715f69 Michael Hanselmann

1967 ea03467c Iustin Pop
    This shutdowns all the worker threads an closes the queue.
1968 ea03467c Iustin Pop

1969 e2715f69 Michael Hanselmann
    """
1970 e2715f69 Michael Hanselmann
    self._wpool.TerminateWorkers()
1971 85f03e0d Michael Hanselmann
1972 a71f9c7d Guido Trotter
    self._queue_filelock.Close()
1973 a71f9c7d Guido Trotter
    self._queue_filelock = None