root / lib / jqueue.py @ be760ba8
History | View | Annotate | Download (53.4 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Google Inc.
|
5 |
#
|
6 |
# This program is free software; you can redistribute it and/or modify
|
7 |
# it under the terms of the GNU General Public License as published by
|
8 |
# the Free Software Foundation; either version 2 of the License, or
|
9 |
# (at your option) any later version.
|
10 |
#
|
11 |
# This program is distributed in the hope that it will be useful, but
|
12 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 |
# General Public License for more details.
|
15 |
#
|
16 |
# You should have received a copy of the GNU General Public License
|
17 |
# along with this program; if not, write to the Free Software
|
18 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
|
22 |
"""Module implementing the job queue handling.
|
23 |
|
24 |
Locking: there's a single, large lock in the L{JobQueue} class. It's
|
25 |
used by all other classes in this module.
|
26 |
|
27 |
@var JOBQUEUE_THREADS: the number of worker threads we start for
|
28 |
processing jobs
|
29 |
|
30 |
"""
|
31 |
|
32 |
import os |
33 |
import logging |
34 |
import errno |
35 |
import re |
36 |
import time |
37 |
import weakref |
38 |
|
39 |
try:
|
40 |
# pylint: disable-msg=E0611
|
41 |
from pyinotify import pyinotify |
42 |
except ImportError: |
43 |
import pyinotify |
44 |
|
45 |
from ganeti import asyncnotifier |
46 |
from ganeti import constants |
47 |
from ganeti import serializer |
48 |
from ganeti import workerpool |
49 |
from ganeti import locking |
50 |
from ganeti import opcodes |
51 |
from ganeti import errors |
52 |
from ganeti import mcpu |
53 |
from ganeti import utils |
54 |
from ganeti import jstore |
55 |
from ganeti import rpc |
56 |
from ganeti import runtime |
57 |
from ganeti import netutils |
58 |
from ganeti import compat |
59 |
|
60 |
|
61 |
JOBQUEUE_THREADS = 25
|
62 |
JOBS_PER_ARCHIVE_DIRECTORY = 10000
|
63 |
|
64 |
# member lock names to be passed to @ssynchronized decorator
|
65 |
_LOCK = "_lock"
|
66 |
_QUEUE = "_queue"
|
67 |
|
68 |
|
69 |
class CancelJob(Exception): |
70 |
"""Special exception to cancel a job.
|
71 |
|
72 |
"""
|
73 |
|
74 |
|
75 |
def TimeStampNow(): |
76 |
"""Returns the current timestamp.
|
77 |
|
78 |
@rtype: tuple
|
79 |
@return: the current time in the (seconds, microseconds) format
|
80 |
|
81 |
"""
|
82 |
return utils.SplitTime(time.time())
|
83 |
|
84 |
|
85 |
class _QueuedOpCode(object): |
86 |
"""Encapsulates an opcode object.
|
87 |
|
88 |
@ivar log: holds the execution log and consists of tuples
|
89 |
of the form C{(log_serial, timestamp, level, message)}
|
90 |
@ivar input: the OpCode we encapsulate
|
91 |
@ivar status: the current status
|
92 |
@ivar result: the result of the LU execution
|
93 |
@ivar start_timestamp: timestamp for the start of the execution
|
94 |
@ivar exec_timestamp: timestamp for the actual LU Exec() function invocation
|
95 |
@ivar stop_timestamp: timestamp for the end of the execution
|
96 |
|
97 |
"""
|
98 |
__slots__ = ["input", "status", "result", "log", "priority", |
99 |
"start_timestamp", "exec_timestamp", "end_timestamp", |
100 |
"__weakref__"]
|
101 |
|
102 |
def __init__(self, op): |
103 |
"""Constructor for the _QuededOpCode.
|
104 |
|
105 |
@type op: L{opcodes.OpCode}
|
106 |
@param op: the opcode we encapsulate
|
107 |
|
108 |
"""
|
109 |
self.input = op
|
110 |
self.status = constants.OP_STATUS_QUEUED
|
111 |
self.result = None |
112 |
self.log = []
|
113 |
self.start_timestamp = None |
114 |
self.exec_timestamp = None |
115 |
self.end_timestamp = None |
116 |
|
117 |
# Get initial priority (it might change during the lifetime of this opcode)
|
118 |
self.priority = getattr(op, "priority", constants.OP_PRIO_DEFAULT) |
119 |
|
120 |
@classmethod
|
121 |
def Restore(cls, state): |
122 |
"""Restore the _QueuedOpCode from the serialized form.
|
123 |
|
124 |
@type state: dict
|
125 |
@param state: the serialized state
|
126 |
@rtype: _QueuedOpCode
|
127 |
@return: a new _QueuedOpCode instance
|
128 |
|
129 |
"""
|
130 |
obj = _QueuedOpCode.__new__(cls) |
131 |
obj.input = opcodes.OpCode.LoadOpCode(state["input"])
|
132 |
obj.status = state["status"]
|
133 |
obj.result = state["result"]
|
134 |
obj.log = state["log"]
|
135 |
obj.start_timestamp = state.get("start_timestamp", None) |
136 |
obj.exec_timestamp = state.get("exec_timestamp", None) |
137 |
obj.end_timestamp = state.get("end_timestamp", None) |
138 |
obj.priority = state.get("priority", constants.OP_PRIO_DEFAULT)
|
139 |
return obj
|
140 |
|
141 |
def Serialize(self): |
142 |
"""Serializes this _QueuedOpCode.
|
143 |
|
144 |
@rtype: dict
|
145 |
@return: the dictionary holding the serialized state
|
146 |
|
147 |
"""
|
148 |
return {
|
149 |
"input": self.input.__getstate__(), |
150 |
"status": self.status, |
151 |
"result": self.result, |
152 |
"log": self.log, |
153 |
"start_timestamp": self.start_timestamp, |
154 |
"exec_timestamp": self.exec_timestamp, |
155 |
"end_timestamp": self.end_timestamp, |
156 |
"priority": self.priority, |
157 |
} |
158 |
|
159 |
|
160 |
class _QueuedJob(object): |
161 |
"""In-memory job representation.
|
162 |
|
163 |
This is what we use to track the user-submitted jobs. Locking must
|
164 |
be taken care of by users of this class.
|
165 |
|
166 |
@type queue: L{JobQueue}
|
167 |
@ivar queue: the parent queue
|
168 |
@ivar id: the job ID
|
169 |
@type ops: list
|
170 |
@ivar ops: the list of _QueuedOpCode that constitute the job
|
171 |
@type log_serial: int
|
172 |
@ivar log_serial: holds the index for the next log entry
|
173 |
@ivar received_timestamp: the timestamp for when the job was received
|
174 |
@ivar start_timestmap: the timestamp for start of execution
|
175 |
@ivar end_timestamp: the timestamp for end of execution
|
176 |
|
177 |
"""
|
178 |
# pylint: disable-msg=W0212
|
179 |
__slots__ = ["queue", "id", "ops", "log_serial", "current_op", |
180 |
"received_timestamp", "start_timestamp", "end_timestamp", |
181 |
"__weakref__"]
|
182 |
|
183 |
def __init__(self, queue, job_id, ops): |
184 |
"""Constructor for the _QueuedJob.
|
185 |
|
186 |
@type queue: L{JobQueue}
|
187 |
@param queue: our parent queue
|
188 |
@type job_id: job_id
|
189 |
@param job_id: our job id
|
190 |
@type ops: list
|
191 |
@param ops: the list of opcodes we hold, which will be encapsulated
|
192 |
in _QueuedOpCodes
|
193 |
|
194 |
"""
|
195 |
if not ops: |
196 |
raise errors.GenericError("A job needs at least one opcode") |
197 |
|
198 |
self.queue = queue
|
199 |
self.id = job_id
|
200 |
self.ops = [_QueuedOpCode(op) for op in ops] |
201 |
self.log_serial = 0 |
202 |
self.received_timestamp = TimeStampNow()
|
203 |
self.start_timestamp = None |
204 |
self.end_timestamp = None |
205 |
|
206 |
self.current_op = None |
207 |
|
208 |
def __repr__(self): |
209 |
status = ["%s.%s" % (self.__class__.__module__, self.__class__.__name__), |
210 |
"id=%s" % self.id, |
211 |
"ops=%s" % ",".join([op.input.Summary() for op in self.ops])] |
212 |
|
213 |
return "<%s at %#x>" % (" ".join(status), id(self)) |
214 |
|
215 |
@classmethod
|
216 |
def Restore(cls, queue, state): |
217 |
"""Restore a _QueuedJob from serialized state:
|
218 |
|
219 |
@type queue: L{JobQueue}
|
220 |
@param queue: to which queue the restored job belongs
|
221 |
@type state: dict
|
222 |
@param state: the serialized state
|
223 |
@rtype: _JobQueue
|
224 |
@return: the restored _JobQueue instance
|
225 |
|
226 |
"""
|
227 |
obj = _QueuedJob.__new__(cls) |
228 |
obj.queue = queue |
229 |
obj.id = state["id"]
|
230 |
obj.received_timestamp = state.get("received_timestamp", None) |
231 |
obj.start_timestamp = state.get("start_timestamp", None) |
232 |
obj.end_timestamp = state.get("end_timestamp", None) |
233 |
|
234 |
obj.ops = [] |
235 |
obj.log_serial = 0
|
236 |
for op_state in state["ops"]: |
237 |
op = _QueuedOpCode.Restore(op_state) |
238 |
for log_entry in op.log: |
239 |
obj.log_serial = max(obj.log_serial, log_entry[0]) |
240 |
obj.ops.append(op) |
241 |
|
242 |
obj.current_op = None
|
243 |
|
244 |
return obj
|
245 |
|
246 |
def Serialize(self): |
247 |
"""Serialize the _JobQueue instance.
|
248 |
|
249 |
@rtype: dict
|
250 |
@return: the serialized state
|
251 |
|
252 |
"""
|
253 |
return {
|
254 |
"id": self.id, |
255 |
"ops": [op.Serialize() for op in self.ops], |
256 |
"start_timestamp": self.start_timestamp, |
257 |
"end_timestamp": self.end_timestamp, |
258 |
"received_timestamp": self.received_timestamp, |
259 |
} |
260 |
|
261 |
def CalcStatus(self): |
262 |
"""Compute the status of this job.
|
263 |
|
264 |
This function iterates over all the _QueuedOpCodes in the job and
|
265 |
based on their status, computes the job status.
|
266 |
|
267 |
The algorithm is:
|
268 |
- if we find a cancelled, or finished with error, the job
|
269 |
status will be the same
|
270 |
- otherwise, the last opcode with the status one of:
|
271 |
- waitlock
|
272 |
- canceling
|
273 |
- running
|
274 |
|
275 |
will determine the job status
|
276 |
|
277 |
- otherwise, it means either all opcodes are queued, or success,
|
278 |
and the job status will be the same
|
279 |
|
280 |
@return: the job status
|
281 |
|
282 |
"""
|
283 |
status = constants.JOB_STATUS_QUEUED |
284 |
|
285 |
all_success = True
|
286 |
for op in self.ops: |
287 |
if op.status == constants.OP_STATUS_SUCCESS:
|
288 |
continue
|
289 |
|
290 |
all_success = False
|
291 |
|
292 |
if op.status == constants.OP_STATUS_QUEUED:
|
293 |
pass
|
294 |
elif op.status == constants.OP_STATUS_WAITLOCK:
|
295 |
status = constants.JOB_STATUS_WAITLOCK |
296 |
elif op.status == constants.OP_STATUS_RUNNING:
|
297 |
status = constants.JOB_STATUS_RUNNING |
298 |
elif op.status == constants.OP_STATUS_CANCELING:
|
299 |
status = constants.JOB_STATUS_CANCELING |
300 |
break
|
301 |
elif op.status == constants.OP_STATUS_ERROR:
|
302 |
status = constants.JOB_STATUS_ERROR |
303 |
# The whole job fails if one opcode failed
|
304 |
break
|
305 |
elif op.status == constants.OP_STATUS_CANCELED:
|
306 |
status = constants.OP_STATUS_CANCELED |
307 |
break
|
308 |
|
309 |
if all_success:
|
310 |
status = constants.JOB_STATUS_SUCCESS |
311 |
|
312 |
return status
|
313 |
|
314 |
def CalcPriority(self): |
315 |
"""Gets the current priority for this job.
|
316 |
|
317 |
Only unfinished opcodes are considered. When all are done, the default
|
318 |
priority is used.
|
319 |
|
320 |
@rtype: int
|
321 |
|
322 |
"""
|
323 |
priorities = [op.priority for op in self.ops |
324 |
if op.status not in constants.OPS_FINALIZED] |
325 |
|
326 |
if not priorities: |
327 |
# All opcodes are done, assume default priority
|
328 |
return constants.OP_PRIO_DEFAULT
|
329 |
|
330 |
return min(priorities) |
331 |
|
332 |
def GetLogEntries(self, newer_than): |
333 |
"""Selectively returns the log entries.
|
334 |
|
335 |
@type newer_than: None or int
|
336 |
@param newer_than: if this is None, return all log entries,
|
337 |
otherwise return only the log entries with serial higher
|
338 |
than this value
|
339 |
@rtype: list
|
340 |
@return: the list of the log entries selected
|
341 |
|
342 |
"""
|
343 |
if newer_than is None: |
344 |
serial = -1
|
345 |
else:
|
346 |
serial = newer_than |
347 |
|
348 |
entries = [] |
349 |
for op in self.ops: |
350 |
entries.extend(filter(lambda entry: entry[0] > serial, op.log)) |
351 |
|
352 |
return entries
|
353 |
|
354 |
def GetInfo(self, fields): |
355 |
"""Returns information about a job.
|
356 |
|
357 |
@type fields: list
|
358 |
@param fields: names of fields to return
|
359 |
@rtype: list
|
360 |
@return: list with one element for each field
|
361 |
@raise errors.OpExecError: when an invalid field
|
362 |
has been passed
|
363 |
|
364 |
"""
|
365 |
row = [] |
366 |
for fname in fields: |
367 |
if fname == "id": |
368 |
row.append(self.id)
|
369 |
elif fname == "status": |
370 |
row.append(self.CalcStatus())
|
371 |
elif fname == "ops": |
372 |
row.append([op.input.__getstate__() for op in self.ops]) |
373 |
elif fname == "opresult": |
374 |
row.append([op.result for op in self.ops]) |
375 |
elif fname == "opstatus": |
376 |
row.append([op.status for op in self.ops]) |
377 |
elif fname == "oplog": |
378 |
row.append([op.log for op in self.ops]) |
379 |
elif fname == "opstart": |
380 |
row.append([op.start_timestamp for op in self.ops]) |
381 |
elif fname == "opexec": |
382 |
row.append([op.exec_timestamp for op in self.ops]) |
383 |
elif fname == "opend": |
384 |
row.append([op.end_timestamp for op in self.ops]) |
385 |
elif fname == "received_ts": |
386 |
row.append(self.received_timestamp)
|
387 |
elif fname == "start_ts": |
388 |
row.append(self.start_timestamp)
|
389 |
elif fname == "end_ts": |
390 |
row.append(self.end_timestamp)
|
391 |
elif fname == "summary": |
392 |
row.append([op.input.Summary() for op in self.ops]) |
393 |
else:
|
394 |
raise errors.OpExecError("Invalid self query field '%s'" % fname) |
395 |
return row
|
396 |
|
397 |
def MarkUnfinishedOps(self, status, result): |
398 |
"""Mark unfinished opcodes with a given status and result.
|
399 |
|
400 |
This is an utility function for marking all running or waiting to
|
401 |
be run opcodes with a given status. Opcodes which are already
|
402 |
finalised are not changed.
|
403 |
|
404 |
@param status: a given opcode status
|
405 |
@param result: the opcode result
|
406 |
|
407 |
"""
|
408 |
not_marked = True
|
409 |
for op in self.ops: |
410 |
if op.status in constants.OPS_FINALIZED: |
411 |
assert not_marked, "Finalized opcodes found after non-finalized ones" |
412 |
continue
|
413 |
op.status = status |
414 |
op.result = result |
415 |
not_marked = False
|
416 |
|
417 |
def Cancel(self): |
418 |
"""Marks job as canceled/-ing if possible.
|
419 |
|
420 |
@rtype: tuple; (bool, string)
|
421 |
@return: Boolean describing whether job was successfully canceled or marked
|
422 |
as canceling and a text message
|
423 |
|
424 |
"""
|
425 |
status = self.CalcStatus()
|
426 |
|
427 |
if status not in (constants.JOB_STATUS_QUEUED, |
428 |
constants.JOB_STATUS_WAITLOCK): |
429 |
logging.debug("Job %s is no longer waiting in the queue", self.id) |
430 |
return (False, "Job %s is no longer waiting in the queue" % self.id) |
431 |
|
432 |
if status == constants.JOB_STATUS_QUEUED:
|
433 |
self.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
|
434 |
"Job canceled by request")
|
435 |
msg = "Job %s canceled" % self.id |
436 |
|
437 |
elif status == constants.JOB_STATUS_WAITLOCK:
|
438 |
# The worker will notice the new status and cancel the job
|
439 |
self.MarkUnfinishedOps(constants.OP_STATUS_CANCELING, None) |
440 |
msg = "Job %s will be canceled" % self.id |
441 |
|
442 |
return (True, msg) |
443 |
|
444 |
|
445 |
class _OpExecCallbacks(mcpu.OpExecCbBase): |
446 |
def __init__(self, queue, job, op): |
447 |
"""Initializes this class.
|
448 |
|
449 |
@type queue: L{JobQueue}
|
450 |
@param queue: Job queue
|
451 |
@type job: L{_QueuedJob}
|
452 |
@param job: Job object
|
453 |
@type op: L{_QueuedOpCode}
|
454 |
@param op: OpCode
|
455 |
|
456 |
"""
|
457 |
assert queue, "Queue is missing" |
458 |
assert job, "Job is missing" |
459 |
assert op, "Opcode is missing" |
460 |
|
461 |
self._queue = queue
|
462 |
self._job = job
|
463 |
self._op = op
|
464 |
|
465 |
def _CheckCancel(self): |
466 |
"""Raises an exception to cancel the job if asked to.
|
467 |
|
468 |
"""
|
469 |
# Cancel here if we were asked to
|
470 |
if self._op.status == constants.OP_STATUS_CANCELING: |
471 |
logging.debug("Canceling opcode")
|
472 |
raise CancelJob()
|
473 |
|
474 |
@locking.ssynchronized(_QUEUE, shared=1) |
475 |
def NotifyStart(self): |
476 |
"""Mark the opcode as running, not lock-waiting.
|
477 |
|
478 |
This is called from the mcpu code as a notifier function, when the LU is
|
479 |
finally about to start the Exec() method. Of course, to have end-user
|
480 |
visible results, the opcode must be initially (before calling into
|
481 |
Processor.ExecOpCode) set to OP_STATUS_WAITLOCK.
|
482 |
|
483 |
"""
|
484 |
assert self._op in self._job.ops |
485 |
assert self._op.status in (constants.OP_STATUS_WAITLOCK, |
486 |
constants.OP_STATUS_CANCELING) |
487 |
|
488 |
# Cancel here if we were asked to
|
489 |
self._CheckCancel()
|
490 |
|
491 |
logging.debug("Opcode is now running")
|
492 |
|
493 |
self._op.status = constants.OP_STATUS_RUNNING
|
494 |
self._op.exec_timestamp = TimeStampNow()
|
495 |
|
496 |
# And finally replicate the job status
|
497 |
self._queue.UpdateJobUnlocked(self._job) |
498 |
|
499 |
@locking.ssynchronized(_QUEUE, shared=1) |
500 |
def _AppendFeedback(self, timestamp, log_type, log_msg): |
501 |
"""Internal feedback append function, with locks
|
502 |
|
503 |
"""
|
504 |
self._job.log_serial += 1 |
505 |
self._op.log.append((self._job.log_serial, timestamp, log_type, log_msg)) |
506 |
self._queue.UpdateJobUnlocked(self._job, replicate=False) |
507 |
|
508 |
def Feedback(self, *args): |
509 |
"""Append a log entry.
|
510 |
|
511 |
"""
|
512 |
assert len(args) < 3 |
513 |
|
514 |
if len(args) == 1: |
515 |
log_type = constants.ELOG_MESSAGE |
516 |
log_msg = args[0]
|
517 |
else:
|
518 |
(log_type, log_msg) = args |
519 |
|
520 |
# The time is split to make serialization easier and not lose
|
521 |
# precision.
|
522 |
timestamp = utils.SplitTime(time.time()) |
523 |
self._AppendFeedback(timestamp, log_type, log_msg)
|
524 |
|
525 |
def CheckCancel(self): |
526 |
"""Check whether job has been cancelled.
|
527 |
|
528 |
"""
|
529 |
assert self._op.status in (constants.OP_STATUS_WAITLOCK, |
530 |
constants.OP_STATUS_CANCELING) |
531 |
|
532 |
# Cancel here if we were asked to
|
533 |
self._CheckCancel()
|
534 |
|
535 |
|
536 |
class _JobChangesChecker(object): |
537 |
def __init__(self, fields, prev_job_info, prev_log_serial): |
538 |
"""Initializes this class.
|
539 |
|
540 |
@type fields: list of strings
|
541 |
@param fields: Fields requested by LUXI client
|
542 |
@type prev_job_info: string
|
543 |
@param prev_job_info: previous job info, as passed by the LUXI client
|
544 |
@type prev_log_serial: string
|
545 |
@param prev_log_serial: previous job serial, as passed by the LUXI client
|
546 |
|
547 |
"""
|
548 |
self._fields = fields
|
549 |
self._prev_job_info = prev_job_info
|
550 |
self._prev_log_serial = prev_log_serial
|
551 |
|
552 |
def __call__(self, job): |
553 |
"""Checks whether job has changed.
|
554 |
|
555 |
@type job: L{_QueuedJob}
|
556 |
@param job: Job object
|
557 |
|
558 |
"""
|
559 |
status = job.CalcStatus() |
560 |
job_info = job.GetInfo(self._fields)
|
561 |
log_entries = job.GetLogEntries(self._prev_log_serial)
|
562 |
|
563 |
# Serializing and deserializing data can cause type changes (e.g. from
|
564 |
# tuple to list) or precision loss. We're doing it here so that we get
|
565 |
# the same modifications as the data received from the client. Without
|
566 |
# this, the comparison afterwards might fail without the data being
|
567 |
# significantly different.
|
568 |
# TODO: we just deserialized from disk, investigate how to make sure that
|
569 |
# the job info and log entries are compatible to avoid this further step.
|
570 |
# TODO: Doing something like in testutils.py:UnifyValueType might be more
|
571 |
# efficient, though floats will be tricky
|
572 |
job_info = serializer.LoadJson(serializer.DumpJson(job_info)) |
573 |
log_entries = serializer.LoadJson(serializer.DumpJson(log_entries)) |
574 |
|
575 |
# Don't even try to wait if the job is no longer running, there will be
|
576 |
# no changes.
|
577 |
if (status not in (constants.JOB_STATUS_QUEUED, |
578 |
constants.JOB_STATUS_RUNNING, |
579 |
constants.JOB_STATUS_WAITLOCK) or
|
580 |
job_info != self._prev_job_info or |
581 |
(log_entries and self._prev_log_serial != log_entries[0][0])): |
582 |
logging.debug("Job %s changed", job.id)
|
583 |
return (job_info, log_entries)
|
584 |
|
585 |
return None |
586 |
|
587 |
|
588 |
class _JobFileChangesWaiter(object): |
589 |
def __init__(self, filename): |
590 |
"""Initializes this class.
|
591 |
|
592 |
@type filename: string
|
593 |
@param filename: Path to job file
|
594 |
@raises errors.InotifyError: if the notifier cannot be setup
|
595 |
|
596 |
"""
|
597 |
self._wm = pyinotify.WatchManager()
|
598 |
self._inotify_handler = \
|
599 |
asyncnotifier.SingleFileEventHandler(self._wm, self._OnInotify, filename) |
600 |
self._notifier = \
|
601 |
pyinotify.Notifier(self._wm, default_proc_fun=self._inotify_handler) |
602 |
try:
|
603 |
self._inotify_handler.enable()
|
604 |
except Exception: |
605 |
# pyinotify doesn't close file descriptors automatically
|
606 |
self._notifier.stop()
|
607 |
raise
|
608 |
|
609 |
def _OnInotify(self, notifier_enabled): |
610 |
"""Callback for inotify.
|
611 |
|
612 |
"""
|
613 |
if not notifier_enabled: |
614 |
self._inotify_handler.enable()
|
615 |
|
616 |
def Wait(self, timeout): |
617 |
"""Waits for the job file to change.
|
618 |
|
619 |
@type timeout: float
|
620 |
@param timeout: Timeout in seconds
|
621 |
@return: Whether there have been events
|
622 |
|
623 |
"""
|
624 |
assert timeout >= 0 |
625 |
have_events = self._notifier.check_events(timeout * 1000) |
626 |
if have_events:
|
627 |
self._notifier.read_events()
|
628 |
self._notifier.process_events()
|
629 |
return have_events
|
630 |
|
631 |
def Close(self): |
632 |
"""Closes underlying notifier and its file descriptor.
|
633 |
|
634 |
"""
|
635 |
self._notifier.stop()
|
636 |
|
637 |
|
638 |
class _JobChangesWaiter(object): |
639 |
def __init__(self, filename): |
640 |
"""Initializes this class.
|
641 |
|
642 |
@type filename: string
|
643 |
@param filename: Path to job file
|
644 |
|
645 |
"""
|
646 |
self._filewaiter = None |
647 |
self._filename = filename
|
648 |
|
649 |
def Wait(self, timeout): |
650 |
"""Waits for a job to change.
|
651 |
|
652 |
@type timeout: float
|
653 |
@param timeout: Timeout in seconds
|
654 |
@return: Whether there have been events
|
655 |
|
656 |
"""
|
657 |
if self._filewaiter: |
658 |
return self._filewaiter.Wait(timeout) |
659 |
|
660 |
# Lazy setup: Avoid inotify setup cost when job file has already changed.
|
661 |
# If this point is reached, return immediately and let caller check the job
|
662 |
# file again in case there were changes since the last check. This avoids a
|
663 |
# race condition.
|
664 |
self._filewaiter = _JobFileChangesWaiter(self._filename) |
665 |
|
666 |
return True |
667 |
|
668 |
def Close(self): |
669 |
"""Closes underlying waiter.
|
670 |
|
671 |
"""
|
672 |
if self._filewaiter: |
673 |
self._filewaiter.Close()
|
674 |
|
675 |
|
676 |
class _WaitForJobChangesHelper(object): |
677 |
"""Helper class using inotify to wait for changes in a job file.
|
678 |
|
679 |
This class takes a previous job status and serial, and alerts the client when
|
680 |
the current job status has changed.
|
681 |
|
682 |
"""
|
683 |
@staticmethod
|
684 |
def _CheckForChanges(job_load_fn, check_fn): |
685 |
job = job_load_fn() |
686 |
if not job: |
687 |
raise errors.JobLost()
|
688 |
|
689 |
result = check_fn(job) |
690 |
if result is None: |
691 |
raise utils.RetryAgain()
|
692 |
|
693 |
return result
|
694 |
|
695 |
def __call__(self, filename, job_load_fn, |
696 |
fields, prev_job_info, prev_log_serial, timeout): |
697 |
"""Waits for changes on a job.
|
698 |
|
699 |
@type filename: string
|
700 |
@param filename: File on which to wait for changes
|
701 |
@type job_load_fn: callable
|
702 |
@param job_load_fn: Function to load job
|
703 |
@type fields: list of strings
|
704 |
@param fields: Which fields to check for changes
|
705 |
@type prev_job_info: list or None
|
706 |
@param prev_job_info: Last job information returned
|
707 |
@type prev_log_serial: int
|
708 |
@param prev_log_serial: Last job message serial number
|
709 |
@type timeout: float
|
710 |
@param timeout: maximum time to wait in seconds
|
711 |
|
712 |
"""
|
713 |
try:
|
714 |
check_fn = _JobChangesChecker(fields, prev_job_info, prev_log_serial) |
715 |
waiter = _JobChangesWaiter(filename) |
716 |
try:
|
717 |
return utils.Retry(compat.partial(self._CheckForChanges, |
718 |
job_load_fn, check_fn), |
719 |
utils.RETRY_REMAINING_TIME, timeout, |
720 |
wait_fn=waiter.Wait) |
721 |
finally:
|
722 |
waiter.Close() |
723 |
except (errors.InotifyError, errors.JobLost):
|
724 |
return None |
725 |
except utils.RetryTimeout:
|
726 |
return constants.JOB_NOTCHANGED
|
727 |
|
728 |
|
729 |
def _EncodeOpError(err): |
730 |
"""Encodes an error which occurred while processing an opcode.
|
731 |
|
732 |
"""
|
733 |
if isinstance(err, errors.GenericError): |
734 |
to_encode = err |
735 |
else:
|
736 |
to_encode = errors.OpExecError(str(err))
|
737 |
|
738 |
return errors.EncodeException(to_encode)
|
739 |
|
740 |
|
741 |
class _JobProcessor(object): |
742 |
def __init__(self, queue, opexec_fn, job): |
743 |
"""Initializes this class.
|
744 |
|
745 |
"""
|
746 |
self.queue = queue
|
747 |
self.opexec_fn = opexec_fn
|
748 |
self.job = job
|
749 |
|
750 |
@staticmethod
|
751 |
def _FindNextOpcode(job): |
752 |
"""Locates the next opcode to run.
|
753 |
|
754 |
@type job: L{_QueuedJob}
|
755 |
@param job: Job object
|
756 |
|
757 |
"""
|
758 |
# Create some sort of a cache to speed up locating next opcode for future
|
759 |
# lookups
|
760 |
# TODO: Consider splitting _QueuedJob.ops into two separate lists, one for
|
761 |
# pending and one for processed ops.
|
762 |
if job.current_op is None: |
763 |
job.current_op = enumerate(job.ops)
|
764 |
|
765 |
# Find next opcode to run
|
766 |
while True: |
767 |
try:
|
768 |
(idx, op) = job.current_op.next() |
769 |
except StopIteration: |
770 |
raise errors.ProgrammerError("Called for a finished job") |
771 |
|
772 |
if op.status == constants.OP_STATUS_RUNNING:
|
773 |
# Found an opcode already marked as running
|
774 |
raise errors.ProgrammerError("Called for job marked as running") |
775 |
|
776 |
log_prefix = "Op %s/%s" % (idx + 1, len(job.ops)) |
777 |
summary = op.input.Summary() |
778 |
|
779 |
if op.status == constants.OP_STATUS_CANCELED:
|
780 |
# Cancelled jobs are handled by the caller
|
781 |
assert not compat.any(i.status != constants.OP_STATUS_CANCELED |
782 |
for i in job.ops[idx:]) |
783 |
|
784 |
elif op.status in constants.OPS_FINALIZED: |
785 |
# This is a job that was partially completed before master daemon
|
786 |
# shutdown, so it can be expected that some opcodes are already
|
787 |
# completed successfully (if any did error out, then the whole job
|
788 |
# should have been aborted and not resubmitted for processing).
|
789 |
logging.info("%s: opcode %s already processed, skipping",
|
790 |
log_prefix, summary) |
791 |
continue
|
792 |
|
793 |
return (idx, op, log_prefix, summary)
|
794 |
|
795 |
@staticmethod
|
796 |
def _MarkWaitlock(job, op): |
797 |
"""Marks an opcode as waiting for locks.
|
798 |
|
799 |
The job's start timestamp is also set if necessary.
|
800 |
|
801 |
@type job: L{_QueuedJob}
|
802 |
@param job: Job object
|
803 |
@type job: L{_QueuedOpCode}
|
804 |
@param job: Opcode object
|
805 |
|
806 |
"""
|
807 |
assert op in job.ops |
808 |
|
809 |
op.status = constants.OP_STATUS_WAITLOCK |
810 |
op.result = None
|
811 |
op.start_timestamp = TimeStampNow() |
812 |
|
813 |
if job.start_timestamp is None: |
814 |
job.start_timestamp = op.start_timestamp |
815 |
|
816 |
def _ExecOpCodeUnlocked(self, log_prefix, op, summary): |
817 |
"""Processes one opcode and returns the result.
|
818 |
|
819 |
"""
|
820 |
assert op.status == constants.OP_STATUS_WAITLOCK
|
821 |
|
822 |
try:
|
823 |
# Make sure not to hold queue lock while calling ExecOpCode
|
824 |
result = self.opexec_fn(op.input,
|
825 |
_OpExecCallbacks(self.queue, self.job, op)) |
826 |
except CancelJob:
|
827 |
logging.exception("%s: Canceling job", log_prefix)
|
828 |
assert op.status == constants.OP_STATUS_CANCELING
|
829 |
return (constants.OP_STATUS_CANCELING, None) |
830 |
except Exception, err: # pylint: disable-msg=W0703 |
831 |
logging.exception("%s: Caught exception in %s", log_prefix, summary)
|
832 |
return (constants.OP_STATUS_ERROR, _EncodeOpError(err))
|
833 |
else:
|
834 |
logging.debug("%s: %s successful", log_prefix, summary)
|
835 |
return (constants.OP_STATUS_SUCCESS, result)
|
836 |
|
837 |
def __call__(self): |
838 |
"""Continues execution of a job.
|
839 |
|
840 |
@rtype: bool
|
841 |
@return: True if job is finished, False if processor needs to be called
|
842 |
again
|
843 |
|
844 |
"""
|
845 |
queue = self.queue
|
846 |
job = self.job
|
847 |
|
848 |
logging.debug("Processing job %s", job.id)
|
849 |
|
850 |
queue.acquire(shared=1)
|
851 |
try:
|
852 |
opcount = len(job.ops)
|
853 |
|
854 |
(opidx, op, log_prefix, op_summary) = self._FindNextOpcode(job)
|
855 |
|
856 |
# Consistency check
|
857 |
assert compat.all(i.status in (constants.OP_STATUS_QUEUED, |
858 |
constants.OP_STATUS_CANCELED) |
859 |
for i in job.ops[opidx:]) |
860 |
|
861 |
assert op.status in (constants.OP_STATUS_QUEUED, |
862 |
constants.OP_STATUS_WAITLOCK, |
863 |
constants.OP_STATUS_CANCELED) |
864 |
|
865 |
if op.status != constants.OP_STATUS_CANCELED:
|
866 |
# Prepare to start opcode
|
867 |
self._MarkWaitlock(job, op)
|
868 |
|
869 |
assert op.status == constants.OP_STATUS_WAITLOCK
|
870 |
assert job.CalcStatus() == constants.JOB_STATUS_WAITLOCK
|
871 |
|
872 |
# Write to disk
|
873 |
queue.UpdateJobUnlocked(job) |
874 |
|
875 |
logging.info("%s: opcode %s waiting for locks", log_prefix, op_summary)
|
876 |
|
877 |
queue.release() |
878 |
try:
|
879 |
(op_status, op_result) = \ |
880 |
self._ExecOpCodeUnlocked(log_prefix, op, op_summary)
|
881 |
finally:
|
882 |
queue.acquire(shared=1)
|
883 |
|
884 |
# Finalize opcode
|
885 |
op.end_timestamp = TimeStampNow() |
886 |
op.status = op_status |
887 |
op.result = op_result |
888 |
|
889 |
if op.status == constants.OP_STATUS_CANCELING:
|
890 |
assert not compat.any(i.status != constants.OP_STATUS_CANCELING |
891 |
for i in job.ops[opidx:]) |
892 |
else:
|
893 |
assert op.status in constants.OPS_FINALIZED |
894 |
|
895 |
# Ensure all opcodes so far have been successful
|
896 |
assert (opidx == 0 or |
897 |
compat.all(i.status == constants.OP_STATUS_SUCCESS |
898 |
for i in job.ops[:opidx])) |
899 |
|
900 |
if op.status == constants.OP_STATUS_SUCCESS:
|
901 |
finalize = False
|
902 |
|
903 |
elif op.status == constants.OP_STATUS_ERROR:
|
904 |
# Ensure failed opcode has an exception as its result
|
905 |
assert errors.GetEncodedError(job.ops[opidx].result)
|
906 |
|
907 |
to_encode = errors.OpExecError("Preceding opcode failed")
|
908 |
job.MarkUnfinishedOps(constants.OP_STATUS_ERROR, |
909 |
_EncodeOpError(to_encode)) |
910 |
finalize = True
|
911 |
|
912 |
# Consistency check
|
913 |
assert compat.all(i.status == constants.OP_STATUS_ERROR and |
914 |
errors.GetEncodedError(i.result) |
915 |
for i in job.ops[opidx:]) |
916 |
|
917 |
elif op.status == constants.OP_STATUS_CANCELING:
|
918 |
job.MarkUnfinishedOps(constants.OP_STATUS_CANCELED, |
919 |
"Job canceled by request")
|
920 |
finalize = True
|
921 |
|
922 |
elif op.status == constants.OP_STATUS_CANCELED:
|
923 |
finalize = True
|
924 |
|
925 |
else:
|
926 |
raise errors.ProgrammerError("Unknown status '%s'" % op.status) |
927 |
|
928 |
# Finalizing or last opcode?
|
929 |
if finalize or opidx == (opcount - 1): |
930 |
# All opcodes have been run, finalize job
|
931 |
job.end_timestamp = TimeStampNow() |
932 |
|
933 |
# Write to disk. If the job status is final, this is the final write
|
934 |
# allowed. Once the file has been written, it can be archived anytime.
|
935 |
queue.UpdateJobUnlocked(job) |
936 |
|
937 |
if finalize or opidx == (opcount - 1): |
938 |
logging.info("Finished job %s, status = %s", job.id, job.CalcStatus())
|
939 |
return True |
940 |
|
941 |
return False |
942 |
finally:
|
943 |
queue.release() |
944 |
|
945 |
|
946 |
class _JobQueueWorker(workerpool.BaseWorker): |
947 |
"""The actual job workers.
|
948 |
|
949 |
"""
|
950 |
def RunTask(self, job): # pylint: disable-msg=W0221 |
951 |
"""Job executor.
|
952 |
|
953 |
This functions processes a job. It is closely tied to the L{_QueuedJob} and
|
954 |
L{_QueuedOpCode} classes.
|
955 |
|
956 |
@type job: L{_QueuedJob}
|
957 |
@param job: the job to be processed
|
958 |
|
959 |
"""
|
960 |
queue = job.queue |
961 |
assert queue == self.pool.queue |
962 |
|
963 |
self.SetTaskName("Job%s" % job.id) |
964 |
|
965 |
proc = mcpu.Processor(queue.context, job.id) |
966 |
|
967 |
if not _JobProcessor(queue, proc.ExecOpCode, job)(): |
968 |
# Schedule again
|
969 |
raise workerpool.DeferTask()
|
970 |
|
971 |
|
972 |
class _JobQueueWorkerPool(workerpool.WorkerPool): |
973 |
"""Simple class implementing a job-processing workerpool.
|
974 |
|
975 |
"""
|
976 |
def __init__(self, queue): |
977 |
super(_JobQueueWorkerPool, self).__init__("JobQueue", |
978 |
JOBQUEUE_THREADS, |
979 |
_JobQueueWorker) |
980 |
self.queue = queue
|
981 |
|
982 |
|
983 |
def _RequireOpenQueue(fn): |
984 |
"""Decorator for "public" functions.
|
985 |
|
986 |
This function should be used for all 'public' functions. That is,
|
987 |
functions usually called from other classes. Note that this should
|
988 |
be applied only to methods (not plain functions), since it expects
|
989 |
that the decorated function is called with a first argument that has
|
990 |
a '_queue_filelock' argument.
|
991 |
|
992 |
@warning: Use this decorator only after locking.ssynchronized
|
993 |
|
994 |
Example::
|
995 |
@locking.ssynchronized(_LOCK)
|
996 |
@_RequireOpenQueue
|
997 |
def Example(self):
|
998 |
pass
|
999 |
|
1000 |
"""
|
1001 |
def wrapper(self, *args, **kwargs): |
1002 |
# pylint: disable-msg=W0212
|
1003 |
assert self._queue_filelock is not None, "Queue should be open" |
1004 |
return fn(self, *args, **kwargs) |
1005 |
return wrapper
|
1006 |
|
1007 |
|
1008 |
class JobQueue(object): |
1009 |
"""Queue used to manage the jobs.
|
1010 |
|
1011 |
@cvar _RE_JOB_FILE: regex matching the valid job file names
|
1012 |
|
1013 |
"""
|
1014 |
_RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
|
1015 |
|
1016 |
def __init__(self, context): |
1017 |
"""Constructor for JobQueue.
|
1018 |
|
1019 |
The constructor will initialize the job queue object and then
|
1020 |
start loading the current jobs from disk, either for starting them
|
1021 |
(if they were queue) or for aborting them (if they were already
|
1022 |
running).
|
1023 |
|
1024 |
@type context: GanetiContext
|
1025 |
@param context: the context object for access to the configuration
|
1026 |
data and other ganeti objects
|
1027 |
|
1028 |
"""
|
1029 |
self.context = context
|
1030 |
self._memcache = weakref.WeakValueDictionary()
|
1031 |
self._my_hostname = netutils.Hostname.GetSysName()
|
1032 |
|
1033 |
# The Big JobQueue lock. If a code block or method acquires it in shared
|
1034 |
# mode safe it must guarantee concurrency with all the code acquiring it in
|
1035 |
# shared mode, including itself. In order not to acquire it at all
|
1036 |
# concurrency must be guaranteed with all code acquiring it in shared mode
|
1037 |
# and all code acquiring it exclusively.
|
1038 |
self._lock = locking.SharedLock("JobQueue") |
1039 |
|
1040 |
self.acquire = self._lock.acquire |
1041 |
self.release = self._lock.release |
1042 |
|
1043 |
# Initialize the queue, and acquire the filelock.
|
1044 |
# This ensures no other process is working on the job queue.
|
1045 |
self._queue_filelock = jstore.InitAndVerifyQueue(must_lock=True) |
1046 |
|
1047 |
# Read serial file
|
1048 |
self._last_serial = jstore.ReadSerial()
|
1049 |
assert self._last_serial is not None, ("Serial file was modified between" |
1050 |
" check in jstore and here")
|
1051 |
|
1052 |
# Get initial list of nodes
|
1053 |
self._nodes = dict((n.name, n.primary_ip) |
1054 |
for n in self.context.cfg.GetAllNodesInfo().values() |
1055 |
if n.master_candidate)
|
1056 |
|
1057 |
# Remove master node
|
1058 |
self._nodes.pop(self._my_hostname, None) |
1059 |
|
1060 |
# TODO: Check consistency across nodes
|
1061 |
|
1062 |
self._queue_size = 0 |
1063 |
self._UpdateQueueSizeUnlocked()
|
1064 |
self._drained = self._IsQueueMarkedDrain() |
1065 |
|
1066 |
# Setup worker pool
|
1067 |
self._wpool = _JobQueueWorkerPool(self) |
1068 |
try:
|
1069 |
self._InspectQueue()
|
1070 |
except:
|
1071 |
self._wpool.TerminateWorkers()
|
1072 |
raise
|
1073 |
|
1074 |
@locking.ssynchronized(_LOCK)
|
1075 |
@_RequireOpenQueue
|
1076 |
def _InspectQueue(self): |
1077 |
"""Loads the whole job queue and resumes unfinished jobs.
|
1078 |
|
1079 |
This function needs the lock here because WorkerPool.AddTask() may start a
|
1080 |
job while we're still doing our work.
|
1081 |
|
1082 |
"""
|
1083 |
logging.info("Inspecting job queue")
|
1084 |
|
1085 |
restartjobs = [] |
1086 |
|
1087 |
all_job_ids = self._GetJobIDsUnlocked()
|
1088 |
jobs_count = len(all_job_ids)
|
1089 |
lastinfo = time.time() |
1090 |
for idx, job_id in enumerate(all_job_ids): |
1091 |
# Give an update every 1000 jobs or 10 seconds
|
1092 |
if (idx % 1000 == 0 or time.time() >= (lastinfo + 10.0) or |
1093 |
idx == (jobs_count - 1)):
|
1094 |
logging.info("Job queue inspection: %d/%d (%0.1f %%)",
|
1095 |
idx, jobs_count - 1, 100.0 * (idx + 1) / jobs_count) |
1096 |
lastinfo = time.time() |
1097 |
|
1098 |
job = self._LoadJobUnlocked(job_id)
|
1099 |
|
1100 |
# a failure in loading the job can cause 'None' to be returned
|
1101 |
if job is None: |
1102 |
continue
|
1103 |
|
1104 |
status = job.CalcStatus() |
1105 |
|
1106 |
if status in (constants.JOB_STATUS_QUEUED, ): |
1107 |
restartjobs.append(job) |
1108 |
|
1109 |
elif status in (constants.JOB_STATUS_RUNNING, |
1110 |
constants.JOB_STATUS_WAITLOCK, |
1111 |
constants.JOB_STATUS_CANCELING): |
1112 |
logging.warning("Unfinished job %s found: %s", job.id, job)
|
1113 |
job.MarkUnfinishedOps(constants.OP_STATUS_ERROR, |
1114 |
"Unclean master daemon shutdown")
|
1115 |
self.UpdateJobUnlocked(job)
|
1116 |
|
1117 |
if restartjobs:
|
1118 |
logging.info("Restarting %s jobs", len(restartjobs)) |
1119 |
self._EnqueueJobs(restartjobs)
|
1120 |
|
1121 |
logging.info("Job queue inspection finished")
|
1122 |
|
1123 |
@locking.ssynchronized(_LOCK)
|
1124 |
@_RequireOpenQueue
|
1125 |
def AddNode(self, node): |
1126 |
"""Register a new node with the queue.
|
1127 |
|
1128 |
@type node: L{objects.Node}
|
1129 |
@param node: the node object to be added
|
1130 |
|
1131 |
"""
|
1132 |
node_name = node.name |
1133 |
assert node_name != self._my_hostname |
1134 |
|
1135 |
# Clean queue directory on added node
|
1136 |
result = rpc.RpcRunner.call_jobqueue_purge(node_name) |
1137 |
msg = result.fail_msg |
1138 |
if msg:
|
1139 |
logging.warning("Cannot cleanup queue directory on node %s: %s",
|
1140 |
node_name, msg) |
1141 |
|
1142 |
if not node.master_candidate: |
1143 |
# remove if existing, ignoring errors
|
1144 |
self._nodes.pop(node_name, None) |
1145 |
# and skip the replication of the job ids
|
1146 |
return
|
1147 |
|
1148 |
# Upload the whole queue excluding archived jobs
|
1149 |
files = [self._GetJobPath(job_id) for job_id in self._GetJobIDsUnlocked()] |
1150 |
|
1151 |
# Upload current serial file
|
1152 |
files.append(constants.JOB_QUEUE_SERIAL_FILE) |
1153 |
|
1154 |
for file_name in files: |
1155 |
# Read file content
|
1156 |
content = utils.ReadFile(file_name) |
1157 |
|
1158 |
result = rpc.RpcRunner.call_jobqueue_update([node_name], |
1159 |
[node.primary_ip], |
1160 |
file_name, content) |
1161 |
msg = result[node_name].fail_msg |
1162 |
if msg:
|
1163 |
logging.error("Failed to upload file %s to node %s: %s",
|
1164 |
file_name, node_name, msg) |
1165 |
|
1166 |
self._nodes[node_name] = node.primary_ip
|
1167 |
|
1168 |
@locking.ssynchronized(_LOCK)
|
1169 |
@_RequireOpenQueue
|
1170 |
def RemoveNode(self, node_name): |
1171 |
"""Callback called when removing nodes from the cluster.
|
1172 |
|
1173 |
@type node_name: str
|
1174 |
@param node_name: the name of the node to remove
|
1175 |
|
1176 |
"""
|
1177 |
self._nodes.pop(node_name, None) |
1178 |
|
1179 |
@staticmethod
|
1180 |
def _CheckRpcResult(result, nodes, failmsg): |
1181 |
"""Verifies the status of an RPC call.
|
1182 |
|
1183 |
Since we aim to keep consistency should this node (the current
|
1184 |
master) fail, we will log errors if our rpc fail, and especially
|
1185 |
log the case when more than half of the nodes fails.
|
1186 |
|
1187 |
@param result: the data as returned from the rpc call
|
1188 |
@type nodes: list
|
1189 |
@param nodes: the list of nodes we made the call to
|
1190 |
@type failmsg: str
|
1191 |
@param failmsg: the identifier to be used for logging
|
1192 |
|
1193 |
"""
|
1194 |
failed = [] |
1195 |
success = [] |
1196 |
|
1197 |
for node in nodes: |
1198 |
msg = result[node].fail_msg |
1199 |
if msg:
|
1200 |
failed.append(node) |
1201 |
logging.error("RPC call %s (%s) failed on node %s: %s",
|
1202 |
result[node].call, failmsg, node, msg) |
1203 |
else:
|
1204 |
success.append(node) |
1205 |
|
1206 |
# +1 for the master node
|
1207 |
if (len(success) + 1) < len(failed): |
1208 |
# TODO: Handle failing nodes
|
1209 |
logging.error("More than half of the nodes failed")
|
1210 |
|
1211 |
def _GetNodeIp(self): |
1212 |
"""Helper for returning the node name/ip list.
|
1213 |
|
1214 |
@rtype: (list, list)
|
1215 |
@return: a tuple of two lists, the first one with the node
|
1216 |
names and the second one with the node addresses
|
1217 |
|
1218 |
"""
|
1219 |
# TODO: Change to "tuple(map(list, zip(*self._nodes.items())))"?
|
1220 |
name_list = self._nodes.keys()
|
1221 |
addr_list = [self._nodes[name] for name in name_list] |
1222 |
return name_list, addr_list
|
1223 |
|
1224 |
def _UpdateJobQueueFile(self, file_name, data, replicate): |
1225 |
"""Writes a file locally and then replicates it to all nodes.
|
1226 |
|
1227 |
This function will replace the contents of a file on the local
|
1228 |
node and then replicate it to all the other nodes we have.
|
1229 |
|
1230 |
@type file_name: str
|
1231 |
@param file_name: the path of the file to be replicated
|
1232 |
@type data: str
|
1233 |
@param data: the new contents of the file
|
1234 |
@type replicate: boolean
|
1235 |
@param replicate: whether to spread the changes to the remote nodes
|
1236 |
|
1237 |
"""
|
1238 |
getents = runtime.GetEnts() |
1239 |
utils.WriteFile(file_name, data=data, uid=getents.masterd_uid, |
1240 |
gid=getents.masterd_gid) |
1241 |
|
1242 |
if replicate:
|
1243 |
names, addrs = self._GetNodeIp()
|
1244 |
result = rpc.RpcRunner.call_jobqueue_update(names, addrs, file_name, data) |
1245 |
self._CheckRpcResult(result, self._nodes, "Updating %s" % file_name) |
1246 |
|
1247 |
def _RenameFilesUnlocked(self, rename): |
1248 |
"""Renames a file locally and then replicate the change.
|
1249 |
|
1250 |
This function will rename a file in the local queue directory
|
1251 |
and then replicate this rename to all the other nodes we have.
|
1252 |
|
1253 |
@type rename: list of (old, new)
|
1254 |
@param rename: List containing tuples mapping old to new names
|
1255 |
|
1256 |
"""
|
1257 |
# Rename them locally
|
1258 |
for old, new in rename: |
1259 |
utils.RenameFile(old, new, mkdir=True)
|
1260 |
|
1261 |
# ... and on all nodes
|
1262 |
names, addrs = self._GetNodeIp()
|
1263 |
result = rpc.RpcRunner.call_jobqueue_rename(names, addrs, rename) |
1264 |
self._CheckRpcResult(result, self._nodes, "Renaming files (%r)" % rename) |
1265 |
|
1266 |
@staticmethod
|
1267 |
def _FormatJobID(job_id): |
1268 |
"""Convert a job ID to string format.
|
1269 |
|
1270 |
Currently this just does C{str(job_id)} after performing some
|
1271 |
checks, but if we want to change the job id format this will
|
1272 |
abstract this change.
|
1273 |
|
1274 |
@type job_id: int or long
|
1275 |
@param job_id: the numeric job id
|
1276 |
@rtype: str
|
1277 |
@return: the formatted job id
|
1278 |
|
1279 |
"""
|
1280 |
if not isinstance(job_id, (int, long)): |
1281 |
raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id) |
1282 |
if job_id < 0: |
1283 |
raise errors.ProgrammerError("Job ID %s is negative" % job_id) |
1284 |
|
1285 |
return str(job_id) |
1286 |
|
1287 |
@classmethod
|
1288 |
def _GetArchiveDirectory(cls, job_id): |
1289 |
"""Returns the archive directory for a job.
|
1290 |
|
1291 |
@type job_id: str
|
1292 |
@param job_id: Job identifier
|
1293 |
@rtype: str
|
1294 |
@return: Directory name
|
1295 |
|
1296 |
"""
|
1297 |
return str(int(job_id) / JOBS_PER_ARCHIVE_DIRECTORY) |
1298 |
|
1299 |
def _NewSerialsUnlocked(self, count): |
1300 |
"""Generates a new job identifier.
|
1301 |
|
1302 |
Job identifiers are unique during the lifetime of a cluster.
|
1303 |
|
1304 |
@type count: integer
|
1305 |
@param count: how many serials to return
|
1306 |
@rtype: str
|
1307 |
@return: a string representing the job identifier.
|
1308 |
|
1309 |
"""
|
1310 |
assert count > 0 |
1311 |
# New number
|
1312 |
serial = self._last_serial + count
|
1313 |
|
1314 |
# Write to file
|
1315 |
self._UpdateJobQueueFile(constants.JOB_QUEUE_SERIAL_FILE,
|
1316 |
"%s\n" % serial, True) |
1317 |
|
1318 |
result = [self._FormatJobID(v)
|
1319 |
for v in range(self._last_serial, serial + 1)] |
1320 |
# Keep it only if we were able to write the file
|
1321 |
self._last_serial = serial
|
1322 |
|
1323 |
return result
|
1324 |
|
1325 |
@staticmethod
|
1326 |
def _GetJobPath(job_id): |
1327 |
"""Returns the job file for a given job id.
|
1328 |
|
1329 |
@type job_id: str
|
1330 |
@param job_id: the job identifier
|
1331 |
@rtype: str
|
1332 |
@return: the path to the job file
|
1333 |
|
1334 |
"""
|
1335 |
return utils.PathJoin(constants.QUEUE_DIR, "job-%s" % job_id) |
1336 |
|
1337 |
@classmethod
|
1338 |
def _GetArchivedJobPath(cls, job_id): |
1339 |
"""Returns the archived job file for a give job id.
|
1340 |
|
1341 |
@type job_id: str
|
1342 |
@param job_id: the job identifier
|
1343 |
@rtype: str
|
1344 |
@return: the path to the archived job file
|
1345 |
|
1346 |
"""
|
1347 |
return utils.PathJoin(constants.JOB_QUEUE_ARCHIVE_DIR,
|
1348 |
cls._GetArchiveDirectory(job_id), "job-%s" % job_id)
|
1349 |
|
1350 |
def _GetJobIDsUnlocked(self, sort=True): |
1351 |
"""Return all known job IDs.
|
1352 |
|
1353 |
The method only looks at disk because it's a requirement that all
|
1354 |
jobs are present on disk (so in the _memcache we don't have any
|
1355 |
extra IDs).
|
1356 |
|
1357 |
@type sort: boolean
|
1358 |
@param sort: perform sorting on the returned job ids
|
1359 |
@rtype: list
|
1360 |
@return: the list of job IDs
|
1361 |
|
1362 |
"""
|
1363 |
jlist = [] |
1364 |
for filename in utils.ListVisibleFiles(constants.QUEUE_DIR): |
1365 |
m = self._RE_JOB_FILE.match(filename)
|
1366 |
if m:
|
1367 |
jlist.append(m.group(1))
|
1368 |
if sort:
|
1369 |
jlist = utils.NiceSort(jlist) |
1370 |
return jlist
|
1371 |
|
1372 |
def _LoadJobUnlocked(self, job_id): |
1373 |
"""Loads a job from the disk or memory.
|
1374 |
|
1375 |
Given a job id, this will return the cached job object if
|
1376 |
existing, or try to load the job from the disk. If loading from
|
1377 |
disk, it will also add the job to the cache.
|
1378 |
|
1379 |
@param job_id: the job id
|
1380 |
@rtype: L{_QueuedJob} or None
|
1381 |
@return: either None or the job object
|
1382 |
|
1383 |
"""
|
1384 |
job = self._memcache.get(job_id, None) |
1385 |
if job:
|
1386 |
logging.debug("Found job %s in memcache", job_id)
|
1387 |
return job
|
1388 |
|
1389 |
try:
|
1390 |
job = self._LoadJobFromDisk(job_id)
|
1391 |
if job is None: |
1392 |
return job
|
1393 |
except errors.JobFileCorrupted:
|
1394 |
old_path = self._GetJobPath(job_id)
|
1395 |
new_path = self._GetArchivedJobPath(job_id)
|
1396 |
if old_path == new_path:
|
1397 |
# job already archived (future case)
|
1398 |
logging.exception("Can't parse job %s", job_id)
|
1399 |
else:
|
1400 |
# non-archived case
|
1401 |
logging.exception("Can't parse job %s, will archive.", job_id)
|
1402 |
self._RenameFilesUnlocked([(old_path, new_path)])
|
1403 |
return None |
1404 |
|
1405 |
self._memcache[job_id] = job
|
1406 |
logging.debug("Added job %s to the cache", job_id)
|
1407 |
return job
|
1408 |
|
1409 |
def _LoadJobFromDisk(self, job_id): |
1410 |
"""Load the given job file from disk.
|
1411 |
|
1412 |
Given a job file, read, load and restore it in a _QueuedJob format.
|
1413 |
|
1414 |
@type job_id: string
|
1415 |
@param job_id: job identifier
|
1416 |
@rtype: L{_QueuedJob} or None
|
1417 |
@return: either None or the job object
|
1418 |
|
1419 |
"""
|
1420 |
filepath = self._GetJobPath(job_id)
|
1421 |
logging.debug("Loading job from %s", filepath)
|
1422 |
try:
|
1423 |
raw_data = utils.ReadFile(filepath) |
1424 |
except EnvironmentError, err: |
1425 |
if err.errno in (errno.ENOENT, ): |
1426 |
return None |
1427 |
raise
|
1428 |
|
1429 |
try:
|
1430 |
data = serializer.LoadJson(raw_data) |
1431 |
job = _QueuedJob.Restore(self, data)
|
1432 |
except Exception, err: # pylint: disable-msg=W0703 |
1433 |
raise errors.JobFileCorrupted(err)
|
1434 |
|
1435 |
return job
|
1436 |
|
1437 |
def SafeLoadJobFromDisk(self, job_id): |
1438 |
"""Load the given job file from disk.
|
1439 |
|
1440 |
Given a job file, read, load and restore it in a _QueuedJob format.
|
1441 |
In case of error reading the job, it gets returned as None, and the
|
1442 |
exception is logged.
|
1443 |
|
1444 |
@type job_id: string
|
1445 |
@param job_id: job identifier
|
1446 |
@rtype: L{_QueuedJob} or None
|
1447 |
@return: either None or the job object
|
1448 |
|
1449 |
"""
|
1450 |
try:
|
1451 |
return self._LoadJobFromDisk(job_id) |
1452 |
except (errors.JobFileCorrupted, EnvironmentError): |
1453 |
logging.exception("Can't load/parse job %s", job_id)
|
1454 |
return None |
1455 |
|
1456 |
@staticmethod
|
1457 |
def _IsQueueMarkedDrain(): |
1458 |
"""Check if the queue is marked from drain.
|
1459 |
|
1460 |
This currently uses the queue drain file, which makes it a
|
1461 |
per-node flag. In the future this can be moved to the config file.
|
1462 |
|
1463 |
@rtype: boolean
|
1464 |
@return: True of the job queue is marked for draining
|
1465 |
|
1466 |
"""
|
1467 |
return os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
|
1468 |
|
1469 |
def _UpdateQueueSizeUnlocked(self): |
1470 |
"""Update the queue size.
|
1471 |
|
1472 |
"""
|
1473 |
self._queue_size = len(self._GetJobIDsUnlocked(sort=False)) |
1474 |
|
1475 |
@locking.ssynchronized(_LOCK)
|
1476 |
@_RequireOpenQueue
|
1477 |
def SetDrainFlag(self, drain_flag): |
1478 |
"""Sets the drain flag for the queue.
|
1479 |
|
1480 |
@type drain_flag: boolean
|
1481 |
@param drain_flag: Whether to set or unset the drain flag
|
1482 |
|
1483 |
"""
|
1484 |
getents = runtime.GetEnts() |
1485 |
|
1486 |
if drain_flag:
|
1487 |
utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True, |
1488 |
uid=getents.masterd_uid, gid=getents.masterd_gid) |
1489 |
else:
|
1490 |
utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE) |
1491 |
|
1492 |
self._drained = drain_flag
|
1493 |
|
1494 |
return True |
1495 |
|
1496 |
@_RequireOpenQueue
|
1497 |
def _SubmitJobUnlocked(self, job_id, ops): |
1498 |
"""Create and store a new job.
|
1499 |
|
1500 |
This enters the job into our job queue and also puts it on the new
|
1501 |
queue, in order for it to be picked up by the queue processors.
|
1502 |
|
1503 |
@type job_id: job ID
|
1504 |
@param job_id: the job ID for the new job
|
1505 |
@type ops: list
|
1506 |
@param ops: The list of OpCodes that will become the new job.
|
1507 |
@rtype: L{_QueuedJob}
|
1508 |
@return: the job object to be queued
|
1509 |
@raise errors.JobQueueDrainError: if the job queue is marked for draining
|
1510 |
@raise errors.JobQueueFull: if the job queue has too many jobs in it
|
1511 |
@raise errors.GenericError: If an opcode is not valid
|
1512 |
|
1513 |
"""
|
1514 |
# Ok when sharing the big job queue lock, as the drain file is created when
|
1515 |
# the lock is exclusive.
|
1516 |
if self._drained: |
1517 |
raise errors.JobQueueDrainError("Job queue is drained, refusing job") |
1518 |
|
1519 |
if self._queue_size >= constants.JOB_QUEUE_SIZE_HARD_LIMIT: |
1520 |
raise errors.JobQueueFull()
|
1521 |
|
1522 |
job = _QueuedJob(self, job_id, ops)
|
1523 |
|
1524 |
# Check priority
|
1525 |
for idx, op in enumerate(job.ops): |
1526 |
if op.priority not in constants.OP_PRIO_SUBMIT_VALID: |
1527 |
allowed = utils.CommaJoin(constants.OP_PRIO_SUBMIT_VALID) |
1528 |
raise errors.GenericError("Opcode %s has invalid priority %s, allowed" |
1529 |
" are %s" % (idx, op.priority, allowed))
|
1530 |
|
1531 |
# Write to disk
|
1532 |
self.UpdateJobUnlocked(job)
|
1533 |
|
1534 |
self._queue_size += 1 |
1535 |
|
1536 |
logging.debug("Adding new job %s to the cache", job_id)
|
1537 |
self._memcache[job_id] = job
|
1538 |
|
1539 |
return job
|
1540 |
|
1541 |
@locking.ssynchronized(_LOCK)
|
1542 |
@_RequireOpenQueue
|
1543 |
def SubmitJob(self, ops): |
1544 |
"""Create and store a new job.
|
1545 |
|
1546 |
@see: L{_SubmitJobUnlocked}
|
1547 |
|
1548 |
"""
|
1549 |
job_id = self._NewSerialsUnlocked(1)[0] |
1550 |
self._EnqueueJobs([self._SubmitJobUnlocked(job_id, ops)]) |
1551 |
return job_id
|
1552 |
|
1553 |
@locking.ssynchronized(_LOCK)
|
1554 |
@_RequireOpenQueue
|
1555 |
def SubmitManyJobs(self, jobs): |
1556 |
"""Create and store multiple jobs.
|
1557 |
|
1558 |
@see: L{_SubmitJobUnlocked}
|
1559 |
|
1560 |
"""
|
1561 |
results = [] |
1562 |
added_jobs = [] |
1563 |
all_job_ids = self._NewSerialsUnlocked(len(jobs)) |
1564 |
for job_id, ops in zip(all_job_ids, jobs): |
1565 |
try:
|
1566 |
added_jobs.append(self._SubmitJobUnlocked(job_id, ops))
|
1567 |
status = True
|
1568 |
data = job_id |
1569 |
except errors.GenericError, err:
|
1570 |
data = str(err)
|
1571 |
status = False
|
1572 |
results.append((status, data)) |
1573 |
|
1574 |
self._EnqueueJobs(added_jobs)
|
1575 |
|
1576 |
return results
|
1577 |
|
1578 |
def _EnqueueJobs(self, jobs): |
1579 |
"""Helper function to add jobs to worker pool's queue.
|
1580 |
|
1581 |
@type jobs: list
|
1582 |
@param jobs: List of all jobs
|
1583 |
|
1584 |
"""
|
1585 |
self._wpool.AddManyTasks([(job, ) for job in jobs], |
1586 |
priority=[job.CalcPriority() for job in jobs]) |
1587 |
|
1588 |
@_RequireOpenQueue
|
1589 |
def UpdateJobUnlocked(self, job, replicate=True): |
1590 |
"""Update a job's on disk storage.
|
1591 |
|
1592 |
After a job has been modified, this function needs to be called in
|
1593 |
order to write the changes to disk and replicate them to the other
|
1594 |
nodes.
|
1595 |
|
1596 |
@type job: L{_QueuedJob}
|
1597 |
@param job: the changed job
|
1598 |
@type replicate: boolean
|
1599 |
@param replicate: whether to replicate the change to remote nodes
|
1600 |
|
1601 |
"""
|
1602 |
filename = self._GetJobPath(job.id)
|
1603 |
data = serializer.DumpJson(job.Serialize(), indent=False)
|
1604 |
logging.debug("Writing job %s to %s", job.id, filename)
|
1605 |
self._UpdateJobQueueFile(filename, data, replicate)
|
1606 |
|
1607 |
def WaitForJobChanges(self, job_id, fields, prev_job_info, prev_log_serial, |
1608 |
timeout): |
1609 |
"""Waits for changes in a job.
|
1610 |
|
1611 |
@type job_id: string
|
1612 |
@param job_id: Job identifier
|
1613 |
@type fields: list of strings
|
1614 |
@param fields: Which fields to check for changes
|
1615 |
@type prev_job_info: list or None
|
1616 |
@param prev_job_info: Last job information returned
|
1617 |
@type prev_log_serial: int
|
1618 |
@param prev_log_serial: Last job message serial number
|
1619 |
@type timeout: float
|
1620 |
@param timeout: maximum time to wait in seconds
|
1621 |
@rtype: tuple (job info, log entries)
|
1622 |
@return: a tuple of the job information as required via
|
1623 |
the fields parameter, and the log entries as a list
|
1624 |
|
1625 |
if the job has not changed and the timeout has expired,
|
1626 |
we instead return a special value,
|
1627 |
L{constants.JOB_NOTCHANGED}, which should be interpreted
|
1628 |
as such by the clients
|
1629 |
|
1630 |
"""
|
1631 |
load_fn = compat.partial(self.SafeLoadJobFromDisk, job_id)
|
1632 |
|
1633 |
helper = _WaitForJobChangesHelper() |
1634 |
|
1635 |
return helper(self._GetJobPath(job_id), load_fn, |
1636 |
fields, prev_job_info, prev_log_serial, timeout) |
1637 |
|
1638 |
@locking.ssynchronized(_LOCK)
|
1639 |
@_RequireOpenQueue
|
1640 |
def CancelJob(self, job_id): |
1641 |
"""Cancels a job.
|
1642 |
|
1643 |
This will only succeed if the job has not started yet.
|
1644 |
|
1645 |
@type job_id: string
|
1646 |
@param job_id: job ID of job to be cancelled.
|
1647 |
|
1648 |
"""
|
1649 |
logging.info("Cancelling job %s", job_id)
|
1650 |
|
1651 |
job = self._LoadJobUnlocked(job_id)
|
1652 |
if not job: |
1653 |
logging.debug("Job %s not found", job_id)
|
1654 |
return (False, "Job %s not found" % job_id) |
1655 |
|
1656 |
(success, msg) = job.Cancel() |
1657 |
|
1658 |
if success:
|
1659 |
self.UpdateJobUnlocked(job)
|
1660 |
|
1661 |
return (success, msg)
|
1662 |
|
1663 |
@_RequireOpenQueue
|
1664 |
def _ArchiveJobsUnlocked(self, jobs): |
1665 |
"""Archives jobs.
|
1666 |
|
1667 |
@type jobs: list of L{_QueuedJob}
|
1668 |
@param jobs: Job objects
|
1669 |
@rtype: int
|
1670 |
@return: Number of archived jobs
|
1671 |
|
1672 |
"""
|
1673 |
archive_jobs = [] |
1674 |
rename_files = [] |
1675 |
for job in jobs: |
1676 |
if job.CalcStatus() not in constants.JOBS_FINALIZED: |
1677 |
logging.debug("Job %s is not yet done", job.id)
|
1678 |
continue
|
1679 |
|
1680 |
archive_jobs.append(job) |
1681 |
|
1682 |
old = self._GetJobPath(job.id)
|
1683 |
new = self._GetArchivedJobPath(job.id)
|
1684 |
rename_files.append((old, new)) |
1685 |
|
1686 |
# TODO: What if 1..n files fail to rename?
|
1687 |
self._RenameFilesUnlocked(rename_files)
|
1688 |
|
1689 |
logging.debug("Successfully archived job(s) %s",
|
1690 |
utils.CommaJoin(job.id for job in archive_jobs)) |
1691 |
|
1692 |
# Since we haven't quite checked, above, if we succeeded or failed renaming
|
1693 |
# the files, we update the cached queue size from the filesystem. When we
|
1694 |
# get around to fix the TODO: above, we can use the number of actually
|
1695 |
# archived jobs to fix this.
|
1696 |
self._UpdateQueueSizeUnlocked()
|
1697 |
return len(archive_jobs) |
1698 |
|
1699 |
@locking.ssynchronized(_LOCK)
|
1700 |
@_RequireOpenQueue
|
1701 |
def ArchiveJob(self, job_id): |
1702 |
"""Archives a job.
|
1703 |
|
1704 |
This is just a wrapper over L{_ArchiveJobsUnlocked}.
|
1705 |
|
1706 |
@type job_id: string
|
1707 |
@param job_id: Job ID of job to be archived.
|
1708 |
@rtype: bool
|
1709 |
@return: Whether job was archived
|
1710 |
|
1711 |
"""
|
1712 |
logging.info("Archiving job %s", job_id)
|
1713 |
|
1714 |
job = self._LoadJobUnlocked(job_id)
|
1715 |
if not job: |
1716 |
logging.debug("Job %s not found", job_id)
|
1717 |
return False |
1718 |
|
1719 |
return self._ArchiveJobsUnlocked([job]) == 1 |
1720 |
|
1721 |
@locking.ssynchronized(_LOCK)
|
1722 |
@_RequireOpenQueue
|
1723 |
def AutoArchiveJobs(self, age, timeout): |
1724 |
"""Archives all jobs based on age.
|
1725 |
|
1726 |
The method will archive all jobs which are older than the age
|
1727 |
parameter. For jobs that don't have an end timestamp, the start
|
1728 |
timestamp will be considered. The special '-1' age will cause
|
1729 |
archival of all jobs (that are not running or queued).
|
1730 |
|
1731 |
@type age: int
|
1732 |
@param age: the minimum age in seconds
|
1733 |
|
1734 |
"""
|
1735 |
logging.info("Archiving jobs with age more than %s seconds", age)
|
1736 |
|
1737 |
now = time.time() |
1738 |
end_time = now + timeout |
1739 |
archived_count = 0
|
1740 |
last_touched = 0
|
1741 |
|
1742 |
all_job_ids = self._GetJobIDsUnlocked()
|
1743 |
pending = [] |
1744 |
for idx, job_id in enumerate(all_job_ids): |
1745 |
last_touched = idx + 1
|
1746 |
|
1747 |
# Not optimal because jobs could be pending
|
1748 |
# TODO: Measure average duration for job archival and take number of
|
1749 |
# pending jobs into account.
|
1750 |
if time.time() > end_time:
|
1751 |
break
|
1752 |
|
1753 |
# Returns None if the job failed to load
|
1754 |
job = self._LoadJobUnlocked(job_id)
|
1755 |
if job:
|
1756 |
if job.end_timestamp is None: |
1757 |
if job.start_timestamp is None: |
1758 |
job_age = job.received_timestamp |
1759 |
else:
|
1760 |
job_age = job.start_timestamp |
1761 |
else:
|
1762 |
job_age = job.end_timestamp |
1763 |
|
1764 |
if age == -1 or now - job_age[0] > age: |
1765 |
pending.append(job) |
1766 |
|
1767 |
# Archive 10 jobs at a time
|
1768 |
if len(pending) >= 10: |
1769 |
archived_count += self._ArchiveJobsUnlocked(pending)
|
1770 |
pending = [] |
1771 |
|
1772 |
if pending:
|
1773 |
archived_count += self._ArchiveJobsUnlocked(pending)
|
1774 |
|
1775 |
return (archived_count, len(all_job_ids) - last_touched) |
1776 |
|
1777 |
def QueryJobs(self, job_ids, fields): |
1778 |
"""Returns a list of jobs in queue.
|
1779 |
|
1780 |
@type job_ids: list
|
1781 |
@param job_ids: sequence of job identifiers or None for all
|
1782 |
@type fields: list
|
1783 |
@param fields: names of fields to return
|
1784 |
@rtype: list
|
1785 |
@return: list one element per job, each element being list with
|
1786 |
the requested fields
|
1787 |
|
1788 |
"""
|
1789 |
jobs = [] |
1790 |
list_all = False
|
1791 |
if not job_ids: |
1792 |
# Since files are added to/removed from the queue atomically, there's no
|
1793 |
# risk of getting the job ids in an inconsistent state.
|
1794 |
job_ids = self._GetJobIDsUnlocked()
|
1795 |
list_all = True
|
1796 |
|
1797 |
for job_id in job_ids: |
1798 |
job = self.SafeLoadJobFromDisk(job_id)
|
1799 |
if job is not None: |
1800 |
jobs.append(job.GetInfo(fields)) |
1801 |
elif not list_all: |
1802 |
jobs.append(None)
|
1803 |
|
1804 |
return jobs
|
1805 |
|
1806 |
@locking.ssynchronized(_LOCK)
|
1807 |
@_RequireOpenQueue
|
1808 |
def Shutdown(self): |
1809 |
"""Stops the job queue.
|
1810 |
|
1811 |
This shutdowns all the worker threads an closes the queue.
|
1812 |
|
1813 |
"""
|
1814 |
self._wpool.TerminateWorkers()
|
1815 |
|
1816 |
self._queue_filelock.Close()
|
1817 |
self._queue_filelock = None |