Statistics
| Branch: | Tag: | Revision:

root / lib / jqueue.py @ 18c8f361

History | View | Annotate | Download (41.3 kB)

1 498ae1cc Iustin Pop
#
2 498ae1cc Iustin Pop
#
3 498ae1cc Iustin Pop
4 5685c1a5 Michael Hanselmann
# Copyright (C) 2006, 2007, 2008 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 f1da30e6 Michael Hanselmann
import os
33 e2715f69 Michael Hanselmann
import logging
34 e2715f69 Michael Hanselmann
import threading
35 f1da30e6 Michael Hanselmann
import errno
36 f1da30e6 Michael Hanselmann
import re
37 f1048938 Iustin Pop
import time
38 5685c1a5 Michael Hanselmann
import weakref
39 498ae1cc Iustin Pop
40 e2715f69 Michael Hanselmann
from ganeti import constants
41 f1da30e6 Michael Hanselmann
from ganeti import serializer
42 e2715f69 Michael Hanselmann
from ganeti import workerpool
43 f1da30e6 Michael Hanselmann
from ganeti import opcodes
44 7a1ecaed Iustin Pop
from ganeti import errors
45 e2715f69 Michael Hanselmann
from ganeti import mcpu
46 7996a135 Iustin Pop
from ganeti import utils
47 04ab05ce Michael Hanselmann
from ganeti import jstore
48 c3f0a12f Iustin Pop
from ganeti import rpc
49 e2715f69 Michael Hanselmann
50 fbf0262f Michael Hanselmann
51 1daae384 Iustin Pop
JOBQUEUE_THREADS = 25
52 58b22b6e Michael Hanselmann
JOBS_PER_ARCHIVE_DIRECTORY = 10000
53 e2715f69 Michael Hanselmann
54 498ae1cc Iustin Pop
55 9728ae5d Iustin Pop
class CancelJob(Exception):
56 fbf0262f Michael Hanselmann
  """Special exception to cancel a job.
57 fbf0262f Michael Hanselmann

58 fbf0262f Michael Hanselmann
  """
59 fbf0262f Michael Hanselmann
60 fbf0262f Michael Hanselmann
61 70552c46 Michael Hanselmann
def TimeStampNow():
62 ea03467c Iustin Pop
  """Returns the current timestamp.
63 ea03467c Iustin Pop

64 ea03467c Iustin Pop
  @rtype: tuple
65 ea03467c Iustin Pop
  @return: the current time in the (seconds, microseconds) format
66 ea03467c Iustin Pop

67 ea03467c Iustin Pop
  """
68 70552c46 Michael Hanselmann
  return utils.SplitTime(time.time())
69 70552c46 Michael Hanselmann
70 70552c46 Michael Hanselmann
71 e2715f69 Michael Hanselmann
class _QueuedOpCode(object):
72 5bbd3f7f Michael Hanselmann
  """Encapsulates an opcode object.
73 e2715f69 Michael Hanselmann

74 ea03467c Iustin Pop
  @ivar log: holds the execution log and consists of tuples
75 ea03467c Iustin Pop
  of the form C{(log_serial, timestamp, level, message)}
76 ea03467c Iustin Pop
  @ivar input: the OpCode we encapsulate
77 ea03467c Iustin Pop
  @ivar status: the current status
78 ea03467c Iustin Pop
  @ivar result: the result of the LU execution
79 ea03467c Iustin Pop
  @ivar start_timestamp: timestamp for the start of the execution
80 ea03467c Iustin Pop
  @ivar stop_timestamp: timestamp for the end of the execution
81 f1048938 Iustin Pop

82 e2715f69 Michael Hanselmann
  """
83 66d895a8 Iustin Pop
  __slots__ = ["input", "status", "result", "log",
84 66d895a8 Iustin Pop
               "start_timestamp", "end_timestamp",
85 66d895a8 Iustin Pop
               "__weakref__"]
86 66d895a8 Iustin Pop
87 85f03e0d Michael Hanselmann
  def __init__(self, op):
88 ea03467c Iustin Pop
    """Constructor for the _QuededOpCode.
89 ea03467c Iustin Pop

90 ea03467c Iustin Pop
    @type op: L{opcodes.OpCode}
91 ea03467c Iustin Pop
    @param op: the opcode we encapsulate
92 ea03467c Iustin Pop

93 ea03467c Iustin Pop
    """
94 85f03e0d Michael Hanselmann
    self.input = op
95 85f03e0d Michael Hanselmann
    self.status = constants.OP_STATUS_QUEUED
96 85f03e0d Michael Hanselmann
    self.result = None
97 85f03e0d Michael Hanselmann
    self.log = []
98 70552c46 Michael Hanselmann
    self.start_timestamp = None
99 70552c46 Michael Hanselmann
    self.end_timestamp = None
100 f1da30e6 Michael Hanselmann
101 f1da30e6 Michael Hanselmann
  @classmethod
102 f1da30e6 Michael Hanselmann
  def Restore(cls, state):
103 ea03467c Iustin Pop
    """Restore the _QueuedOpCode from the serialized form.
104 ea03467c Iustin Pop

105 ea03467c Iustin Pop
    @type state: dict
106 ea03467c Iustin Pop
    @param state: the serialized state
107 ea03467c Iustin Pop
    @rtype: _QueuedOpCode
108 ea03467c Iustin Pop
    @return: a new _QueuedOpCode instance
109 ea03467c Iustin Pop

110 ea03467c Iustin Pop
    """
111 85f03e0d Michael Hanselmann
    obj = _QueuedOpCode.__new__(cls)
112 85f03e0d Michael Hanselmann
    obj.input = opcodes.OpCode.LoadOpCode(state["input"])
113 85f03e0d Michael Hanselmann
    obj.status = state["status"]
114 85f03e0d Michael Hanselmann
    obj.result = state["result"]
115 85f03e0d Michael Hanselmann
    obj.log = state["log"]
116 70552c46 Michael Hanselmann
    obj.start_timestamp = state.get("start_timestamp", None)
117 70552c46 Michael Hanselmann
    obj.end_timestamp = state.get("end_timestamp", None)
118 f1da30e6 Michael Hanselmann
    return obj
119 f1da30e6 Michael Hanselmann
120 f1da30e6 Michael Hanselmann
  def Serialize(self):
121 ea03467c Iustin Pop
    """Serializes this _QueuedOpCode.
122 ea03467c Iustin Pop

123 ea03467c Iustin Pop
    @rtype: dict
124 ea03467c Iustin Pop
    @return: the dictionary holding the serialized state
125 ea03467c Iustin Pop

126 ea03467c Iustin Pop
    """
127 6c5a7090 Michael Hanselmann
    return {
128 6c5a7090 Michael Hanselmann
      "input": self.input.__getstate__(),
129 6c5a7090 Michael Hanselmann
      "status": self.status,
130 6c5a7090 Michael Hanselmann
      "result": self.result,
131 6c5a7090 Michael Hanselmann
      "log": self.log,
132 70552c46 Michael Hanselmann
      "start_timestamp": self.start_timestamp,
133 70552c46 Michael Hanselmann
      "end_timestamp": self.end_timestamp,
134 6c5a7090 Michael Hanselmann
      }
135 f1048938 Iustin Pop
136 e2715f69 Michael Hanselmann
137 e2715f69 Michael Hanselmann
class _QueuedJob(object):
138 e2715f69 Michael Hanselmann
  """In-memory job representation.
139 e2715f69 Michael Hanselmann

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

143 ea03467c Iustin Pop
  @type queue: L{JobQueue}
144 ea03467c Iustin Pop
  @ivar queue: the parent queue
145 ea03467c Iustin Pop
  @ivar id: the job ID
146 ea03467c Iustin Pop
  @type ops: list
147 ea03467c Iustin Pop
  @ivar ops: the list of _QueuedOpCode that constitute the job
148 ea03467c Iustin Pop
  @type log_serial: int
149 ea03467c Iustin Pop
  @ivar log_serial: holds the index for the next log entry
150 ea03467c Iustin Pop
  @ivar received_timestamp: the timestamp for when the job was received
151 ea03467c Iustin Pop
  @ivar start_timestmap: the timestamp for start of execution
152 ea03467c Iustin Pop
  @ivar end_timestamp: the timestamp for end of execution
153 ef2df7d3 Michael Hanselmann
  @ivar lock_status: In-memory locking information for debugging
154 ea03467c Iustin Pop
  @ivar change: a Condition variable we use for waiting for job changes
155 e2715f69 Michael Hanselmann

156 e2715f69 Michael Hanselmann
  """
157 d25c1d6a Michael Hanselmann
  __slots__ = ["queue", "id", "ops", "log_serial",
158 66d895a8 Iustin Pop
               "received_timestamp", "start_timestamp", "end_timestamp",
159 ef2df7d3 Michael Hanselmann
               "lock_status", "change",
160 66d895a8 Iustin Pop
               "__weakref__"]
161 66d895a8 Iustin Pop
162 85f03e0d Michael Hanselmann
  def __init__(self, queue, job_id, ops):
163 ea03467c Iustin Pop
    """Constructor for the _QueuedJob.
164 ea03467c Iustin Pop

165 ea03467c Iustin Pop
    @type queue: L{JobQueue}
166 ea03467c Iustin Pop
    @param queue: our parent queue
167 ea03467c Iustin Pop
    @type job_id: job_id
168 ea03467c Iustin Pop
    @param job_id: our job id
169 ea03467c Iustin Pop
    @type ops: list
170 ea03467c Iustin Pop
    @param ops: the list of opcodes we hold, which will be encapsulated
171 ea03467c Iustin Pop
        in _QueuedOpCodes
172 ea03467c Iustin Pop

173 ea03467c Iustin Pop
    """
174 e2715f69 Michael Hanselmann
    if not ops:
175 ea03467c Iustin Pop
      # TODO: use a better exception
176 e2715f69 Michael Hanselmann
      raise Exception("No opcodes")
177 e2715f69 Michael Hanselmann
178 85f03e0d Michael Hanselmann
    self.queue = queue
179 f1da30e6 Michael Hanselmann
    self.id = job_id
180 85f03e0d Michael Hanselmann
    self.ops = [_QueuedOpCode(op) for op in ops]
181 6c5a7090 Michael Hanselmann
    self.log_serial = 0
182 c56ec146 Iustin Pop
    self.received_timestamp = TimeStampNow()
183 c56ec146 Iustin Pop
    self.start_timestamp = None
184 c56ec146 Iustin Pop
    self.end_timestamp = None
185 6c5a7090 Michael Hanselmann
186 ef2df7d3 Michael Hanselmann
    # In-memory attributes
187 ef2df7d3 Michael Hanselmann
    self.lock_status = None
188 ef2df7d3 Michael Hanselmann
189 6c5a7090 Michael Hanselmann
    # Condition to wait for changes
190 6c5a7090 Michael Hanselmann
    self.change = threading.Condition(self.queue._lock)
191 f1da30e6 Michael Hanselmann
192 f1da30e6 Michael Hanselmann
  @classmethod
193 85f03e0d Michael Hanselmann
  def Restore(cls, queue, state):
194 ea03467c Iustin Pop
    """Restore a _QueuedJob from serialized state:
195 ea03467c Iustin Pop

196 ea03467c Iustin Pop
    @type queue: L{JobQueue}
197 ea03467c Iustin Pop
    @param queue: to which queue the restored job belongs
198 ea03467c Iustin Pop
    @type state: dict
199 ea03467c Iustin Pop
    @param state: the serialized state
200 ea03467c Iustin Pop
    @rtype: _JobQueue
201 ea03467c Iustin Pop
    @return: the restored _JobQueue instance
202 ea03467c Iustin Pop

203 ea03467c Iustin Pop
    """
204 85f03e0d Michael Hanselmann
    obj = _QueuedJob.__new__(cls)
205 85f03e0d Michael Hanselmann
    obj.queue = queue
206 85f03e0d Michael Hanselmann
    obj.id = state["id"]
207 c56ec146 Iustin Pop
    obj.received_timestamp = state.get("received_timestamp", None)
208 c56ec146 Iustin Pop
    obj.start_timestamp = state.get("start_timestamp", None)
209 c56ec146 Iustin Pop
    obj.end_timestamp = state.get("end_timestamp", None)
210 6c5a7090 Michael Hanselmann
211 ef2df7d3 Michael Hanselmann
    # In-memory attributes
212 ef2df7d3 Michael Hanselmann
    obj.lock_status = None
213 ef2df7d3 Michael Hanselmann
214 6c5a7090 Michael Hanselmann
    obj.ops = []
215 6c5a7090 Michael Hanselmann
    obj.log_serial = 0
216 6c5a7090 Michael Hanselmann
    for op_state in state["ops"]:
217 6c5a7090 Michael Hanselmann
      op = _QueuedOpCode.Restore(op_state)
218 6c5a7090 Michael Hanselmann
      for log_entry in op.log:
219 6c5a7090 Michael Hanselmann
        obj.log_serial = max(obj.log_serial, log_entry[0])
220 6c5a7090 Michael Hanselmann
      obj.ops.append(op)
221 6c5a7090 Michael Hanselmann
222 6c5a7090 Michael Hanselmann
    # Condition to wait for changes
223 6c5a7090 Michael Hanselmann
    obj.change = threading.Condition(obj.queue._lock)
224 6c5a7090 Michael Hanselmann
225 f1da30e6 Michael Hanselmann
    return obj
226 f1da30e6 Michael Hanselmann
227 f1da30e6 Michael Hanselmann
  def Serialize(self):
228 ea03467c Iustin Pop
    """Serialize the _JobQueue instance.
229 ea03467c Iustin Pop

230 ea03467c Iustin Pop
    @rtype: dict
231 ea03467c Iustin Pop
    @return: the serialized state
232 ea03467c Iustin Pop

233 ea03467c Iustin Pop
    """
234 f1da30e6 Michael Hanselmann
    return {
235 f1da30e6 Michael Hanselmann
      "id": self.id,
236 85f03e0d Michael Hanselmann
      "ops": [op.Serialize() for op in self.ops],
237 c56ec146 Iustin Pop
      "start_timestamp": self.start_timestamp,
238 c56ec146 Iustin Pop
      "end_timestamp": self.end_timestamp,
239 c56ec146 Iustin Pop
      "received_timestamp": self.received_timestamp,
240 f1da30e6 Michael Hanselmann
      }
241 f1da30e6 Michael Hanselmann
242 85f03e0d Michael Hanselmann
  def CalcStatus(self):
243 ea03467c Iustin Pop
    """Compute the status of this job.
244 ea03467c Iustin Pop

245 ea03467c Iustin Pop
    This function iterates over all the _QueuedOpCodes in the job and
246 ea03467c Iustin Pop
    based on their status, computes the job status.
247 ea03467c Iustin Pop

248 ea03467c Iustin Pop
    The algorithm is:
249 ea03467c Iustin Pop
      - if we find a cancelled, or finished with error, the job
250 ea03467c Iustin Pop
        status will be the same
251 ea03467c Iustin Pop
      - otherwise, the last opcode with the status one of:
252 ea03467c Iustin Pop
          - waitlock
253 fbf0262f Michael Hanselmann
          - canceling
254 ea03467c Iustin Pop
          - running
255 ea03467c Iustin Pop

256 ea03467c Iustin Pop
        will determine the job status
257 ea03467c Iustin Pop

258 ea03467c Iustin Pop
      - otherwise, it means either all opcodes are queued, or success,
259 ea03467c Iustin Pop
        and the job status will be the same
260 ea03467c Iustin Pop

261 ea03467c Iustin Pop
    @return: the job status
262 ea03467c Iustin Pop

263 ea03467c Iustin Pop
    """
264 e2715f69 Michael Hanselmann
    status = constants.JOB_STATUS_QUEUED
265 e2715f69 Michael Hanselmann
266 e2715f69 Michael Hanselmann
    all_success = True
267 85f03e0d Michael Hanselmann
    for op in self.ops:
268 85f03e0d Michael Hanselmann
      if op.status == constants.OP_STATUS_SUCCESS:
269 e2715f69 Michael Hanselmann
        continue
270 e2715f69 Michael Hanselmann
271 e2715f69 Michael Hanselmann
      all_success = False
272 e2715f69 Michael Hanselmann
273 85f03e0d Michael Hanselmann
      if op.status == constants.OP_STATUS_QUEUED:
274 e2715f69 Michael Hanselmann
        pass
275 e92376d7 Iustin Pop
      elif op.status == constants.OP_STATUS_WAITLOCK:
276 e92376d7 Iustin Pop
        status = constants.JOB_STATUS_WAITLOCK
277 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_RUNNING:
278 e2715f69 Michael Hanselmann
        status = constants.JOB_STATUS_RUNNING
279 fbf0262f Michael Hanselmann
      elif op.status == constants.OP_STATUS_CANCELING:
280 fbf0262f Michael Hanselmann
        status = constants.JOB_STATUS_CANCELING
281 fbf0262f Michael Hanselmann
        break
282 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_ERROR:
283 f1da30e6 Michael Hanselmann
        status = constants.JOB_STATUS_ERROR
284 f1da30e6 Michael Hanselmann
        # The whole job fails if one opcode failed
285 f1da30e6 Michael Hanselmann
        break
286 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_CANCELED:
287 4cb1d919 Michael Hanselmann
        status = constants.OP_STATUS_CANCELED
288 4cb1d919 Michael Hanselmann
        break
289 e2715f69 Michael Hanselmann
290 e2715f69 Michael Hanselmann
    if all_success:
291 e2715f69 Michael Hanselmann
      status = constants.JOB_STATUS_SUCCESS
292 e2715f69 Michael Hanselmann
293 e2715f69 Michael Hanselmann
    return status
294 e2715f69 Michael Hanselmann
295 6c5a7090 Michael Hanselmann
  def GetLogEntries(self, newer_than):
296 ea03467c Iustin Pop
    """Selectively returns the log entries.
297 ea03467c Iustin Pop

298 ea03467c Iustin Pop
    @type newer_than: None or int
299 5bbd3f7f Michael Hanselmann
    @param newer_than: if this is None, return all log entries,
300 ea03467c Iustin Pop
        otherwise return only the log entries with serial higher
301 ea03467c Iustin Pop
        than this value
302 ea03467c Iustin Pop
    @rtype: list
303 ea03467c Iustin Pop
    @return: the list of the log entries selected
304 ea03467c Iustin Pop

305 ea03467c Iustin Pop
    """
306 6c5a7090 Michael Hanselmann
    if newer_than is None:
307 6c5a7090 Michael Hanselmann
      serial = -1
308 6c5a7090 Michael Hanselmann
    else:
309 6c5a7090 Michael Hanselmann
      serial = newer_than
310 6c5a7090 Michael Hanselmann
311 6c5a7090 Michael Hanselmann
    entries = []
312 6c5a7090 Michael Hanselmann
    for op in self.ops:
313 63712a09 Iustin Pop
      entries.extend(filter(lambda entry: entry[0] > serial, op.log))
314 6c5a7090 Michael Hanselmann
315 6c5a7090 Michael Hanselmann
    return entries
316 6c5a7090 Michael Hanselmann
317 34327f51 Iustin Pop
  def MarkUnfinishedOps(self, status, result):
318 34327f51 Iustin Pop
    """Mark unfinished opcodes with a given status and result.
319 34327f51 Iustin Pop

320 34327f51 Iustin Pop
    This is an utility function for marking all running or waiting to
321 34327f51 Iustin Pop
    be run opcodes with a given status. Opcodes which are already
322 34327f51 Iustin Pop
    finalised are not changed.
323 34327f51 Iustin Pop

324 34327f51 Iustin Pop
    @param status: a given opcode status
325 34327f51 Iustin Pop
    @param result: the opcode result
326 34327f51 Iustin Pop

327 34327f51 Iustin Pop
    """
328 34327f51 Iustin Pop
    not_marked = True
329 34327f51 Iustin Pop
    for op in self.ops:
330 34327f51 Iustin Pop
      if op.status in constants.OPS_FINALIZED:
331 34327f51 Iustin Pop
        assert not_marked, "Finalized opcodes found after non-finalized ones"
332 34327f51 Iustin Pop
        continue
333 34327f51 Iustin Pop
      op.status = status
334 34327f51 Iustin Pop
      op.result = result
335 34327f51 Iustin Pop
      not_marked = False
336 34327f51 Iustin Pop
337 f1048938 Iustin Pop
338 ef2df7d3 Michael Hanselmann
class _OpExecCallbacks(mcpu.OpExecCbBase):
339 031a3e57 Michael Hanselmann
  def __init__(self, queue, job, op):
340 031a3e57 Michael Hanselmann
    """Initializes this class.
341 ea03467c Iustin Pop

342 031a3e57 Michael Hanselmann
    @type queue: L{JobQueue}
343 031a3e57 Michael Hanselmann
    @param queue: Job queue
344 031a3e57 Michael Hanselmann
    @type job: L{_QueuedJob}
345 031a3e57 Michael Hanselmann
    @param job: Job object
346 031a3e57 Michael Hanselmann
    @type op: L{_QueuedOpCode}
347 031a3e57 Michael Hanselmann
    @param op: OpCode
348 031a3e57 Michael Hanselmann

349 031a3e57 Michael Hanselmann
    """
350 031a3e57 Michael Hanselmann
    assert queue, "Queue is missing"
351 031a3e57 Michael Hanselmann
    assert job, "Job is missing"
352 031a3e57 Michael Hanselmann
    assert op, "Opcode is missing"
353 031a3e57 Michael Hanselmann
354 031a3e57 Michael Hanselmann
    self._queue = queue
355 031a3e57 Michael Hanselmann
    self._job = job
356 031a3e57 Michael Hanselmann
    self._op = op
357 031a3e57 Michael Hanselmann
358 031a3e57 Michael Hanselmann
  def NotifyStart(self):
359 e92376d7 Iustin Pop
    """Mark the opcode as running, not lock-waiting.
360 e92376d7 Iustin Pop

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

366 e92376d7 Iustin Pop
    """
367 031a3e57 Michael Hanselmann
    self._queue.acquire()
368 e92376d7 Iustin Pop
    try:
369 031a3e57 Michael Hanselmann
      assert self._op.status in (constants.OP_STATUS_WAITLOCK,
370 031a3e57 Michael Hanselmann
                                 constants.OP_STATUS_CANCELING)
371 fbf0262f Michael Hanselmann
372 ef2df7d3 Michael Hanselmann
      # All locks are acquired by now
373 ef2df7d3 Michael Hanselmann
      self._job.lock_status = None
374 ef2df7d3 Michael Hanselmann
375 fbf0262f Michael Hanselmann
      # Cancel here if we were asked to
376 031a3e57 Michael Hanselmann
      if self._op.status == constants.OP_STATUS_CANCELING:
377 fbf0262f Michael Hanselmann
        raise CancelJob()
378 fbf0262f Michael Hanselmann
379 031a3e57 Michael Hanselmann
      self._op.status = constants.OP_STATUS_RUNNING
380 e92376d7 Iustin Pop
    finally:
381 031a3e57 Michael Hanselmann
      self._queue.release()
382 031a3e57 Michael Hanselmann
383 031a3e57 Michael Hanselmann
  def Feedback(self, *args):
384 031a3e57 Michael Hanselmann
    """Append a log entry.
385 031a3e57 Michael Hanselmann

386 031a3e57 Michael Hanselmann
    """
387 031a3e57 Michael Hanselmann
    assert len(args) < 3
388 031a3e57 Michael Hanselmann
389 031a3e57 Michael Hanselmann
    if len(args) == 1:
390 031a3e57 Michael Hanselmann
      log_type = constants.ELOG_MESSAGE
391 031a3e57 Michael Hanselmann
      log_msg = args[0]
392 031a3e57 Michael Hanselmann
    else:
393 031a3e57 Michael Hanselmann
      (log_type, log_msg) = args
394 031a3e57 Michael Hanselmann
395 031a3e57 Michael Hanselmann
    # The time is split to make serialization easier and not lose
396 031a3e57 Michael Hanselmann
    # precision.
397 031a3e57 Michael Hanselmann
    timestamp = utils.SplitTime(time.time())
398 e92376d7 Iustin Pop
399 031a3e57 Michael Hanselmann
    self._queue.acquire()
400 031a3e57 Michael Hanselmann
    try:
401 031a3e57 Michael Hanselmann
      self._job.log_serial += 1
402 031a3e57 Michael Hanselmann
      self._op.log.append((self._job.log_serial, timestamp, log_type, log_msg))
403 031a3e57 Michael Hanselmann
404 031a3e57 Michael Hanselmann
      self._job.change.notifyAll()
405 031a3e57 Michael Hanselmann
    finally:
406 031a3e57 Michael Hanselmann
      self._queue.release()
407 031a3e57 Michael Hanselmann
408 ef2df7d3 Michael Hanselmann
  def ReportLocks(self, msg):
409 ef2df7d3 Michael Hanselmann
    """Write locking information to the job.
410 ef2df7d3 Michael Hanselmann

411 ef2df7d3 Michael Hanselmann
    Called whenever the LU processor is waiting for a lock or has acquired one.
412 ef2df7d3 Michael Hanselmann

413 ef2df7d3 Michael Hanselmann
    """
414 ef2df7d3 Michael Hanselmann
    # Not getting the queue lock because this is a single assignment
415 ef2df7d3 Michael Hanselmann
    self._job.lock_status = msg
416 ef2df7d3 Michael Hanselmann
417 031a3e57 Michael Hanselmann
418 031a3e57 Michael Hanselmann
class _JobQueueWorker(workerpool.BaseWorker):
419 031a3e57 Michael Hanselmann
  """The actual job workers.
420 031a3e57 Michael Hanselmann

421 031a3e57 Michael Hanselmann
  """
422 85f03e0d Michael Hanselmann
  def RunTask(self, job):
423 e2715f69 Michael Hanselmann
    """Job executor.
424 e2715f69 Michael Hanselmann

425 6c5a7090 Michael Hanselmann
    This functions processes a job. It is closely tied to the _QueuedJob and
426 6c5a7090 Michael Hanselmann
    _QueuedOpCode classes.
427 e2715f69 Michael Hanselmann

428 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
429 ea03467c Iustin Pop
    @param job: the job to be processed
430 ea03467c Iustin Pop

431 e2715f69 Michael Hanselmann
    """
432 d21d09d6 Iustin Pop
    logging.info("Worker %s processing job %s",
433 e2715f69 Michael Hanselmann
                  self.worker_id, job.id)
434 adfa97e3 Guido Trotter
    proc = mcpu.Processor(self.pool.queue.context, job.id)
435 031a3e57 Michael Hanselmann
    queue = job.queue
436 e2715f69 Michael Hanselmann
    try:
437 85f03e0d Michael Hanselmann
      try:
438 85f03e0d Michael Hanselmann
        count = len(job.ops)
439 85f03e0d Michael Hanselmann
        for idx, op in enumerate(job.ops):
440 d21d09d6 Iustin Pop
          op_summary = op.input.Summary()
441 f6424741 Iustin Pop
          if op.status == constants.OP_STATUS_SUCCESS:
442 f6424741 Iustin Pop
            # this is a job that was partially completed before master
443 f6424741 Iustin Pop
            # daemon shutdown, so it can be expected that some opcodes
444 f6424741 Iustin Pop
            # are already completed successfully (if any did error
445 f6424741 Iustin Pop
            # out, then the whole job should have been aborted and not
446 f6424741 Iustin Pop
            # resubmitted for processing)
447 f6424741 Iustin Pop
            logging.info("Op %s/%s: opcode %s already processed, skipping",
448 f6424741 Iustin Pop
                         idx + 1, count, op_summary)
449 f6424741 Iustin Pop
            continue
450 85f03e0d Michael Hanselmann
          try:
451 d21d09d6 Iustin Pop
            logging.info("Op %s/%s: Starting opcode %s", idx + 1, count,
452 d21d09d6 Iustin Pop
                         op_summary)
453 85f03e0d Michael Hanselmann
454 85f03e0d Michael Hanselmann
            queue.acquire()
455 85f03e0d Michael Hanselmann
            try:
456 df0fb067 Iustin Pop
              if op.status == constants.OP_STATUS_CANCELED:
457 df0fb067 Iustin Pop
                raise CancelJob()
458 fbf0262f Michael Hanselmann
              assert op.status == constants.OP_STATUS_QUEUED
459 e92376d7 Iustin Pop
              op.status = constants.OP_STATUS_WAITLOCK
460 85f03e0d Michael Hanselmann
              op.result = None
461 70552c46 Michael Hanselmann
              op.start_timestamp = TimeStampNow()
462 c56ec146 Iustin Pop
              if idx == 0: # first opcode
463 c56ec146 Iustin Pop
                job.start_timestamp = op.start_timestamp
464 85f03e0d Michael Hanselmann
              queue.UpdateJobUnlocked(job)
465 85f03e0d Michael Hanselmann
466 38206f3c Iustin Pop
              input_opcode = op.input
467 85f03e0d Michael Hanselmann
            finally:
468 85f03e0d Michael Hanselmann
              queue.release()
469 85f03e0d Michael Hanselmann
470 031a3e57 Michael Hanselmann
            # Make sure not to hold queue lock while calling ExecOpCode
471 031a3e57 Michael Hanselmann
            result = proc.ExecOpCode(input_opcode,
472 ef2df7d3 Michael Hanselmann
                                     _OpExecCallbacks(queue, job, op))
473 85f03e0d Michael Hanselmann
474 85f03e0d Michael Hanselmann
            queue.acquire()
475 85f03e0d Michael Hanselmann
            try:
476 85f03e0d Michael Hanselmann
              op.status = constants.OP_STATUS_SUCCESS
477 85f03e0d Michael Hanselmann
              op.result = result
478 70552c46 Michael Hanselmann
              op.end_timestamp = TimeStampNow()
479 85f03e0d Michael Hanselmann
              queue.UpdateJobUnlocked(job)
480 85f03e0d Michael Hanselmann
            finally:
481 85f03e0d Michael Hanselmann
              queue.release()
482 85f03e0d Michael Hanselmann
483 d21d09d6 Iustin Pop
            logging.info("Op %s/%s: Successfully finished opcode %s",
484 d21d09d6 Iustin Pop
                         idx + 1, count, op_summary)
485 fbf0262f Michael Hanselmann
          except CancelJob:
486 fbf0262f Michael Hanselmann
            # Will be handled further up
487 fbf0262f Michael Hanselmann
            raise
488 85f03e0d Michael Hanselmann
          except Exception, err:
489 85f03e0d Michael Hanselmann
            queue.acquire()
490 85f03e0d Michael Hanselmann
            try:
491 85f03e0d Michael Hanselmann
              try:
492 85f03e0d Michael Hanselmann
                op.status = constants.OP_STATUS_ERROR
493 bcb66fca Iustin Pop
                if isinstance(err, errors.GenericError):
494 bcb66fca Iustin Pop
                  op.result = errors.EncodeException(err)
495 bcb66fca Iustin Pop
                else:
496 bcb66fca Iustin Pop
                  op.result = str(err)
497 70552c46 Michael Hanselmann
                op.end_timestamp = TimeStampNow()
498 0f6be82a Iustin Pop
                logging.info("Op %s/%s: Error in opcode %s: %s",
499 0f6be82a Iustin Pop
                             idx + 1, count, op_summary, err)
500 85f03e0d Michael Hanselmann
              finally:
501 85f03e0d Michael Hanselmann
                queue.UpdateJobUnlocked(job)
502 85f03e0d Michael Hanselmann
            finally:
503 85f03e0d Michael Hanselmann
              queue.release()
504 85f03e0d Michael Hanselmann
            raise
505 85f03e0d Michael Hanselmann
506 fbf0262f Michael Hanselmann
      except CancelJob:
507 fbf0262f Michael Hanselmann
        queue.acquire()
508 fbf0262f Michael Hanselmann
        try:
509 fbf0262f Michael Hanselmann
          queue.CancelJobUnlocked(job)
510 fbf0262f Michael Hanselmann
        finally:
511 fbf0262f Michael Hanselmann
          queue.release()
512 85f03e0d Michael Hanselmann
      except errors.GenericError, err:
513 85f03e0d Michael Hanselmann
        logging.exception("Ganeti exception")
514 85f03e0d Michael Hanselmann
      except:
515 85f03e0d Michael Hanselmann
        logging.exception("Unhandled exception")
516 e2715f69 Michael Hanselmann
    finally:
517 85f03e0d Michael Hanselmann
      queue.acquire()
518 85f03e0d Michael Hanselmann
      try:
519 65548ed5 Michael Hanselmann
        try:
520 ef2df7d3 Michael Hanselmann
          job.lock_status = None
521 c56ec146 Iustin Pop
          job.end_timestamp = TimeStampNow()
522 65548ed5 Michael Hanselmann
          queue.UpdateJobUnlocked(job)
523 65548ed5 Michael Hanselmann
        finally:
524 65548ed5 Michael Hanselmann
          job_id = job.id
525 65548ed5 Michael Hanselmann
          status = job.CalcStatus()
526 85f03e0d Michael Hanselmann
      finally:
527 85f03e0d Michael Hanselmann
        queue.release()
528 ef2df7d3 Michael Hanselmann
529 d21d09d6 Iustin Pop
      logging.info("Worker %s finished job %s, status = %s",
530 d21d09d6 Iustin Pop
                   self.worker_id, job_id, status)
531 e2715f69 Michael Hanselmann
532 e2715f69 Michael Hanselmann
533 e2715f69 Michael Hanselmann
class _JobQueueWorkerPool(workerpool.WorkerPool):
534 ea03467c Iustin Pop
  """Simple class implementing a job-processing workerpool.
535 ea03467c Iustin Pop

536 ea03467c Iustin Pop
  """
537 5bdce580 Michael Hanselmann
  def __init__(self, queue):
538 e2715f69 Michael Hanselmann
    super(_JobQueueWorkerPool, self).__init__(JOBQUEUE_THREADS,
539 e2715f69 Michael Hanselmann
                                              _JobQueueWorker)
540 5bdce580 Michael Hanselmann
    self.queue = queue
541 e2715f69 Michael Hanselmann
542 e2715f69 Michael Hanselmann
543 6c881c52 Iustin Pop
def _RequireOpenQueue(fn):
544 6c881c52 Iustin Pop
  """Decorator for "public" functions.
545 ea03467c Iustin Pop

546 6c881c52 Iustin Pop
  This function should be used for all 'public' functions. That is,
547 6c881c52 Iustin Pop
  functions usually called from other classes. Note that this should
548 6c881c52 Iustin Pop
  be applied only to methods (not plain functions), since it expects
549 6c881c52 Iustin Pop
  that the decorated function is called with a first argument that has
550 6c881c52 Iustin Pop
  a '_queue_lock' argument.
551 ea03467c Iustin Pop

552 6c881c52 Iustin Pop
  @warning: Use this decorator only after utils.LockedMethod!
553 f1da30e6 Michael Hanselmann

554 6c881c52 Iustin Pop
  Example::
555 6c881c52 Iustin Pop
    @utils.LockedMethod
556 6c881c52 Iustin Pop
    @_RequireOpenQueue
557 6c881c52 Iustin Pop
    def Example(self):
558 6c881c52 Iustin Pop
      pass
559 db37da70 Michael Hanselmann

560 6c881c52 Iustin Pop
  """
561 6c881c52 Iustin Pop
  def wrapper(self, *args, **kwargs):
562 6c881c52 Iustin Pop
    assert self._queue_lock is not None, "Queue should be open"
563 6c881c52 Iustin Pop
    return fn(self, *args, **kwargs)
564 6c881c52 Iustin Pop
  return wrapper
565 db37da70 Michael Hanselmann
566 db37da70 Michael Hanselmann
567 6c881c52 Iustin Pop
class JobQueue(object):
568 6c881c52 Iustin Pop
  """Queue used to manage the jobs.
569 db37da70 Michael Hanselmann

570 6c881c52 Iustin Pop
  @cvar _RE_JOB_FILE: regex matching the valid job file names
571 6c881c52 Iustin Pop

572 6c881c52 Iustin Pop
  """
573 6c881c52 Iustin Pop
  _RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
574 db37da70 Michael Hanselmann
575 85f03e0d Michael Hanselmann
  def __init__(self, context):
576 ea03467c Iustin Pop
    """Constructor for JobQueue.
577 ea03467c Iustin Pop

578 ea03467c Iustin Pop
    The constructor will initialize the job queue object and then
579 ea03467c Iustin Pop
    start loading the current jobs from disk, either for starting them
580 ea03467c Iustin Pop
    (if they were queue) or for aborting them (if they were already
581 ea03467c Iustin Pop
    running).
582 ea03467c Iustin Pop

583 ea03467c Iustin Pop
    @type context: GanetiContext
584 ea03467c Iustin Pop
    @param context: the context object for access to the configuration
585 ea03467c Iustin Pop
        data and other ganeti objects
586 ea03467c Iustin Pop

587 ea03467c Iustin Pop
    """
588 5bdce580 Michael Hanselmann
    self.context = context
589 5685c1a5 Michael Hanselmann
    self._memcache = weakref.WeakValueDictionary()
590 c3f0a12f Iustin Pop
    self._my_hostname = utils.HostInfo().name
591 f1da30e6 Michael Hanselmann
592 85f03e0d Michael Hanselmann
    # Locking
593 85f03e0d Michael Hanselmann
    self._lock = threading.Lock()
594 85f03e0d Michael Hanselmann
    self.acquire = self._lock.acquire
595 85f03e0d Michael Hanselmann
    self.release = self._lock.release
596 85f03e0d Michael Hanselmann
597 04ab05ce Michael Hanselmann
    # Initialize
598 5d6fb8eb Michael Hanselmann
    self._queue_lock = jstore.InitAndVerifyQueue(must_lock=True)
599 f1da30e6 Michael Hanselmann
600 04ab05ce Michael Hanselmann
    # Read serial file
601 04ab05ce Michael Hanselmann
    self._last_serial = jstore.ReadSerial()
602 04ab05ce Michael Hanselmann
    assert self._last_serial is not None, ("Serial file was modified between"
603 04ab05ce Michael Hanselmann
                                           " check in jstore and here")
604 c4beba1c Iustin Pop
605 23752136 Michael Hanselmann
    # Get initial list of nodes
606 99aabbed Iustin Pop
    self._nodes = dict((n.name, n.primary_ip)
607 59303563 Iustin Pop
                       for n in self.context.cfg.GetAllNodesInfo().values()
608 59303563 Iustin Pop
                       if n.master_candidate)
609 8e00939c Michael Hanselmann
610 8e00939c Michael Hanselmann
    # Remove master node
611 8e00939c Michael Hanselmann
    try:
612 99aabbed Iustin Pop
      del self._nodes[self._my_hostname]
613 33987705 Iustin Pop
    except KeyError:
614 8e00939c Michael Hanselmann
      pass
615 23752136 Michael Hanselmann
616 23752136 Michael Hanselmann
    # TODO: Check consistency across nodes
617 23752136 Michael Hanselmann
618 85f03e0d Michael Hanselmann
    # Setup worker pool
619 5bdce580 Michael Hanselmann
    self._wpool = _JobQueueWorkerPool(self)
620 85f03e0d Michael Hanselmann
    try:
621 16714921 Michael Hanselmann
      # We need to lock here because WorkerPool.AddTask() may start a job while
622 16714921 Michael Hanselmann
      # we're still doing our work.
623 16714921 Michael Hanselmann
      self.acquire()
624 16714921 Michael Hanselmann
      try:
625 711b5124 Michael Hanselmann
        logging.info("Inspecting job queue")
626 711b5124 Michael Hanselmann
627 711b5124 Michael Hanselmann
        all_job_ids = self._GetJobIDsUnlocked()
628 b7cb9024 Michael Hanselmann
        jobs_count = len(all_job_ids)
629 711b5124 Michael Hanselmann
        lastinfo = time.time()
630 711b5124 Michael Hanselmann
        for idx, job_id in enumerate(all_job_ids):
631 711b5124 Michael Hanselmann
          # Give an update every 1000 jobs or 10 seconds
632 b7cb9024 Michael Hanselmann
          if (idx % 1000 == 0 or time.time() >= (lastinfo + 10.0) or
633 b7cb9024 Michael Hanselmann
              idx == (jobs_count - 1)):
634 711b5124 Michael Hanselmann
            logging.info("Job queue inspection: %d/%d (%0.1f %%)",
635 b7cb9024 Michael Hanselmann
                         idx, jobs_count - 1, 100.0 * (idx + 1) / jobs_count)
636 711b5124 Michael Hanselmann
            lastinfo = time.time()
637 711b5124 Michael Hanselmann
638 711b5124 Michael Hanselmann
          job = self._LoadJobUnlocked(job_id)
639 711b5124 Michael Hanselmann
640 16714921 Michael Hanselmann
          # a failure in loading the job can cause 'None' to be returned
641 16714921 Michael Hanselmann
          if job is None:
642 16714921 Michael Hanselmann
            continue
643 94ed59a5 Iustin Pop
644 16714921 Michael Hanselmann
          status = job.CalcStatus()
645 85f03e0d Michael Hanselmann
646 16714921 Michael Hanselmann
          if status in (constants.JOB_STATUS_QUEUED, ):
647 16714921 Michael Hanselmann
            self._wpool.AddTask(job)
648 85f03e0d Michael Hanselmann
649 16714921 Michael Hanselmann
          elif status in (constants.JOB_STATUS_RUNNING,
650 fbf0262f Michael Hanselmann
                          constants.JOB_STATUS_WAITLOCK,
651 fbf0262f Michael Hanselmann
                          constants.JOB_STATUS_CANCELING):
652 16714921 Michael Hanselmann
            logging.warning("Unfinished job %s found: %s", job.id, job)
653 16714921 Michael Hanselmann
            try:
654 34327f51 Iustin Pop
              job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
655 34327f51 Iustin Pop
                                    "Unclean master daemon shutdown")
656 16714921 Michael Hanselmann
            finally:
657 16714921 Michael Hanselmann
              self.UpdateJobUnlocked(job)
658 711b5124 Michael Hanselmann
659 711b5124 Michael Hanselmann
        logging.info("Job queue inspection finished")
660 16714921 Michael Hanselmann
      finally:
661 16714921 Michael Hanselmann
        self.release()
662 16714921 Michael Hanselmann
    except:
663 16714921 Michael Hanselmann
      self._wpool.TerminateWorkers()
664 16714921 Michael Hanselmann
      raise
665 85f03e0d Michael Hanselmann
666 d2e03a33 Michael Hanselmann
  @utils.LockedMethod
667 d2e03a33 Michael Hanselmann
  @_RequireOpenQueue
668 99aabbed Iustin Pop
  def AddNode(self, node):
669 99aabbed Iustin Pop
    """Register a new node with the queue.
670 99aabbed Iustin Pop

671 99aabbed Iustin Pop
    @type node: L{objects.Node}
672 99aabbed Iustin Pop
    @param node: the node object to be added
673 99aabbed Iustin Pop

674 99aabbed Iustin Pop
    """
675 99aabbed Iustin Pop
    node_name = node.name
676 d2e03a33 Michael Hanselmann
    assert node_name != self._my_hostname
677 23752136 Michael Hanselmann
678 9f774ee8 Michael Hanselmann
    # Clean queue directory on added node
679 c8457ce7 Iustin Pop
    result = rpc.RpcRunner.call_jobqueue_purge(node_name)
680 3cebe102 Michael Hanselmann
    msg = result.fail_msg
681 c8457ce7 Iustin Pop
    if msg:
682 c8457ce7 Iustin Pop
      logging.warning("Cannot cleanup queue directory on node %s: %s",
683 c8457ce7 Iustin Pop
                      node_name, msg)
684 23752136 Michael Hanselmann
685 59303563 Iustin Pop
    if not node.master_candidate:
686 59303563 Iustin Pop
      # remove if existing, ignoring errors
687 59303563 Iustin Pop
      self._nodes.pop(node_name, None)
688 59303563 Iustin Pop
      # and skip the replication of the job ids
689 59303563 Iustin Pop
      return
690 59303563 Iustin Pop
691 d2e03a33 Michael Hanselmann
    # Upload the whole queue excluding archived jobs
692 d2e03a33 Michael Hanselmann
    files = [self._GetJobPath(job_id) for job_id in self._GetJobIDsUnlocked()]
693 23752136 Michael Hanselmann
694 d2e03a33 Michael Hanselmann
    # Upload current serial file
695 d2e03a33 Michael Hanselmann
    files.append(constants.JOB_QUEUE_SERIAL_FILE)
696 d2e03a33 Michael Hanselmann
697 d2e03a33 Michael Hanselmann
    for file_name in files:
698 9f774ee8 Michael Hanselmann
      # Read file content
699 13998ef2 Michael Hanselmann
      content = utils.ReadFile(file_name)
700 9f774ee8 Michael Hanselmann
701 a3811745 Michael Hanselmann
      result = rpc.RpcRunner.call_jobqueue_update([node_name],
702 a3811745 Michael Hanselmann
                                                  [node.primary_ip],
703 a3811745 Michael Hanselmann
                                                  file_name, content)
704 3cebe102 Michael Hanselmann
      msg = result[node_name].fail_msg
705 c8457ce7 Iustin Pop
      if msg:
706 c8457ce7 Iustin Pop
        logging.error("Failed to upload file %s to node %s: %s",
707 c8457ce7 Iustin Pop
                      file_name, node_name, msg)
708 d2e03a33 Michael Hanselmann
709 99aabbed Iustin Pop
    self._nodes[node_name] = node.primary_ip
710 d2e03a33 Michael Hanselmann
711 d2e03a33 Michael Hanselmann
  @utils.LockedMethod
712 d2e03a33 Michael Hanselmann
  @_RequireOpenQueue
713 d2e03a33 Michael Hanselmann
  def RemoveNode(self, node_name):
714 ea03467c Iustin Pop
    """Callback called when removing nodes from the cluster.
715 ea03467c Iustin Pop

716 ea03467c Iustin Pop
    @type node_name: str
717 ea03467c Iustin Pop
    @param node_name: the name of the node to remove
718 ea03467c Iustin Pop

719 ea03467c Iustin Pop
    """
720 23752136 Michael Hanselmann
    try:
721 d2e03a33 Michael Hanselmann
      # The queue is removed by the "leave node" RPC call.
722 99aabbed Iustin Pop
      del self._nodes[node_name]
723 d2e03a33 Michael Hanselmann
    except KeyError:
724 23752136 Michael Hanselmann
      pass
725 23752136 Michael Hanselmann
726 e74798c1 Michael Hanselmann
  def _CheckRpcResult(self, result, nodes, failmsg):
727 ea03467c Iustin Pop
    """Verifies the status of an RPC call.
728 ea03467c Iustin Pop

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

733 ea03467c Iustin Pop
    @param result: the data as returned from the rpc call
734 ea03467c Iustin Pop
    @type nodes: list
735 ea03467c Iustin Pop
    @param nodes: the list of nodes we made the call to
736 ea03467c Iustin Pop
    @type failmsg: str
737 ea03467c Iustin Pop
    @param failmsg: the identifier to be used for logging
738 ea03467c Iustin Pop

739 ea03467c Iustin Pop
    """
740 e74798c1 Michael Hanselmann
    failed = []
741 e74798c1 Michael Hanselmann
    success = []
742 e74798c1 Michael Hanselmann
743 e74798c1 Michael Hanselmann
    for node in nodes:
744 3cebe102 Michael Hanselmann
      msg = result[node].fail_msg
745 c8457ce7 Iustin Pop
      if msg:
746 e74798c1 Michael Hanselmann
        failed.append(node)
747 c8457ce7 Iustin Pop
        logging.error("RPC call %s failed on node %s: %s",
748 c8457ce7 Iustin Pop
                      result[node].call, node, msg)
749 c8457ce7 Iustin Pop
      else:
750 c8457ce7 Iustin Pop
        success.append(node)
751 e74798c1 Michael Hanselmann
752 e74798c1 Michael Hanselmann
    # +1 for the master node
753 e74798c1 Michael Hanselmann
    if (len(success) + 1) < len(failed):
754 e74798c1 Michael Hanselmann
      # TODO: Handle failing nodes
755 e74798c1 Michael Hanselmann
      logging.error("More than half of the nodes failed")
756 e74798c1 Michael Hanselmann
757 99aabbed Iustin Pop
  def _GetNodeIp(self):
758 99aabbed Iustin Pop
    """Helper for returning the node name/ip list.
759 99aabbed Iustin Pop

760 ea03467c Iustin Pop
    @rtype: (list, list)
761 ea03467c Iustin Pop
    @return: a tuple of two lists, the first one with the node
762 ea03467c Iustin Pop
        names and the second one with the node addresses
763 ea03467c Iustin Pop

764 99aabbed Iustin Pop
    """
765 99aabbed Iustin Pop
    name_list = self._nodes.keys()
766 99aabbed Iustin Pop
    addr_list = [self._nodes[name] for name in name_list]
767 99aabbed Iustin Pop
    return name_list, addr_list
768 99aabbed Iustin Pop
769 8e00939c Michael Hanselmann
  def _WriteAndReplicateFileUnlocked(self, file_name, data):
770 8e00939c Michael Hanselmann
    """Writes a file locally and then replicates it to all nodes.
771 8e00939c Michael Hanselmann

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

775 ea03467c Iustin Pop
    @type file_name: str
776 ea03467c Iustin Pop
    @param file_name: the path of the file to be replicated
777 ea03467c Iustin Pop
    @type data: str
778 ea03467c Iustin Pop
    @param data: the new contents of the file
779 ea03467c Iustin Pop

780 8e00939c Michael Hanselmann
    """
781 8e00939c Michael Hanselmann
    utils.WriteFile(file_name, data=data)
782 8e00939c Michael Hanselmann
783 99aabbed Iustin Pop
    names, addrs = self._GetNodeIp()
784 a3811745 Michael Hanselmann
    result = rpc.RpcRunner.call_jobqueue_update(names, addrs, file_name, data)
785 e74798c1 Michael Hanselmann
    self._CheckRpcResult(result, self._nodes,
786 e74798c1 Michael Hanselmann
                         "Updating %s" % file_name)
787 23752136 Michael Hanselmann
788 d7fd1f28 Michael Hanselmann
  def _RenameFilesUnlocked(self, rename):
789 ea03467c Iustin Pop
    """Renames a file locally and then replicate the change.
790 ea03467c Iustin Pop

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

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

797 ea03467c Iustin Pop
    """
798 dd875d32 Michael Hanselmann
    # Rename them locally
799 d7fd1f28 Michael Hanselmann
    for old, new in rename:
800 d7fd1f28 Michael Hanselmann
      utils.RenameFile(old, new, mkdir=True)
801 abc1f2ce Michael Hanselmann
802 dd875d32 Michael Hanselmann
    # ... and on all nodes
803 dd875d32 Michael Hanselmann
    names, addrs = self._GetNodeIp()
804 dd875d32 Michael Hanselmann
    result = rpc.RpcRunner.call_jobqueue_rename(names, addrs, rename)
805 dd875d32 Michael Hanselmann
    self._CheckRpcResult(result, self._nodes, "Renaming files (%r)" % rename)
806 abc1f2ce Michael Hanselmann
807 85f03e0d Michael Hanselmann
  def _FormatJobID(self, job_id):
808 ea03467c Iustin Pop
    """Convert a job ID to string format.
809 ea03467c Iustin Pop

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

814 ea03467c Iustin Pop
    @type job_id: int or long
815 ea03467c Iustin Pop
    @param job_id: the numeric job id
816 ea03467c Iustin Pop
    @rtype: str
817 ea03467c Iustin Pop
    @return: the formatted job id
818 ea03467c Iustin Pop

819 ea03467c Iustin Pop
    """
820 85f03e0d Michael Hanselmann
    if not isinstance(job_id, (int, long)):
821 85f03e0d Michael Hanselmann
      raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id)
822 85f03e0d Michael Hanselmann
    if job_id < 0:
823 85f03e0d Michael Hanselmann
      raise errors.ProgrammerError("Job ID %s is negative" % job_id)
824 85f03e0d Michael Hanselmann
825 85f03e0d Michael Hanselmann
    return str(job_id)
826 85f03e0d Michael Hanselmann
827 58b22b6e Michael Hanselmann
  @classmethod
828 58b22b6e Michael Hanselmann
  def _GetArchiveDirectory(cls, job_id):
829 58b22b6e Michael Hanselmann
    """Returns the archive directory for a job.
830 58b22b6e Michael Hanselmann

831 58b22b6e Michael Hanselmann
    @type job_id: str
832 58b22b6e Michael Hanselmann
    @param job_id: Job identifier
833 58b22b6e Michael Hanselmann
    @rtype: str
834 58b22b6e Michael Hanselmann
    @return: Directory name
835 58b22b6e Michael Hanselmann

836 58b22b6e Michael Hanselmann
    """
837 58b22b6e Michael Hanselmann
    return str(int(job_id) / JOBS_PER_ARCHIVE_DIRECTORY)
838 58b22b6e Michael Hanselmann
839 009e73d0 Iustin Pop
  def _NewSerialsUnlocked(self, count):
840 f1da30e6 Michael Hanselmann
    """Generates a new job identifier.
841 f1da30e6 Michael Hanselmann

842 f1da30e6 Michael Hanselmann
    Job identifiers are unique during the lifetime of a cluster.
843 f1da30e6 Michael Hanselmann

844 009e73d0 Iustin Pop
    @type count: integer
845 009e73d0 Iustin Pop
    @param count: how many serials to return
846 ea03467c Iustin Pop
    @rtype: str
847 ea03467c Iustin Pop
    @return: a string representing the job identifier.
848 f1da30e6 Michael Hanselmann

849 f1da30e6 Michael Hanselmann
    """
850 009e73d0 Iustin Pop
    assert count > 0
851 f1da30e6 Michael Hanselmann
    # New number
852 009e73d0 Iustin Pop
    serial = self._last_serial + count
853 f1da30e6 Michael Hanselmann
854 f1da30e6 Michael Hanselmann
    # Write to file
855 23752136 Michael Hanselmann
    self._WriteAndReplicateFileUnlocked(constants.JOB_QUEUE_SERIAL_FILE,
856 23752136 Michael Hanselmann
                                        "%s\n" % serial)
857 f1da30e6 Michael Hanselmann
858 009e73d0 Iustin Pop
    result = [self._FormatJobID(v)
859 009e73d0 Iustin Pop
              for v in range(self._last_serial, serial + 1)]
860 f1da30e6 Michael Hanselmann
    # Keep it only if we were able to write the file
861 f1da30e6 Michael Hanselmann
    self._last_serial = serial
862 f1da30e6 Michael Hanselmann
863 009e73d0 Iustin Pop
    return result
864 f1da30e6 Michael Hanselmann
865 85f03e0d Michael Hanselmann
  @staticmethod
866 85f03e0d Michael Hanselmann
  def _GetJobPath(job_id):
867 ea03467c Iustin Pop
    """Returns the job file for a given job id.
868 ea03467c Iustin Pop

869 ea03467c Iustin Pop
    @type job_id: str
870 ea03467c Iustin Pop
    @param job_id: the job identifier
871 ea03467c Iustin Pop
    @rtype: str
872 ea03467c Iustin Pop
    @return: the path to the job file
873 ea03467c Iustin Pop

874 ea03467c Iustin Pop
    """
875 f1da30e6 Michael Hanselmann
    return os.path.join(constants.QUEUE_DIR, "job-%s" % job_id)
876 f1da30e6 Michael Hanselmann
877 58b22b6e Michael Hanselmann
  @classmethod
878 58b22b6e Michael Hanselmann
  def _GetArchivedJobPath(cls, job_id):
879 ea03467c Iustin Pop
    """Returns the archived job file for a give job id.
880 ea03467c Iustin Pop

881 ea03467c Iustin Pop
    @type job_id: str
882 ea03467c Iustin Pop
    @param job_id: the job identifier
883 ea03467c Iustin Pop
    @rtype: str
884 ea03467c Iustin Pop
    @return: the path to the archived job file
885 ea03467c Iustin Pop

886 ea03467c Iustin Pop
    """
887 58b22b6e Michael Hanselmann
    path = "%s/job-%s" % (cls._GetArchiveDirectory(job_id), job_id)
888 58b22b6e Michael Hanselmann
    return os.path.join(constants.JOB_QUEUE_ARCHIVE_DIR, path)
889 0cb94105 Michael Hanselmann
890 85f03e0d Michael Hanselmann
  @classmethod
891 85f03e0d Michael Hanselmann
  def _ExtractJobID(cls, name):
892 ea03467c Iustin Pop
    """Extract the job id from a filename.
893 ea03467c Iustin Pop

894 ea03467c Iustin Pop
    @type name: str
895 ea03467c Iustin Pop
    @param name: the job filename
896 ea03467c Iustin Pop
    @rtype: job id or None
897 ea03467c Iustin Pop
    @return: the job id corresponding to the given filename,
898 ea03467c Iustin Pop
        or None if the filename does not represent a valid
899 ea03467c Iustin Pop
        job file
900 ea03467c Iustin Pop

901 ea03467c Iustin Pop
    """
902 85f03e0d Michael Hanselmann
    m = cls._RE_JOB_FILE.match(name)
903 fae737ac Michael Hanselmann
    if m:
904 fae737ac Michael Hanselmann
      return m.group(1)
905 fae737ac Michael Hanselmann
    else:
906 fae737ac Michael Hanselmann
      return None
907 fae737ac Michael Hanselmann
908 911a495b Iustin Pop
  def _GetJobIDsUnlocked(self, archived=False):
909 911a495b Iustin Pop
    """Return all known job IDs.
910 911a495b Iustin Pop

911 911a495b Iustin Pop
    If the parameter archived is True, archived jobs IDs will be
912 911a495b Iustin Pop
    included. Currently this argument is unused.
913 911a495b Iustin Pop

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

918 ea03467c Iustin Pop
    @rtype: list
919 ea03467c Iustin Pop
    @return: the list of job IDs
920 ea03467c Iustin Pop

921 911a495b Iustin Pop
    """
922 fae737ac Michael Hanselmann
    jlist = [self._ExtractJobID(name) for name in self._ListJobFiles()]
923 3b87986e Iustin Pop
    jlist = utils.NiceSort(jlist)
924 f0d874fe Iustin Pop
    return jlist
925 911a495b Iustin Pop
926 f1da30e6 Michael Hanselmann
  def _ListJobFiles(self):
927 ea03467c Iustin Pop
    """Returns the list of current job files.
928 ea03467c Iustin Pop

929 ea03467c Iustin Pop
    @rtype: list
930 ea03467c Iustin Pop
    @return: the list of job file names
931 ea03467c Iustin Pop

932 ea03467c Iustin Pop
    """
933 f1da30e6 Michael Hanselmann
    return [name for name in utils.ListVisibleFiles(constants.QUEUE_DIR)
934 f1da30e6 Michael Hanselmann
            if self._RE_JOB_FILE.match(name)]
935 f1da30e6 Michael Hanselmann
936 911a495b Iustin Pop
  def _LoadJobUnlocked(self, job_id):
937 ea03467c Iustin Pop
    """Loads a job from the disk or memory.
938 ea03467c Iustin Pop

939 ea03467c Iustin Pop
    Given a job id, this will return the cached job object if
940 ea03467c Iustin Pop
    existing, or try to load the job from the disk. If loading from
941 ea03467c Iustin Pop
    disk, it will also add the job to the cache.
942 ea03467c Iustin Pop

943 ea03467c Iustin Pop
    @param job_id: the job id
944 ea03467c Iustin Pop
    @rtype: L{_QueuedJob} or None
945 ea03467c Iustin Pop
    @return: either None or the job object
946 ea03467c Iustin Pop

947 ea03467c Iustin Pop
    """
948 5685c1a5 Michael Hanselmann
    job = self._memcache.get(job_id, None)
949 5685c1a5 Michael Hanselmann
    if job:
950 205d71fd Michael Hanselmann
      logging.debug("Found job %s in memcache", job_id)
951 5685c1a5 Michael Hanselmann
      return job
952 ac0930b9 Iustin Pop
953 911a495b Iustin Pop
    filepath = self._GetJobPath(job_id)
954 f1da30e6 Michael Hanselmann
    logging.debug("Loading job from %s", filepath)
955 f1da30e6 Michael Hanselmann
    try:
956 13998ef2 Michael Hanselmann
      raw_data = utils.ReadFile(filepath)
957 f1da30e6 Michael Hanselmann
    except IOError, err:
958 f1da30e6 Michael Hanselmann
      if err.errno in (errno.ENOENT, ):
959 f1da30e6 Michael Hanselmann
        return None
960 f1da30e6 Michael Hanselmann
      raise
961 13998ef2 Michael Hanselmann
962 13998ef2 Michael Hanselmann
    data = serializer.LoadJson(raw_data)
963 f1da30e6 Michael Hanselmann
964 94ed59a5 Iustin Pop
    try:
965 94ed59a5 Iustin Pop
      job = _QueuedJob.Restore(self, data)
966 94ed59a5 Iustin Pop
    except Exception, err:
967 94ed59a5 Iustin Pop
      new_path = self._GetArchivedJobPath(job_id)
968 94ed59a5 Iustin Pop
      if filepath == new_path:
969 94ed59a5 Iustin Pop
        # job already archived (future case)
970 94ed59a5 Iustin Pop
        logging.exception("Can't parse job %s", job_id)
971 94ed59a5 Iustin Pop
      else:
972 94ed59a5 Iustin Pop
        # non-archived case
973 94ed59a5 Iustin Pop
        logging.exception("Can't parse job %s, will archive.", job_id)
974 d7fd1f28 Michael Hanselmann
        self._RenameFilesUnlocked([(filepath, new_path)])
975 94ed59a5 Iustin Pop
      return None
976 94ed59a5 Iustin Pop
977 ac0930b9 Iustin Pop
    self._memcache[job_id] = job
978 205d71fd Michael Hanselmann
    logging.debug("Added job %s to the cache", job_id)
979 ac0930b9 Iustin Pop
    return job
980 f1da30e6 Michael Hanselmann
981 f1da30e6 Michael Hanselmann
  def _GetJobsUnlocked(self, job_ids):
982 ea03467c Iustin Pop
    """Return a list of jobs based on their IDs.
983 ea03467c Iustin Pop

984 ea03467c Iustin Pop
    @type job_ids: list
985 ea03467c Iustin Pop
    @param job_ids: either an empty list (meaning all jobs),
986 ea03467c Iustin Pop
        or a list of job IDs
987 ea03467c Iustin Pop
    @rtype: list
988 ea03467c Iustin Pop
    @return: the list of job objects
989 ea03467c Iustin Pop

990 ea03467c Iustin Pop
    """
991 911a495b Iustin Pop
    if not job_ids:
992 911a495b Iustin Pop
      job_ids = self._GetJobIDsUnlocked()
993 f1da30e6 Michael Hanselmann
994 911a495b Iustin Pop
    return [self._LoadJobUnlocked(job_id) for job_id in job_ids]
995 f1da30e6 Michael Hanselmann
996 686d7433 Iustin Pop
  @staticmethod
997 686d7433 Iustin Pop
  def _IsQueueMarkedDrain():
998 686d7433 Iustin Pop
    """Check if the queue is marked from drain.
999 686d7433 Iustin Pop

1000 686d7433 Iustin Pop
    This currently uses the queue drain file, which makes it a
1001 686d7433 Iustin Pop
    per-node flag. In the future this can be moved to the config file.
1002 686d7433 Iustin Pop

1003 ea03467c Iustin Pop
    @rtype: boolean
1004 ea03467c Iustin Pop
    @return: True of the job queue is marked for draining
1005 ea03467c Iustin Pop

1006 686d7433 Iustin Pop
    """
1007 686d7433 Iustin Pop
    return os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
1008 686d7433 Iustin Pop
1009 3ccafd0e Iustin Pop
  @staticmethod
1010 3ccafd0e Iustin Pop
  def SetDrainFlag(drain_flag):
1011 3ccafd0e Iustin Pop
    """Sets the drain flag for the queue.
1012 3ccafd0e Iustin Pop

1013 3ccafd0e Iustin Pop
    This is similar to the function L{backend.JobQueueSetDrainFlag},
1014 3ccafd0e Iustin Pop
    and in the future we might merge them.
1015 3ccafd0e Iustin Pop

1016 ea03467c Iustin Pop
    @type drain_flag: boolean
1017 5bbd3f7f Michael Hanselmann
    @param drain_flag: Whether to set or unset the drain flag
1018 ea03467c Iustin Pop

1019 3ccafd0e Iustin Pop
    """
1020 3ccafd0e Iustin Pop
    if drain_flag:
1021 3ccafd0e Iustin Pop
      utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
1022 3ccafd0e Iustin Pop
    else:
1023 3ccafd0e Iustin Pop
      utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
1024 3ccafd0e Iustin Pop
    return True
1025 3ccafd0e Iustin Pop
1026 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1027 009e73d0 Iustin Pop
  def _SubmitJobUnlocked(self, job_id, ops):
1028 85f03e0d Michael Hanselmann
    """Create and store a new job.
1029 f1da30e6 Michael Hanselmann

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

1033 009e73d0 Iustin Pop
    @type job_id: job ID
1034 69b99987 Michael Hanselmann
    @param job_id: the job ID for the new job
1035 c3f0a12f Iustin Pop
    @type ops: list
1036 205d71fd Michael Hanselmann
    @param ops: The list of OpCodes that will become the new job.
1037 ea03467c Iustin Pop
    @rtype: job ID
1038 ea03467c Iustin Pop
    @return: the job ID of the newly created job
1039 ea03467c Iustin Pop
    @raise errors.JobQueueDrainError: if the job is marked for draining
1040 c3f0a12f Iustin Pop

1041 c3f0a12f Iustin Pop
    """
1042 686d7433 Iustin Pop
    if self._IsQueueMarkedDrain():
1043 2971c913 Iustin Pop
      raise errors.JobQueueDrainError("Job queue is drained, refusing job")
1044 f87b405e Michael Hanselmann
1045 f87b405e Michael Hanselmann
    # Check job queue size
1046 f87b405e Michael Hanselmann
    size = len(self._ListJobFiles())
1047 f87b405e Michael Hanselmann
    if size >= constants.JOB_QUEUE_SIZE_SOFT_LIMIT:
1048 f87b405e Michael Hanselmann
      # TODO: Autoarchive jobs. Make sure it's not done on every job
1049 f87b405e Michael Hanselmann
      # submission, though.
1050 f87b405e Michael Hanselmann
      #size = ...
1051 f87b405e Michael Hanselmann
      pass
1052 f87b405e Michael Hanselmann
1053 f87b405e Michael Hanselmann
    if size >= constants.JOB_QUEUE_SIZE_HARD_LIMIT:
1054 f87b405e Michael Hanselmann
      raise errors.JobQueueFull()
1055 f87b405e Michael Hanselmann
1056 f1da30e6 Michael Hanselmann
    job = _QueuedJob(self, job_id, ops)
1057 f1da30e6 Michael Hanselmann
1058 f1da30e6 Michael Hanselmann
    # Write to disk
1059 85f03e0d Michael Hanselmann
    self.UpdateJobUnlocked(job)
1060 f1da30e6 Michael Hanselmann
1061 5685c1a5 Michael Hanselmann
    logging.debug("Adding new job %s to the cache", job_id)
1062 ac0930b9 Iustin Pop
    self._memcache[job_id] = job
1063 ac0930b9 Iustin Pop
1064 85f03e0d Michael Hanselmann
    # Add to worker pool
1065 85f03e0d Michael Hanselmann
    self._wpool.AddTask(job)
1066 85f03e0d Michael Hanselmann
1067 85f03e0d Michael Hanselmann
    return job.id
1068 f1da30e6 Michael Hanselmann
1069 2971c913 Iustin Pop
  @utils.LockedMethod
1070 2971c913 Iustin Pop
  @_RequireOpenQueue
1071 2971c913 Iustin Pop
  def SubmitJob(self, ops):
1072 2971c913 Iustin Pop
    """Create and store a new job.
1073 2971c913 Iustin Pop

1074 2971c913 Iustin Pop
    @see: L{_SubmitJobUnlocked}
1075 2971c913 Iustin Pop

1076 2971c913 Iustin Pop
    """
1077 009e73d0 Iustin Pop
    job_id = self._NewSerialsUnlocked(1)[0]
1078 009e73d0 Iustin Pop
    return self._SubmitJobUnlocked(job_id, ops)
1079 2971c913 Iustin Pop
1080 2971c913 Iustin Pop
  @utils.LockedMethod
1081 2971c913 Iustin Pop
  @_RequireOpenQueue
1082 2971c913 Iustin Pop
  def SubmitManyJobs(self, jobs):
1083 2971c913 Iustin Pop
    """Create and store multiple jobs.
1084 2971c913 Iustin Pop

1085 2971c913 Iustin Pop
    @see: L{_SubmitJobUnlocked}
1086 2971c913 Iustin Pop

1087 2971c913 Iustin Pop
    """
1088 2971c913 Iustin Pop
    results = []
1089 009e73d0 Iustin Pop
    all_job_ids = self._NewSerialsUnlocked(len(jobs))
1090 009e73d0 Iustin Pop
    for job_id, ops in zip(all_job_ids, jobs):
1091 2971c913 Iustin Pop
      try:
1092 009e73d0 Iustin Pop
        data = self._SubmitJobUnlocked(job_id, ops)
1093 2971c913 Iustin Pop
        status = True
1094 2971c913 Iustin Pop
      except errors.GenericError, err:
1095 2971c913 Iustin Pop
        data = str(err)
1096 2971c913 Iustin Pop
        status = False
1097 2971c913 Iustin Pop
      results.append((status, data))
1098 2971c913 Iustin Pop
1099 2971c913 Iustin Pop
    return results
1100 2971c913 Iustin Pop
1101 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1102 85f03e0d Michael Hanselmann
  def UpdateJobUnlocked(self, job):
1103 ea03467c Iustin Pop
    """Update a job's on disk storage.
1104 ea03467c Iustin Pop

1105 ea03467c Iustin Pop
    After a job has been modified, this function needs to be called in
1106 ea03467c Iustin Pop
    order to write the changes to disk and replicate them to the other
1107 ea03467c Iustin Pop
    nodes.
1108 ea03467c Iustin Pop

1109 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
1110 ea03467c Iustin Pop
    @param job: the changed job
1111 ea03467c Iustin Pop

1112 ea03467c Iustin Pop
    """
1113 f1da30e6 Michael Hanselmann
    filename = self._GetJobPath(job.id)
1114 23752136 Michael Hanselmann
    data = serializer.DumpJson(job.Serialize(), indent=False)
1115 f1da30e6 Michael Hanselmann
    logging.debug("Writing job %s to %s", job.id, filename)
1116 23752136 Michael Hanselmann
    self._WriteAndReplicateFileUnlocked(filename, data)
1117 ac0930b9 Iustin Pop
1118 dfe57c22 Michael Hanselmann
    # Notify waiters about potential changes
1119 6c5a7090 Michael Hanselmann
    job.change.notifyAll()
1120 dfe57c22 Michael Hanselmann
1121 6c5a7090 Michael Hanselmann
  @utils.LockedMethod
1122 dfe57c22 Michael Hanselmann
  @_RequireOpenQueue
1123 5c735209 Iustin Pop
  def WaitForJobChanges(self, job_id, fields, prev_job_info, prev_log_serial,
1124 5c735209 Iustin Pop
                        timeout):
1125 6c5a7090 Michael Hanselmann
    """Waits for changes in a job.
1126 6c5a7090 Michael Hanselmann

1127 6c5a7090 Michael Hanselmann
    @type job_id: string
1128 6c5a7090 Michael Hanselmann
    @param job_id: Job identifier
1129 6c5a7090 Michael Hanselmann
    @type fields: list of strings
1130 6c5a7090 Michael Hanselmann
    @param fields: Which fields to check for changes
1131 6c5a7090 Michael Hanselmann
    @type prev_job_info: list or None
1132 6c5a7090 Michael Hanselmann
    @param prev_job_info: Last job information returned
1133 6c5a7090 Michael Hanselmann
    @type prev_log_serial: int
1134 6c5a7090 Michael Hanselmann
    @param prev_log_serial: Last job message serial number
1135 5c735209 Iustin Pop
    @type timeout: float
1136 5c735209 Iustin Pop
    @param timeout: maximum time to wait
1137 ea03467c Iustin Pop
    @rtype: tuple (job info, log entries)
1138 ea03467c Iustin Pop
    @return: a tuple of the job information as required via
1139 ea03467c Iustin Pop
        the fields parameter, and the log entries as a list
1140 ea03467c Iustin Pop

1141 ea03467c Iustin Pop
        if the job has not changed and the timeout has expired,
1142 ea03467c Iustin Pop
        we instead return a special value,
1143 ea03467c Iustin Pop
        L{constants.JOB_NOTCHANGED}, which should be interpreted
1144 ea03467c Iustin Pop
        as such by the clients
1145 6c5a7090 Michael Hanselmann

1146 6c5a7090 Michael Hanselmann
    """
1147 6bcb1446 Michael Hanselmann
    job = self._LoadJobUnlocked(job_id)
1148 6bcb1446 Michael Hanselmann
    if not job:
1149 6bcb1446 Michael Hanselmann
      logging.debug("Job %s not found", job_id)
1150 6bcb1446 Michael Hanselmann
      return None
1151 5c735209 Iustin Pop
1152 6bcb1446 Michael Hanselmann
    def _CheckForChanges():
1153 6bcb1446 Michael Hanselmann
      logging.debug("Waiting for changes in job %s", job_id)
1154 dfe57c22 Michael Hanselmann
1155 6c5a7090 Michael Hanselmann
      status = job.CalcStatus()
1156 6c5a7090 Michael Hanselmann
      job_info = self._GetJobInfoUnlocked(job, fields)
1157 6c5a7090 Michael Hanselmann
      log_entries = job.GetLogEntries(prev_log_serial)
1158 dfe57c22 Michael Hanselmann
1159 dfe57c22 Michael Hanselmann
      # Serializing and deserializing data can cause type changes (e.g. from
1160 dfe57c22 Michael Hanselmann
      # tuple to list) or precision loss. We're doing it here so that we get
1161 dfe57c22 Michael Hanselmann
      # the same modifications as the data received from the client. Without
1162 dfe57c22 Michael Hanselmann
      # this, the comparison afterwards might fail without the data being
1163 dfe57c22 Michael Hanselmann
      # significantly different.
1164 6c5a7090 Michael Hanselmann
      job_info = serializer.LoadJson(serializer.DumpJson(job_info))
1165 6c5a7090 Michael Hanselmann
      log_entries = serializer.LoadJson(serializer.DumpJson(log_entries))
1166 dfe57c22 Michael Hanselmann
1167 6bcb1446 Michael Hanselmann
      # Don't even try to wait if the job is no longer running, there will be
1168 6bcb1446 Michael Hanselmann
      # no changes.
1169 6bcb1446 Michael Hanselmann
      if (status not in (constants.JOB_STATUS_QUEUED,
1170 6bcb1446 Michael Hanselmann
                         constants.JOB_STATUS_RUNNING,
1171 6bcb1446 Michael Hanselmann
                         constants.JOB_STATUS_WAITLOCK) or
1172 6bcb1446 Michael Hanselmann
          prev_job_info != job_info or
1173 6c5a7090 Michael Hanselmann
          (log_entries and prev_log_serial != log_entries[0][0])):
1174 6bcb1446 Michael Hanselmann
        logging.debug("Job %s changed", job_id)
1175 6bcb1446 Michael Hanselmann
        return (job_info, log_entries)
1176 dfe57c22 Michael Hanselmann
1177 6bcb1446 Michael Hanselmann
      raise utils.RetryAgain()
1178 dfe57c22 Michael Hanselmann
1179 6bcb1446 Michael Hanselmann
    try:
1180 6bcb1446 Michael Hanselmann
      # Setting wait function to release the queue lock while waiting
1181 6bcb1446 Michael Hanselmann
      return utils.Retry(_CheckForChanges, utils.RETRY_REMAINING_TIME, timeout,
1182 6bcb1446 Michael Hanselmann
                         wait_fn=job.change.wait)
1183 6bcb1446 Michael Hanselmann
    except utils.RetryTimeout:
1184 6bcb1446 Michael Hanselmann
      return constants.JOB_NOTCHANGED
1185 dfe57c22 Michael Hanselmann
1186 f1da30e6 Michael Hanselmann
  @utils.LockedMethod
1187 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1188 188c5e0a Michael Hanselmann
  def CancelJob(self, job_id):
1189 188c5e0a Michael Hanselmann
    """Cancels a job.
1190 188c5e0a Michael Hanselmann

1191 ea03467c Iustin Pop
    This will only succeed if the job has not started yet.
1192 ea03467c Iustin Pop

1193 188c5e0a Michael Hanselmann
    @type job_id: string
1194 ea03467c Iustin Pop
    @param job_id: job ID of job to be cancelled.
1195 188c5e0a Michael Hanselmann

1196 188c5e0a Michael Hanselmann
    """
1197 fbf0262f Michael Hanselmann
    logging.info("Cancelling job %s", job_id)
1198 188c5e0a Michael Hanselmann
1199 85f03e0d Michael Hanselmann
    job = self._LoadJobUnlocked(job_id)
1200 188c5e0a Michael Hanselmann
    if not job:
1201 188c5e0a Michael Hanselmann
      logging.debug("Job %s not found", job_id)
1202 fbf0262f Michael Hanselmann
      return (False, "Job %s not found" % job_id)
1203 fbf0262f Michael Hanselmann
1204 fbf0262f Michael Hanselmann
    job_status = job.CalcStatus()
1205 188c5e0a Michael Hanselmann
1206 fbf0262f Michael Hanselmann
    if job_status not in (constants.JOB_STATUS_QUEUED,
1207 fbf0262f Michael Hanselmann
                          constants.JOB_STATUS_WAITLOCK):
1208 a9e97393 Michael Hanselmann
      logging.debug("Job %s is no longer waiting in the queue", job.id)
1209 a9e97393 Michael Hanselmann
      return (False, "Job %s is no longer waiting in the queue" % job.id)
1210 fbf0262f Michael Hanselmann
1211 fbf0262f Michael Hanselmann
    if job_status == constants.JOB_STATUS_QUEUED:
1212 fbf0262f Michael Hanselmann
      self.CancelJobUnlocked(job)
1213 fbf0262f Michael Hanselmann
      return (True, "Job %s canceled" % job.id)
1214 188c5e0a Michael Hanselmann
1215 fbf0262f Michael Hanselmann
    elif job_status == constants.JOB_STATUS_WAITLOCK:
1216 fbf0262f Michael Hanselmann
      # The worker will notice the new status and cancel the job
1217 fbf0262f Michael Hanselmann
      try:
1218 34327f51 Iustin Pop
        job.MarkUnfinishedOps(constants.OP_STATUS_CANCELING, None)
1219 fbf0262f Michael Hanselmann
      finally:
1220 fbf0262f Michael Hanselmann
        self.UpdateJobUnlocked(job)
1221 fbf0262f Michael Hanselmann
      return (True, "Job %s will be canceled" % job.id)
1222 fbf0262f Michael Hanselmann
1223 fbf0262f Michael Hanselmann
  @_RequireOpenQueue
1224 fbf0262f Michael Hanselmann
  def CancelJobUnlocked(self, job):
1225 fbf0262f Michael Hanselmann
    """Marks a job as canceled.
1226 fbf0262f Michael Hanselmann

1227 fbf0262f Michael Hanselmann
    """
1228 85f03e0d Michael Hanselmann
    try:
1229 34327f51 Iustin Pop
      job.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
1230 34327f51 Iustin Pop
                            "Job canceled by request")
1231 85f03e0d Michael Hanselmann
    finally:
1232 85f03e0d Michael Hanselmann
      self.UpdateJobUnlocked(job)
1233 188c5e0a Michael Hanselmann
1234 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1235 d7fd1f28 Michael Hanselmann
  def _ArchiveJobsUnlocked(self, jobs):
1236 d7fd1f28 Michael Hanselmann
    """Archives jobs.
1237 c609f802 Michael Hanselmann

1238 d7fd1f28 Michael Hanselmann
    @type jobs: list of L{_QueuedJob}
1239 25e7b43f Iustin Pop
    @param jobs: Job objects
1240 d7fd1f28 Michael Hanselmann
    @rtype: int
1241 d7fd1f28 Michael Hanselmann
    @return: Number of archived jobs
1242 c609f802 Michael Hanselmann

1243 c609f802 Michael Hanselmann
    """
1244 d7fd1f28 Michael Hanselmann
    archive_jobs = []
1245 d7fd1f28 Michael Hanselmann
    rename_files = []
1246 d7fd1f28 Michael Hanselmann
    for job in jobs:
1247 d7fd1f28 Michael Hanselmann
      if job.CalcStatus() not in (constants.JOB_STATUS_CANCELED,
1248 d7fd1f28 Michael Hanselmann
                                  constants.JOB_STATUS_SUCCESS,
1249 d7fd1f28 Michael Hanselmann
                                  constants.JOB_STATUS_ERROR):
1250 d7fd1f28 Michael Hanselmann
        logging.debug("Job %s is not yet done", job.id)
1251 d7fd1f28 Michael Hanselmann
        continue
1252 c609f802 Michael Hanselmann
1253 d7fd1f28 Michael Hanselmann
      archive_jobs.append(job)
1254 c609f802 Michael Hanselmann
1255 d7fd1f28 Michael Hanselmann
      old = self._GetJobPath(job.id)
1256 d7fd1f28 Michael Hanselmann
      new = self._GetArchivedJobPath(job.id)
1257 d7fd1f28 Michael Hanselmann
      rename_files.append((old, new))
1258 c609f802 Michael Hanselmann
1259 d7fd1f28 Michael Hanselmann
    # TODO: What if 1..n files fail to rename?
1260 d7fd1f28 Michael Hanselmann
    self._RenameFilesUnlocked(rename_files)
1261 f1da30e6 Michael Hanselmann
1262 d7fd1f28 Michael Hanselmann
    logging.debug("Successfully archived job(s) %s",
1263 1f864b60 Iustin Pop
                  utils.CommaJoin(job.id for job in archive_jobs))
1264 d7fd1f28 Michael Hanselmann
1265 d7fd1f28 Michael Hanselmann
    return len(archive_jobs)
1266 78d12585 Michael Hanselmann
1267 07cd723a Iustin Pop
  @utils.LockedMethod
1268 07cd723a Iustin Pop
  @_RequireOpenQueue
1269 07cd723a Iustin Pop
  def ArchiveJob(self, job_id):
1270 07cd723a Iustin Pop
    """Archives a job.
1271 07cd723a Iustin Pop

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

1274 07cd723a Iustin Pop
    @type job_id: string
1275 07cd723a Iustin Pop
    @param job_id: Job ID of job to be archived.
1276 78d12585 Michael Hanselmann
    @rtype: bool
1277 78d12585 Michael Hanselmann
    @return: Whether job was archived
1278 07cd723a Iustin Pop

1279 07cd723a Iustin Pop
    """
1280 78d12585 Michael Hanselmann
    logging.info("Archiving job %s", job_id)
1281 78d12585 Michael Hanselmann
1282 78d12585 Michael Hanselmann
    job = self._LoadJobUnlocked(job_id)
1283 78d12585 Michael Hanselmann
    if not job:
1284 78d12585 Michael Hanselmann
      logging.debug("Job %s not found", job_id)
1285 78d12585 Michael Hanselmann
      return False
1286 78d12585 Michael Hanselmann
1287 5278185a Iustin Pop
    return self._ArchiveJobsUnlocked([job]) == 1
1288 07cd723a Iustin Pop
1289 07cd723a Iustin Pop
  @utils.LockedMethod
1290 07cd723a Iustin Pop
  @_RequireOpenQueue
1291 f8ad5591 Michael Hanselmann
  def AutoArchiveJobs(self, age, timeout):
1292 07cd723a Iustin Pop
    """Archives all jobs based on age.
1293 07cd723a Iustin Pop

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

1299 07cd723a Iustin Pop
    @type age: int
1300 07cd723a Iustin Pop
    @param age: the minimum age in seconds
1301 07cd723a Iustin Pop

1302 07cd723a Iustin Pop
    """
1303 07cd723a Iustin Pop
    logging.info("Archiving jobs with age more than %s seconds", age)
1304 07cd723a Iustin Pop
1305 07cd723a Iustin Pop
    now = time.time()
1306 f8ad5591 Michael Hanselmann
    end_time = now + timeout
1307 f8ad5591 Michael Hanselmann
    archived_count = 0
1308 f8ad5591 Michael Hanselmann
    last_touched = 0
1309 f8ad5591 Michael Hanselmann
1310 f8ad5591 Michael Hanselmann
    all_job_ids = self._GetJobIDsUnlocked(archived=False)
1311 d7fd1f28 Michael Hanselmann
    pending = []
1312 f8ad5591 Michael Hanselmann
    for idx, job_id in enumerate(all_job_ids):
1313 f8ad5591 Michael Hanselmann
      last_touched = idx
1314 f8ad5591 Michael Hanselmann
1315 d7fd1f28 Michael Hanselmann
      # Not optimal because jobs could be pending
1316 d7fd1f28 Michael Hanselmann
      # TODO: Measure average duration for job archival and take number of
1317 d7fd1f28 Michael Hanselmann
      # pending jobs into account.
1318 f8ad5591 Michael Hanselmann
      if time.time() > end_time:
1319 f8ad5591 Michael Hanselmann
        break
1320 f8ad5591 Michael Hanselmann
1321 78d12585 Michael Hanselmann
      # Returns None if the job failed to load
1322 78d12585 Michael Hanselmann
      job = self._LoadJobUnlocked(job_id)
1323 f8ad5591 Michael Hanselmann
      if job:
1324 f8ad5591 Michael Hanselmann
        if job.end_timestamp is None:
1325 f8ad5591 Michael Hanselmann
          if job.start_timestamp is None:
1326 f8ad5591 Michael Hanselmann
            job_age = job.received_timestamp
1327 f8ad5591 Michael Hanselmann
          else:
1328 f8ad5591 Michael Hanselmann
            job_age = job.start_timestamp
1329 07cd723a Iustin Pop
        else:
1330 f8ad5591 Michael Hanselmann
          job_age = job.end_timestamp
1331 f8ad5591 Michael Hanselmann
1332 f8ad5591 Michael Hanselmann
        if age == -1 or now - job_age[0] > age:
1333 d7fd1f28 Michael Hanselmann
          pending.append(job)
1334 d7fd1f28 Michael Hanselmann
1335 d7fd1f28 Michael Hanselmann
          # Archive 10 jobs at a time
1336 d7fd1f28 Michael Hanselmann
          if len(pending) >= 10:
1337 d7fd1f28 Michael Hanselmann
            archived_count += self._ArchiveJobsUnlocked(pending)
1338 d7fd1f28 Michael Hanselmann
            pending = []
1339 f8ad5591 Michael Hanselmann
1340 d7fd1f28 Michael Hanselmann
    if pending:
1341 d7fd1f28 Michael Hanselmann
      archived_count += self._ArchiveJobsUnlocked(pending)
1342 07cd723a Iustin Pop
1343 f8ad5591 Michael Hanselmann
    return (archived_count, len(all_job_ids) - last_touched - 1)
1344 07cd723a Iustin Pop
1345 85f03e0d Michael Hanselmann
  def _GetJobInfoUnlocked(self, job, fields):
1346 ea03467c Iustin Pop
    """Returns information about a job.
1347 ea03467c Iustin Pop

1348 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
1349 ea03467c Iustin Pop
    @param job: the job which we query
1350 ea03467c Iustin Pop
    @type fields: list
1351 ea03467c Iustin Pop
    @param fields: names of fields to return
1352 ea03467c Iustin Pop
    @rtype: list
1353 ea03467c Iustin Pop
    @return: list with one element for each field
1354 ea03467c Iustin Pop
    @raise errors.OpExecError: when an invalid field
1355 ea03467c Iustin Pop
        has been passed
1356 ea03467c Iustin Pop

1357 ea03467c Iustin Pop
    """
1358 e2715f69 Michael Hanselmann
    row = []
1359 e2715f69 Michael Hanselmann
    for fname in fields:
1360 e2715f69 Michael Hanselmann
      if fname == "id":
1361 e2715f69 Michael Hanselmann
        row.append(job.id)
1362 e2715f69 Michael Hanselmann
      elif fname == "status":
1363 85f03e0d Michael Hanselmann
        row.append(job.CalcStatus())
1364 af30b2fd Michael Hanselmann
      elif fname == "ops":
1365 85f03e0d Michael Hanselmann
        row.append([op.input.__getstate__() for op in job.ops])
1366 af30b2fd Michael Hanselmann
      elif fname == "opresult":
1367 85f03e0d Michael Hanselmann
        row.append([op.result for op in job.ops])
1368 af30b2fd Michael Hanselmann
      elif fname == "opstatus":
1369 85f03e0d Michael Hanselmann
        row.append([op.status for op in job.ops])
1370 5b23c34c Iustin Pop
      elif fname == "oplog":
1371 5b23c34c Iustin Pop
        row.append([op.log for op in job.ops])
1372 c56ec146 Iustin Pop
      elif fname == "opstart":
1373 c56ec146 Iustin Pop
        row.append([op.start_timestamp for op in job.ops])
1374 c56ec146 Iustin Pop
      elif fname == "opend":
1375 c56ec146 Iustin Pop
        row.append([op.end_timestamp for op in job.ops])
1376 c56ec146 Iustin Pop
      elif fname == "received_ts":
1377 c56ec146 Iustin Pop
        row.append(job.received_timestamp)
1378 c56ec146 Iustin Pop
      elif fname == "start_ts":
1379 c56ec146 Iustin Pop
        row.append(job.start_timestamp)
1380 c56ec146 Iustin Pop
      elif fname == "end_ts":
1381 c56ec146 Iustin Pop
        row.append(job.end_timestamp)
1382 1d2dcdfd Michael Hanselmann
      elif fname == "lock_status":
1383 1d2dcdfd Michael Hanselmann
        row.append(job.lock_status)
1384 60dd1473 Iustin Pop
      elif fname == "summary":
1385 60dd1473 Iustin Pop
        row.append([op.input.Summary() for op in job.ops])
1386 e2715f69 Michael Hanselmann
      else:
1387 e2715f69 Michael Hanselmann
        raise errors.OpExecError("Invalid job query field '%s'" % fname)
1388 e2715f69 Michael Hanselmann
    return row
1389 e2715f69 Michael Hanselmann
1390 85f03e0d Michael Hanselmann
  @utils.LockedMethod
1391 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1392 e2715f69 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1393 e2715f69 Michael Hanselmann
    """Returns a list of jobs in queue.
1394 e2715f69 Michael Hanselmann

1395 ea03467c Iustin Pop
    This is a wrapper of L{_GetJobsUnlocked}, which actually does the
1396 ea03467c Iustin Pop
    processing for each job.
1397 ea03467c Iustin Pop

1398 ea03467c Iustin Pop
    @type job_ids: list
1399 ea03467c Iustin Pop
    @param job_ids: sequence of job identifiers or None for all
1400 ea03467c Iustin Pop
    @type fields: list
1401 ea03467c Iustin Pop
    @param fields: names of fields to return
1402 ea03467c Iustin Pop
    @rtype: list
1403 ea03467c Iustin Pop
    @return: list one element per job, each element being list with
1404 ea03467c Iustin Pop
        the requested fields
1405 e2715f69 Michael Hanselmann

1406 e2715f69 Michael Hanselmann
    """
1407 85f03e0d Michael Hanselmann
    jobs = []
1408 e2715f69 Michael Hanselmann
1409 85f03e0d Michael Hanselmann
    for job in self._GetJobsUnlocked(job_ids):
1410 85f03e0d Michael Hanselmann
      if job is None:
1411 85f03e0d Michael Hanselmann
        jobs.append(None)
1412 85f03e0d Michael Hanselmann
      else:
1413 85f03e0d Michael Hanselmann
        jobs.append(self._GetJobInfoUnlocked(job, fields))
1414 e2715f69 Michael Hanselmann
1415 85f03e0d Michael Hanselmann
    return jobs
1416 e2715f69 Michael Hanselmann
1417 f1da30e6 Michael Hanselmann
  @utils.LockedMethod
1418 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1419 e2715f69 Michael Hanselmann
  def Shutdown(self):
1420 e2715f69 Michael Hanselmann
    """Stops the job queue.
1421 e2715f69 Michael Hanselmann

1422 ea03467c Iustin Pop
    This shutdowns all the worker threads an closes the queue.
1423 ea03467c Iustin Pop

1424 e2715f69 Michael Hanselmann
    """
1425 e2715f69 Michael Hanselmann
    self._wpool.TerminateWorkers()
1426 85f03e0d Michael Hanselmann
1427 04ab05ce Michael Hanselmann
    self._queue_lock.Close()
1428 04ab05ce Michael Hanselmann
    self._queue_lock = None