Statistics
| Branch: | Tag: | Revision:

root / lib / jqueue.py @ f95c81bf

History | View | Annotate | Download (40.5 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 run_op_index: int
149 ea03467c Iustin Pop
  @ivar run_op_index: the currently executing opcode, or -1 if
150 ea03467c Iustin Pop
      we didn't yet start executing
151 ea03467c Iustin Pop
  @type log_serial: int
152 ea03467c Iustin Pop
  @ivar log_serial: holds the index for the next log entry
153 ea03467c Iustin Pop
  @ivar received_timestamp: the timestamp for when the job was received
154 ea03467c Iustin Pop
  @ivar start_timestmap: the timestamp for start of execution
155 ea03467c Iustin Pop
  @ivar end_timestamp: the timestamp for end of execution
156 ea03467c Iustin Pop
  @ivar change: a Condition variable we use for waiting for job changes
157 e2715f69 Michael Hanselmann

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

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

175 ea03467c Iustin Pop
    """
176 e2715f69 Michael Hanselmann
    if not ops:
177 ea03467c Iustin Pop
      # TODO: use a better exception
178 e2715f69 Michael Hanselmann
      raise Exception("No opcodes")
179 e2715f69 Michael Hanselmann
180 85f03e0d Michael Hanselmann
    self.queue = queue
181 f1da30e6 Michael Hanselmann
    self.id = job_id
182 85f03e0d Michael Hanselmann
    self.ops = [_QueuedOpCode(op) for op in ops]
183 85f03e0d Michael Hanselmann
    self.run_op_index = -1
184 6c5a7090 Michael Hanselmann
    self.log_serial = 0
185 c56ec146 Iustin Pop
    self.received_timestamp = TimeStampNow()
186 c56ec146 Iustin Pop
    self.start_timestamp = None
187 c56ec146 Iustin Pop
    self.end_timestamp = None
188 6c5a7090 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 85f03e0d Michael Hanselmann
    obj.run_op_index = state["run_op_index"]
208 c56ec146 Iustin Pop
    obj.received_timestamp = state.get("received_timestamp", None)
209 c56ec146 Iustin Pop
    obj.start_timestamp = state.get("start_timestamp", None)
210 c56ec146 Iustin Pop
    obj.end_timestamp = state.get("end_timestamp", None)
211 6c5a7090 Michael Hanselmann
212 6c5a7090 Michael Hanselmann
    obj.ops = []
213 6c5a7090 Michael Hanselmann
    obj.log_serial = 0
214 6c5a7090 Michael Hanselmann
    for op_state in state["ops"]:
215 6c5a7090 Michael Hanselmann
      op = _QueuedOpCode.Restore(op_state)
216 6c5a7090 Michael Hanselmann
      for log_entry in op.log:
217 6c5a7090 Michael Hanselmann
        obj.log_serial = max(obj.log_serial, log_entry[0])
218 6c5a7090 Michael Hanselmann
      obj.ops.append(op)
219 6c5a7090 Michael Hanselmann
220 6c5a7090 Michael Hanselmann
    # Condition to wait for changes
221 6c5a7090 Michael Hanselmann
    obj.change = threading.Condition(obj.queue._lock)
222 6c5a7090 Michael Hanselmann
223 f1da30e6 Michael Hanselmann
    return obj
224 f1da30e6 Michael Hanselmann
225 f1da30e6 Michael Hanselmann
  def Serialize(self):
226 ea03467c Iustin Pop
    """Serialize the _JobQueue instance.
227 ea03467c Iustin Pop

228 ea03467c Iustin Pop
    @rtype: dict
229 ea03467c Iustin Pop
    @return: the serialized state
230 ea03467c Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

326 34327f51 Iustin Pop
    """
327 34327f51 Iustin Pop
    not_marked = True
328 34327f51 Iustin Pop
    for op in self.ops:
329 34327f51 Iustin Pop
      if op.status in constants.OPS_FINALIZED:
330 34327f51 Iustin Pop
        assert not_marked, "Finalized opcodes found after non-finalized ones"
331 34327f51 Iustin Pop
        continue
332 34327f51 Iustin Pop
      op.status = status
333 34327f51 Iustin Pop
      op.result = result
334 34327f51 Iustin Pop
      not_marked = False
335 34327f51 Iustin Pop
336 f1048938 Iustin Pop
337 85f03e0d Michael Hanselmann
class _JobQueueWorker(workerpool.BaseWorker):
338 ea03467c Iustin Pop
  """The actual job workers.
339 ea03467c Iustin Pop

340 ea03467c Iustin Pop
  """
341 e92376d7 Iustin Pop
  def _NotifyStart(self):
342 e92376d7 Iustin Pop
    """Mark the opcode as running, not lock-waiting.
343 e92376d7 Iustin Pop

344 e92376d7 Iustin Pop
    This is called from the mcpu code as a notifier function, when the
345 e92376d7 Iustin Pop
    LU is finally about to start the Exec() method. Of course, to have
346 e92376d7 Iustin Pop
    end-user visible results, the opcode must be initially (before
347 e92376d7 Iustin Pop
    calling into Processor.ExecOpCode) set to OP_STATUS_WAITLOCK.
348 e92376d7 Iustin Pop

349 e92376d7 Iustin Pop
    """
350 e92376d7 Iustin Pop
    assert self.queue, "Queue attribute is missing"
351 e92376d7 Iustin Pop
    assert self.opcode, "Opcode attribute is missing"
352 e92376d7 Iustin Pop
353 e92376d7 Iustin Pop
    self.queue.acquire()
354 e92376d7 Iustin Pop
    try:
355 fbf0262f Michael Hanselmann
      assert self.opcode.status in (constants.OP_STATUS_WAITLOCK,
356 fbf0262f Michael Hanselmann
                                    constants.OP_STATUS_CANCELING)
357 fbf0262f Michael Hanselmann
358 fbf0262f Michael Hanselmann
      # Cancel here if we were asked to
359 fbf0262f Michael Hanselmann
      if self.opcode.status == constants.OP_STATUS_CANCELING:
360 fbf0262f Michael Hanselmann
        raise CancelJob()
361 fbf0262f Michael Hanselmann
362 e92376d7 Iustin Pop
      self.opcode.status = constants.OP_STATUS_RUNNING
363 e92376d7 Iustin Pop
    finally:
364 e92376d7 Iustin Pop
      self.queue.release()
365 e92376d7 Iustin Pop
366 85f03e0d Michael Hanselmann
  def RunTask(self, job):
367 e2715f69 Michael Hanselmann
    """Job executor.
368 e2715f69 Michael Hanselmann

369 6c5a7090 Michael Hanselmann
    This functions processes a job. It is closely tied to the _QueuedJob and
370 6c5a7090 Michael Hanselmann
    _QueuedOpCode classes.
371 e2715f69 Michael Hanselmann

372 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
373 ea03467c Iustin Pop
    @param job: the job to be processed
374 ea03467c Iustin Pop

375 e2715f69 Michael Hanselmann
    """
376 d21d09d6 Iustin Pop
    logging.info("Worker %s processing job %s",
377 e2715f69 Michael Hanselmann
                  self.worker_id, job.id)
378 5bdce580 Michael Hanselmann
    proc = mcpu.Processor(self.pool.queue.context)
379 e92376d7 Iustin Pop
    self.queue = queue = job.queue
380 e2715f69 Michael Hanselmann
    try:
381 85f03e0d Michael Hanselmann
      try:
382 85f03e0d Michael Hanselmann
        count = len(job.ops)
383 85f03e0d Michael Hanselmann
        for idx, op in enumerate(job.ops):
384 d21d09d6 Iustin Pop
          op_summary = op.input.Summary()
385 f6424741 Iustin Pop
          if op.status == constants.OP_STATUS_SUCCESS:
386 f6424741 Iustin Pop
            # this is a job that was partially completed before master
387 f6424741 Iustin Pop
            # daemon shutdown, so it can be expected that some opcodes
388 f6424741 Iustin Pop
            # are already completed successfully (if any did error
389 f6424741 Iustin Pop
            # out, then the whole job should have been aborted and not
390 f6424741 Iustin Pop
            # resubmitted for processing)
391 f6424741 Iustin Pop
            logging.info("Op %s/%s: opcode %s already processed, skipping",
392 f6424741 Iustin Pop
                         idx + 1, count, op_summary)
393 f6424741 Iustin Pop
            continue
394 85f03e0d Michael Hanselmann
          try:
395 d21d09d6 Iustin Pop
            logging.info("Op %s/%s: Starting opcode %s", idx + 1, count,
396 d21d09d6 Iustin Pop
                         op_summary)
397 85f03e0d Michael Hanselmann
398 85f03e0d Michael Hanselmann
            queue.acquire()
399 85f03e0d Michael Hanselmann
            try:
400 df0fb067 Iustin Pop
              if op.status == constants.OP_STATUS_CANCELED:
401 df0fb067 Iustin Pop
                raise CancelJob()
402 fbf0262f Michael Hanselmann
              assert op.status == constants.OP_STATUS_QUEUED
403 85f03e0d Michael Hanselmann
              job.run_op_index = idx
404 e92376d7 Iustin Pop
              op.status = constants.OP_STATUS_WAITLOCK
405 85f03e0d Michael Hanselmann
              op.result = None
406 70552c46 Michael Hanselmann
              op.start_timestamp = TimeStampNow()
407 c56ec146 Iustin Pop
              if idx == 0: # first opcode
408 c56ec146 Iustin Pop
                job.start_timestamp = op.start_timestamp
409 85f03e0d Michael Hanselmann
              queue.UpdateJobUnlocked(job)
410 85f03e0d Michael Hanselmann
411 38206f3c Iustin Pop
              input_opcode = op.input
412 85f03e0d Michael Hanselmann
            finally:
413 85f03e0d Michael Hanselmann
              queue.release()
414 85f03e0d Michael Hanselmann
415 dfe57c22 Michael Hanselmann
            def _Log(*args):
416 6c5a7090 Michael Hanselmann
              """Append a log entry.
417 6c5a7090 Michael Hanselmann

418 6c5a7090 Michael Hanselmann
              """
419 6c5a7090 Michael Hanselmann
              assert len(args) < 3
420 6c5a7090 Michael Hanselmann
421 6c5a7090 Michael Hanselmann
              if len(args) == 1:
422 6c5a7090 Michael Hanselmann
                log_type = constants.ELOG_MESSAGE
423 6c5a7090 Michael Hanselmann
                log_msg = args[0]
424 6c5a7090 Michael Hanselmann
              else:
425 6c5a7090 Michael Hanselmann
                log_type, log_msg = args
426 6c5a7090 Michael Hanselmann
427 6c5a7090 Michael Hanselmann
              # The time is split to make serialization easier and not lose
428 6c5a7090 Michael Hanselmann
              # precision.
429 6c5a7090 Michael Hanselmann
              timestamp = utils.SplitTime(time.time())
430 dfe57c22 Michael Hanselmann
431 6c5a7090 Michael Hanselmann
              queue.acquire()
432 dfe57c22 Michael Hanselmann
              try:
433 6c5a7090 Michael Hanselmann
                job.log_serial += 1
434 6c5a7090 Michael Hanselmann
                op.log.append((job.log_serial, timestamp, log_type, log_msg))
435 6c5a7090 Michael Hanselmann
436 dfe57c22 Michael Hanselmann
                job.change.notifyAll()
437 dfe57c22 Michael Hanselmann
              finally:
438 6c5a7090 Michael Hanselmann
                queue.release()
439 dfe57c22 Michael Hanselmann
440 6c5a7090 Michael Hanselmann
            # Make sure not to hold lock while _Log is called
441 e92376d7 Iustin Pop
            self.opcode = op
442 e92376d7 Iustin Pop
            result = proc.ExecOpCode(input_opcode, _Log, self._NotifyStart)
443 85f03e0d Michael Hanselmann
444 85f03e0d Michael Hanselmann
            queue.acquire()
445 85f03e0d Michael Hanselmann
            try:
446 85f03e0d Michael Hanselmann
              op.status = constants.OP_STATUS_SUCCESS
447 85f03e0d Michael Hanselmann
              op.result = result
448 70552c46 Michael Hanselmann
              op.end_timestamp = TimeStampNow()
449 85f03e0d Michael Hanselmann
              queue.UpdateJobUnlocked(job)
450 85f03e0d Michael Hanselmann
            finally:
451 85f03e0d Michael Hanselmann
              queue.release()
452 85f03e0d Michael Hanselmann
453 d21d09d6 Iustin Pop
            logging.info("Op %s/%s: Successfully finished opcode %s",
454 d21d09d6 Iustin Pop
                         idx + 1, count, op_summary)
455 fbf0262f Michael Hanselmann
          except CancelJob:
456 fbf0262f Michael Hanselmann
            # Will be handled further up
457 fbf0262f Michael Hanselmann
            raise
458 85f03e0d Michael Hanselmann
          except Exception, err:
459 85f03e0d Michael Hanselmann
            queue.acquire()
460 85f03e0d Michael Hanselmann
            try:
461 85f03e0d Michael Hanselmann
              try:
462 85f03e0d Michael Hanselmann
                op.status = constants.OP_STATUS_ERROR
463 e6345c35 Iustin Pop
                if isinstance(err, errors.GenericError):
464 e6345c35 Iustin Pop
                  op.result = errors.EncodeException(err)
465 e6345c35 Iustin Pop
                else:
466 e6345c35 Iustin Pop
                  op.result = str(err)
467 70552c46 Michael Hanselmann
                op.end_timestamp = TimeStampNow()
468 0f6be82a Iustin Pop
                logging.info("Op %s/%s: Error in opcode %s: %s",
469 0f6be82a Iustin Pop
                             idx + 1, count, op_summary, err)
470 85f03e0d Michael Hanselmann
              finally:
471 85f03e0d Michael Hanselmann
                queue.UpdateJobUnlocked(job)
472 85f03e0d Michael Hanselmann
            finally:
473 85f03e0d Michael Hanselmann
              queue.release()
474 85f03e0d Michael Hanselmann
            raise
475 85f03e0d Michael Hanselmann
476 fbf0262f Michael Hanselmann
      except CancelJob:
477 fbf0262f Michael Hanselmann
        queue.acquire()
478 fbf0262f Michael Hanselmann
        try:
479 fbf0262f Michael Hanselmann
          queue.CancelJobUnlocked(job)
480 fbf0262f Michael Hanselmann
        finally:
481 fbf0262f Michael Hanselmann
          queue.release()
482 85f03e0d Michael Hanselmann
      except errors.GenericError, err:
483 85f03e0d Michael Hanselmann
        logging.exception("Ganeti exception")
484 85f03e0d Michael Hanselmann
      except:
485 85f03e0d Michael Hanselmann
        logging.exception("Unhandled exception")
486 e2715f69 Michael Hanselmann
    finally:
487 85f03e0d Michael Hanselmann
      queue.acquire()
488 85f03e0d Michael Hanselmann
      try:
489 65548ed5 Michael Hanselmann
        try:
490 ed21712b Iustin Pop
          job.run_op_index = -1
491 c56ec146 Iustin Pop
          job.end_timestamp = TimeStampNow()
492 65548ed5 Michael Hanselmann
          queue.UpdateJobUnlocked(job)
493 65548ed5 Michael Hanselmann
        finally:
494 65548ed5 Michael Hanselmann
          job_id = job.id
495 65548ed5 Michael Hanselmann
          status = job.CalcStatus()
496 85f03e0d Michael Hanselmann
      finally:
497 85f03e0d Michael Hanselmann
        queue.release()
498 d21d09d6 Iustin Pop
      logging.info("Worker %s finished job %s, status = %s",
499 d21d09d6 Iustin Pop
                   self.worker_id, job_id, status)
500 e2715f69 Michael Hanselmann
501 e2715f69 Michael Hanselmann
502 e2715f69 Michael Hanselmann
class _JobQueueWorkerPool(workerpool.WorkerPool):
503 ea03467c Iustin Pop
  """Simple class implementing a job-processing workerpool.
504 ea03467c Iustin Pop

505 ea03467c Iustin Pop
  """
506 5bdce580 Michael Hanselmann
  def __init__(self, queue):
507 e2715f69 Michael Hanselmann
    super(_JobQueueWorkerPool, self).__init__(JOBQUEUE_THREADS,
508 e2715f69 Michael Hanselmann
                                              _JobQueueWorker)
509 5bdce580 Michael Hanselmann
    self.queue = queue
510 e2715f69 Michael Hanselmann
511 e2715f69 Michael Hanselmann
512 85f03e0d Michael Hanselmann
class JobQueue(object):
513 5bbd3f7f Michael Hanselmann
  """Queue used to manage the jobs.
514 ea03467c Iustin Pop

515 ea03467c Iustin Pop
  @cvar _RE_JOB_FILE: regex matching the valid job file names
516 ea03467c Iustin Pop

517 ea03467c Iustin Pop
  """
518 bac5ffc3 Oleksiy Mishchenko
  _RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
519 f1da30e6 Michael Hanselmann
520 db37da70 Michael Hanselmann
  def _RequireOpenQueue(fn):
521 db37da70 Michael Hanselmann
    """Decorator for "public" functions.
522 db37da70 Michael Hanselmann

523 ea03467c Iustin Pop
    This function should be used for all 'public' functions. That is,
524 ea03467c Iustin Pop
    functions usually called from other classes.
525 db37da70 Michael Hanselmann

526 ea03467c Iustin Pop
    @warning: Use this decorator only after utils.LockedMethod!
527 db37da70 Michael Hanselmann

528 ea03467c Iustin Pop
    Example::
529 db37da70 Michael Hanselmann
      @utils.LockedMethod
530 db37da70 Michael Hanselmann
      @_RequireOpenQueue
531 db37da70 Michael Hanselmann
      def Example(self):
532 db37da70 Michael Hanselmann
        pass
533 db37da70 Michael Hanselmann

534 db37da70 Michael Hanselmann
    """
535 db37da70 Michael Hanselmann
    def wrapper(self, *args, **kwargs):
536 04ab05ce Michael Hanselmann
      assert self._queue_lock is not None, "Queue should be open"
537 db37da70 Michael Hanselmann
      return fn(self, *args, **kwargs)
538 db37da70 Michael Hanselmann
    return wrapper
539 db37da70 Michael Hanselmann
540 85f03e0d Michael Hanselmann
  def __init__(self, context):
541 ea03467c Iustin Pop
    """Constructor for JobQueue.
542 ea03467c Iustin Pop

543 ea03467c Iustin Pop
    The constructor will initialize the job queue object and then
544 ea03467c Iustin Pop
    start loading the current jobs from disk, either for starting them
545 ea03467c Iustin Pop
    (if they were queue) or for aborting them (if they were already
546 ea03467c Iustin Pop
    running).
547 ea03467c Iustin Pop

548 ea03467c Iustin Pop
    @type context: GanetiContext
549 ea03467c Iustin Pop
    @param context: the context object for access to the configuration
550 ea03467c Iustin Pop
        data and other ganeti objects
551 ea03467c Iustin Pop

552 ea03467c Iustin Pop
    """
553 5bdce580 Michael Hanselmann
    self.context = context
554 5685c1a5 Michael Hanselmann
    self._memcache = weakref.WeakValueDictionary()
555 c3f0a12f Iustin Pop
    self._my_hostname = utils.HostInfo().name
556 f1da30e6 Michael Hanselmann
557 85f03e0d Michael Hanselmann
    # Locking
558 85f03e0d Michael Hanselmann
    self._lock = threading.Lock()
559 85f03e0d Michael Hanselmann
    self.acquire = self._lock.acquire
560 85f03e0d Michael Hanselmann
    self.release = self._lock.release
561 85f03e0d Michael Hanselmann
562 04ab05ce Michael Hanselmann
    # Initialize
563 5d6fb8eb Michael Hanselmann
    self._queue_lock = jstore.InitAndVerifyQueue(must_lock=True)
564 f1da30e6 Michael Hanselmann
565 04ab05ce Michael Hanselmann
    # Read serial file
566 04ab05ce Michael Hanselmann
    self._last_serial = jstore.ReadSerial()
567 04ab05ce Michael Hanselmann
    assert self._last_serial is not None, ("Serial file was modified between"
568 04ab05ce Michael Hanselmann
                                           " check in jstore and here")
569 c4beba1c Iustin Pop
570 23752136 Michael Hanselmann
    # Get initial list of nodes
571 99aabbed Iustin Pop
    self._nodes = dict((n.name, n.primary_ip)
572 59303563 Iustin Pop
                       for n in self.context.cfg.GetAllNodesInfo().values()
573 59303563 Iustin Pop
                       if n.master_candidate)
574 8e00939c Michael Hanselmann
575 8e00939c Michael Hanselmann
    # Remove master node
576 8e00939c Michael Hanselmann
    try:
577 99aabbed Iustin Pop
      del self._nodes[self._my_hostname]
578 33987705 Iustin Pop
    except KeyError:
579 8e00939c Michael Hanselmann
      pass
580 23752136 Michael Hanselmann
581 23752136 Michael Hanselmann
    # TODO: Check consistency across nodes
582 23752136 Michael Hanselmann
583 85f03e0d Michael Hanselmann
    # Setup worker pool
584 5bdce580 Michael Hanselmann
    self._wpool = _JobQueueWorkerPool(self)
585 85f03e0d Michael Hanselmann
    try:
586 16714921 Michael Hanselmann
      # We need to lock here because WorkerPool.AddTask() may start a job while
587 16714921 Michael Hanselmann
      # we're still doing our work.
588 16714921 Michael Hanselmann
      self.acquire()
589 16714921 Michael Hanselmann
      try:
590 711b5124 Michael Hanselmann
        logging.info("Inspecting job queue")
591 711b5124 Michael Hanselmann
592 711b5124 Michael Hanselmann
        all_job_ids = self._GetJobIDsUnlocked()
593 b7cb9024 Michael Hanselmann
        jobs_count = len(all_job_ids)
594 711b5124 Michael Hanselmann
        lastinfo = time.time()
595 711b5124 Michael Hanselmann
        for idx, job_id in enumerate(all_job_ids):
596 711b5124 Michael Hanselmann
          # Give an update every 1000 jobs or 10 seconds
597 b7cb9024 Michael Hanselmann
          if (idx % 1000 == 0 or time.time() >= (lastinfo + 10.0) or
598 b7cb9024 Michael Hanselmann
              idx == (jobs_count - 1)):
599 711b5124 Michael Hanselmann
            logging.info("Job queue inspection: %d/%d (%0.1f %%)",
600 b7cb9024 Michael Hanselmann
                         idx, jobs_count - 1, 100.0 * (idx + 1) / jobs_count)
601 711b5124 Michael Hanselmann
            lastinfo = time.time()
602 711b5124 Michael Hanselmann
603 711b5124 Michael Hanselmann
          job = self._LoadJobUnlocked(job_id)
604 711b5124 Michael Hanselmann
605 16714921 Michael Hanselmann
          # a failure in loading the job can cause 'None' to be returned
606 16714921 Michael Hanselmann
          if job is None:
607 16714921 Michael Hanselmann
            continue
608 94ed59a5 Iustin Pop
609 16714921 Michael Hanselmann
          status = job.CalcStatus()
610 85f03e0d Michael Hanselmann
611 16714921 Michael Hanselmann
          if status in (constants.JOB_STATUS_QUEUED, ):
612 16714921 Michael Hanselmann
            self._wpool.AddTask(job)
613 85f03e0d Michael Hanselmann
614 16714921 Michael Hanselmann
          elif status in (constants.JOB_STATUS_RUNNING,
615 fbf0262f Michael Hanselmann
                          constants.JOB_STATUS_WAITLOCK,
616 fbf0262f Michael Hanselmann
                          constants.JOB_STATUS_CANCELING):
617 16714921 Michael Hanselmann
            logging.warning("Unfinished job %s found: %s", job.id, job)
618 16714921 Michael Hanselmann
            try:
619 34327f51 Iustin Pop
              job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
620 34327f51 Iustin Pop
                                    "Unclean master daemon shutdown")
621 16714921 Michael Hanselmann
            finally:
622 16714921 Michael Hanselmann
              self.UpdateJobUnlocked(job)
623 711b5124 Michael Hanselmann
624 711b5124 Michael Hanselmann
        logging.info("Job queue inspection finished")
625 16714921 Michael Hanselmann
      finally:
626 16714921 Michael Hanselmann
        self.release()
627 16714921 Michael Hanselmann
    except:
628 16714921 Michael Hanselmann
      self._wpool.TerminateWorkers()
629 16714921 Michael Hanselmann
      raise
630 85f03e0d Michael Hanselmann
631 d2e03a33 Michael Hanselmann
  @utils.LockedMethod
632 d2e03a33 Michael Hanselmann
  @_RequireOpenQueue
633 99aabbed Iustin Pop
  def AddNode(self, node):
634 99aabbed Iustin Pop
    """Register a new node with the queue.
635 99aabbed Iustin Pop

636 99aabbed Iustin Pop
    @type node: L{objects.Node}
637 99aabbed Iustin Pop
    @param node: the node object to be added
638 99aabbed Iustin Pop

639 99aabbed Iustin Pop
    """
640 99aabbed Iustin Pop
    node_name = node.name
641 d2e03a33 Michael Hanselmann
    assert node_name != self._my_hostname
642 23752136 Michael Hanselmann
643 9f774ee8 Michael Hanselmann
    # Clean queue directory on added node
644 a3811745 Michael Hanselmann
    rpc.RpcRunner.call_jobqueue_purge(node_name)
645 23752136 Michael Hanselmann
646 59303563 Iustin Pop
    if not node.master_candidate:
647 59303563 Iustin Pop
      # remove if existing, ignoring errors
648 59303563 Iustin Pop
      self._nodes.pop(node_name, None)
649 59303563 Iustin Pop
      # and skip the replication of the job ids
650 59303563 Iustin Pop
      return
651 59303563 Iustin Pop
652 d2e03a33 Michael Hanselmann
    # Upload the whole queue excluding archived jobs
653 d2e03a33 Michael Hanselmann
    files = [self._GetJobPath(job_id) for job_id in self._GetJobIDsUnlocked()]
654 23752136 Michael Hanselmann
655 d2e03a33 Michael Hanselmann
    # Upload current serial file
656 d2e03a33 Michael Hanselmann
    files.append(constants.JOB_QUEUE_SERIAL_FILE)
657 d2e03a33 Michael Hanselmann
658 d2e03a33 Michael Hanselmann
    for file_name in files:
659 9f774ee8 Michael Hanselmann
      # Read file content
660 9f774ee8 Michael Hanselmann
      fd = open(file_name, "r")
661 9f774ee8 Michael Hanselmann
      try:
662 9f774ee8 Michael Hanselmann
        content = fd.read()
663 9f774ee8 Michael Hanselmann
      finally:
664 9f774ee8 Michael Hanselmann
        fd.close()
665 9f774ee8 Michael Hanselmann
666 a3811745 Michael Hanselmann
      result = rpc.RpcRunner.call_jobqueue_update([node_name],
667 a3811745 Michael Hanselmann
                                                  [node.primary_ip],
668 a3811745 Michael Hanselmann
                                                  file_name, content)
669 d2e03a33 Michael Hanselmann
      if not result[node_name]:
670 d2e03a33 Michael Hanselmann
        logging.error("Failed to upload %s to %s", file_name, node_name)
671 d2e03a33 Michael Hanselmann
672 99aabbed Iustin Pop
    self._nodes[node_name] = node.primary_ip
673 d2e03a33 Michael Hanselmann
674 d2e03a33 Michael Hanselmann
  @utils.LockedMethod
675 d2e03a33 Michael Hanselmann
  @_RequireOpenQueue
676 d2e03a33 Michael Hanselmann
  def RemoveNode(self, node_name):
677 ea03467c Iustin Pop
    """Callback called when removing nodes from the cluster.
678 ea03467c Iustin Pop

679 ea03467c Iustin Pop
    @type node_name: str
680 ea03467c Iustin Pop
    @param node_name: the name of the node to remove
681 ea03467c Iustin Pop

682 ea03467c Iustin Pop
    """
683 23752136 Michael Hanselmann
    try:
684 d2e03a33 Michael Hanselmann
      # The queue is removed by the "leave node" RPC call.
685 99aabbed Iustin Pop
      del self._nodes[node_name]
686 d2e03a33 Michael Hanselmann
    except KeyError:
687 23752136 Michael Hanselmann
      pass
688 23752136 Michael Hanselmann
689 e74798c1 Michael Hanselmann
  def _CheckRpcResult(self, result, nodes, failmsg):
690 ea03467c Iustin Pop
    """Verifies the status of an RPC call.
691 ea03467c Iustin Pop

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

696 ea03467c Iustin Pop
    @param result: the data as returned from the rpc call
697 ea03467c Iustin Pop
    @type nodes: list
698 ea03467c Iustin Pop
    @param nodes: the list of nodes we made the call to
699 ea03467c Iustin Pop
    @type failmsg: str
700 ea03467c Iustin Pop
    @param failmsg: the identifier to be used for logging
701 ea03467c Iustin Pop

702 ea03467c Iustin Pop
    """
703 e74798c1 Michael Hanselmann
    failed = []
704 e74798c1 Michael Hanselmann
    success = []
705 e74798c1 Michael Hanselmann
706 e74798c1 Michael Hanselmann
    for node in nodes:
707 e74798c1 Michael Hanselmann
      if result[node]:
708 e74798c1 Michael Hanselmann
        success.append(node)
709 e74798c1 Michael Hanselmann
      else:
710 e74798c1 Michael Hanselmann
        failed.append(node)
711 e74798c1 Michael Hanselmann
712 e74798c1 Michael Hanselmann
    if failed:
713 e74798c1 Michael Hanselmann
      logging.error("%s failed on %s", failmsg, ", ".join(failed))
714 e74798c1 Michael Hanselmann
715 e74798c1 Michael Hanselmann
    # +1 for the master node
716 e74798c1 Michael Hanselmann
    if (len(success) + 1) < len(failed):
717 e74798c1 Michael Hanselmann
      # TODO: Handle failing nodes
718 e74798c1 Michael Hanselmann
      logging.error("More than half of the nodes failed")
719 e74798c1 Michael Hanselmann
720 99aabbed Iustin Pop
  def _GetNodeIp(self):
721 99aabbed Iustin Pop
    """Helper for returning the node name/ip list.
722 99aabbed Iustin Pop

723 ea03467c Iustin Pop
    @rtype: (list, list)
724 ea03467c Iustin Pop
    @return: a tuple of two lists, the first one with the node
725 ea03467c Iustin Pop
        names and the second one with the node addresses
726 ea03467c Iustin Pop

727 99aabbed Iustin Pop
    """
728 99aabbed Iustin Pop
    name_list = self._nodes.keys()
729 99aabbed Iustin Pop
    addr_list = [self._nodes[name] for name in name_list]
730 99aabbed Iustin Pop
    return name_list, addr_list
731 99aabbed Iustin Pop
732 8e00939c Michael Hanselmann
  def _WriteAndReplicateFileUnlocked(self, file_name, data):
733 8e00939c Michael Hanselmann
    """Writes a file locally and then replicates it to all nodes.
734 8e00939c Michael Hanselmann

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

738 ea03467c Iustin Pop
    @type file_name: str
739 ea03467c Iustin Pop
    @param file_name: the path of the file to be replicated
740 ea03467c Iustin Pop
    @type data: str
741 ea03467c Iustin Pop
    @param data: the new contents of the file
742 ea03467c Iustin Pop

743 8e00939c Michael Hanselmann
    """
744 8e00939c Michael Hanselmann
    utils.WriteFile(file_name, data=data)
745 8e00939c Michael Hanselmann
746 99aabbed Iustin Pop
    names, addrs = self._GetNodeIp()
747 a3811745 Michael Hanselmann
    result = rpc.RpcRunner.call_jobqueue_update(names, addrs, file_name, data)
748 e74798c1 Michael Hanselmann
    self._CheckRpcResult(result, self._nodes,
749 e74798c1 Michael Hanselmann
                         "Updating %s" % file_name)
750 23752136 Michael Hanselmann
751 d7fd1f28 Michael Hanselmann
  def _RenameFilesUnlocked(self, rename):
752 ea03467c Iustin Pop
    """Renames a file locally and then replicate the change.
753 ea03467c Iustin Pop

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

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

760 ea03467c Iustin Pop
    """
761 dd875d32 Michael Hanselmann
    # Rename them locally
762 d7fd1f28 Michael Hanselmann
    for old, new in rename:
763 d7fd1f28 Michael Hanselmann
      utils.RenameFile(old, new, mkdir=True)
764 abc1f2ce Michael Hanselmann
765 dd875d32 Michael Hanselmann
    # ... and on all nodes
766 dd875d32 Michael Hanselmann
    names, addrs = self._GetNodeIp()
767 dd875d32 Michael Hanselmann
    result = rpc.RpcRunner.call_jobqueue_rename(names, addrs, rename)
768 dd875d32 Michael Hanselmann
    self._CheckRpcResult(result, self._nodes, "Renaming files (%r)" % rename)
769 abc1f2ce Michael Hanselmann
770 85f03e0d Michael Hanselmann
  def _FormatJobID(self, job_id):
771 ea03467c Iustin Pop
    """Convert a job ID to string format.
772 ea03467c Iustin Pop

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

777 ea03467c Iustin Pop
    @type job_id: int or long
778 ea03467c Iustin Pop
    @param job_id: the numeric job id
779 ea03467c Iustin Pop
    @rtype: str
780 ea03467c Iustin Pop
    @return: the formatted job id
781 ea03467c Iustin Pop

782 ea03467c Iustin Pop
    """
783 85f03e0d Michael Hanselmann
    if not isinstance(job_id, (int, long)):
784 85f03e0d Michael Hanselmann
      raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id)
785 85f03e0d Michael Hanselmann
    if job_id < 0:
786 85f03e0d Michael Hanselmann
      raise errors.ProgrammerError("Job ID %s is negative" % job_id)
787 85f03e0d Michael Hanselmann
788 85f03e0d Michael Hanselmann
    return str(job_id)
789 85f03e0d Michael Hanselmann
790 58b22b6e Michael Hanselmann
  @classmethod
791 58b22b6e Michael Hanselmann
  def _GetArchiveDirectory(cls, job_id):
792 58b22b6e Michael Hanselmann
    """Returns the archive directory for a job.
793 58b22b6e Michael Hanselmann

794 58b22b6e Michael Hanselmann
    @type job_id: str
795 58b22b6e Michael Hanselmann
    @param job_id: Job identifier
796 58b22b6e Michael Hanselmann
    @rtype: str
797 58b22b6e Michael Hanselmann
    @return: Directory name
798 58b22b6e Michael Hanselmann

799 58b22b6e Michael Hanselmann
    """
800 58b22b6e Michael Hanselmann
    return str(int(job_id) / JOBS_PER_ARCHIVE_DIRECTORY)
801 58b22b6e Michael Hanselmann
802 009e73d0 Iustin Pop
  def _NewSerialsUnlocked(self, count):
803 f1da30e6 Michael Hanselmann
    """Generates a new job identifier.
804 f1da30e6 Michael Hanselmann

805 f1da30e6 Michael Hanselmann
    Job identifiers are unique during the lifetime of a cluster.
806 f1da30e6 Michael Hanselmann

807 009e73d0 Iustin Pop
    @type count: integer
808 009e73d0 Iustin Pop
    @param count: how many serials to return
809 ea03467c Iustin Pop
    @rtype: str
810 ea03467c Iustin Pop
    @return: a string representing the job identifier.
811 f1da30e6 Michael Hanselmann

812 f1da30e6 Michael Hanselmann
    """
813 009e73d0 Iustin Pop
    assert count > 0
814 f1da30e6 Michael Hanselmann
    # New number
815 009e73d0 Iustin Pop
    serial = self._last_serial + count
816 f1da30e6 Michael Hanselmann
817 f1da30e6 Michael Hanselmann
    # Write to file
818 23752136 Michael Hanselmann
    self._WriteAndReplicateFileUnlocked(constants.JOB_QUEUE_SERIAL_FILE,
819 23752136 Michael Hanselmann
                                        "%s\n" % serial)
820 f1da30e6 Michael Hanselmann
821 009e73d0 Iustin Pop
    result = [self._FormatJobID(v)
822 009e73d0 Iustin Pop
              for v in range(self._last_serial, serial + 1)]
823 f1da30e6 Michael Hanselmann
    # Keep it only if we were able to write the file
824 f1da30e6 Michael Hanselmann
    self._last_serial = serial
825 f1da30e6 Michael Hanselmann
826 009e73d0 Iustin Pop
    return result
827 f1da30e6 Michael Hanselmann
828 85f03e0d Michael Hanselmann
  @staticmethod
829 85f03e0d Michael Hanselmann
  def _GetJobPath(job_id):
830 ea03467c Iustin Pop
    """Returns the job file for a given job id.
831 ea03467c Iustin Pop

832 ea03467c Iustin Pop
    @type job_id: str
833 ea03467c Iustin Pop
    @param job_id: the job identifier
834 ea03467c Iustin Pop
    @rtype: str
835 ea03467c Iustin Pop
    @return: the path to the job file
836 ea03467c Iustin Pop

837 ea03467c Iustin Pop
    """
838 f1da30e6 Michael Hanselmann
    return os.path.join(constants.QUEUE_DIR, "job-%s" % job_id)
839 f1da30e6 Michael Hanselmann
840 58b22b6e Michael Hanselmann
  @classmethod
841 58b22b6e Michael Hanselmann
  def _GetArchivedJobPath(cls, job_id):
842 ea03467c Iustin Pop
    """Returns the archived job file for a give job id.
843 ea03467c Iustin Pop

844 ea03467c Iustin Pop
    @type job_id: str
845 ea03467c Iustin Pop
    @param job_id: the job identifier
846 ea03467c Iustin Pop
    @rtype: str
847 ea03467c Iustin Pop
    @return: the path to the archived job file
848 ea03467c Iustin Pop

849 ea03467c Iustin Pop
    """
850 58b22b6e Michael Hanselmann
    path = "%s/job-%s" % (cls._GetArchiveDirectory(job_id), job_id)
851 58b22b6e Michael Hanselmann
    return os.path.join(constants.JOB_QUEUE_ARCHIVE_DIR, path)
852 0cb94105 Michael Hanselmann
853 85f03e0d Michael Hanselmann
  @classmethod
854 85f03e0d Michael Hanselmann
  def _ExtractJobID(cls, name):
855 ea03467c Iustin Pop
    """Extract the job id from a filename.
856 ea03467c Iustin Pop

857 ea03467c Iustin Pop
    @type name: str
858 ea03467c Iustin Pop
    @param name: the job filename
859 ea03467c Iustin Pop
    @rtype: job id or None
860 ea03467c Iustin Pop
    @return: the job id corresponding to the given filename,
861 ea03467c Iustin Pop
        or None if the filename does not represent a valid
862 ea03467c Iustin Pop
        job file
863 ea03467c Iustin Pop

864 ea03467c Iustin Pop
    """
865 85f03e0d Michael Hanselmann
    m = cls._RE_JOB_FILE.match(name)
866 fae737ac Michael Hanselmann
    if m:
867 fae737ac Michael Hanselmann
      return m.group(1)
868 fae737ac Michael Hanselmann
    else:
869 fae737ac Michael Hanselmann
      return None
870 fae737ac Michael Hanselmann
871 911a495b Iustin Pop
  def _GetJobIDsUnlocked(self, archived=False):
872 911a495b Iustin Pop
    """Return all known job IDs.
873 911a495b Iustin Pop

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

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

881 ea03467c Iustin Pop
    @rtype: list
882 ea03467c Iustin Pop
    @return: the list of job IDs
883 ea03467c Iustin Pop

884 911a495b Iustin Pop
    """
885 fae737ac Michael Hanselmann
    jlist = [self._ExtractJobID(name) for name in self._ListJobFiles()]
886 3b87986e Iustin Pop
    jlist = utils.NiceSort(jlist)
887 f0d874fe Iustin Pop
    return jlist
888 911a495b Iustin Pop
889 f1da30e6 Michael Hanselmann
  def _ListJobFiles(self):
890 ea03467c Iustin Pop
    """Returns the list of current job files.
891 ea03467c Iustin Pop

892 ea03467c Iustin Pop
    @rtype: list
893 ea03467c Iustin Pop
    @return: the list of job file names
894 ea03467c Iustin Pop

895 ea03467c Iustin Pop
    """
896 f1da30e6 Michael Hanselmann
    return [name for name in utils.ListVisibleFiles(constants.QUEUE_DIR)
897 f1da30e6 Michael Hanselmann
            if self._RE_JOB_FILE.match(name)]
898 f1da30e6 Michael Hanselmann
899 911a495b Iustin Pop
  def _LoadJobUnlocked(self, job_id):
900 ea03467c Iustin Pop
    """Loads a job from the disk or memory.
901 ea03467c Iustin Pop

902 ea03467c Iustin Pop
    Given a job id, this will return the cached job object if
903 ea03467c Iustin Pop
    existing, or try to load the job from the disk. If loading from
904 ea03467c Iustin Pop
    disk, it will also add the job to the cache.
905 ea03467c Iustin Pop

906 ea03467c Iustin Pop
    @param job_id: the job id
907 ea03467c Iustin Pop
    @rtype: L{_QueuedJob} or None
908 ea03467c Iustin Pop
    @return: either None or the job object
909 ea03467c Iustin Pop

910 ea03467c Iustin Pop
    """
911 5685c1a5 Michael Hanselmann
    job = self._memcache.get(job_id, None)
912 5685c1a5 Michael Hanselmann
    if job:
913 205d71fd Michael Hanselmann
      logging.debug("Found job %s in memcache", job_id)
914 5685c1a5 Michael Hanselmann
      return job
915 ac0930b9 Iustin Pop
916 911a495b Iustin Pop
    filepath = self._GetJobPath(job_id)
917 f1da30e6 Michael Hanselmann
    logging.debug("Loading job from %s", filepath)
918 f1da30e6 Michael Hanselmann
    try:
919 f1da30e6 Michael Hanselmann
      fd = open(filepath, "r")
920 f1da30e6 Michael Hanselmann
    except IOError, err:
921 f1da30e6 Michael Hanselmann
      if err.errno in (errno.ENOENT, ):
922 f1da30e6 Michael Hanselmann
        return None
923 f1da30e6 Michael Hanselmann
      raise
924 f1da30e6 Michael Hanselmann
    try:
925 f1da30e6 Michael Hanselmann
      data = serializer.LoadJson(fd.read())
926 f1da30e6 Michael Hanselmann
    finally:
927 f1da30e6 Michael Hanselmann
      fd.close()
928 f1da30e6 Michael Hanselmann
929 94ed59a5 Iustin Pop
    try:
930 94ed59a5 Iustin Pop
      job = _QueuedJob.Restore(self, data)
931 94ed59a5 Iustin Pop
    except Exception, err:
932 94ed59a5 Iustin Pop
      new_path = self._GetArchivedJobPath(job_id)
933 94ed59a5 Iustin Pop
      if filepath == new_path:
934 94ed59a5 Iustin Pop
        # job already archived (future case)
935 94ed59a5 Iustin Pop
        logging.exception("Can't parse job %s", job_id)
936 94ed59a5 Iustin Pop
      else:
937 94ed59a5 Iustin Pop
        # non-archived case
938 94ed59a5 Iustin Pop
        logging.exception("Can't parse job %s, will archive.", job_id)
939 d7fd1f28 Michael Hanselmann
        self._RenameFilesUnlocked([(filepath, new_path)])
940 94ed59a5 Iustin Pop
      return None
941 94ed59a5 Iustin Pop
942 ac0930b9 Iustin Pop
    self._memcache[job_id] = job
943 205d71fd Michael Hanselmann
    logging.debug("Added job %s to the cache", job_id)
944 ac0930b9 Iustin Pop
    return job
945 f1da30e6 Michael Hanselmann
946 f1da30e6 Michael Hanselmann
  def _GetJobsUnlocked(self, job_ids):
947 ea03467c Iustin Pop
    """Return a list of jobs based on their IDs.
948 ea03467c Iustin Pop

949 ea03467c Iustin Pop
    @type job_ids: list
950 ea03467c Iustin Pop
    @param job_ids: either an empty list (meaning all jobs),
951 ea03467c Iustin Pop
        or a list of job IDs
952 ea03467c Iustin Pop
    @rtype: list
953 ea03467c Iustin Pop
    @return: the list of job objects
954 ea03467c Iustin Pop

955 ea03467c Iustin Pop
    """
956 911a495b Iustin Pop
    if not job_ids:
957 911a495b Iustin Pop
      job_ids = self._GetJobIDsUnlocked()
958 f1da30e6 Michael Hanselmann
959 911a495b Iustin Pop
    return [self._LoadJobUnlocked(job_id) for job_id in job_ids]
960 f1da30e6 Michael Hanselmann
961 686d7433 Iustin Pop
  @staticmethod
962 686d7433 Iustin Pop
  def _IsQueueMarkedDrain():
963 686d7433 Iustin Pop
    """Check if the queue is marked from drain.
964 686d7433 Iustin Pop

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

968 ea03467c Iustin Pop
    @rtype: boolean
969 ea03467c Iustin Pop
    @return: True of the job queue is marked for draining
970 ea03467c Iustin Pop

971 686d7433 Iustin Pop
    """
972 686d7433 Iustin Pop
    return os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
973 686d7433 Iustin Pop
974 3ccafd0e Iustin Pop
  @staticmethod
975 3ccafd0e Iustin Pop
  def SetDrainFlag(drain_flag):
976 3ccafd0e Iustin Pop
    """Sets the drain flag for the queue.
977 3ccafd0e Iustin Pop

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

981 ea03467c Iustin Pop
    @type drain_flag: boolean
982 5bbd3f7f Michael Hanselmann
    @param drain_flag: Whether to set or unset the drain flag
983 ea03467c Iustin Pop

984 3ccafd0e Iustin Pop
    """
985 3ccafd0e Iustin Pop
    if drain_flag:
986 3ccafd0e Iustin Pop
      utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
987 3ccafd0e Iustin Pop
    else:
988 3ccafd0e Iustin Pop
      utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
989 3ccafd0e Iustin Pop
    return True
990 3ccafd0e Iustin Pop
991 db37da70 Michael Hanselmann
  @_RequireOpenQueue
992 009e73d0 Iustin Pop
  def _SubmitJobUnlocked(self, job_id, ops):
993 85f03e0d Michael Hanselmann
    """Create and store a new job.
994 f1da30e6 Michael Hanselmann

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

998 009e73d0 Iustin Pop
    @type job_id: job ID
999 009e73d0 Iustin Pop
    @param jod_id: the job ID for the new job
1000 c3f0a12f Iustin Pop
    @type ops: list
1001 205d71fd Michael Hanselmann
    @param ops: The list of OpCodes that will become the new job.
1002 ea03467c Iustin Pop
    @rtype: job ID
1003 ea03467c Iustin Pop
    @return: the job ID of the newly created job
1004 ea03467c Iustin Pop
    @raise errors.JobQueueDrainError: if the job is marked for draining
1005 c3f0a12f Iustin Pop

1006 c3f0a12f Iustin Pop
    """
1007 686d7433 Iustin Pop
    if self._IsQueueMarkedDrain():
1008 56d8ff91 Iustin Pop
      raise errors.JobQueueDrainError("Job queue is drained, refusing job")
1009 f87b405e Michael Hanselmann
1010 f87b405e Michael Hanselmann
    # Check job queue size
1011 f87b405e Michael Hanselmann
    size = len(self._ListJobFiles())
1012 f87b405e Michael Hanselmann
    if size >= constants.JOB_QUEUE_SIZE_SOFT_LIMIT:
1013 f87b405e Michael Hanselmann
      # TODO: Autoarchive jobs. Make sure it's not done on every job
1014 f87b405e Michael Hanselmann
      # submission, though.
1015 f87b405e Michael Hanselmann
      #size = ...
1016 f87b405e Michael Hanselmann
      pass
1017 f87b405e Michael Hanselmann
1018 f87b405e Michael Hanselmann
    if size >= constants.JOB_QUEUE_SIZE_HARD_LIMIT:
1019 f87b405e Michael Hanselmann
      raise errors.JobQueueFull()
1020 f87b405e Michael Hanselmann
1021 f1da30e6 Michael Hanselmann
    job = _QueuedJob(self, job_id, ops)
1022 f1da30e6 Michael Hanselmann
1023 f1da30e6 Michael Hanselmann
    # Write to disk
1024 85f03e0d Michael Hanselmann
    self.UpdateJobUnlocked(job)
1025 f1da30e6 Michael Hanselmann
1026 5685c1a5 Michael Hanselmann
    logging.debug("Adding new job %s to the cache", job_id)
1027 ac0930b9 Iustin Pop
    self._memcache[job_id] = job
1028 ac0930b9 Iustin Pop
1029 85f03e0d Michael Hanselmann
    # Add to worker pool
1030 85f03e0d Michael Hanselmann
    self._wpool.AddTask(job)
1031 85f03e0d Michael Hanselmann
1032 85f03e0d Michael Hanselmann
    return job.id
1033 f1da30e6 Michael Hanselmann
1034 56d8ff91 Iustin Pop
  @utils.LockedMethod
1035 56d8ff91 Iustin Pop
  @_RequireOpenQueue
1036 56d8ff91 Iustin Pop
  def SubmitJob(self, ops):
1037 56d8ff91 Iustin Pop
    """Create and store a new job.
1038 56d8ff91 Iustin Pop

1039 56d8ff91 Iustin Pop
    @see: L{_SubmitJobUnlocked}
1040 56d8ff91 Iustin Pop

1041 56d8ff91 Iustin Pop
    """
1042 009e73d0 Iustin Pop
    job_id = self._NewSerialsUnlocked(1)[0]
1043 009e73d0 Iustin Pop
    return self._SubmitJobUnlocked(job_id, ops)
1044 56d8ff91 Iustin Pop
1045 56d8ff91 Iustin Pop
  @utils.LockedMethod
1046 56d8ff91 Iustin Pop
  @_RequireOpenQueue
1047 56d8ff91 Iustin Pop
  def SubmitManyJobs(self, jobs):
1048 56d8ff91 Iustin Pop
    """Create and store multiple jobs.
1049 56d8ff91 Iustin Pop

1050 56d8ff91 Iustin Pop
    @see: L{_SubmitJobUnlocked}
1051 56d8ff91 Iustin Pop

1052 56d8ff91 Iustin Pop
    """
1053 56d8ff91 Iustin Pop
    results = []
1054 009e73d0 Iustin Pop
    all_job_ids = self._NewSerialsUnlocked(len(jobs))
1055 009e73d0 Iustin Pop
    for job_id, ops in zip(all_job_ids, jobs):
1056 56d8ff91 Iustin Pop
      try:
1057 009e73d0 Iustin Pop
        data = self._SubmitJobUnlocked(job_id, ops)
1058 56d8ff91 Iustin Pop
        status = True
1059 56d8ff91 Iustin Pop
      except errors.GenericError, err:
1060 56d8ff91 Iustin Pop
        data = str(err)
1061 56d8ff91 Iustin Pop
        status = False
1062 56d8ff91 Iustin Pop
      results.append((status, data))
1063 56d8ff91 Iustin Pop
1064 56d8ff91 Iustin Pop
    return results
1065 56d8ff91 Iustin Pop
1066 56d8ff91 Iustin Pop
1067 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1068 85f03e0d Michael Hanselmann
  def UpdateJobUnlocked(self, job):
1069 ea03467c Iustin Pop
    """Update a job's on disk storage.
1070 ea03467c Iustin Pop

1071 ea03467c Iustin Pop
    After a job has been modified, this function needs to be called in
1072 ea03467c Iustin Pop
    order to write the changes to disk and replicate them to the other
1073 ea03467c Iustin Pop
    nodes.
1074 ea03467c Iustin Pop

1075 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
1076 ea03467c Iustin Pop
    @param job: the changed job
1077 ea03467c Iustin Pop

1078 ea03467c Iustin Pop
    """
1079 f1da30e6 Michael Hanselmann
    filename = self._GetJobPath(job.id)
1080 23752136 Michael Hanselmann
    data = serializer.DumpJson(job.Serialize(), indent=False)
1081 f1da30e6 Michael Hanselmann
    logging.debug("Writing job %s to %s", job.id, filename)
1082 23752136 Michael Hanselmann
    self._WriteAndReplicateFileUnlocked(filename, data)
1083 ac0930b9 Iustin Pop
1084 dfe57c22 Michael Hanselmann
    # Notify waiters about potential changes
1085 6c5a7090 Michael Hanselmann
    job.change.notifyAll()
1086 dfe57c22 Michael Hanselmann
1087 6c5a7090 Michael Hanselmann
  @utils.LockedMethod
1088 dfe57c22 Michael Hanselmann
  @_RequireOpenQueue
1089 5c735209 Iustin Pop
  def WaitForJobChanges(self, job_id, fields, prev_job_info, prev_log_serial,
1090 5c735209 Iustin Pop
                        timeout):
1091 6c5a7090 Michael Hanselmann
    """Waits for changes in a job.
1092 6c5a7090 Michael Hanselmann

1093 6c5a7090 Michael Hanselmann
    @type job_id: string
1094 6c5a7090 Michael Hanselmann
    @param job_id: Job identifier
1095 6c5a7090 Michael Hanselmann
    @type fields: list of strings
1096 6c5a7090 Michael Hanselmann
    @param fields: Which fields to check for changes
1097 6c5a7090 Michael Hanselmann
    @type prev_job_info: list or None
1098 6c5a7090 Michael Hanselmann
    @param prev_job_info: Last job information returned
1099 6c5a7090 Michael Hanselmann
    @type prev_log_serial: int
1100 6c5a7090 Michael Hanselmann
    @param prev_log_serial: Last job message serial number
1101 5c735209 Iustin Pop
    @type timeout: float
1102 5c735209 Iustin Pop
    @param timeout: maximum time to wait
1103 ea03467c Iustin Pop
    @rtype: tuple (job info, log entries)
1104 ea03467c Iustin Pop
    @return: a tuple of the job information as required via
1105 ea03467c Iustin Pop
        the fields parameter, and the log entries as a list
1106 ea03467c Iustin Pop

1107 ea03467c Iustin Pop
        if the job has not changed and the timeout has expired,
1108 ea03467c Iustin Pop
        we instead return a special value,
1109 ea03467c Iustin Pop
        L{constants.JOB_NOTCHANGED}, which should be interpreted
1110 ea03467c Iustin Pop
        as such by the clients
1111 6c5a7090 Michael Hanselmann

1112 6c5a7090 Michael Hanselmann
    """
1113 dfe57c22 Michael Hanselmann
    logging.debug("Waiting for changes in job %s", job_id)
1114 6e237482 Michael Hanselmann
1115 6e237482 Michael Hanselmann
    job_info = None
1116 6e237482 Michael Hanselmann
    log_entries = None
1117 6e237482 Michael Hanselmann
1118 5c735209 Iustin Pop
    end_time = time.time() + timeout
1119 dfe57c22 Michael Hanselmann
    while True:
1120 5c735209 Iustin Pop
      delta_time = end_time - time.time()
1121 5c735209 Iustin Pop
      if delta_time < 0:
1122 5c735209 Iustin Pop
        return constants.JOB_NOTCHANGED
1123 5c735209 Iustin Pop
1124 6c5a7090 Michael Hanselmann
      job = self._LoadJobUnlocked(job_id)
1125 6c5a7090 Michael Hanselmann
      if not job:
1126 6c5a7090 Michael Hanselmann
        logging.debug("Job %s not found", job_id)
1127 6c5a7090 Michael Hanselmann
        break
1128 dfe57c22 Michael Hanselmann
1129 6c5a7090 Michael Hanselmann
      status = job.CalcStatus()
1130 6c5a7090 Michael Hanselmann
      job_info = self._GetJobInfoUnlocked(job, fields)
1131 6c5a7090 Michael Hanselmann
      log_entries = job.GetLogEntries(prev_log_serial)
1132 dfe57c22 Michael Hanselmann
1133 dfe57c22 Michael Hanselmann
      # Serializing and deserializing data can cause type changes (e.g. from
1134 dfe57c22 Michael Hanselmann
      # tuple to list) or precision loss. We're doing it here so that we get
1135 dfe57c22 Michael Hanselmann
      # the same modifications as the data received from the client. Without
1136 dfe57c22 Michael Hanselmann
      # this, the comparison afterwards might fail without the data being
1137 dfe57c22 Michael Hanselmann
      # significantly different.
1138 6c5a7090 Michael Hanselmann
      job_info = serializer.LoadJson(serializer.DumpJson(job_info))
1139 6c5a7090 Michael Hanselmann
      log_entries = serializer.LoadJson(serializer.DumpJson(log_entries))
1140 dfe57c22 Michael Hanselmann
1141 6c5a7090 Michael Hanselmann
      if status not in (constants.JOB_STATUS_QUEUED,
1142 e92376d7 Iustin Pop
                        constants.JOB_STATUS_RUNNING,
1143 e92376d7 Iustin Pop
                        constants.JOB_STATUS_WAITLOCK):
1144 6c5a7090 Michael Hanselmann
        # Don't even try to wait if the job is no longer running, there will be
1145 6c5a7090 Michael Hanselmann
        # no changes.
1146 dfe57c22 Michael Hanselmann
        break
1147 dfe57c22 Michael Hanselmann
1148 6c5a7090 Michael Hanselmann
      if (prev_job_info != job_info or
1149 6c5a7090 Michael Hanselmann
          (log_entries and prev_log_serial != log_entries[0][0])):
1150 6c5a7090 Michael Hanselmann
        break
1151 6c5a7090 Michael Hanselmann
1152 6c5a7090 Michael Hanselmann
      logging.debug("Waiting again")
1153 6c5a7090 Michael Hanselmann
1154 6c5a7090 Michael Hanselmann
      # Release the queue lock while waiting
1155 5c735209 Iustin Pop
      job.change.wait(delta_time)
1156 dfe57c22 Michael Hanselmann
1157 dfe57c22 Michael Hanselmann
    logging.debug("Job %s changed", job_id)
1158 dfe57c22 Michael Hanselmann
1159 6e237482 Michael Hanselmann
    if job_info is None and log_entries is None:
1160 6e237482 Michael Hanselmann
      return None
1161 6e237482 Michael Hanselmann
    else:
1162 6e237482 Michael Hanselmann
      return (job_info, log_entries)
1163 dfe57c22 Michael Hanselmann
1164 f1da30e6 Michael Hanselmann
  @utils.LockedMethod
1165 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1166 188c5e0a Michael Hanselmann
  def CancelJob(self, job_id):
1167 188c5e0a Michael Hanselmann
    """Cancels a job.
1168 188c5e0a Michael Hanselmann

1169 ea03467c Iustin Pop
    This will only succeed if the job has not started yet.
1170 ea03467c Iustin Pop

1171 188c5e0a Michael Hanselmann
    @type job_id: string
1172 ea03467c Iustin Pop
    @param job_id: job ID of job to be cancelled.
1173 188c5e0a Michael Hanselmann

1174 188c5e0a Michael Hanselmann
    """
1175 fbf0262f Michael Hanselmann
    logging.info("Cancelling job %s", job_id)
1176 188c5e0a Michael Hanselmann
1177 85f03e0d Michael Hanselmann
    job = self._LoadJobUnlocked(job_id)
1178 188c5e0a Michael Hanselmann
    if not job:
1179 188c5e0a Michael Hanselmann
      logging.debug("Job %s not found", job_id)
1180 fbf0262f Michael Hanselmann
      return (False, "Job %s not found" % job_id)
1181 fbf0262f Michael Hanselmann
1182 fbf0262f Michael Hanselmann
    job_status = job.CalcStatus()
1183 188c5e0a Michael Hanselmann
1184 fbf0262f Michael Hanselmann
    if job_status not in (constants.JOB_STATUS_QUEUED,
1185 fbf0262f Michael Hanselmann
                          constants.JOB_STATUS_WAITLOCK):
1186 a9e97393 Michael Hanselmann
      logging.debug("Job %s is no longer waiting in the queue", job.id)
1187 a9e97393 Michael Hanselmann
      return (False, "Job %s is no longer waiting in the queue" % job.id)
1188 fbf0262f Michael Hanselmann
1189 fbf0262f Michael Hanselmann
    if job_status == constants.JOB_STATUS_QUEUED:
1190 fbf0262f Michael Hanselmann
      self.CancelJobUnlocked(job)
1191 fbf0262f Michael Hanselmann
      return (True, "Job %s canceled" % job.id)
1192 188c5e0a Michael Hanselmann
1193 fbf0262f Michael Hanselmann
    elif job_status == constants.JOB_STATUS_WAITLOCK:
1194 fbf0262f Michael Hanselmann
      # The worker will notice the new status and cancel the job
1195 fbf0262f Michael Hanselmann
      try:
1196 34327f51 Iustin Pop
        job.MarkUnfinishedOps(constants.OP_STATUS_CANCELING, None)
1197 fbf0262f Michael Hanselmann
      finally:
1198 fbf0262f Michael Hanselmann
        self.UpdateJobUnlocked(job)
1199 fbf0262f Michael Hanselmann
      return (True, "Job %s will be canceled" % job.id)
1200 fbf0262f Michael Hanselmann
1201 fbf0262f Michael Hanselmann
  @_RequireOpenQueue
1202 fbf0262f Michael Hanselmann
  def CancelJobUnlocked(self, job):
1203 fbf0262f Michael Hanselmann
    """Marks a job as canceled.
1204 fbf0262f Michael Hanselmann

1205 fbf0262f Michael Hanselmann
    """
1206 85f03e0d Michael Hanselmann
    try:
1207 34327f51 Iustin Pop
      job.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
1208 34327f51 Iustin Pop
                            "Job canceled by request")
1209 85f03e0d Michael Hanselmann
    finally:
1210 85f03e0d Michael Hanselmann
      self.UpdateJobUnlocked(job)
1211 188c5e0a Michael Hanselmann
1212 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1213 d7fd1f28 Michael Hanselmann
  def _ArchiveJobsUnlocked(self, jobs):
1214 d7fd1f28 Michael Hanselmann
    """Archives jobs.
1215 c609f802 Michael Hanselmann

1216 d7fd1f28 Michael Hanselmann
    @type jobs: list of L{_QueuedJob}
1217 25e7b43f Iustin Pop
    @param jobs: Job objects
1218 d7fd1f28 Michael Hanselmann
    @rtype: int
1219 d7fd1f28 Michael Hanselmann
    @return: Number of archived jobs
1220 c609f802 Michael Hanselmann

1221 c609f802 Michael Hanselmann
    """
1222 d7fd1f28 Michael Hanselmann
    archive_jobs = []
1223 d7fd1f28 Michael Hanselmann
    rename_files = []
1224 d7fd1f28 Michael Hanselmann
    for job in jobs:
1225 d7fd1f28 Michael Hanselmann
      if job.CalcStatus() not in (constants.JOB_STATUS_CANCELED,
1226 d7fd1f28 Michael Hanselmann
                                  constants.JOB_STATUS_SUCCESS,
1227 d7fd1f28 Michael Hanselmann
                                  constants.JOB_STATUS_ERROR):
1228 d7fd1f28 Michael Hanselmann
        logging.debug("Job %s is not yet done", job.id)
1229 d7fd1f28 Michael Hanselmann
        continue
1230 c609f802 Michael Hanselmann
1231 d7fd1f28 Michael Hanselmann
      archive_jobs.append(job)
1232 c609f802 Michael Hanselmann
1233 d7fd1f28 Michael Hanselmann
      old = self._GetJobPath(job.id)
1234 d7fd1f28 Michael Hanselmann
      new = self._GetArchivedJobPath(job.id)
1235 d7fd1f28 Michael Hanselmann
      rename_files.append((old, new))
1236 c609f802 Michael Hanselmann
1237 d7fd1f28 Michael Hanselmann
    # TODO: What if 1..n files fail to rename?
1238 d7fd1f28 Michael Hanselmann
    self._RenameFilesUnlocked(rename_files)
1239 f1da30e6 Michael Hanselmann
1240 d7fd1f28 Michael Hanselmann
    logging.debug("Successfully archived job(s) %s",
1241 d7fd1f28 Michael Hanselmann
                  ", ".join(job.id for job in archive_jobs))
1242 d7fd1f28 Michael Hanselmann
1243 d7fd1f28 Michael Hanselmann
    return len(archive_jobs)
1244 78d12585 Michael Hanselmann
1245 07cd723a Iustin Pop
  @utils.LockedMethod
1246 07cd723a Iustin Pop
  @_RequireOpenQueue
1247 07cd723a Iustin Pop
  def ArchiveJob(self, job_id):
1248 07cd723a Iustin Pop
    """Archives a job.
1249 07cd723a Iustin Pop

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

1252 07cd723a Iustin Pop
    @type job_id: string
1253 07cd723a Iustin Pop
    @param job_id: Job ID of job to be archived.
1254 78d12585 Michael Hanselmann
    @rtype: bool
1255 78d12585 Michael Hanselmann
    @return: Whether job was archived
1256 07cd723a Iustin Pop

1257 07cd723a Iustin Pop
    """
1258 78d12585 Michael Hanselmann
    logging.info("Archiving job %s", job_id)
1259 78d12585 Michael Hanselmann
1260 78d12585 Michael Hanselmann
    job = self._LoadJobUnlocked(job_id)
1261 78d12585 Michael Hanselmann
    if not job:
1262 78d12585 Michael Hanselmann
      logging.debug("Job %s not found", job_id)
1263 78d12585 Michael Hanselmann
      return False
1264 78d12585 Michael Hanselmann
1265 5278185a Iustin Pop
    return self._ArchiveJobsUnlocked([job]) == 1
1266 07cd723a Iustin Pop
1267 07cd723a Iustin Pop
  @utils.LockedMethod
1268 07cd723a Iustin Pop
  @_RequireOpenQueue
1269 f8ad5591 Michael Hanselmann
  def AutoArchiveJobs(self, age, timeout):
1270 07cd723a Iustin Pop
    """Archives all jobs based on age.
1271 07cd723a Iustin Pop

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

1277 07cd723a Iustin Pop
    @type age: int
1278 07cd723a Iustin Pop
    @param age: the minimum age in seconds
1279 07cd723a Iustin Pop

1280 07cd723a Iustin Pop
    """
1281 07cd723a Iustin Pop
    logging.info("Archiving jobs with age more than %s seconds", age)
1282 07cd723a Iustin Pop
1283 07cd723a Iustin Pop
    now = time.time()
1284 f8ad5591 Michael Hanselmann
    end_time = now + timeout
1285 f8ad5591 Michael Hanselmann
    archived_count = 0
1286 f8ad5591 Michael Hanselmann
    last_touched = 0
1287 f8ad5591 Michael Hanselmann
1288 f8ad5591 Michael Hanselmann
    all_job_ids = self._GetJobIDsUnlocked(archived=False)
1289 d7fd1f28 Michael Hanselmann
    pending = []
1290 f8ad5591 Michael Hanselmann
    for idx, job_id in enumerate(all_job_ids):
1291 f8ad5591 Michael Hanselmann
      last_touched = idx
1292 f8ad5591 Michael Hanselmann
1293 d7fd1f28 Michael Hanselmann
      # Not optimal because jobs could be pending
1294 d7fd1f28 Michael Hanselmann
      # TODO: Measure average duration for job archival and take number of
1295 d7fd1f28 Michael Hanselmann
      # pending jobs into account.
1296 f8ad5591 Michael Hanselmann
      if time.time() > end_time:
1297 f8ad5591 Michael Hanselmann
        break
1298 f8ad5591 Michael Hanselmann
1299 78d12585 Michael Hanselmann
      # Returns None if the job failed to load
1300 78d12585 Michael Hanselmann
      job = self._LoadJobUnlocked(job_id)
1301 f8ad5591 Michael Hanselmann
      if job:
1302 f8ad5591 Michael Hanselmann
        if job.end_timestamp is None:
1303 f8ad5591 Michael Hanselmann
          if job.start_timestamp is None:
1304 f8ad5591 Michael Hanselmann
            job_age = job.received_timestamp
1305 f8ad5591 Michael Hanselmann
          else:
1306 f8ad5591 Michael Hanselmann
            job_age = job.start_timestamp
1307 07cd723a Iustin Pop
        else:
1308 f8ad5591 Michael Hanselmann
          job_age = job.end_timestamp
1309 f8ad5591 Michael Hanselmann
1310 f8ad5591 Michael Hanselmann
        if age == -1 or now - job_age[0] > age:
1311 d7fd1f28 Michael Hanselmann
          pending.append(job)
1312 d7fd1f28 Michael Hanselmann
1313 d7fd1f28 Michael Hanselmann
          # Archive 10 jobs at a time
1314 d7fd1f28 Michael Hanselmann
          if len(pending) >= 10:
1315 d7fd1f28 Michael Hanselmann
            archived_count += self._ArchiveJobsUnlocked(pending)
1316 d7fd1f28 Michael Hanselmann
            pending = []
1317 f8ad5591 Michael Hanselmann
1318 d7fd1f28 Michael Hanselmann
    if pending:
1319 d7fd1f28 Michael Hanselmann
      archived_count += self._ArchiveJobsUnlocked(pending)
1320 07cd723a Iustin Pop
1321 f8ad5591 Michael Hanselmann
    return (archived_count, len(all_job_ids) - last_touched - 1)
1322 07cd723a Iustin Pop
1323 85f03e0d Michael Hanselmann
  def _GetJobInfoUnlocked(self, job, fields):
1324 ea03467c Iustin Pop
    """Returns information about a job.
1325 ea03467c Iustin Pop

1326 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
1327 ea03467c Iustin Pop
    @param job: the job which we query
1328 ea03467c Iustin Pop
    @type fields: list
1329 ea03467c Iustin Pop
    @param fields: names of fields to return
1330 ea03467c Iustin Pop
    @rtype: list
1331 ea03467c Iustin Pop
    @return: list with one element for each field
1332 ea03467c Iustin Pop
    @raise errors.OpExecError: when an invalid field
1333 ea03467c Iustin Pop
        has been passed
1334 ea03467c Iustin Pop

1335 ea03467c Iustin Pop
    """
1336 e2715f69 Michael Hanselmann
    row = []
1337 e2715f69 Michael Hanselmann
    for fname in fields:
1338 e2715f69 Michael Hanselmann
      if fname == "id":
1339 e2715f69 Michael Hanselmann
        row.append(job.id)
1340 e2715f69 Michael Hanselmann
      elif fname == "status":
1341 85f03e0d Michael Hanselmann
        row.append(job.CalcStatus())
1342 af30b2fd Michael Hanselmann
      elif fname == "ops":
1343 85f03e0d Michael Hanselmann
        row.append([op.input.__getstate__() for op in job.ops])
1344 af30b2fd Michael Hanselmann
      elif fname == "opresult":
1345 85f03e0d Michael Hanselmann
        row.append([op.result for op in job.ops])
1346 af30b2fd Michael Hanselmann
      elif fname == "opstatus":
1347 85f03e0d Michael Hanselmann
        row.append([op.status for op in job.ops])
1348 5b23c34c Iustin Pop
      elif fname == "oplog":
1349 5b23c34c Iustin Pop
        row.append([op.log for op in job.ops])
1350 c56ec146 Iustin Pop
      elif fname == "opstart":
1351 c56ec146 Iustin Pop
        row.append([op.start_timestamp for op in job.ops])
1352 c56ec146 Iustin Pop
      elif fname == "opend":
1353 c56ec146 Iustin Pop
        row.append([op.end_timestamp for op in job.ops])
1354 c56ec146 Iustin Pop
      elif fname == "received_ts":
1355 c56ec146 Iustin Pop
        row.append(job.received_timestamp)
1356 c56ec146 Iustin Pop
      elif fname == "start_ts":
1357 c56ec146 Iustin Pop
        row.append(job.start_timestamp)
1358 c56ec146 Iustin Pop
      elif fname == "end_ts":
1359 c56ec146 Iustin Pop
        row.append(job.end_timestamp)
1360 60dd1473 Iustin Pop
      elif fname == "summary":
1361 60dd1473 Iustin Pop
        row.append([op.input.Summary() for op in job.ops])
1362 e2715f69 Michael Hanselmann
      else:
1363 e2715f69 Michael Hanselmann
        raise errors.OpExecError("Invalid job query field '%s'" % fname)
1364 e2715f69 Michael Hanselmann
    return row
1365 e2715f69 Michael Hanselmann
1366 85f03e0d Michael Hanselmann
  @utils.LockedMethod
1367 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1368 e2715f69 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1369 e2715f69 Michael Hanselmann
    """Returns a list of jobs in queue.
1370 e2715f69 Michael Hanselmann

1371 ea03467c Iustin Pop
    This is a wrapper of L{_GetJobsUnlocked}, which actually does the
1372 ea03467c Iustin Pop
    processing for each job.
1373 ea03467c Iustin Pop

1374 ea03467c Iustin Pop
    @type job_ids: list
1375 ea03467c Iustin Pop
    @param job_ids: sequence of job identifiers or None for all
1376 ea03467c Iustin Pop
    @type fields: list
1377 ea03467c Iustin Pop
    @param fields: names of fields to return
1378 ea03467c Iustin Pop
    @rtype: list
1379 ea03467c Iustin Pop
    @return: list one element per job, each element being list with
1380 ea03467c Iustin Pop
        the requested fields
1381 e2715f69 Michael Hanselmann

1382 e2715f69 Michael Hanselmann
    """
1383 85f03e0d Michael Hanselmann
    jobs = []
1384 e2715f69 Michael Hanselmann
1385 85f03e0d Michael Hanselmann
    for job in self._GetJobsUnlocked(job_ids):
1386 85f03e0d Michael Hanselmann
      if job is None:
1387 85f03e0d Michael Hanselmann
        jobs.append(None)
1388 85f03e0d Michael Hanselmann
      else:
1389 85f03e0d Michael Hanselmann
        jobs.append(self._GetJobInfoUnlocked(job, fields))
1390 e2715f69 Michael Hanselmann
1391 85f03e0d Michael Hanselmann
    return jobs
1392 e2715f69 Michael Hanselmann
1393 f1da30e6 Michael Hanselmann
  @utils.LockedMethod
1394 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1395 e2715f69 Michael Hanselmann
  def Shutdown(self):
1396 e2715f69 Michael Hanselmann
    """Stops the job queue.
1397 e2715f69 Michael Hanselmann

1398 ea03467c Iustin Pop
    This shutdowns all the worker threads an closes the queue.
1399 ea03467c Iustin Pop

1400 e2715f69 Michael Hanselmann
    """
1401 e2715f69 Michael Hanselmann
    self._wpool.TerminateWorkers()
1402 85f03e0d Michael Hanselmann
1403 04ab05ce Michael Hanselmann
    self._queue_lock.Close()
1404 04ab05ce Michael Hanselmann
    self._queue_lock = None