Statistics
| Branch: | Tag: | Revision:

root / lib / jqueue.py @ 5a672c30

History | View | Annotate | Download (45.9 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 f1da30e6 Michael Hanselmann
import errno
35 f1da30e6 Michael Hanselmann
import re
36 f1048938 Iustin Pop
import time
37 5685c1a5 Michael Hanselmann
import weakref
38 498ae1cc Iustin Pop
39 6c2549d6 Guido Trotter
try:
40 6c2549d6 Guido Trotter
  # pylint: disable-msg=E0611
41 6c2549d6 Guido Trotter
  from pyinotify import pyinotify
42 6c2549d6 Guido Trotter
except ImportError:
43 6c2549d6 Guido Trotter
  import pyinotify
44 6c2549d6 Guido Trotter
45 6c2549d6 Guido Trotter
from ganeti import asyncnotifier
46 e2715f69 Michael Hanselmann
from ganeti import constants
47 f1da30e6 Michael Hanselmann
from ganeti import serializer
48 e2715f69 Michael Hanselmann
from ganeti import workerpool
49 99bd4f0a Guido Trotter
from ganeti import locking
50 f1da30e6 Michael Hanselmann
from ganeti import opcodes
51 7a1ecaed Iustin Pop
from ganeti import errors
52 e2715f69 Michael Hanselmann
from ganeti import mcpu
53 7996a135 Iustin Pop
from ganeti import utils
54 04ab05ce Michael Hanselmann
from ganeti import jstore
55 c3f0a12f Iustin Pop
from ganeti import rpc
56 e2715f69 Michael Hanselmann
57 fbf0262f Michael Hanselmann
58 1daae384 Iustin Pop
JOBQUEUE_THREADS = 25
59 58b22b6e Michael Hanselmann
JOBS_PER_ARCHIVE_DIRECTORY = 10000
60 e2715f69 Michael Hanselmann
61 ebb80afa Guido Trotter
# member lock names to be passed to @ssynchronized decorator
62 ebb80afa Guido Trotter
_LOCK = "_lock"
63 ebb80afa Guido Trotter
_QUEUE = "_queue"
64 99bd4f0a Guido Trotter
65 498ae1cc Iustin Pop
66 9728ae5d Iustin Pop
class CancelJob(Exception):
67 fbf0262f Michael Hanselmann
  """Special exception to cancel a job.
68 fbf0262f Michael Hanselmann

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

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

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

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

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

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

105 ea03467c Iustin Pop
    """
106 85f03e0d Michael Hanselmann
    self.input = op
107 85f03e0d Michael Hanselmann
    self.status = constants.OP_STATUS_QUEUED
108 85f03e0d Michael Hanselmann
    self.result = None
109 85f03e0d Michael Hanselmann
    self.log = []
110 70552c46 Michael Hanselmann
    self.start_timestamp = None
111 b9b5abcb Iustin Pop
    self.exec_timestamp = None
112 70552c46 Michael Hanselmann
    self.end_timestamp = None
113 f1da30e6 Michael Hanselmann
114 f1da30e6 Michael Hanselmann
  @classmethod
115 f1da30e6 Michael Hanselmann
  def Restore(cls, state):
116 ea03467c Iustin Pop
    """Restore the _QueuedOpCode from the serialized form.
117 ea03467c Iustin Pop

118 ea03467c Iustin Pop
    @type state: dict
119 ea03467c Iustin Pop
    @param state: the serialized state
120 ea03467c Iustin Pop
    @rtype: _QueuedOpCode
121 ea03467c Iustin Pop
    @return: a new _QueuedOpCode instance
122 ea03467c Iustin Pop

123 ea03467c Iustin Pop
    """
124 85f03e0d Michael Hanselmann
    obj = _QueuedOpCode.__new__(cls)
125 85f03e0d Michael Hanselmann
    obj.input = opcodes.OpCode.LoadOpCode(state["input"])
126 85f03e0d Michael Hanselmann
    obj.status = state["status"]
127 85f03e0d Michael Hanselmann
    obj.result = state["result"]
128 85f03e0d Michael Hanselmann
    obj.log = state["log"]
129 70552c46 Michael Hanselmann
    obj.start_timestamp = state.get("start_timestamp", None)
130 b9b5abcb Iustin Pop
    obj.exec_timestamp = state.get("exec_timestamp", None)
131 70552c46 Michael Hanselmann
    obj.end_timestamp = state.get("end_timestamp", None)
132 f1da30e6 Michael Hanselmann
    return obj
133 f1da30e6 Michael Hanselmann
134 f1da30e6 Michael Hanselmann
  def Serialize(self):
135 ea03467c Iustin Pop
    """Serializes this _QueuedOpCode.
136 ea03467c Iustin Pop

137 ea03467c Iustin Pop
    @rtype: dict
138 ea03467c Iustin Pop
    @return: the dictionary holding the serialized state
139 ea03467c Iustin Pop

140 ea03467c Iustin Pop
    """
141 6c5a7090 Michael Hanselmann
    return {
142 6c5a7090 Michael Hanselmann
      "input": self.input.__getstate__(),
143 6c5a7090 Michael Hanselmann
      "status": self.status,
144 6c5a7090 Michael Hanselmann
      "result": self.result,
145 6c5a7090 Michael Hanselmann
      "log": self.log,
146 70552c46 Michael Hanselmann
      "start_timestamp": self.start_timestamp,
147 b9b5abcb Iustin Pop
      "exec_timestamp": self.exec_timestamp,
148 70552c46 Michael Hanselmann
      "end_timestamp": self.end_timestamp,
149 6c5a7090 Michael Hanselmann
      }
150 f1048938 Iustin Pop
151 e2715f69 Michael Hanselmann
152 e2715f69 Michael Hanselmann
class _QueuedJob(object):
153 e2715f69 Michael Hanselmann
  """In-memory job representation.
154 e2715f69 Michael Hanselmann

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

158 ea03467c Iustin Pop
  @type queue: L{JobQueue}
159 ea03467c Iustin Pop
  @ivar queue: the parent queue
160 ea03467c Iustin Pop
  @ivar id: the job ID
161 ea03467c Iustin Pop
  @type ops: list
162 ea03467c Iustin Pop
  @ivar ops: the list of _QueuedOpCode that constitute the job
163 ea03467c Iustin Pop
  @type log_serial: int
164 ea03467c Iustin Pop
  @ivar log_serial: holds the index for the next log entry
165 ea03467c Iustin Pop
  @ivar received_timestamp: the timestamp for when the job was received
166 ea03467c Iustin Pop
  @ivar start_timestmap: the timestamp for start of execution
167 ea03467c Iustin Pop
  @ivar end_timestamp: the timestamp for end of execution
168 ef2df7d3 Michael Hanselmann
  @ivar lock_status: In-memory locking information for debugging
169 e2715f69 Michael Hanselmann

170 e2715f69 Michael Hanselmann
  """
171 7260cfbe Iustin Pop
  # pylint: disable-msg=W0212
172 d25c1d6a Michael Hanselmann
  __slots__ = ["queue", "id", "ops", "log_serial",
173 66d895a8 Iustin Pop
               "received_timestamp", "start_timestamp", "end_timestamp",
174 ef2df7d3 Michael Hanselmann
               "lock_status", "change",
175 66d895a8 Iustin Pop
               "__weakref__"]
176 66d895a8 Iustin Pop
177 85f03e0d Michael Hanselmann
  def __init__(self, queue, job_id, ops):
178 ea03467c Iustin Pop
    """Constructor for the _QueuedJob.
179 ea03467c Iustin Pop

180 ea03467c Iustin Pop
    @type queue: L{JobQueue}
181 ea03467c Iustin Pop
    @param queue: our parent queue
182 ea03467c Iustin Pop
    @type job_id: job_id
183 ea03467c Iustin Pop
    @param job_id: our job id
184 ea03467c Iustin Pop
    @type ops: list
185 ea03467c Iustin Pop
    @param ops: the list of opcodes we hold, which will be encapsulated
186 ea03467c Iustin Pop
        in _QueuedOpCodes
187 ea03467c Iustin Pop

188 ea03467c Iustin Pop
    """
189 e2715f69 Michael Hanselmann
    if not ops:
190 c910bccb Guido Trotter
      raise errors.GenericError("A job needs at least one opcode")
191 e2715f69 Michael Hanselmann
192 85f03e0d Michael Hanselmann
    self.queue = queue
193 f1da30e6 Michael Hanselmann
    self.id = job_id
194 85f03e0d Michael Hanselmann
    self.ops = [_QueuedOpCode(op) for op in ops]
195 6c5a7090 Michael Hanselmann
    self.log_serial = 0
196 c56ec146 Iustin Pop
    self.received_timestamp = TimeStampNow()
197 c56ec146 Iustin Pop
    self.start_timestamp = None
198 c56ec146 Iustin Pop
    self.end_timestamp = None
199 6c5a7090 Michael Hanselmann
200 ef2df7d3 Michael Hanselmann
    # In-memory attributes
201 ef2df7d3 Michael Hanselmann
    self.lock_status = None
202 ef2df7d3 Michael Hanselmann
203 9fa2e150 Michael Hanselmann
  def __repr__(self):
204 9fa2e150 Michael Hanselmann
    status = ["%s.%s" % (self.__class__.__module__, self.__class__.__name__),
205 9fa2e150 Michael Hanselmann
              "id=%s" % self.id,
206 9fa2e150 Michael Hanselmann
              "ops=%s" % ",".join([op.input.Summary() for op in self.ops])]
207 9fa2e150 Michael Hanselmann
208 9fa2e150 Michael Hanselmann
    return "<%s at %#x>" % (" ".join(status), id(self))
209 9fa2e150 Michael Hanselmann
210 f1da30e6 Michael Hanselmann
  @classmethod
211 85f03e0d Michael Hanselmann
  def Restore(cls, queue, state):
212 ea03467c Iustin Pop
    """Restore a _QueuedJob from serialized state:
213 ea03467c Iustin Pop

214 ea03467c Iustin Pop
    @type queue: L{JobQueue}
215 ea03467c Iustin Pop
    @param queue: to which queue the restored job belongs
216 ea03467c Iustin Pop
    @type state: dict
217 ea03467c Iustin Pop
    @param state: the serialized state
218 ea03467c Iustin Pop
    @rtype: _JobQueue
219 ea03467c Iustin Pop
    @return: the restored _JobQueue instance
220 ea03467c Iustin Pop

221 ea03467c Iustin Pop
    """
222 85f03e0d Michael Hanselmann
    obj = _QueuedJob.__new__(cls)
223 85f03e0d Michael Hanselmann
    obj.queue = queue
224 85f03e0d Michael Hanselmann
    obj.id = state["id"]
225 c56ec146 Iustin Pop
    obj.received_timestamp = state.get("received_timestamp", None)
226 c56ec146 Iustin Pop
    obj.start_timestamp = state.get("start_timestamp", None)
227 c56ec146 Iustin Pop
    obj.end_timestamp = state.get("end_timestamp", None)
228 6c5a7090 Michael Hanselmann
229 ef2df7d3 Michael Hanselmann
    # In-memory attributes
230 ef2df7d3 Michael Hanselmann
    obj.lock_status = None
231 ef2df7d3 Michael Hanselmann
232 6c5a7090 Michael Hanselmann
    obj.ops = []
233 6c5a7090 Michael Hanselmann
    obj.log_serial = 0
234 6c5a7090 Michael Hanselmann
    for op_state in state["ops"]:
235 6c5a7090 Michael Hanselmann
      op = _QueuedOpCode.Restore(op_state)
236 6c5a7090 Michael Hanselmann
      for log_entry in op.log:
237 6c5a7090 Michael Hanselmann
        obj.log_serial = max(obj.log_serial, log_entry[0])
238 6c5a7090 Michael Hanselmann
      obj.ops.append(op)
239 6c5a7090 Michael Hanselmann
240 f1da30e6 Michael Hanselmann
    return obj
241 f1da30e6 Michael Hanselmann
242 f1da30e6 Michael Hanselmann
  def Serialize(self):
243 ea03467c Iustin Pop
    """Serialize the _JobQueue instance.
244 ea03467c Iustin Pop

245 ea03467c Iustin Pop
    @rtype: dict
246 ea03467c Iustin Pop
    @return: the serialized state
247 ea03467c Iustin Pop

248 ea03467c Iustin Pop
    """
249 f1da30e6 Michael Hanselmann
    return {
250 f1da30e6 Michael Hanselmann
      "id": self.id,
251 85f03e0d Michael Hanselmann
      "ops": [op.Serialize() for op in self.ops],
252 c56ec146 Iustin Pop
      "start_timestamp": self.start_timestamp,
253 c56ec146 Iustin Pop
      "end_timestamp": self.end_timestamp,
254 c56ec146 Iustin Pop
      "received_timestamp": self.received_timestamp,
255 f1da30e6 Michael Hanselmann
      }
256 f1da30e6 Michael Hanselmann
257 85f03e0d Michael Hanselmann
  def CalcStatus(self):
258 ea03467c Iustin Pop
    """Compute the status of this job.
259 ea03467c Iustin Pop

260 ea03467c Iustin Pop
    This function iterates over all the _QueuedOpCodes in the job and
261 ea03467c Iustin Pop
    based on their status, computes the job status.
262 ea03467c Iustin Pop

263 ea03467c Iustin Pop
    The algorithm is:
264 ea03467c Iustin Pop
      - if we find a cancelled, or finished with error, the job
265 ea03467c Iustin Pop
        status will be the same
266 ea03467c Iustin Pop
      - otherwise, the last opcode with the status one of:
267 ea03467c Iustin Pop
          - waitlock
268 fbf0262f Michael Hanselmann
          - canceling
269 ea03467c Iustin Pop
          - running
270 ea03467c Iustin Pop

271 ea03467c Iustin Pop
        will determine the job status
272 ea03467c Iustin Pop

273 ea03467c Iustin Pop
      - otherwise, it means either all opcodes are queued, or success,
274 ea03467c Iustin Pop
        and the job status will be the same
275 ea03467c Iustin Pop

276 ea03467c Iustin Pop
    @return: the job status
277 ea03467c Iustin Pop

278 ea03467c Iustin Pop
    """
279 e2715f69 Michael Hanselmann
    status = constants.JOB_STATUS_QUEUED
280 e2715f69 Michael Hanselmann
281 e2715f69 Michael Hanselmann
    all_success = True
282 85f03e0d Michael Hanselmann
    for op in self.ops:
283 85f03e0d Michael Hanselmann
      if op.status == constants.OP_STATUS_SUCCESS:
284 e2715f69 Michael Hanselmann
        continue
285 e2715f69 Michael Hanselmann
286 e2715f69 Michael Hanselmann
      all_success = False
287 e2715f69 Michael Hanselmann
288 85f03e0d Michael Hanselmann
      if op.status == constants.OP_STATUS_QUEUED:
289 e2715f69 Michael Hanselmann
        pass
290 e92376d7 Iustin Pop
      elif op.status == constants.OP_STATUS_WAITLOCK:
291 e92376d7 Iustin Pop
        status = constants.JOB_STATUS_WAITLOCK
292 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_RUNNING:
293 e2715f69 Michael Hanselmann
        status = constants.JOB_STATUS_RUNNING
294 fbf0262f Michael Hanselmann
      elif op.status == constants.OP_STATUS_CANCELING:
295 fbf0262f Michael Hanselmann
        status = constants.JOB_STATUS_CANCELING
296 fbf0262f Michael Hanselmann
        break
297 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_ERROR:
298 f1da30e6 Michael Hanselmann
        status = constants.JOB_STATUS_ERROR
299 f1da30e6 Michael Hanselmann
        # The whole job fails if one opcode failed
300 f1da30e6 Michael Hanselmann
        break
301 85f03e0d Michael Hanselmann
      elif op.status == constants.OP_STATUS_CANCELED:
302 4cb1d919 Michael Hanselmann
        status = constants.OP_STATUS_CANCELED
303 4cb1d919 Michael Hanselmann
        break
304 e2715f69 Michael Hanselmann
305 e2715f69 Michael Hanselmann
    if all_success:
306 e2715f69 Michael Hanselmann
      status = constants.JOB_STATUS_SUCCESS
307 e2715f69 Michael Hanselmann
308 e2715f69 Michael Hanselmann
    return status
309 e2715f69 Michael Hanselmann
310 6c5a7090 Michael Hanselmann
  def GetLogEntries(self, newer_than):
311 ea03467c Iustin Pop
    """Selectively returns the log entries.
312 ea03467c Iustin Pop

313 ea03467c Iustin Pop
    @type newer_than: None or int
314 5bbd3f7f Michael Hanselmann
    @param newer_than: if this is None, return all log entries,
315 ea03467c Iustin Pop
        otherwise return only the log entries with serial higher
316 ea03467c Iustin Pop
        than this value
317 ea03467c Iustin Pop
    @rtype: list
318 ea03467c Iustin Pop
    @return: the list of the log entries selected
319 ea03467c Iustin Pop

320 ea03467c Iustin Pop
    """
321 6c5a7090 Michael Hanselmann
    if newer_than is None:
322 6c5a7090 Michael Hanselmann
      serial = -1
323 6c5a7090 Michael Hanselmann
    else:
324 6c5a7090 Michael Hanselmann
      serial = newer_than
325 6c5a7090 Michael Hanselmann
326 6c5a7090 Michael Hanselmann
    entries = []
327 6c5a7090 Michael Hanselmann
    for op in self.ops:
328 63712a09 Iustin Pop
      entries.extend(filter(lambda entry: entry[0] > serial, op.log))
329 6c5a7090 Michael Hanselmann
330 6c5a7090 Michael Hanselmann
    return entries
331 6c5a7090 Michael Hanselmann
332 6a290889 Guido Trotter
  def GetInfo(self, fields):
333 6a290889 Guido Trotter
    """Returns information about a job.
334 6a290889 Guido Trotter

335 6a290889 Guido Trotter
    @type fields: list
336 6a290889 Guido Trotter
    @param fields: names of fields to return
337 6a290889 Guido Trotter
    @rtype: list
338 6a290889 Guido Trotter
    @return: list with one element for each field
339 6a290889 Guido Trotter
    @raise errors.OpExecError: when an invalid field
340 6a290889 Guido Trotter
        has been passed
341 6a290889 Guido Trotter

342 6a290889 Guido Trotter
    """
343 6a290889 Guido Trotter
    row = []
344 6a290889 Guido Trotter
    for fname in fields:
345 6a290889 Guido Trotter
      if fname == "id":
346 6a290889 Guido Trotter
        row.append(self.id)
347 6a290889 Guido Trotter
      elif fname == "status":
348 6a290889 Guido Trotter
        row.append(self.CalcStatus())
349 6a290889 Guido Trotter
      elif fname == "ops":
350 6a290889 Guido Trotter
        row.append([op.input.__getstate__() for op in self.ops])
351 6a290889 Guido Trotter
      elif fname == "opresult":
352 6a290889 Guido Trotter
        row.append([op.result for op in self.ops])
353 6a290889 Guido Trotter
      elif fname == "opstatus":
354 6a290889 Guido Trotter
        row.append([op.status for op in self.ops])
355 6a290889 Guido Trotter
      elif fname == "oplog":
356 6a290889 Guido Trotter
        row.append([op.log for op in self.ops])
357 6a290889 Guido Trotter
      elif fname == "opstart":
358 6a290889 Guido Trotter
        row.append([op.start_timestamp for op in self.ops])
359 6a290889 Guido Trotter
      elif fname == "opexec":
360 6a290889 Guido Trotter
        row.append([op.exec_timestamp for op in self.ops])
361 6a290889 Guido Trotter
      elif fname == "opend":
362 6a290889 Guido Trotter
        row.append([op.end_timestamp for op in self.ops])
363 6a290889 Guido Trotter
      elif fname == "received_ts":
364 6a290889 Guido Trotter
        row.append(self.received_timestamp)
365 6a290889 Guido Trotter
      elif fname == "start_ts":
366 6a290889 Guido Trotter
        row.append(self.start_timestamp)
367 6a290889 Guido Trotter
      elif fname == "end_ts":
368 6a290889 Guido Trotter
        row.append(self.end_timestamp)
369 6a290889 Guido Trotter
      elif fname == "lock_status":
370 6a290889 Guido Trotter
        row.append(self.lock_status)
371 6a290889 Guido Trotter
      elif fname == "summary":
372 6a290889 Guido Trotter
        row.append([op.input.Summary() for op in self.ops])
373 6a290889 Guido Trotter
      else:
374 6a290889 Guido Trotter
        raise errors.OpExecError("Invalid self query field '%s'" % fname)
375 6a290889 Guido Trotter
    return row
376 6a290889 Guido Trotter
377 34327f51 Iustin Pop
  def MarkUnfinishedOps(self, status, result):
378 34327f51 Iustin Pop
    """Mark unfinished opcodes with a given status and result.
379 34327f51 Iustin Pop

380 34327f51 Iustin Pop
    This is an utility function for marking all running or waiting to
381 34327f51 Iustin Pop
    be run opcodes with a given status. Opcodes which are already
382 34327f51 Iustin Pop
    finalised are not changed.
383 34327f51 Iustin Pop

384 34327f51 Iustin Pop
    @param status: a given opcode status
385 34327f51 Iustin Pop
    @param result: the opcode result
386 34327f51 Iustin Pop

387 34327f51 Iustin Pop
    """
388 39ed3a98 Guido Trotter
    try:
389 39ed3a98 Guido Trotter
      not_marked = True
390 39ed3a98 Guido Trotter
      for op in self.ops:
391 39ed3a98 Guido Trotter
        if op.status in constants.OPS_FINALIZED:
392 39ed3a98 Guido Trotter
          assert not_marked, "Finalized opcodes found after non-finalized ones"
393 39ed3a98 Guido Trotter
          continue
394 39ed3a98 Guido Trotter
        op.status = status
395 39ed3a98 Guido Trotter
        op.result = result
396 39ed3a98 Guido Trotter
        not_marked = False
397 39ed3a98 Guido Trotter
    finally:
398 39ed3a98 Guido Trotter
      self.queue.UpdateJobUnlocked(self)
399 34327f51 Iustin Pop
400 f1048938 Iustin Pop
401 ef2df7d3 Michael Hanselmann
class _OpExecCallbacks(mcpu.OpExecCbBase):
402 031a3e57 Michael Hanselmann
  def __init__(self, queue, job, op):
403 031a3e57 Michael Hanselmann
    """Initializes this class.
404 ea03467c Iustin Pop

405 031a3e57 Michael Hanselmann
    @type queue: L{JobQueue}
406 031a3e57 Michael Hanselmann
    @param queue: Job queue
407 031a3e57 Michael Hanselmann
    @type job: L{_QueuedJob}
408 031a3e57 Michael Hanselmann
    @param job: Job object
409 031a3e57 Michael Hanselmann
    @type op: L{_QueuedOpCode}
410 031a3e57 Michael Hanselmann
    @param op: OpCode
411 031a3e57 Michael Hanselmann

412 031a3e57 Michael Hanselmann
    """
413 031a3e57 Michael Hanselmann
    assert queue, "Queue is missing"
414 031a3e57 Michael Hanselmann
    assert job, "Job is missing"
415 031a3e57 Michael Hanselmann
    assert op, "Opcode is missing"
416 031a3e57 Michael Hanselmann
417 031a3e57 Michael Hanselmann
    self._queue = queue
418 031a3e57 Michael Hanselmann
    self._job = job
419 031a3e57 Michael Hanselmann
    self._op = op
420 031a3e57 Michael Hanselmann
421 031a3e57 Michael Hanselmann
  def NotifyStart(self):
422 e92376d7 Iustin Pop
    """Mark the opcode as running, not lock-waiting.
423 e92376d7 Iustin Pop

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

429 e92376d7 Iustin Pop
    """
430 3c0d60d0 Guido Trotter
    self._queue.acquire(shared=1)
431 e92376d7 Iustin Pop
    try:
432 031a3e57 Michael Hanselmann
      assert self._op.status in (constants.OP_STATUS_WAITLOCK,
433 031a3e57 Michael Hanselmann
                                 constants.OP_STATUS_CANCELING)
434 fbf0262f Michael Hanselmann
435 ef2df7d3 Michael Hanselmann
      # All locks are acquired by now
436 ef2df7d3 Michael Hanselmann
      self._job.lock_status = None
437 ef2df7d3 Michael Hanselmann
438 fbf0262f Michael Hanselmann
      # Cancel here if we were asked to
439 031a3e57 Michael Hanselmann
      if self._op.status == constants.OP_STATUS_CANCELING:
440 fbf0262f Michael Hanselmann
        raise CancelJob()
441 fbf0262f Michael Hanselmann
442 031a3e57 Michael Hanselmann
      self._op.status = constants.OP_STATUS_RUNNING
443 b9b5abcb Iustin Pop
      self._op.exec_timestamp = TimeStampNow()
444 e92376d7 Iustin Pop
    finally:
445 031a3e57 Michael Hanselmann
      self._queue.release()
446 031a3e57 Michael Hanselmann
447 ebb80afa Guido Trotter
  @locking.ssynchronized(_QUEUE, shared=1)
448 9bf5e01f Guido Trotter
  def _AppendFeedback(self, timestamp, log_type, log_msg):
449 9bf5e01f Guido Trotter
    """Internal feedback append function, with locks
450 9bf5e01f Guido Trotter

451 9bf5e01f Guido Trotter
    """
452 9bf5e01f Guido Trotter
    self._job.log_serial += 1
453 9bf5e01f Guido Trotter
    self._op.log.append((self._job.log_serial, timestamp, log_type, log_msg))
454 9bf5e01f Guido Trotter
    self._queue.UpdateJobUnlocked(self._job, replicate=False)
455 9bf5e01f Guido Trotter
456 031a3e57 Michael Hanselmann
  def Feedback(self, *args):
457 031a3e57 Michael Hanselmann
    """Append a log entry.
458 031a3e57 Michael Hanselmann

459 031a3e57 Michael Hanselmann
    """
460 031a3e57 Michael Hanselmann
    assert len(args) < 3
461 031a3e57 Michael Hanselmann
462 031a3e57 Michael Hanselmann
    if len(args) == 1:
463 031a3e57 Michael Hanselmann
      log_type = constants.ELOG_MESSAGE
464 031a3e57 Michael Hanselmann
      log_msg = args[0]
465 031a3e57 Michael Hanselmann
    else:
466 031a3e57 Michael Hanselmann
      (log_type, log_msg) = args
467 031a3e57 Michael Hanselmann
468 031a3e57 Michael Hanselmann
    # The time is split to make serialization easier and not lose
469 031a3e57 Michael Hanselmann
    # precision.
470 031a3e57 Michael Hanselmann
    timestamp = utils.SplitTime(time.time())
471 9bf5e01f Guido Trotter
    self._AppendFeedback(timestamp, log_type, log_msg)
472 031a3e57 Michael Hanselmann
473 ef2df7d3 Michael Hanselmann
  def ReportLocks(self, msg):
474 ef2df7d3 Michael Hanselmann
    """Write locking information to the job.
475 ef2df7d3 Michael Hanselmann

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

478 ef2df7d3 Michael Hanselmann
    """
479 ef2df7d3 Michael Hanselmann
    # Not getting the queue lock because this is a single assignment
480 ef2df7d3 Michael Hanselmann
    self._job.lock_status = msg
481 ef2df7d3 Michael Hanselmann
482 031a3e57 Michael Hanselmann
483 6c2549d6 Guido Trotter
class _WaitForJobChangesHelper(object):
484 6c2549d6 Guido Trotter
  """Helper class using initofy to wait for changes in a job file.
485 6c2549d6 Guido Trotter

486 6c2549d6 Guido Trotter
  This class takes a previous job status and serial, and alerts the client when
487 6c2549d6 Guido Trotter
  the current job status has changed.
488 6c2549d6 Guido Trotter

489 6c2549d6 Guido Trotter
  @type job_id: string
490 6c2549d6 Guido Trotter
  @ivar job_id: id of the job we're watching
491 6c2549d6 Guido Trotter
  @type prev_job_info: string
492 6c2549d6 Guido Trotter
  @ivar prev_job_info: previous job info, as passed by the luxi client
493 6c2549d6 Guido Trotter
  @type prev_log_serial: string
494 6c2549d6 Guido Trotter
  @ivar prev_log_serial: previous job serial, as passed by the luxi client
495 6c2549d6 Guido Trotter
  @type queue: L{JobQueue}
496 6c2549d6 Guido Trotter
  @ivar queue: job queue (used for a few utility functions)
497 6c2549d6 Guido Trotter
  @type job_path: string
498 6c2549d6 Guido Trotter
  @ivar job_path: absolute path of the job file
499 6c2549d6 Guido Trotter
  @type wm: pyinotify.WatchManager (or None)
500 6c2549d6 Guido Trotter
  @ivar wm: inotify watch manager to watch for changes
501 6c2549d6 Guido Trotter
  @type inotify_handler: L{asyncnotifier.SingleFileEventHandler}
502 6c2549d6 Guido Trotter
  @ivar inotify_handler: single file event handler, used for watching
503 6c2549d6 Guido Trotter
  @type notifier: pyinotify.Notifier
504 6c2549d6 Guido Trotter
  @ivar notifier: inotify single-threaded notifier, used for watching
505 6c2549d6 Guido Trotter

506 6c2549d6 Guido Trotter
  """
507 6c2549d6 Guido Trotter
  def __init__(self, job_id, fields, prev_job_info, prev_log_serial, queue):
508 6c2549d6 Guido Trotter
    self.job_id = job_id
509 6c2549d6 Guido Trotter
    self.fields = fields
510 6c2549d6 Guido Trotter
    self.prev_job_info = prev_job_info
511 6c2549d6 Guido Trotter
    self.prev_log_serial = prev_log_serial
512 6c2549d6 Guido Trotter
    self.queue = queue
513 6c2549d6 Guido Trotter
    # pylint: disable-msg=W0212
514 6c2549d6 Guido Trotter
    self.job_path = self.queue._GetJobPath(self.job_id)
515 6c2549d6 Guido Trotter
    self.wm = None
516 6c2549d6 Guido Trotter
    self.inotify_handler = None
517 6c2549d6 Guido Trotter
    self.notifier = None
518 6c2549d6 Guido Trotter
519 6c2549d6 Guido Trotter
  def _SetupInotify(self):
520 6c2549d6 Guido Trotter
    """Create the inotify
521 6c2549d6 Guido Trotter

522 6c2549d6 Guido Trotter
    @raises errors.InotifyError: if the notifier cannot be setup
523 6c2549d6 Guido Trotter

524 6c2549d6 Guido Trotter
    """
525 6c2549d6 Guido Trotter
    if self.wm:
526 6c2549d6 Guido Trotter
      return
527 6c2549d6 Guido Trotter
    self.wm = pyinotify.WatchManager()
528 6c2549d6 Guido Trotter
    self.inotify_handler = asyncnotifier.SingleFileEventHandler(self.wm,
529 6c2549d6 Guido Trotter
                                                                self.OnInotify,
530 6c2549d6 Guido Trotter
                                                                self.job_path)
531 6c2549d6 Guido Trotter
    self.notifier = pyinotify.Notifier(self.wm, self.inotify_handler)
532 6c2549d6 Guido Trotter
    self.inotify_handler.enable()
533 6c2549d6 Guido Trotter
534 6c2549d6 Guido Trotter
  def _LoadDiskStatus(self):
535 6c2549d6 Guido Trotter
    job = self.queue.SafeLoadJobFromDisk(self.job_id)
536 6c2549d6 Guido Trotter
    if not job:
537 6c2549d6 Guido Trotter
      raise errors.JobLost()
538 6c2549d6 Guido Trotter
    self.job_status = job.CalcStatus()
539 6c2549d6 Guido Trotter
540 6c2549d6 Guido Trotter
    job_info = job.GetInfo(self.fields)
541 6c2549d6 Guido Trotter
    log_entries = job.GetLogEntries(self.prev_log_serial)
542 6c2549d6 Guido Trotter
    # Serializing and deserializing data can cause type changes (e.g. from
543 6c2549d6 Guido Trotter
    # tuple to list) or precision loss. We're doing it here so that we get
544 6c2549d6 Guido Trotter
    # the same modifications as the data received from the client. Without
545 6c2549d6 Guido Trotter
    # this, the comparison afterwards might fail without the data being
546 6c2549d6 Guido Trotter
    # significantly different.
547 6c2549d6 Guido Trotter
    # TODO: we just deserialized from disk, investigate how to make sure that
548 6c2549d6 Guido Trotter
    # the job info and log entries are compatible to avoid this further step.
549 6c2549d6 Guido Trotter
    self.job_info = serializer.LoadJson(serializer.DumpJson(job_info))
550 6c2549d6 Guido Trotter
    self.log_entries = serializer.LoadJson(serializer.DumpJson(log_entries))
551 6c2549d6 Guido Trotter
552 6c2549d6 Guido Trotter
  def _CheckForChanges(self):
553 6c2549d6 Guido Trotter
    self._LoadDiskStatus()
554 6c2549d6 Guido Trotter
    # Don't even try to wait if the job is no longer running, there will be
555 6c2549d6 Guido Trotter
    # no changes.
556 6c2549d6 Guido Trotter
    if (self.job_status not in (constants.JOB_STATUS_QUEUED,
557 6c2549d6 Guido Trotter
                                constants.JOB_STATUS_RUNNING,
558 6c2549d6 Guido Trotter
                                constants.JOB_STATUS_WAITLOCK) or
559 6c2549d6 Guido Trotter
        self.prev_job_info != self.job_info or
560 6c2549d6 Guido Trotter
        (self.log_entries and self.prev_log_serial != self.log_entries[0][0])):
561 6c2549d6 Guido Trotter
      logging.debug("Job %s changed", self.job_id)
562 6c2549d6 Guido Trotter
      return (self.job_info, self.log_entries)
563 6c2549d6 Guido Trotter
564 6c2549d6 Guido Trotter
    raise utils.RetryAgain()
565 6c2549d6 Guido Trotter
566 6c2549d6 Guido Trotter
  def OnInotify(self, notifier_enabled):
567 6c2549d6 Guido Trotter
    if not notifier_enabled:
568 6c2549d6 Guido Trotter
      self.inotify_handler.enable()
569 6c2549d6 Guido Trotter
570 6c2549d6 Guido Trotter
  def WaitFn(self, timeout):
571 6c2549d6 Guido Trotter
    self._SetupInotify()
572 6c2549d6 Guido Trotter
    if self.notifier.check_events(timeout*1000):
573 6c2549d6 Guido Trotter
      self.notifier.read_events()
574 6c2549d6 Guido Trotter
    self.notifier.process_events()
575 6c2549d6 Guido Trotter
576 6c2549d6 Guido Trotter
  def WaitForChanges(self, timeout):
577 6c2549d6 Guido Trotter
    try:
578 6c2549d6 Guido Trotter
      return utils.Retry(self._CheckForChanges,
579 6c2549d6 Guido Trotter
                         utils.RETRY_REMAINING_TIME,
580 6c2549d6 Guido Trotter
                         timeout,
581 6c2549d6 Guido Trotter
                         wait_fn=self.WaitFn)
582 6c2549d6 Guido Trotter
    except (errors.InotifyError, errors.JobLost):
583 6c2549d6 Guido Trotter
      return None
584 6c2549d6 Guido Trotter
    except utils.RetryTimeout:
585 6c2549d6 Guido Trotter
      return constants.JOB_NOTCHANGED
586 6c2549d6 Guido Trotter
587 6c2549d6 Guido Trotter
  def Close(self):
588 6c2549d6 Guido Trotter
    if self.wm:
589 6c2549d6 Guido Trotter
      self.notifier.stop()
590 6c2549d6 Guido Trotter
591 6c2549d6 Guido Trotter
592 031a3e57 Michael Hanselmann
class _JobQueueWorker(workerpool.BaseWorker):
593 031a3e57 Michael Hanselmann
  """The actual job workers.
594 031a3e57 Michael Hanselmann

595 031a3e57 Michael Hanselmann
  """
596 7260cfbe Iustin Pop
  def RunTask(self, job): # pylint: disable-msg=W0221
597 e2715f69 Michael Hanselmann
    """Job executor.
598 e2715f69 Michael Hanselmann

599 6c5a7090 Michael Hanselmann
    This functions processes a job. It is closely tied to the _QueuedJob and
600 6c5a7090 Michael Hanselmann
    _QueuedOpCode classes.
601 e2715f69 Michael Hanselmann

602 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
603 ea03467c Iustin Pop
    @param job: the job to be processed
604 ea03467c Iustin Pop

605 e2715f69 Michael Hanselmann
    """
606 02fc74da Michael Hanselmann
    logging.info("Processing job %s", job.id)
607 adfa97e3 Guido Trotter
    proc = mcpu.Processor(self.pool.queue.context, job.id)
608 031a3e57 Michael Hanselmann
    queue = job.queue
609 e2715f69 Michael Hanselmann
    try:
610 85f03e0d Michael Hanselmann
      try:
611 85f03e0d Michael Hanselmann
        count = len(job.ops)
612 85f03e0d Michael Hanselmann
        for idx, op in enumerate(job.ops):
613 d21d09d6 Iustin Pop
          op_summary = op.input.Summary()
614 f6424741 Iustin Pop
          if op.status == constants.OP_STATUS_SUCCESS:
615 f6424741 Iustin Pop
            # this is a job that was partially completed before master
616 f6424741 Iustin Pop
            # daemon shutdown, so it can be expected that some opcodes
617 f6424741 Iustin Pop
            # are already completed successfully (if any did error
618 f6424741 Iustin Pop
            # out, then the whole job should have been aborted and not
619 f6424741 Iustin Pop
            # resubmitted for processing)
620 f6424741 Iustin Pop
            logging.info("Op %s/%s: opcode %s already processed, skipping",
621 f6424741 Iustin Pop
                         idx + 1, count, op_summary)
622 f6424741 Iustin Pop
            continue
623 85f03e0d Michael Hanselmann
          try:
624 d21d09d6 Iustin Pop
            logging.info("Op %s/%s: Starting opcode %s", idx + 1, count,
625 d21d09d6 Iustin Pop
                         op_summary)
626 85f03e0d Michael Hanselmann
627 3c0d60d0 Guido Trotter
            queue.acquire(shared=1)
628 85f03e0d Michael Hanselmann
            try:
629 df0fb067 Iustin Pop
              if op.status == constants.OP_STATUS_CANCELED:
630 df0fb067 Iustin Pop
                raise CancelJob()
631 fbf0262f Michael Hanselmann
              assert op.status == constants.OP_STATUS_QUEUED
632 e92376d7 Iustin Pop
              op.status = constants.OP_STATUS_WAITLOCK
633 85f03e0d Michael Hanselmann
              op.result = None
634 70552c46 Michael Hanselmann
              op.start_timestamp = TimeStampNow()
635 c56ec146 Iustin Pop
              if idx == 0: # first opcode
636 c56ec146 Iustin Pop
                job.start_timestamp = op.start_timestamp
637 85f03e0d Michael Hanselmann
              queue.UpdateJobUnlocked(job)
638 85f03e0d Michael Hanselmann
639 38206f3c Iustin Pop
              input_opcode = op.input
640 85f03e0d Michael Hanselmann
            finally:
641 85f03e0d Michael Hanselmann
              queue.release()
642 85f03e0d Michael Hanselmann
643 031a3e57 Michael Hanselmann
            # Make sure not to hold queue lock while calling ExecOpCode
644 031a3e57 Michael Hanselmann
            result = proc.ExecOpCode(input_opcode,
645 ef2df7d3 Michael Hanselmann
                                     _OpExecCallbacks(queue, job, op))
646 85f03e0d Michael Hanselmann
647 3c0d60d0 Guido Trotter
            queue.acquire(shared=1)
648 85f03e0d Michael Hanselmann
            try:
649 85f03e0d Michael Hanselmann
              op.status = constants.OP_STATUS_SUCCESS
650 85f03e0d Michael Hanselmann
              op.result = result
651 70552c46 Michael Hanselmann
              op.end_timestamp = TimeStampNow()
652 85f03e0d Michael Hanselmann
              queue.UpdateJobUnlocked(job)
653 85f03e0d Michael Hanselmann
            finally:
654 85f03e0d Michael Hanselmann
              queue.release()
655 85f03e0d Michael Hanselmann
656 d21d09d6 Iustin Pop
            logging.info("Op %s/%s: Successfully finished opcode %s",
657 d21d09d6 Iustin Pop
                         idx + 1, count, op_summary)
658 fbf0262f Michael Hanselmann
          except CancelJob:
659 fbf0262f Michael Hanselmann
            # Will be handled further up
660 fbf0262f Michael Hanselmann
            raise
661 85f03e0d Michael Hanselmann
          except Exception, err:
662 3c0d60d0 Guido Trotter
            queue.acquire(shared=1)
663 85f03e0d Michael Hanselmann
            try:
664 85f03e0d Michael Hanselmann
              try:
665 85f03e0d Michael Hanselmann
                op.status = constants.OP_STATUS_ERROR
666 bcb66fca Iustin Pop
                if isinstance(err, errors.GenericError):
667 bcb66fca Iustin Pop
                  op.result = errors.EncodeException(err)
668 bcb66fca Iustin Pop
                else:
669 bcb66fca Iustin Pop
                  op.result = str(err)
670 70552c46 Michael Hanselmann
                op.end_timestamp = TimeStampNow()
671 0f6be82a Iustin Pop
                logging.info("Op %s/%s: Error in opcode %s: %s",
672 0f6be82a Iustin Pop
                             idx + 1, count, op_summary, err)
673 85f03e0d Michael Hanselmann
              finally:
674 85f03e0d Michael Hanselmann
                queue.UpdateJobUnlocked(job)
675 85f03e0d Michael Hanselmann
            finally:
676 85f03e0d Michael Hanselmann
              queue.release()
677 85f03e0d Michael Hanselmann
            raise
678 85f03e0d Michael Hanselmann
679 fbf0262f Michael Hanselmann
      except CancelJob:
680 3c0d60d0 Guido Trotter
        queue.acquire(shared=1)
681 fbf0262f Michael Hanselmann
        try:
682 39ed3a98 Guido Trotter
          job.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
683 39ed3a98 Guido Trotter
                                "Job canceled by request")
684 fbf0262f Michael Hanselmann
        finally:
685 fbf0262f Michael Hanselmann
          queue.release()
686 85f03e0d Michael Hanselmann
      except errors.GenericError, err:
687 85f03e0d Michael Hanselmann
        logging.exception("Ganeti exception")
688 85f03e0d Michael Hanselmann
      except:
689 85f03e0d Michael Hanselmann
        logging.exception("Unhandled exception")
690 e2715f69 Michael Hanselmann
    finally:
691 3c0d60d0 Guido Trotter
      queue.acquire(shared=1)
692 85f03e0d Michael Hanselmann
      try:
693 65548ed5 Michael Hanselmann
        try:
694 ef2df7d3 Michael Hanselmann
          job.lock_status = None
695 c56ec146 Iustin Pop
          job.end_timestamp = TimeStampNow()
696 65548ed5 Michael Hanselmann
          queue.UpdateJobUnlocked(job)
697 65548ed5 Michael Hanselmann
        finally:
698 65548ed5 Michael Hanselmann
          job_id = job.id
699 65548ed5 Michael Hanselmann
          status = job.CalcStatus()
700 85f03e0d Michael Hanselmann
      finally:
701 85f03e0d Michael Hanselmann
        queue.release()
702 ef2df7d3 Michael Hanselmann
703 02fc74da Michael Hanselmann
      logging.info("Finished job %s, status = %s", job_id, status)
704 e2715f69 Michael Hanselmann
705 e2715f69 Michael Hanselmann
706 e2715f69 Michael Hanselmann
class _JobQueueWorkerPool(workerpool.WorkerPool):
707 ea03467c Iustin Pop
  """Simple class implementing a job-processing workerpool.
708 ea03467c Iustin Pop

709 ea03467c Iustin Pop
  """
710 5bdce580 Michael Hanselmann
  def __init__(self, queue):
711 89e2b4d2 Michael Hanselmann
    super(_JobQueueWorkerPool, self).__init__("JobQueue",
712 89e2b4d2 Michael Hanselmann
                                              JOBQUEUE_THREADS,
713 e2715f69 Michael Hanselmann
                                              _JobQueueWorker)
714 5bdce580 Michael Hanselmann
    self.queue = queue
715 e2715f69 Michael Hanselmann
716 e2715f69 Michael Hanselmann
717 6c881c52 Iustin Pop
def _RequireOpenQueue(fn):
718 6c881c52 Iustin Pop
  """Decorator for "public" functions.
719 ea03467c Iustin Pop

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

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

728 6c881c52 Iustin Pop
  Example::
729 ebb80afa Guido Trotter
    @locking.ssynchronized(_LOCK)
730 6c881c52 Iustin Pop
    @_RequireOpenQueue
731 6c881c52 Iustin Pop
    def Example(self):
732 6c881c52 Iustin Pop
      pass
733 db37da70 Michael Hanselmann

734 6c881c52 Iustin Pop
  """
735 6c881c52 Iustin Pop
  def wrapper(self, *args, **kwargs):
736 7260cfbe Iustin Pop
    # pylint: disable-msg=W0212
737 a71f9c7d Guido Trotter
    assert self._queue_filelock is not None, "Queue should be open"
738 6c881c52 Iustin Pop
    return fn(self, *args, **kwargs)
739 6c881c52 Iustin Pop
  return wrapper
740 db37da70 Michael Hanselmann
741 db37da70 Michael Hanselmann
742 6c881c52 Iustin Pop
class JobQueue(object):
743 6c881c52 Iustin Pop
  """Queue used to manage the jobs.
744 db37da70 Michael Hanselmann

745 6c881c52 Iustin Pop
  @cvar _RE_JOB_FILE: regex matching the valid job file names
746 6c881c52 Iustin Pop

747 6c881c52 Iustin Pop
  """
748 6c881c52 Iustin Pop
  _RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
749 db37da70 Michael Hanselmann
750 85f03e0d Michael Hanselmann
  def __init__(self, context):
751 ea03467c Iustin Pop
    """Constructor for JobQueue.
752 ea03467c Iustin Pop

753 ea03467c Iustin Pop
    The constructor will initialize the job queue object and then
754 ea03467c Iustin Pop
    start loading the current jobs from disk, either for starting them
755 ea03467c Iustin Pop
    (if they were queue) or for aborting them (if they were already
756 ea03467c Iustin Pop
    running).
757 ea03467c Iustin Pop

758 ea03467c Iustin Pop
    @type context: GanetiContext
759 ea03467c Iustin Pop
    @param context: the context object for access to the configuration
760 ea03467c Iustin Pop
        data and other ganeti objects
761 ea03467c Iustin Pop

762 ea03467c Iustin Pop
    """
763 5bdce580 Michael Hanselmann
    self.context = context
764 5685c1a5 Michael Hanselmann
    self._memcache = weakref.WeakValueDictionary()
765 c3f0a12f Iustin Pop
    self._my_hostname = utils.HostInfo().name
766 f1da30e6 Michael Hanselmann
767 ebb80afa Guido Trotter
    # The Big JobQueue lock. If a code block or method acquires it in shared
768 ebb80afa Guido Trotter
    # mode safe it must guarantee concurrency with all the code acquiring it in
769 ebb80afa Guido Trotter
    # shared mode, including itself. In order not to acquire it at all
770 ebb80afa Guido Trotter
    # concurrency must be guaranteed with all code acquiring it in shared mode
771 ebb80afa Guido Trotter
    # and all code acquiring it exclusively.
772 ebb80afa Guido Trotter
    self._lock = locking.SharedLock()
773 ebb80afa Guido Trotter
774 ebb80afa Guido Trotter
    self.acquire = self._lock.acquire
775 ebb80afa Guido Trotter
    self.release = self._lock.release
776 85f03e0d Michael Hanselmann
777 a71f9c7d Guido Trotter
    # Initialize the queue, and acquire the filelock.
778 a71f9c7d Guido Trotter
    # This ensures no other process is working on the job queue.
779 a71f9c7d Guido Trotter
    self._queue_filelock = jstore.InitAndVerifyQueue(must_lock=True)
780 f1da30e6 Michael Hanselmann
781 04ab05ce Michael Hanselmann
    # Read serial file
782 04ab05ce Michael Hanselmann
    self._last_serial = jstore.ReadSerial()
783 04ab05ce Michael Hanselmann
    assert self._last_serial is not None, ("Serial file was modified between"
784 04ab05ce Michael Hanselmann
                                           " check in jstore and here")
785 c4beba1c Iustin Pop
786 23752136 Michael Hanselmann
    # Get initial list of nodes
787 99aabbed Iustin Pop
    self._nodes = dict((n.name, n.primary_ip)
788 59303563 Iustin Pop
                       for n in self.context.cfg.GetAllNodesInfo().values()
789 59303563 Iustin Pop
                       if n.master_candidate)
790 8e00939c Michael Hanselmann
791 8e00939c Michael Hanselmann
    # Remove master node
792 d8e0dc17 Guido Trotter
    self._nodes.pop(self._my_hostname, None)
793 23752136 Michael Hanselmann
794 23752136 Michael Hanselmann
    # TODO: Check consistency across nodes
795 23752136 Michael Hanselmann
796 20571a26 Guido Trotter
    self._queue_size = 0
797 20571a26 Guido Trotter
    self._UpdateQueueSizeUnlocked()
798 20571a26 Guido Trotter
    self._drained = self._IsQueueMarkedDrain()
799 20571a26 Guido Trotter
800 85f03e0d Michael Hanselmann
    # Setup worker pool
801 5bdce580 Michael Hanselmann
    self._wpool = _JobQueueWorkerPool(self)
802 85f03e0d Michael Hanselmann
    try:
803 16714921 Michael Hanselmann
      # We need to lock here because WorkerPool.AddTask() may start a job while
804 16714921 Michael Hanselmann
      # we're still doing our work.
805 16714921 Michael Hanselmann
      self.acquire()
806 16714921 Michael Hanselmann
      try:
807 711b5124 Michael Hanselmann
        logging.info("Inspecting job queue")
808 711b5124 Michael Hanselmann
809 711b5124 Michael Hanselmann
        all_job_ids = self._GetJobIDsUnlocked()
810 b7cb9024 Michael Hanselmann
        jobs_count = len(all_job_ids)
811 711b5124 Michael Hanselmann
        lastinfo = time.time()
812 711b5124 Michael Hanselmann
        for idx, job_id in enumerate(all_job_ids):
813 711b5124 Michael Hanselmann
          # Give an update every 1000 jobs or 10 seconds
814 b7cb9024 Michael Hanselmann
          if (idx % 1000 == 0 or time.time() >= (lastinfo + 10.0) or
815 b7cb9024 Michael Hanselmann
              idx == (jobs_count - 1)):
816 711b5124 Michael Hanselmann
            logging.info("Job queue inspection: %d/%d (%0.1f %%)",
817 b7cb9024 Michael Hanselmann
                         idx, jobs_count - 1, 100.0 * (idx + 1) / jobs_count)
818 711b5124 Michael Hanselmann
            lastinfo = time.time()
819 711b5124 Michael Hanselmann
820 711b5124 Michael Hanselmann
          job = self._LoadJobUnlocked(job_id)
821 711b5124 Michael Hanselmann
822 16714921 Michael Hanselmann
          # a failure in loading the job can cause 'None' to be returned
823 16714921 Michael Hanselmann
          if job is None:
824 16714921 Michael Hanselmann
            continue
825 94ed59a5 Iustin Pop
826 16714921 Michael Hanselmann
          status = job.CalcStatus()
827 85f03e0d Michael Hanselmann
828 16714921 Michael Hanselmann
          if status in (constants.JOB_STATUS_QUEUED, ):
829 16714921 Michael Hanselmann
            self._wpool.AddTask(job)
830 85f03e0d Michael Hanselmann
831 16714921 Michael Hanselmann
          elif status in (constants.JOB_STATUS_RUNNING,
832 fbf0262f Michael Hanselmann
                          constants.JOB_STATUS_WAITLOCK,
833 fbf0262f Michael Hanselmann
                          constants.JOB_STATUS_CANCELING):
834 16714921 Michael Hanselmann
            logging.warning("Unfinished job %s found: %s", job.id, job)
835 39ed3a98 Guido Trotter
            job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
836 39ed3a98 Guido Trotter
                                  "Unclean master daemon shutdown")
837 711b5124 Michael Hanselmann
838 711b5124 Michael Hanselmann
        logging.info("Job queue inspection finished")
839 16714921 Michael Hanselmann
      finally:
840 16714921 Michael Hanselmann
        self.release()
841 16714921 Michael Hanselmann
    except:
842 16714921 Michael Hanselmann
      self._wpool.TerminateWorkers()
843 16714921 Michael Hanselmann
      raise
844 85f03e0d Michael Hanselmann
845 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
846 d2e03a33 Michael Hanselmann
  @_RequireOpenQueue
847 99aabbed Iustin Pop
  def AddNode(self, node):
848 99aabbed Iustin Pop
    """Register a new node with the queue.
849 99aabbed Iustin Pop

850 99aabbed Iustin Pop
    @type node: L{objects.Node}
851 99aabbed Iustin Pop
    @param node: the node object to be added
852 99aabbed Iustin Pop

853 99aabbed Iustin Pop
    """
854 99aabbed Iustin Pop
    node_name = node.name
855 d2e03a33 Michael Hanselmann
    assert node_name != self._my_hostname
856 23752136 Michael Hanselmann
857 9f774ee8 Michael Hanselmann
    # Clean queue directory on added node
858 c8457ce7 Iustin Pop
    result = rpc.RpcRunner.call_jobqueue_purge(node_name)
859 3cebe102 Michael Hanselmann
    msg = result.fail_msg
860 c8457ce7 Iustin Pop
    if msg:
861 c8457ce7 Iustin Pop
      logging.warning("Cannot cleanup queue directory on node %s: %s",
862 c8457ce7 Iustin Pop
                      node_name, msg)
863 23752136 Michael Hanselmann
864 59303563 Iustin Pop
    if not node.master_candidate:
865 59303563 Iustin Pop
      # remove if existing, ignoring errors
866 59303563 Iustin Pop
      self._nodes.pop(node_name, None)
867 59303563 Iustin Pop
      # and skip the replication of the job ids
868 59303563 Iustin Pop
      return
869 59303563 Iustin Pop
870 d2e03a33 Michael Hanselmann
    # Upload the whole queue excluding archived jobs
871 d2e03a33 Michael Hanselmann
    files = [self._GetJobPath(job_id) for job_id in self._GetJobIDsUnlocked()]
872 23752136 Michael Hanselmann
873 d2e03a33 Michael Hanselmann
    # Upload current serial file
874 d2e03a33 Michael Hanselmann
    files.append(constants.JOB_QUEUE_SERIAL_FILE)
875 d2e03a33 Michael Hanselmann
876 d2e03a33 Michael Hanselmann
    for file_name in files:
877 9f774ee8 Michael Hanselmann
      # Read file content
878 13998ef2 Michael Hanselmann
      content = utils.ReadFile(file_name)
879 9f774ee8 Michael Hanselmann
880 a3811745 Michael Hanselmann
      result = rpc.RpcRunner.call_jobqueue_update([node_name],
881 a3811745 Michael Hanselmann
                                                  [node.primary_ip],
882 a3811745 Michael Hanselmann
                                                  file_name, content)
883 3cebe102 Michael Hanselmann
      msg = result[node_name].fail_msg
884 c8457ce7 Iustin Pop
      if msg:
885 c8457ce7 Iustin Pop
        logging.error("Failed to upload file %s to node %s: %s",
886 c8457ce7 Iustin Pop
                      file_name, node_name, msg)
887 d2e03a33 Michael Hanselmann
888 99aabbed Iustin Pop
    self._nodes[node_name] = node.primary_ip
889 d2e03a33 Michael Hanselmann
890 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
891 d2e03a33 Michael Hanselmann
  @_RequireOpenQueue
892 d2e03a33 Michael Hanselmann
  def RemoveNode(self, node_name):
893 ea03467c Iustin Pop
    """Callback called when removing nodes from the cluster.
894 ea03467c Iustin Pop

895 ea03467c Iustin Pop
    @type node_name: str
896 ea03467c Iustin Pop
    @param node_name: the name of the node to remove
897 ea03467c Iustin Pop

898 ea03467c Iustin Pop
    """
899 d8e0dc17 Guido Trotter
    self._nodes.pop(node_name, None)
900 23752136 Michael Hanselmann
901 7e950d31 Iustin Pop
  @staticmethod
902 7e950d31 Iustin Pop
  def _CheckRpcResult(result, nodes, failmsg):
903 ea03467c Iustin Pop
    """Verifies the status of an RPC call.
904 ea03467c Iustin Pop

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

909 ea03467c Iustin Pop
    @param result: the data as returned from the rpc call
910 ea03467c Iustin Pop
    @type nodes: list
911 ea03467c Iustin Pop
    @param nodes: the list of nodes we made the call to
912 ea03467c Iustin Pop
    @type failmsg: str
913 ea03467c Iustin Pop
    @param failmsg: the identifier to be used for logging
914 ea03467c Iustin Pop

915 ea03467c Iustin Pop
    """
916 e74798c1 Michael Hanselmann
    failed = []
917 e74798c1 Michael Hanselmann
    success = []
918 e74798c1 Michael Hanselmann
919 e74798c1 Michael Hanselmann
    for node in nodes:
920 3cebe102 Michael Hanselmann
      msg = result[node].fail_msg
921 c8457ce7 Iustin Pop
      if msg:
922 e74798c1 Michael Hanselmann
        failed.append(node)
923 45e0d704 Iustin Pop
        logging.error("RPC call %s (%s) failed on node %s: %s",
924 45e0d704 Iustin Pop
                      result[node].call, failmsg, node, msg)
925 c8457ce7 Iustin Pop
      else:
926 c8457ce7 Iustin Pop
        success.append(node)
927 e74798c1 Michael Hanselmann
928 e74798c1 Michael Hanselmann
    # +1 for the master node
929 e74798c1 Michael Hanselmann
    if (len(success) + 1) < len(failed):
930 e74798c1 Michael Hanselmann
      # TODO: Handle failing nodes
931 e74798c1 Michael Hanselmann
      logging.error("More than half of the nodes failed")
932 e74798c1 Michael Hanselmann
933 99aabbed Iustin Pop
  def _GetNodeIp(self):
934 99aabbed Iustin Pop
    """Helper for returning the node name/ip list.
935 99aabbed Iustin Pop

936 ea03467c Iustin Pop
    @rtype: (list, list)
937 ea03467c Iustin Pop
    @return: a tuple of two lists, the first one with the node
938 ea03467c Iustin Pop
        names and the second one with the node addresses
939 ea03467c Iustin Pop

940 99aabbed Iustin Pop
    """
941 99aabbed Iustin Pop
    name_list = self._nodes.keys()
942 99aabbed Iustin Pop
    addr_list = [self._nodes[name] for name in name_list]
943 99aabbed Iustin Pop
    return name_list, addr_list
944 99aabbed Iustin Pop
945 4c36bdf5 Guido Trotter
  def _UpdateJobQueueFile(self, file_name, data, replicate):
946 8e00939c Michael Hanselmann
    """Writes a file locally and then replicates it to all nodes.
947 8e00939c Michael Hanselmann

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

951 ea03467c Iustin Pop
    @type file_name: str
952 ea03467c Iustin Pop
    @param file_name: the path of the file to be replicated
953 ea03467c Iustin Pop
    @type data: str
954 ea03467c Iustin Pop
    @param data: the new contents of the file
955 4c36bdf5 Guido Trotter
    @type replicate: boolean
956 4c36bdf5 Guido Trotter
    @param replicate: whether to spread the changes to the remote nodes
957 ea03467c Iustin Pop

958 8e00939c Michael Hanselmann
    """
959 8e00939c Michael Hanselmann
    utils.WriteFile(file_name, data=data)
960 8e00939c Michael Hanselmann
961 4c36bdf5 Guido Trotter
    if replicate:
962 4c36bdf5 Guido Trotter
      names, addrs = self._GetNodeIp()
963 4c36bdf5 Guido Trotter
      result = rpc.RpcRunner.call_jobqueue_update(names, addrs, file_name, data)
964 4c36bdf5 Guido Trotter
      self._CheckRpcResult(result, self._nodes, "Updating %s" % file_name)
965 23752136 Michael Hanselmann
966 d7fd1f28 Michael Hanselmann
  def _RenameFilesUnlocked(self, rename):
967 ea03467c Iustin Pop
    """Renames a file locally and then replicate the change.
968 ea03467c Iustin Pop

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

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

975 ea03467c Iustin Pop
    """
976 dd875d32 Michael Hanselmann
    # Rename them locally
977 d7fd1f28 Michael Hanselmann
    for old, new in rename:
978 d7fd1f28 Michael Hanselmann
      utils.RenameFile(old, new, mkdir=True)
979 abc1f2ce Michael Hanselmann
980 dd875d32 Michael Hanselmann
    # ... and on all nodes
981 dd875d32 Michael Hanselmann
    names, addrs = self._GetNodeIp()
982 dd875d32 Michael Hanselmann
    result = rpc.RpcRunner.call_jobqueue_rename(names, addrs, rename)
983 dd875d32 Michael Hanselmann
    self._CheckRpcResult(result, self._nodes, "Renaming files (%r)" % rename)
984 abc1f2ce Michael Hanselmann
985 7e950d31 Iustin Pop
  @staticmethod
986 7e950d31 Iustin Pop
  def _FormatJobID(job_id):
987 ea03467c Iustin Pop
    """Convert a job ID to string format.
988 ea03467c Iustin Pop

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

993 ea03467c Iustin Pop
    @type job_id: int or long
994 ea03467c Iustin Pop
    @param job_id: the numeric job id
995 ea03467c Iustin Pop
    @rtype: str
996 ea03467c Iustin Pop
    @return: the formatted job id
997 ea03467c Iustin Pop

998 ea03467c Iustin Pop
    """
999 85f03e0d Michael Hanselmann
    if not isinstance(job_id, (int, long)):
1000 85f03e0d Michael Hanselmann
      raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id)
1001 85f03e0d Michael Hanselmann
    if job_id < 0:
1002 85f03e0d Michael Hanselmann
      raise errors.ProgrammerError("Job ID %s is negative" % job_id)
1003 85f03e0d Michael Hanselmann
1004 85f03e0d Michael Hanselmann
    return str(job_id)
1005 85f03e0d Michael Hanselmann
1006 58b22b6e Michael Hanselmann
  @classmethod
1007 58b22b6e Michael Hanselmann
  def _GetArchiveDirectory(cls, job_id):
1008 58b22b6e Michael Hanselmann
    """Returns the archive directory for a job.
1009 58b22b6e Michael Hanselmann

1010 58b22b6e Michael Hanselmann
    @type job_id: str
1011 58b22b6e Michael Hanselmann
    @param job_id: Job identifier
1012 58b22b6e Michael Hanselmann
    @rtype: str
1013 58b22b6e Michael Hanselmann
    @return: Directory name
1014 58b22b6e Michael Hanselmann

1015 58b22b6e Michael Hanselmann
    """
1016 58b22b6e Michael Hanselmann
    return str(int(job_id) / JOBS_PER_ARCHIVE_DIRECTORY)
1017 58b22b6e Michael Hanselmann
1018 009e73d0 Iustin Pop
  def _NewSerialsUnlocked(self, count):
1019 f1da30e6 Michael Hanselmann
    """Generates a new job identifier.
1020 f1da30e6 Michael Hanselmann

1021 f1da30e6 Michael Hanselmann
    Job identifiers are unique during the lifetime of a cluster.
1022 f1da30e6 Michael Hanselmann

1023 009e73d0 Iustin Pop
    @type count: integer
1024 009e73d0 Iustin Pop
    @param count: how many serials to return
1025 ea03467c Iustin Pop
    @rtype: str
1026 ea03467c Iustin Pop
    @return: a string representing the job identifier.
1027 f1da30e6 Michael Hanselmann

1028 f1da30e6 Michael Hanselmann
    """
1029 009e73d0 Iustin Pop
    assert count > 0
1030 f1da30e6 Michael Hanselmann
    # New number
1031 009e73d0 Iustin Pop
    serial = self._last_serial + count
1032 f1da30e6 Michael Hanselmann
1033 f1da30e6 Michael Hanselmann
    # Write to file
1034 4c36bdf5 Guido Trotter
    self._UpdateJobQueueFile(constants.JOB_QUEUE_SERIAL_FILE,
1035 4c36bdf5 Guido Trotter
                             "%s\n" % serial, True)
1036 f1da30e6 Michael Hanselmann
1037 009e73d0 Iustin Pop
    result = [self._FormatJobID(v)
1038 009e73d0 Iustin Pop
              for v in range(self._last_serial, serial + 1)]
1039 f1da30e6 Michael Hanselmann
    # Keep it only if we were able to write the file
1040 f1da30e6 Michael Hanselmann
    self._last_serial = serial
1041 f1da30e6 Michael Hanselmann
1042 009e73d0 Iustin Pop
    return result
1043 f1da30e6 Michael Hanselmann
1044 85f03e0d Michael Hanselmann
  @staticmethod
1045 85f03e0d Michael Hanselmann
  def _GetJobPath(job_id):
1046 ea03467c Iustin Pop
    """Returns the job file for a given job id.
1047 ea03467c Iustin Pop

1048 ea03467c Iustin Pop
    @type job_id: str
1049 ea03467c Iustin Pop
    @param job_id: the job identifier
1050 ea03467c Iustin Pop
    @rtype: str
1051 ea03467c Iustin Pop
    @return: the path to the job file
1052 ea03467c Iustin Pop

1053 ea03467c Iustin Pop
    """
1054 c4feafe8 Iustin Pop
    return utils.PathJoin(constants.QUEUE_DIR, "job-%s" % job_id)
1055 f1da30e6 Michael Hanselmann
1056 58b22b6e Michael Hanselmann
  @classmethod
1057 58b22b6e Michael Hanselmann
  def _GetArchivedJobPath(cls, job_id):
1058 ea03467c Iustin Pop
    """Returns the archived job file for a give job id.
1059 ea03467c Iustin Pop

1060 ea03467c Iustin Pop
    @type job_id: str
1061 ea03467c Iustin Pop
    @param job_id: the job identifier
1062 ea03467c Iustin Pop
    @rtype: str
1063 ea03467c Iustin Pop
    @return: the path to the archived job file
1064 ea03467c Iustin Pop

1065 ea03467c Iustin Pop
    """
1066 0411c011 Iustin Pop
    return utils.PathJoin(constants.JOB_QUEUE_ARCHIVE_DIR,
1067 0411c011 Iustin Pop
                          cls._GetArchiveDirectory(job_id), "job-%s" % job_id)
1068 0cb94105 Michael Hanselmann
1069 85a1c57d Guido Trotter
  def _GetJobIDsUnlocked(self, sort=True):
1070 911a495b Iustin Pop
    """Return all known job IDs.
1071 911a495b Iustin Pop

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

1076 85a1c57d Guido Trotter
    @type sort: boolean
1077 85a1c57d Guido Trotter
    @param sort: perform sorting on the returned job ids
1078 ea03467c Iustin Pop
    @rtype: list
1079 ea03467c Iustin Pop
    @return: the list of job IDs
1080 ea03467c Iustin Pop

1081 911a495b Iustin Pop
    """
1082 85a1c57d Guido Trotter
    jlist = []
1083 b5b8309d Guido Trotter
    for filename in utils.ListVisibleFiles(constants.QUEUE_DIR):
1084 85a1c57d Guido Trotter
      m = self._RE_JOB_FILE.match(filename)
1085 85a1c57d Guido Trotter
      if m:
1086 85a1c57d Guido Trotter
        jlist.append(m.group(1))
1087 85a1c57d Guido Trotter
    if sort:
1088 85a1c57d Guido Trotter
      jlist = utils.NiceSort(jlist)
1089 f0d874fe Iustin Pop
    return jlist
1090 911a495b Iustin Pop
1091 911a495b Iustin Pop
  def _LoadJobUnlocked(self, job_id):
1092 ea03467c Iustin Pop
    """Loads a job from the disk or memory.
1093 ea03467c Iustin Pop

1094 ea03467c Iustin Pop
    Given a job id, this will return the cached job object if
1095 ea03467c Iustin Pop
    existing, or try to load the job from the disk. If loading from
1096 ea03467c Iustin Pop
    disk, it will also add the job to the cache.
1097 ea03467c Iustin Pop

1098 ea03467c Iustin Pop
    @param job_id: the job id
1099 ea03467c Iustin Pop
    @rtype: L{_QueuedJob} or None
1100 ea03467c Iustin Pop
    @return: either None or the job object
1101 ea03467c Iustin Pop

1102 ea03467c Iustin Pop
    """
1103 5685c1a5 Michael Hanselmann
    job = self._memcache.get(job_id, None)
1104 5685c1a5 Michael Hanselmann
    if job:
1105 205d71fd Michael Hanselmann
      logging.debug("Found job %s in memcache", job_id)
1106 5685c1a5 Michael Hanselmann
      return job
1107 ac0930b9 Iustin Pop
1108 3d6c5566 Guido Trotter
    try:
1109 3d6c5566 Guido Trotter
      job = self._LoadJobFromDisk(job_id)
1110 3d6c5566 Guido Trotter
    except errors.JobFileCorrupted:
1111 3d6c5566 Guido Trotter
      old_path = self._GetJobPath(job_id)
1112 3d6c5566 Guido Trotter
      new_path = self._GetArchivedJobPath(job_id)
1113 3d6c5566 Guido Trotter
      if old_path == new_path:
1114 3d6c5566 Guido Trotter
        # job already archived (future case)
1115 3d6c5566 Guido Trotter
        logging.exception("Can't parse job %s", job_id)
1116 3d6c5566 Guido Trotter
      else:
1117 3d6c5566 Guido Trotter
        # non-archived case
1118 3d6c5566 Guido Trotter
        logging.exception("Can't parse job %s, will archive.", job_id)
1119 3d6c5566 Guido Trotter
        self._RenameFilesUnlocked([(old_path, new_path)])
1120 3d6c5566 Guido Trotter
      return None
1121 162c8636 Guido Trotter
1122 162c8636 Guido Trotter
    self._memcache[job_id] = job
1123 162c8636 Guido Trotter
    logging.debug("Added job %s to the cache", job_id)
1124 162c8636 Guido Trotter
    return job
1125 162c8636 Guido Trotter
1126 162c8636 Guido Trotter
  def _LoadJobFromDisk(self, job_id):
1127 162c8636 Guido Trotter
    """Load the given job file from disk.
1128 162c8636 Guido Trotter

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

1131 162c8636 Guido Trotter
    @type job_id: string
1132 162c8636 Guido Trotter
    @param job_id: job identifier
1133 162c8636 Guido Trotter
    @rtype: L{_QueuedJob} or None
1134 162c8636 Guido Trotter
    @return: either None or the job object
1135 162c8636 Guido Trotter

1136 162c8636 Guido Trotter
    """
1137 911a495b Iustin Pop
    filepath = self._GetJobPath(job_id)
1138 f1da30e6 Michael Hanselmann
    logging.debug("Loading job from %s", filepath)
1139 f1da30e6 Michael Hanselmann
    try:
1140 13998ef2 Michael Hanselmann
      raw_data = utils.ReadFile(filepath)
1141 162c8636 Guido Trotter
    except EnvironmentError, err:
1142 f1da30e6 Michael Hanselmann
      if err.errno in (errno.ENOENT, ):
1143 f1da30e6 Michael Hanselmann
        return None
1144 f1da30e6 Michael Hanselmann
      raise
1145 13998ef2 Michael Hanselmann
1146 94ed59a5 Iustin Pop
    try:
1147 162c8636 Guido Trotter
      data = serializer.LoadJson(raw_data)
1148 94ed59a5 Iustin Pop
      job = _QueuedJob.Restore(self, data)
1149 7260cfbe Iustin Pop
    except Exception, err: # pylint: disable-msg=W0703
1150 3d6c5566 Guido Trotter
      raise errors.JobFileCorrupted(err)
1151 94ed59a5 Iustin Pop
1152 ac0930b9 Iustin Pop
    return job
1153 f1da30e6 Michael Hanselmann
1154 0f9c08dc Guido Trotter
  def SafeLoadJobFromDisk(self, job_id):
1155 0f9c08dc Guido Trotter
    """Load the given job file from disk.
1156 0f9c08dc Guido Trotter

1157 0f9c08dc Guido Trotter
    Given a job file, read, load and restore it in a _QueuedJob format.
1158 0f9c08dc Guido Trotter
    In case of error reading the job, it gets returned as None, and the
1159 0f9c08dc Guido Trotter
    exception is logged.
1160 0f9c08dc Guido Trotter

1161 0f9c08dc Guido Trotter
    @type job_id: string
1162 0f9c08dc Guido Trotter
    @param job_id: job identifier
1163 0f9c08dc Guido Trotter
    @rtype: L{_QueuedJob} or None
1164 0f9c08dc Guido Trotter
    @return: either None or the job object
1165 0f9c08dc Guido Trotter

1166 0f9c08dc Guido Trotter
    """
1167 0f9c08dc Guido Trotter
    try:
1168 0f9c08dc Guido Trotter
      return self._LoadJobFromDisk(job_id)
1169 0f9c08dc Guido Trotter
    except (errors.JobFileCorrupted, EnvironmentError):
1170 0f9c08dc Guido Trotter
      logging.exception("Can't load/parse job %s", job_id)
1171 0f9c08dc Guido Trotter
      return None
1172 0f9c08dc Guido Trotter
1173 686d7433 Iustin Pop
  @staticmethod
1174 686d7433 Iustin Pop
  def _IsQueueMarkedDrain():
1175 686d7433 Iustin Pop
    """Check if the queue is marked from drain.
1176 686d7433 Iustin Pop

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

1180 ea03467c Iustin Pop
    @rtype: boolean
1181 ea03467c Iustin Pop
    @return: True of the job queue is marked for draining
1182 ea03467c Iustin Pop

1183 686d7433 Iustin Pop
    """
1184 686d7433 Iustin Pop
    return os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
1185 686d7433 Iustin Pop
1186 20571a26 Guido Trotter
  def _UpdateQueueSizeUnlocked(self):
1187 20571a26 Guido Trotter
    """Update the queue size.
1188 20571a26 Guido Trotter

1189 20571a26 Guido Trotter
    """
1190 20571a26 Guido Trotter
    self._queue_size = len(self._GetJobIDsUnlocked(sort=False))
1191 20571a26 Guido Trotter
1192 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1193 20571a26 Guido Trotter
  @_RequireOpenQueue
1194 20571a26 Guido Trotter
  def SetDrainFlag(self, drain_flag):
1195 3ccafd0e Iustin Pop
    """Sets the drain flag for the queue.
1196 3ccafd0e Iustin Pop

1197 ea03467c Iustin Pop
    @type drain_flag: boolean
1198 5bbd3f7f Michael Hanselmann
    @param drain_flag: Whether to set or unset the drain flag
1199 ea03467c Iustin Pop

1200 3ccafd0e Iustin Pop
    """
1201 3ccafd0e Iustin Pop
    if drain_flag:
1202 3ccafd0e Iustin Pop
      utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
1203 3ccafd0e Iustin Pop
    else:
1204 3ccafd0e Iustin Pop
      utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
1205 20571a26 Guido Trotter
1206 20571a26 Guido Trotter
    self._drained = drain_flag
1207 20571a26 Guido Trotter
1208 3ccafd0e Iustin Pop
    return True
1209 3ccafd0e Iustin Pop
1210 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1211 009e73d0 Iustin Pop
  def _SubmitJobUnlocked(self, job_id, ops):
1212 85f03e0d Michael Hanselmann
    """Create and store a new job.
1213 f1da30e6 Michael Hanselmann

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

1217 009e73d0 Iustin Pop
    @type job_id: job ID
1218 69b99987 Michael Hanselmann
    @param job_id: the job ID for the new job
1219 c3f0a12f Iustin Pop
    @type ops: list
1220 205d71fd Michael Hanselmann
    @param ops: The list of OpCodes that will become the new job.
1221 7beb1e53 Guido Trotter
    @rtype: L{_QueuedJob}
1222 7beb1e53 Guido Trotter
    @return: the job object to be queued
1223 7beb1e53 Guido Trotter
    @raise errors.JobQueueDrainError: if the job queue is marked for draining
1224 7beb1e53 Guido Trotter
    @raise errors.JobQueueFull: if the job queue has too many jobs in it
1225 c3f0a12f Iustin Pop

1226 c3f0a12f Iustin Pop
    """
1227 20571a26 Guido Trotter
    # Ok when sharing the big job queue lock, as the drain file is created when
1228 20571a26 Guido Trotter
    # the lock is exclusive.
1229 20571a26 Guido Trotter
    if self._drained:
1230 2971c913 Iustin Pop
      raise errors.JobQueueDrainError("Job queue is drained, refusing job")
1231 f87b405e Michael Hanselmann
1232 20571a26 Guido Trotter
    if self._queue_size >= constants.JOB_QUEUE_SIZE_HARD_LIMIT:
1233 f87b405e Michael Hanselmann
      raise errors.JobQueueFull()
1234 f87b405e Michael Hanselmann
1235 f1da30e6 Michael Hanselmann
    job = _QueuedJob(self, job_id, ops)
1236 f1da30e6 Michael Hanselmann
1237 f1da30e6 Michael Hanselmann
    # Write to disk
1238 85f03e0d Michael Hanselmann
    self.UpdateJobUnlocked(job)
1239 f1da30e6 Michael Hanselmann
1240 20571a26 Guido Trotter
    self._queue_size += 1
1241 20571a26 Guido Trotter
1242 5685c1a5 Michael Hanselmann
    logging.debug("Adding new job %s to the cache", job_id)
1243 ac0930b9 Iustin Pop
    self._memcache[job_id] = job
1244 ac0930b9 Iustin Pop
1245 7beb1e53 Guido Trotter
    return job
1246 f1da30e6 Michael Hanselmann
1247 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1248 2971c913 Iustin Pop
  @_RequireOpenQueue
1249 2971c913 Iustin Pop
  def SubmitJob(self, ops):
1250 2971c913 Iustin Pop
    """Create and store a new job.
1251 2971c913 Iustin Pop

1252 2971c913 Iustin Pop
    @see: L{_SubmitJobUnlocked}
1253 2971c913 Iustin Pop

1254 2971c913 Iustin Pop
    """
1255 009e73d0 Iustin Pop
    job_id = self._NewSerialsUnlocked(1)[0]
1256 7beb1e53 Guido Trotter
    self._wpool.AddTask(self._SubmitJobUnlocked(job_id, ops))
1257 7beb1e53 Guido Trotter
    return job_id
1258 2971c913 Iustin Pop
1259 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1260 2971c913 Iustin Pop
  @_RequireOpenQueue
1261 2971c913 Iustin Pop
  def SubmitManyJobs(self, jobs):
1262 2971c913 Iustin Pop
    """Create and store multiple jobs.
1263 2971c913 Iustin Pop

1264 2971c913 Iustin Pop
    @see: L{_SubmitJobUnlocked}
1265 2971c913 Iustin Pop

1266 2971c913 Iustin Pop
    """
1267 2971c913 Iustin Pop
    results = []
1268 7beb1e53 Guido Trotter
    tasks = []
1269 009e73d0 Iustin Pop
    all_job_ids = self._NewSerialsUnlocked(len(jobs))
1270 009e73d0 Iustin Pop
    for job_id, ops in zip(all_job_ids, jobs):
1271 2971c913 Iustin Pop
      try:
1272 7beb1e53 Guido Trotter
        tasks.append((self._SubmitJobUnlocked(job_id, ops), ))
1273 2971c913 Iustin Pop
        status = True
1274 7beb1e53 Guido Trotter
        data = job_id
1275 2971c913 Iustin Pop
      except errors.GenericError, err:
1276 2971c913 Iustin Pop
        data = str(err)
1277 2971c913 Iustin Pop
        status = False
1278 2971c913 Iustin Pop
      results.append((status, data))
1279 7beb1e53 Guido Trotter
    self._wpool.AddManyTasks(tasks)
1280 2971c913 Iustin Pop
1281 2971c913 Iustin Pop
    return results
1282 2971c913 Iustin Pop
1283 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1284 4c36bdf5 Guido Trotter
  def UpdateJobUnlocked(self, job, replicate=True):
1285 ea03467c Iustin Pop
    """Update a job's on disk storage.
1286 ea03467c Iustin Pop

1287 ea03467c Iustin Pop
    After a job has been modified, this function needs to be called in
1288 ea03467c Iustin Pop
    order to write the changes to disk and replicate them to the other
1289 ea03467c Iustin Pop
    nodes.
1290 ea03467c Iustin Pop

1291 ea03467c Iustin Pop
    @type job: L{_QueuedJob}
1292 ea03467c Iustin Pop
    @param job: the changed job
1293 4c36bdf5 Guido Trotter
    @type replicate: boolean
1294 4c36bdf5 Guido Trotter
    @param replicate: whether to replicate the change to remote nodes
1295 ea03467c Iustin Pop

1296 ea03467c Iustin Pop
    """
1297 f1da30e6 Michael Hanselmann
    filename = self._GetJobPath(job.id)
1298 23752136 Michael Hanselmann
    data = serializer.DumpJson(job.Serialize(), indent=False)
1299 f1da30e6 Michael Hanselmann
    logging.debug("Writing job %s to %s", job.id, filename)
1300 4c36bdf5 Guido Trotter
    self._UpdateJobQueueFile(filename, data, replicate)
1301 ac0930b9 Iustin Pop
1302 5c735209 Iustin Pop
  def WaitForJobChanges(self, job_id, fields, prev_job_info, prev_log_serial,
1303 5c735209 Iustin Pop
                        timeout):
1304 6c5a7090 Michael Hanselmann
    """Waits for changes in a job.
1305 6c5a7090 Michael Hanselmann

1306 6c5a7090 Michael Hanselmann
    @type job_id: string
1307 6c5a7090 Michael Hanselmann
    @param job_id: Job identifier
1308 6c5a7090 Michael Hanselmann
    @type fields: list of strings
1309 6c5a7090 Michael Hanselmann
    @param fields: Which fields to check for changes
1310 6c5a7090 Michael Hanselmann
    @type prev_job_info: list or None
1311 6c5a7090 Michael Hanselmann
    @param prev_job_info: Last job information returned
1312 6c5a7090 Michael Hanselmann
    @type prev_log_serial: int
1313 6c5a7090 Michael Hanselmann
    @param prev_log_serial: Last job message serial number
1314 5c735209 Iustin Pop
    @type timeout: float
1315 5c735209 Iustin Pop
    @param timeout: maximum time to wait
1316 ea03467c Iustin Pop
    @rtype: tuple (job info, log entries)
1317 ea03467c Iustin Pop
    @return: a tuple of the job information as required via
1318 ea03467c Iustin Pop
        the fields parameter, and the log entries as a list
1319 ea03467c Iustin Pop

1320 ea03467c Iustin Pop
        if the job has not changed and the timeout has expired,
1321 ea03467c Iustin Pop
        we instead return a special value,
1322 ea03467c Iustin Pop
        L{constants.JOB_NOTCHANGED}, which should be interpreted
1323 ea03467c Iustin Pop
        as such by the clients
1324 6c5a7090 Michael Hanselmann

1325 6c5a7090 Michael Hanselmann
    """
1326 6c2549d6 Guido Trotter
    helper = _WaitForJobChangesHelper(job_id, fields, prev_job_info,
1327 6c2549d6 Guido Trotter
                                      prev_log_serial, self)
1328 6bcb1446 Michael Hanselmann
    try:
1329 6c2549d6 Guido Trotter
      return helper.WaitForChanges(timeout)
1330 6c2549d6 Guido Trotter
    finally:
1331 6c2549d6 Guido Trotter
      helper.Close()
1332 dfe57c22 Michael Hanselmann
1333 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1334 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1335 188c5e0a Michael Hanselmann
  def CancelJob(self, job_id):
1336 188c5e0a Michael Hanselmann
    """Cancels a job.
1337 188c5e0a Michael Hanselmann

1338 ea03467c Iustin Pop
    This will only succeed if the job has not started yet.
1339 ea03467c Iustin Pop

1340 188c5e0a Michael Hanselmann
    @type job_id: string
1341 ea03467c Iustin Pop
    @param job_id: job ID of job to be cancelled.
1342 188c5e0a Michael Hanselmann

1343 188c5e0a Michael Hanselmann
    """
1344 fbf0262f Michael Hanselmann
    logging.info("Cancelling job %s", job_id)
1345 188c5e0a Michael Hanselmann
1346 85f03e0d Michael Hanselmann
    job = self._LoadJobUnlocked(job_id)
1347 188c5e0a Michael Hanselmann
    if not job:
1348 188c5e0a Michael Hanselmann
      logging.debug("Job %s not found", job_id)
1349 fbf0262f Michael Hanselmann
      return (False, "Job %s not found" % job_id)
1350 fbf0262f Michael Hanselmann
1351 fbf0262f Michael Hanselmann
    job_status = job.CalcStatus()
1352 188c5e0a Michael Hanselmann
1353 fbf0262f Michael Hanselmann
    if job_status not in (constants.JOB_STATUS_QUEUED,
1354 fbf0262f Michael Hanselmann
                          constants.JOB_STATUS_WAITLOCK):
1355 a9e97393 Michael Hanselmann
      logging.debug("Job %s is no longer waiting in the queue", job.id)
1356 a9e97393 Michael Hanselmann
      return (False, "Job %s is no longer waiting in the queue" % job.id)
1357 fbf0262f Michael Hanselmann
1358 fbf0262f Michael Hanselmann
    if job_status == constants.JOB_STATUS_QUEUED:
1359 39ed3a98 Guido Trotter
      job.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
1360 39ed3a98 Guido Trotter
                            "Job canceled by request")
1361 fbf0262f Michael Hanselmann
      return (True, "Job %s canceled" % job.id)
1362 188c5e0a Michael Hanselmann
1363 fbf0262f Michael Hanselmann
    elif job_status == constants.JOB_STATUS_WAITLOCK:
1364 fbf0262f Michael Hanselmann
      # The worker will notice the new status and cancel the job
1365 39ed3a98 Guido Trotter
      job.MarkUnfinishedOps(constants.OP_STATUS_CANCELING, None)
1366 fbf0262f Michael Hanselmann
      return (True, "Job %s will be canceled" % job.id)
1367 fbf0262f Michael Hanselmann
1368 fbf0262f Michael Hanselmann
  @_RequireOpenQueue
1369 d7fd1f28 Michael Hanselmann
  def _ArchiveJobsUnlocked(self, jobs):
1370 d7fd1f28 Michael Hanselmann
    """Archives jobs.
1371 c609f802 Michael Hanselmann

1372 d7fd1f28 Michael Hanselmann
    @type jobs: list of L{_QueuedJob}
1373 25e7b43f Iustin Pop
    @param jobs: Job objects
1374 d7fd1f28 Michael Hanselmann
    @rtype: int
1375 d7fd1f28 Michael Hanselmann
    @return: Number of archived jobs
1376 c609f802 Michael Hanselmann

1377 c609f802 Michael Hanselmann
    """
1378 d7fd1f28 Michael Hanselmann
    archive_jobs = []
1379 d7fd1f28 Michael Hanselmann
    rename_files = []
1380 d7fd1f28 Michael Hanselmann
    for job in jobs:
1381 d7fd1f28 Michael Hanselmann
      if job.CalcStatus() not in (constants.JOB_STATUS_CANCELED,
1382 d7fd1f28 Michael Hanselmann
                                  constants.JOB_STATUS_SUCCESS,
1383 d7fd1f28 Michael Hanselmann
                                  constants.JOB_STATUS_ERROR):
1384 d7fd1f28 Michael Hanselmann
        logging.debug("Job %s is not yet done", job.id)
1385 d7fd1f28 Michael Hanselmann
        continue
1386 c609f802 Michael Hanselmann
1387 d7fd1f28 Michael Hanselmann
      archive_jobs.append(job)
1388 c609f802 Michael Hanselmann
1389 d7fd1f28 Michael Hanselmann
      old = self._GetJobPath(job.id)
1390 d7fd1f28 Michael Hanselmann
      new = self._GetArchivedJobPath(job.id)
1391 d7fd1f28 Michael Hanselmann
      rename_files.append((old, new))
1392 c609f802 Michael Hanselmann
1393 d7fd1f28 Michael Hanselmann
    # TODO: What if 1..n files fail to rename?
1394 d7fd1f28 Michael Hanselmann
    self._RenameFilesUnlocked(rename_files)
1395 f1da30e6 Michael Hanselmann
1396 d7fd1f28 Michael Hanselmann
    logging.debug("Successfully archived job(s) %s",
1397 1f864b60 Iustin Pop
                  utils.CommaJoin(job.id for job in archive_jobs))
1398 d7fd1f28 Michael Hanselmann
1399 20571a26 Guido Trotter
    # Since we haven't quite checked, above, if we succeeded or failed renaming
1400 20571a26 Guido Trotter
    # the files, we update the cached queue size from the filesystem. When we
1401 20571a26 Guido Trotter
    # get around to fix the TODO: above, we can use the number of actually
1402 20571a26 Guido Trotter
    # archived jobs to fix this.
1403 20571a26 Guido Trotter
    self._UpdateQueueSizeUnlocked()
1404 d7fd1f28 Michael Hanselmann
    return len(archive_jobs)
1405 78d12585 Michael Hanselmann
1406 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1407 07cd723a Iustin Pop
  @_RequireOpenQueue
1408 07cd723a Iustin Pop
  def ArchiveJob(self, job_id):
1409 07cd723a Iustin Pop
    """Archives a job.
1410 07cd723a Iustin Pop

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

1413 07cd723a Iustin Pop
    @type job_id: string
1414 07cd723a Iustin Pop
    @param job_id: Job ID of job to be archived.
1415 78d12585 Michael Hanselmann
    @rtype: bool
1416 78d12585 Michael Hanselmann
    @return: Whether job was archived
1417 07cd723a Iustin Pop

1418 07cd723a Iustin Pop
    """
1419 78d12585 Michael Hanselmann
    logging.info("Archiving job %s", job_id)
1420 78d12585 Michael Hanselmann
1421 78d12585 Michael Hanselmann
    job = self._LoadJobUnlocked(job_id)
1422 78d12585 Michael Hanselmann
    if not job:
1423 78d12585 Michael Hanselmann
      logging.debug("Job %s not found", job_id)
1424 78d12585 Michael Hanselmann
      return False
1425 78d12585 Michael Hanselmann
1426 5278185a Iustin Pop
    return self._ArchiveJobsUnlocked([job]) == 1
1427 07cd723a Iustin Pop
1428 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1429 07cd723a Iustin Pop
  @_RequireOpenQueue
1430 f8ad5591 Michael Hanselmann
  def AutoArchiveJobs(self, age, timeout):
1431 07cd723a Iustin Pop
    """Archives all jobs based on age.
1432 07cd723a Iustin Pop

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

1438 07cd723a Iustin Pop
    @type age: int
1439 07cd723a Iustin Pop
    @param age: the minimum age in seconds
1440 07cd723a Iustin Pop

1441 07cd723a Iustin Pop
    """
1442 07cd723a Iustin Pop
    logging.info("Archiving jobs with age more than %s seconds", age)
1443 07cd723a Iustin Pop
1444 07cd723a Iustin Pop
    now = time.time()
1445 f8ad5591 Michael Hanselmann
    end_time = now + timeout
1446 f8ad5591 Michael Hanselmann
    archived_count = 0
1447 f8ad5591 Michael Hanselmann
    last_touched = 0
1448 f8ad5591 Michael Hanselmann
1449 69b03fd7 Guido Trotter
    all_job_ids = self._GetJobIDsUnlocked()
1450 d7fd1f28 Michael Hanselmann
    pending = []
1451 f8ad5591 Michael Hanselmann
    for idx, job_id in enumerate(all_job_ids):
1452 d2c8afb1 Michael Hanselmann
      last_touched = idx + 1
1453 f8ad5591 Michael Hanselmann
1454 d7fd1f28 Michael Hanselmann
      # Not optimal because jobs could be pending
1455 d7fd1f28 Michael Hanselmann
      # TODO: Measure average duration for job archival and take number of
1456 d7fd1f28 Michael Hanselmann
      # pending jobs into account.
1457 f8ad5591 Michael Hanselmann
      if time.time() > end_time:
1458 f8ad5591 Michael Hanselmann
        break
1459 f8ad5591 Michael Hanselmann
1460 78d12585 Michael Hanselmann
      # Returns None if the job failed to load
1461 78d12585 Michael Hanselmann
      job = self._LoadJobUnlocked(job_id)
1462 f8ad5591 Michael Hanselmann
      if job:
1463 f8ad5591 Michael Hanselmann
        if job.end_timestamp is None:
1464 f8ad5591 Michael Hanselmann
          if job.start_timestamp is None:
1465 f8ad5591 Michael Hanselmann
            job_age = job.received_timestamp
1466 f8ad5591 Michael Hanselmann
          else:
1467 f8ad5591 Michael Hanselmann
            job_age = job.start_timestamp
1468 07cd723a Iustin Pop
        else:
1469 f8ad5591 Michael Hanselmann
          job_age = job.end_timestamp
1470 f8ad5591 Michael Hanselmann
1471 f8ad5591 Michael Hanselmann
        if age == -1 or now - job_age[0] > age:
1472 d7fd1f28 Michael Hanselmann
          pending.append(job)
1473 d7fd1f28 Michael Hanselmann
1474 d7fd1f28 Michael Hanselmann
          # Archive 10 jobs at a time
1475 d7fd1f28 Michael Hanselmann
          if len(pending) >= 10:
1476 d7fd1f28 Michael Hanselmann
            archived_count += self._ArchiveJobsUnlocked(pending)
1477 d7fd1f28 Michael Hanselmann
            pending = []
1478 f8ad5591 Michael Hanselmann
1479 d7fd1f28 Michael Hanselmann
    if pending:
1480 d7fd1f28 Michael Hanselmann
      archived_count += self._ArchiveJobsUnlocked(pending)
1481 07cd723a Iustin Pop
1482 d2c8afb1 Michael Hanselmann
    return (archived_count, len(all_job_ids) - last_touched)
1483 07cd723a Iustin Pop
1484 e2715f69 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1485 e2715f69 Michael Hanselmann
    """Returns a list of jobs in queue.
1486 e2715f69 Michael Hanselmann

1487 ea03467c Iustin Pop
    @type job_ids: list
1488 ea03467c Iustin Pop
    @param job_ids: sequence of job identifiers or None for all
1489 ea03467c Iustin Pop
    @type fields: list
1490 ea03467c Iustin Pop
    @param fields: names of fields to return
1491 ea03467c Iustin Pop
    @rtype: list
1492 ea03467c Iustin Pop
    @return: list one element per job, each element being list with
1493 ea03467c Iustin Pop
        the requested fields
1494 e2715f69 Michael Hanselmann

1495 e2715f69 Michael Hanselmann
    """
1496 85f03e0d Michael Hanselmann
    jobs = []
1497 9f7b4967 Guido Trotter
    list_all = False
1498 9f7b4967 Guido Trotter
    if not job_ids:
1499 9f7b4967 Guido Trotter
      # Since files are added to/removed from the queue atomically, there's no
1500 9f7b4967 Guido Trotter
      # risk of getting the job ids in an inconsistent state.
1501 9f7b4967 Guido Trotter
      job_ids = self._GetJobIDsUnlocked()
1502 9f7b4967 Guido Trotter
      list_all = True
1503 e2715f69 Michael Hanselmann
1504 9f7b4967 Guido Trotter
    for job_id in job_ids:
1505 9f7b4967 Guido Trotter
      job = self.SafeLoadJobFromDisk(job_id)
1506 9f7b4967 Guido Trotter
      if job is not None:
1507 6a290889 Guido Trotter
        jobs.append(job.GetInfo(fields))
1508 9f7b4967 Guido Trotter
      elif not list_all:
1509 9f7b4967 Guido Trotter
        jobs.append(None)
1510 e2715f69 Michael Hanselmann
1511 85f03e0d Michael Hanselmann
    return jobs
1512 e2715f69 Michael Hanselmann
1513 ebb80afa Guido Trotter
  @locking.ssynchronized(_LOCK)
1514 db37da70 Michael Hanselmann
  @_RequireOpenQueue
1515 e2715f69 Michael Hanselmann
  def Shutdown(self):
1516 e2715f69 Michael Hanselmann
    """Stops the job queue.
1517 e2715f69 Michael Hanselmann

1518 ea03467c Iustin Pop
    This shutdowns all the worker threads an closes the queue.
1519 ea03467c Iustin Pop

1520 e2715f69 Michael Hanselmann
    """
1521 e2715f69 Michael Hanselmann
    self._wpool.TerminateWorkers()
1522 85f03e0d Michael Hanselmann
1523 a71f9c7d Guido Trotter
    self._queue_filelock.Close()
1524 a71f9c7d Guido Trotter
    self._queue_filelock = None