Statistics
| Branch: | Tag: | Revision:

root / lib / jqueue.py @ fa4aa6b4

History | View | Annotate | Download (53.6 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._InitInMemory(self)
207

    
208
  @staticmethod
209
  def _InitInMemory(obj):
210
    """Initializes in-memory variables.
211

212
    """
213
    obj.current_op = None
214

    
215
  def __repr__(self):
216
    status = ["%s.%s" % (self.__class__.__module__, self.__class__.__name__),
217
              "id=%s" % self.id,
218
              "ops=%s" % ",".join([op.input.Summary() for op in self.ops])]
219

    
220
    return "<%s at %#x>" % (" ".join(status), id(self))
221

    
222
  @classmethod
223
  def Restore(cls, queue, state):
224
    """Restore a _QueuedJob from serialized state:
225

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

233
    """
234
    obj = _QueuedJob.__new__(cls)
235
    obj.queue = queue
236
    obj.id = state["id"]
237
    obj.received_timestamp = state.get("received_timestamp", None)
238
    obj.start_timestamp = state.get("start_timestamp", None)
239
    obj.end_timestamp = state.get("end_timestamp", None)
240

    
241
    obj.ops = []
242
    obj.log_serial = 0
243
    for op_state in state["ops"]:
244
      op = _QueuedOpCode.Restore(op_state)
245
      for log_entry in op.log:
246
        obj.log_serial = max(obj.log_serial, log_entry[0])
247
      obj.ops.append(op)
248

    
249
    cls._InitInMemory(obj)
250

    
251
    return obj
252

    
253
  def Serialize(self):
254
    """Serialize the _JobQueue instance.
255

256
    @rtype: dict
257
    @return: the serialized state
258

259
    """
260
    return {
261
      "id": self.id,
262
      "ops": [op.Serialize() for op in self.ops],
263
      "start_timestamp": self.start_timestamp,
264
      "end_timestamp": self.end_timestamp,
265
      "received_timestamp": self.received_timestamp,
266
      }
267

    
268
  def CalcStatus(self):
269
    """Compute the status of this job.
270

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

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

282
        will determine the job status
283

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

287
    @return: the job status
288

289
    """
290
    status = constants.JOB_STATUS_QUEUED
291

    
292
    all_success = True
293
    for op in self.ops:
294
      if op.status == constants.OP_STATUS_SUCCESS:
295
        continue
296

    
297
      all_success = False
298

    
299
      if op.status == constants.OP_STATUS_QUEUED:
300
        pass
301
      elif op.status == constants.OP_STATUS_WAITLOCK:
302
        status = constants.JOB_STATUS_WAITLOCK
303
      elif op.status == constants.OP_STATUS_RUNNING:
304
        status = constants.JOB_STATUS_RUNNING
305
      elif op.status == constants.OP_STATUS_CANCELING:
306
        status = constants.JOB_STATUS_CANCELING
307
        break
308
      elif op.status == constants.OP_STATUS_ERROR:
309
        status = constants.JOB_STATUS_ERROR
310
        # The whole job fails if one opcode failed
311
        break
312
      elif op.status == constants.OP_STATUS_CANCELED:
313
        status = constants.OP_STATUS_CANCELED
314
        break
315

    
316
    if all_success:
317
      status = constants.JOB_STATUS_SUCCESS
318

    
319
    return status
320

    
321
  def CalcPriority(self):
322
    """Gets the current priority for this job.
323

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

327
    @rtype: int
328

329
    """
330
    priorities = [op.priority for op in self.ops
331
                  if op.status not in constants.OPS_FINALIZED]
332

    
333
    if not priorities:
334
      # All opcodes are done, assume default priority
335
      return constants.OP_PRIO_DEFAULT
336

    
337
    return min(priorities)
338

    
339
  def GetLogEntries(self, newer_than):
340
    """Selectively returns the log entries.
341

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

349
    """
350
    if newer_than is None:
351
      serial = -1
352
    else:
353
      serial = newer_than
354

    
355
    entries = []
356
    for op in self.ops:
357
      entries.extend(filter(lambda entry: entry[0] > serial, op.log))
358

    
359
    return entries
360

    
361
  def GetInfo(self, fields):
362
    """Returns information about a job.
363

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

371
    """
372
    row = []
373
    for fname in fields:
374
      if fname == "id":
375
        row.append(self.id)
376
      elif fname == "status":
377
        row.append(self.CalcStatus())
378
      elif fname == "ops":
379
        row.append([op.input.__getstate__() for op in self.ops])
380
      elif fname == "opresult":
381
        row.append([op.result for op in self.ops])
382
      elif fname == "opstatus":
383
        row.append([op.status for op in self.ops])
384
      elif fname == "oplog":
385
        row.append([op.log for op in self.ops])
386
      elif fname == "opstart":
387
        row.append([op.start_timestamp for op in self.ops])
388
      elif fname == "opexec":
389
        row.append([op.exec_timestamp for op in self.ops])
390
      elif fname == "opend":
391
        row.append([op.end_timestamp for op in self.ops])
392
      elif fname == "received_ts":
393
        row.append(self.received_timestamp)
394
      elif fname == "start_ts":
395
        row.append(self.start_timestamp)
396
      elif fname == "end_ts":
397
        row.append(self.end_timestamp)
398
      elif fname == "summary":
399
        row.append([op.input.Summary() for op in self.ops])
400
      else:
401
        raise errors.OpExecError("Invalid self query field '%s'" % fname)
402
    return row
403

    
404
  def MarkUnfinishedOps(self, status, result):
405
    """Mark unfinished opcodes with a given status and result.
406

407
    This is an utility function for marking all running or waiting to
408
    be run opcodes with a given status. Opcodes which are already
409
    finalised are not changed.
410

411
    @param status: a given opcode status
412
    @param result: the opcode result
413

414
    """
415
    not_marked = True
416
    for op in self.ops:
417
      if op.status in constants.OPS_FINALIZED:
418
        assert not_marked, "Finalized opcodes found after non-finalized ones"
419
        continue
420
      op.status = status
421
      op.result = result
422
      not_marked = False
423

    
424
  def Cancel(self):
425
    """Marks job as canceled/-ing if possible.
426

427
    @rtype: tuple; (bool, string)
428
    @return: Boolean describing whether job was successfully canceled or marked
429
      as canceling and a text message
430

431
    """
432
    status = self.CalcStatus()
433

    
434
    if status not in (constants.JOB_STATUS_QUEUED,
435
                      constants.JOB_STATUS_WAITLOCK):
436
      logging.debug("Job %s is no longer waiting in the queue", self.id)
437
      return (False, "Job %s is no longer waiting in the queue" % self.id)
438

    
439
    if status == constants.JOB_STATUS_QUEUED:
440
      self.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
441
                             "Job canceled by request")
442
      msg = "Job %s canceled" % self.id
443

    
444
    elif status == constants.JOB_STATUS_WAITLOCK:
445
      # The worker will notice the new status and cancel the job
446
      self.MarkUnfinishedOps(constants.OP_STATUS_CANCELING, None)
447
      msg = "Job %s will be canceled" % self.id
448

    
449
    return (True, msg)
450

    
451

    
452
class _OpExecCallbacks(mcpu.OpExecCbBase):
453
  def __init__(self, queue, job, op):
454
    """Initializes this class.
455

456
    @type queue: L{JobQueue}
457
    @param queue: Job queue
458
    @type job: L{_QueuedJob}
459
    @param job: Job object
460
    @type op: L{_QueuedOpCode}
461
    @param op: OpCode
462

463
    """
464
    assert queue, "Queue is missing"
465
    assert job, "Job is missing"
466
    assert op, "Opcode is missing"
467

    
468
    self._queue = queue
469
    self._job = job
470
    self._op = op
471

    
472
  def _CheckCancel(self):
473
    """Raises an exception to cancel the job if asked to.
474

475
    """
476
    # Cancel here if we were asked to
477
    if self._op.status == constants.OP_STATUS_CANCELING:
478
      logging.debug("Canceling opcode")
479
      raise CancelJob()
480

    
481
  @locking.ssynchronized(_QUEUE, shared=1)
482
  def NotifyStart(self):
483
    """Mark the opcode as running, not lock-waiting.
484

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

490
    """
491
    assert self._op in self._job.ops
492
    assert self._op.status in (constants.OP_STATUS_WAITLOCK,
493
                               constants.OP_STATUS_CANCELING)
494

    
495
    # Cancel here if we were asked to
496
    self._CheckCancel()
497

    
498
    logging.debug("Opcode is now running")
499

    
500
    self._op.status = constants.OP_STATUS_RUNNING
501
    self._op.exec_timestamp = TimeStampNow()
502

    
503
    # And finally replicate the job status
504
    self._queue.UpdateJobUnlocked(self._job)
505

    
506
  @locking.ssynchronized(_QUEUE, shared=1)
507
  def _AppendFeedback(self, timestamp, log_type, log_msg):
508
    """Internal feedback append function, with locks
509

510
    """
511
    self._job.log_serial += 1
512
    self._op.log.append((self._job.log_serial, timestamp, log_type, log_msg))
513
    self._queue.UpdateJobUnlocked(self._job, replicate=False)
514

    
515
  def Feedback(self, *args):
516
    """Append a log entry.
517

518
    """
519
    assert len(args) < 3
520

    
521
    if len(args) == 1:
522
      log_type = constants.ELOG_MESSAGE
523
      log_msg = args[0]
524
    else:
525
      (log_type, log_msg) = args
526

    
527
    # The time is split to make serialization easier and not lose
528
    # precision.
529
    timestamp = utils.SplitTime(time.time())
530
    self._AppendFeedback(timestamp, log_type, log_msg)
531

    
532
  def CheckCancel(self):
533
    """Check whether job has been cancelled.
534

535
    """
536
    assert self._op.status in (constants.OP_STATUS_WAITLOCK,
537
                               constants.OP_STATUS_CANCELING)
538

    
539
    # Cancel here if we were asked to
540
    self._CheckCancel()
541

    
542

    
543
class _JobChangesChecker(object):
544
  def __init__(self, fields, prev_job_info, prev_log_serial):
545
    """Initializes this class.
546

547
    @type fields: list of strings
548
    @param fields: Fields requested by LUXI client
549
    @type prev_job_info: string
550
    @param prev_job_info: previous job info, as passed by the LUXI client
551
    @type prev_log_serial: string
552
    @param prev_log_serial: previous job serial, as passed by the LUXI client
553

554
    """
555
    self._fields = fields
556
    self._prev_job_info = prev_job_info
557
    self._prev_log_serial = prev_log_serial
558

    
559
  def __call__(self, job):
560
    """Checks whether job has changed.
561

562
    @type job: L{_QueuedJob}
563
    @param job: Job object
564

565
    """
566
    status = job.CalcStatus()
567
    job_info = job.GetInfo(self._fields)
568
    log_entries = job.GetLogEntries(self._prev_log_serial)
569

    
570
    # Serializing and deserializing data can cause type changes (e.g. from
571
    # tuple to list) or precision loss. We're doing it here so that we get
572
    # the same modifications as the data received from the client. Without
573
    # this, the comparison afterwards might fail without the data being
574
    # significantly different.
575
    # TODO: we just deserialized from disk, investigate how to make sure that
576
    # the job info and log entries are compatible to avoid this further step.
577
    # TODO: Doing something like in testutils.py:UnifyValueType might be more
578
    # efficient, though floats will be tricky
579
    job_info = serializer.LoadJson(serializer.DumpJson(job_info))
580
    log_entries = serializer.LoadJson(serializer.DumpJson(log_entries))
581

    
582
    # Don't even try to wait if the job is no longer running, there will be
583
    # no changes.
584
    if (status not in (constants.JOB_STATUS_QUEUED,
585
                       constants.JOB_STATUS_RUNNING,
586
                       constants.JOB_STATUS_WAITLOCK) or
587
        job_info != self._prev_job_info or
588
        (log_entries and self._prev_log_serial != log_entries[0][0])):
589
      logging.debug("Job %s changed", job.id)
590
      return (job_info, log_entries)
591

    
592
    return None
593

    
594

    
595
class _JobFileChangesWaiter(object):
596
  def __init__(self, filename):
597
    """Initializes this class.
598

599
    @type filename: string
600
    @param filename: Path to job file
601
    @raises errors.InotifyError: if the notifier cannot be setup
602

603
    """
604
    self._wm = pyinotify.WatchManager()
605
    self._inotify_handler = \
606
      asyncnotifier.SingleFileEventHandler(self._wm, self._OnInotify, filename)
607
    self._notifier = \
608
      pyinotify.Notifier(self._wm, default_proc_fun=self._inotify_handler)
609
    try:
610
      self._inotify_handler.enable()
611
    except Exception:
612
      # pyinotify doesn't close file descriptors automatically
613
      self._notifier.stop()
614
      raise
615

    
616
  def _OnInotify(self, notifier_enabled):
617
    """Callback for inotify.
618

619
    """
620
    if not notifier_enabled:
621
      self._inotify_handler.enable()
622

    
623
  def Wait(self, timeout):
624
    """Waits for the job file to change.
625

626
    @type timeout: float
627
    @param timeout: Timeout in seconds
628
    @return: Whether there have been events
629

630
    """
631
    assert timeout >= 0
632
    have_events = self._notifier.check_events(timeout * 1000)
633
    if have_events:
634
      self._notifier.read_events()
635
    self._notifier.process_events()
636
    return have_events
637

    
638
  def Close(self):
639
    """Closes underlying notifier and its file descriptor.
640

641
    """
642
    self._notifier.stop()
643

    
644

    
645
class _JobChangesWaiter(object):
646
  def __init__(self, filename):
647
    """Initializes this class.
648

649
    @type filename: string
650
    @param filename: Path to job file
651

652
    """
653
    self._filewaiter = None
654
    self._filename = filename
655

    
656
  def Wait(self, timeout):
657
    """Waits for a job to change.
658

659
    @type timeout: float
660
    @param timeout: Timeout in seconds
661
    @return: Whether there have been events
662

663
    """
664
    if self._filewaiter:
665
      return self._filewaiter.Wait(timeout)
666

    
667
    # Lazy setup: Avoid inotify setup cost when job file has already changed.
668
    # If this point is reached, return immediately and let caller check the job
669
    # file again in case there were changes since the last check. This avoids a
670
    # race condition.
671
    self._filewaiter = _JobFileChangesWaiter(self._filename)
672

    
673
    return True
674

    
675
  def Close(self):
676
    """Closes underlying waiter.
677

678
    """
679
    if self._filewaiter:
680
      self._filewaiter.Close()
681

    
682

    
683
class _WaitForJobChangesHelper(object):
684
  """Helper class using inotify to wait for changes in a job file.
685

686
  This class takes a previous job status and serial, and alerts the client when
687
  the current job status has changed.
688

689
  """
690
  @staticmethod
691
  def _CheckForChanges(job_load_fn, check_fn):
692
    job = job_load_fn()
693
    if not job:
694
      raise errors.JobLost()
695

    
696
    result = check_fn(job)
697
    if result is None:
698
      raise utils.RetryAgain()
699

    
700
    return result
701

    
702
  def __call__(self, filename, job_load_fn,
703
               fields, prev_job_info, prev_log_serial, timeout):
704
    """Waits for changes on a job.
705

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

719
    """
720
    try:
721
      check_fn = _JobChangesChecker(fields, prev_job_info, prev_log_serial)
722
      waiter = _JobChangesWaiter(filename)
723
      try:
724
        return utils.Retry(compat.partial(self._CheckForChanges,
725
                                          job_load_fn, check_fn),
726
                           utils.RETRY_REMAINING_TIME, timeout,
727
                           wait_fn=waiter.Wait)
728
      finally:
729
        waiter.Close()
730
    except (errors.InotifyError, errors.JobLost):
731
      return None
732
    except utils.RetryTimeout:
733
      return constants.JOB_NOTCHANGED
734

    
735

    
736
def _EncodeOpError(err):
737
  """Encodes an error which occurred while processing an opcode.
738

739
  """
740
  if isinstance(err, errors.GenericError):
741
    to_encode = err
742
  else:
743
    to_encode = errors.OpExecError(str(err))
744

    
745
  return errors.EncodeException(to_encode)
746

    
747

    
748
class _JobProcessor(object):
749
  def __init__(self, queue, opexec_fn, job):
750
    """Initializes this class.
751

752
    """
753
    self.queue = queue
754
    self.opexec_fn = opexec_fn
755
    self.job = job
756

    
757
  @staticmethod
758
  def _FindNextOpcode(job):
759
    """Locates the next opcode to run.
760

761
    @type job: L{_QueuedJob}
762
    @param job: Job object
763

764
    """
765
    # Create some sort of a cache to speed up locating next opcode for future
766
    # lookups
767
    # TODO: Consider splitting _QueuedJob.ops into two separate lists, one for
768
    # pending and one for processed ops.
769
    if job.current_op is None:
770
      job.current_op = enumerate(job.ops)
771

    
772
    # Find next opcode to run
773
    while True:
774
      try:
775
        (idx, op) = job.current_op.next()
776
      except StopIteration:
777
        raise errors.ProgrammerError("Called for a finished job")
778

    
779
      if op.status == constants.OP_STATUS_RUNNING:
780
        # Found an opcode already marked as running
781
        raise errors.ProgrammerError("Called for job marked as running")
782

    
783
      log_prefix = "Op %s/%s" % (idx + 1, len(job.ops))
784
      summary = op.input.Summary()
785

    
786
      if op.status == constants.OP_STATUS_CANCELED:
787
        # Cancelled jobs are handled by the caller
788
        assert not compat.any(i.status != constants.OP_STATUS_CANCELED
789
                              for i in job.ops[idx:])
790

    
791
      elif op.status in constants.OPS_FINALIZED:
792
        # This is a job that was partially completed before master daemon
793
        # shutdown, so it can be expected that some opcodes are already
794
        # completed successfully (if any did error out, then the whole job
795
        # should have been aborted and not resubmitted for processing).
796
        logging.info("%s: opcode %s already processed, skipping",
797
                     log_prefix, summary)
798
        continue
799

    
800
      return (idx, op, log_prefix, summary)
801

    
802
  @staticmethod
803
  def _MarkWaitlock(job, op):
804
    """Marks an opcode as waiting for locks.
805

806
    The job's start timestamp is also set if necessary.
807

808
    @type job: L{_QueuedJob}
809
    @param job: Job object
810
    @type job: L{_QueuedOpCode}
811
    @param job: Opcode object
812

813
    """
814
    assert op in job.ops
815

    
816
    op.status = constants.OP_STATUS_WAITLOCK
817
    op.result = None
818
    op.start_timestamp = TimeStampNow()
819

    
820
    if job.start_timestamp is None:
821
      job.start_timestamp = op.start_timestamp
822

    
823
  def _ExecOpCodeUnlocked(self, log_prefix, op, summary):
824
    """Processes one opcode and returns the result.
825

826
    """
827
    assert op.status == constants.OP_STATUS_WAITLOCK
828

    
829
    try:
830
      # Make sure not to hold queue lock while calling ExecOpCode
831
      result = self.opexec_fn(op.input,
832
                              _OpExecCallbacks(self.queue, self.job, op))
833
    except CancelJob:
834
      logging.exception("%s: Canceling job", log_prefix)
835
      assert op.status == constants.OP_STATUS_CANCELING
836
      return (constants.OP_STATUS_CANCELING, None)
837
    except Exception, err: # pylint: disable-msg=W0703
838
      logging.exception("%s: Caught exception in %s", log_prefix, summary)
839
      return (constants.OP_STATUS_ERROR, _EncodeOpError(err))
840
    else:
841
      logging.debug("%s: %s successful", log_prefix, summary)
842
      return (constants.OP_STATUS_SUCCESS, result)
843

    
844
  def __call__(self):
845
    """Continues execution of a job.
846

847
    @rtype: bool
848
    @return: True if job is finished, False if processor needs to be called
849
             again
850

851
    """
852
    queue = self.queue
853
    job = self.job
854

    
855
    logging.debug("Processing job %s", job.id)
856

    
857
    queue.acquire(shared=1)
858
    try:
859
      opcount = len(job.ops)
860

    
861
      (opidx, op, log_prefix, op_summary) = self._FindNextOpcode(job)
862

    
863
      # Consistency check
864
      assert compat.all(i.status in (constants.OP_STATUS_QUEUED,
865
                                     constants.OP_STATUS_CANCELED)
866
                        for i in job.ops[opidx:])
867

    
868
      assert op.status in (constants.OP_STATUS_QUEUED,
869
                           constants.OP_STATUS_WAITLOCK,
870
                           constants.OP_STATUS_CANCELED)
871

    
872
      if op.status != constants.OP_STATUS_CANCELED:
873
        # Prepare to start opcode
874
        self._MarkWaitlock(job, op)
875

    
876
        assert op.status == constants.OP_STATUS_WAITLOCK
877
        assert job.CalcStatus() == constants.JOB_STATUS_WAITLOCK
878

    
879
        # Write to disk
880
        queue.UpdateJobUnlocked(job)
881

    
882
        logging.info("%s: opcode %s waiting for locks", log_prefix, op_summary)
883

    
884
        queue.release()
885
        try:
886
          (op_status, op_result) = \
887
            self._ExecOpCodeUnlocked(log_prefix, op, op_summary)
888
        finally:
889
          queue.acquire(shared=1)
890

    
891
        # Finalize opcode
892
        op.end_timestamp = TimeStampNow()
893
        op.status = op_status
894
        op.result = op_result
895

    
896
        if op.status == constants.OP_STATUS_CANCELING:
897
          assert not compat.any(i.status != constants.OP_STATUS_CANCELING
898
                                for i in job.ops[opidx:])
899
        else:
900
          assert op.status in constants.OPS_FINALIZED
901

    
902
      # Ensure all opcodes so far have been successful
903
      assert (opidx == 0 or
904
              compat.all(i.status == constants.OP_STATUS_SUCCESS
905
                         for i in job.ops[:opidx]))
906

    
907
      if op.status == constants.OP_STATUS_SUCCESS:
908
        finalize = False
909

    
910
      elif op.status == constants.OP_STATUS_ERROR:
911
        # Ensure failed opcode has an exception as its result
912
        assert errors.GetEncodedError(job.ops[opidx].result)
913

    
914
        to_encode = errors.OpExecError("Preceding opcode failed")
915
        job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
916
                              _EncodeOpError(to_encode))
917
        finalize = True
918

    
919
        # Consistency check
920
        assert compat.all(i.status == constants.OP_STATUS_ERROR and
921
                          errors.GetEncodedError(i.result)
922
                          for i in job.ops[opidx:])
923

    
924
      elif op.status == constants.OP_STATUS_CANCELING:
925
        job.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
926
                              "Job canceled by request")
927
        finalize = True
928

    
929
      elif op.status == constants.OP_STATUS_CANCELED:
930
        finalize = True
931

    
932
      else:
933
        raise errors.ProgrammerError("Unknown status '%s'" % op.status)
934

    
935
      # Finalizing or last opcode?
936
      if finalize or opidx == (opcount - 1):
937
        # All opcodes have been run, finalize job
938
        job.end_timestamp = TimeStampNow()
939

    
940
      # Write to disk. If the job status is final, this is the final write
941
      # allowed. Once the file has been written, it can be archived anytime.
942
      queue.UpdateJobUnlocked(job)
943

    
944
      if finalize or opidx == (opcount - 1):
945
        logging.info("Finished job %s, status = %s", job.id, job.CalcStatus())
946
        return True
947

    
948
      return False
949
    finally:
950
      queue.release()
951

    
952

    
953
class _JobQueueWorker(workerpool.BaseWorker):
954
  """The actual job workers.
955

956
  """
957
  def RunTask(self, job): # pylint: disable-msg=W0221
958
    """Job executor.
959

960
    This functions processes a job. It is closely tied to the L{_QueuedJob} and
961
    L{_QueuedOpCode} classes.
962

963
    @type job: L{_QueuedJob}
964
    @param job: the job to be processed
965

966
    """
967
    queue = job.queue
968
    assert queue == self.pool.queue
969

    
970
    self.SetTaskName("Job%s" % job.id)
971

    
972
    proc = mcpu.Processor(queue.context, job.id)
973

    
974
    if not _JobProcessor(queue, proc.ExecOpCode, job)():
975
      # Schedule again
976
      raise workerpool.DeferTask()
977

    
978

    
979
class _JobQueueWorkerPool(workerpool.WorkerPool):
980
  """Simple class implementing a job-processing workerpool.
981

982
  """
983
  def __init__(self, queue):
984
    super(_JobQueueWorkerPool, self).__init__("JobQueue",
985
                                              JOBQUEUE_THREADS,
986
                                              _JobQueueWorker)
987
    self.queue = queue
988

    
989

    
990
def _RequireOpenQueue(fn):
991
  """Decorator for "public" functions.
992

993
  This function should be used for all 'public' functions. That is,
994
  functions usually called from other classes. Note that this should
995
  be applied only to methods (not plain functions), since it expects
996
  that the decorated function is called with a first argument that has
997
  a '_queue_filelock' argument.
998

999
  @warning: Use this decorator only after locking.ssynchronized
1000

1001
  Example::
1002
    @locking.ssynchronized(_LOCK)
1003
    @_RequireOpenQueue
1004
    def Example(self):
1005
      pass
1006

1007
  """
1008
  def wrapper(self, *args, **kwargs):
1009
    # pylint: disable-msg=W0212
1010
    assert self._queue_filelock is not None, "Queue should be open"
1011
    return fn(self, *args, **kwargs)
1012
  return wrapper
1013

    
1014

    
1015
class JobQueue(object):
1016
  """Queue used to manage the jobs.
1017

1018
  @cvar _RE_JOB_FILE: regex matching the valid job file names
1019

1020
  """
1021
  _RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
1022

    
1023
  def __init__(self, context):
1024
    """Constructor for JobQueue.
1025

1026
    The constructor will initialize the job queue object and then
1027
    start loading the current jobs from disk, either for starting them
1028
    (if they were queue) or for aborting them (if they were already
1029
    running).
1030

1031
    @type context: GanetiContext
1032
    @param context: the context object for access to the configuration
1033
        data and other ganeti objects
1034

1035
    """
1036
    self.context = context
1037
    self._memcache = weakref.WeakValueDictionary()
1038
    self._my_hostname = netutils.Hostname.GetSysName()
1039

    
1040
    # The Big JobQueue lock. If a code block or method acquires it in shared
1041
    # mode safe it must guarantee concurrency with all the code acquiring it in
1042
    # shared mode, including itself. In order not to acquire it at all
1043
    # concurrency must be guaranteed with all code acquiring it in shared mode
1044
    # and all code acquiring it exclusively.
1045
    self._lock = locking.SharedLock("JobQueue")
1046

    
1047
    self.acquire = self._lock.acquire
1048
    self.release = self._lock.release
1049

    
1050
    # Initialize the queue, and acquire the filelock.
1051
    # This ensures no other process is working on the job queue.
1052
    self._queue_filelock = jstore.InitAndVerifyQueue(must_lock=True)
1053

    
1054
    # Read serial file
1055
    self._last_serial = jstore.ReadSerial()
1056
    assert self._last_serial is not None, ("Serial file was modified between"
1057
                                           " check in jstore and here")
1058

    
1059
    # Get initial list of nodes
1060
    self._nodes = dict((n.name, n.primary_ip)
1061
                       for n in self.context.cfg.GetAllNodesInfo().values()
1062
                       if n.master_candidate)
1063

    
1064
    # Remove master node
1065
    self._nodes.pop(self._my_hostname, None)
1066

    
1067
    # TODO: Check consistency across nodes
1068

    
1069
    self._queue_size = 0
1070
    self._UpdateQueueSizeUnlocked()
1071
    self._drained = self._IsQueueMarkedDrain()
1072

    
1073
    # Setup worker pool
1074
    self._wpool = _JobQueueWorkerPool(self)
1075
    try:
1076
      self._InspectQueue()
1077
    except:
1078
      self._wpool.TerminateWorkers()
1079
      raise
1080

    
1081
  @locking.ssynchronized(_LOCK)
1082
  @_RequireOpenQueue
1083
  def _InspectQueue(self):
1084
    """Loads the whole job queue and resumes unfinished jobs.
1085

1086
    This function needs the lock here because WorkerPool.AddTask() may start a
1087
    job while we're still doing our work.
1088

1089
    """
1090
    logging.info("Inspecting job queue")
1091

    
1092
    restartjobs = []
1093

    
1094
    all_job_ids = self._GetJobIDsUnlocked()
1095
    jobs_count = len(all_job_ids)
1096
    lastinfo = time.time()
1097
    for idx, job_id in enumerate(all_job_ids):
1098
      # Give an update every 1000 jobs or 10 seconds
1099
      if (idx % 1000 == 0 or time.time() >= (lastinfo + 10.0) or
1100
          idx == (jobs_count - 1)):
1101
        logging.info("Job queue inspection: %d/%d (%0.1f %%)",
1102
                     idx, jobs_count - 1, 100.0 * (idx + 1) / jobs_count)
1103
        lastinfo = time.time()
1104

    
1105
      job = self._LoadJobUnlocked(job_id)
1106

    
1107
      # a failure in loading the job can cause 'None' to be returned
1108
      if job is None:
1109
        continue
1110

    
1111
      status = job.CalcStatus()
1112

    
1113
      if status in (constants.JOB_STATUS_QUEUED, ):
1114
        restartjobs.append(job)
1115

    
1116
      elif status in (constants.JOB_STATUS_RUNNING,
1117
                      constants.JOB_STATUS_WAITLOCK,
1118
                      constants.JOB_STATUS_CANCELING):
1119
        logging.warning("Unfinished job %s found: %s", job.id, job)
1120
        job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
1121
                              "Unclean master daemon shutdown")
1122
        self.UpdateJobUnlocked(job)
1123

    
1124
    if restartjobs:
1125
      logging.info("Restarting %s jobs", len(restartjobs))
1126
      self._EnqueueJobs(restartjobs)
1127

    
1128
    logging.info("Job queue inspection finished")
1129

    
1130
  @locking.ssynchronized(_LOCK)
1131
  @_RequireOpenQueue
1132
  def AddNode(self, node):
1133
    """Register a new node with the queue.
1134

1135
    @type node: L{objects.Node}
1136
    @param node: the node object to be added
1137

1138
    """
1139
    node_name = node.name
1140
    assert node_name != self._my_hostname
1141

    
1142
    # Clean queue directory on added node
1143
    result = rpc.RpcRunner.call_jobqueue_purge(node_name)
1144
    msg = result.fail_msg
1145
    if msg:
1146
      logging.warning("Cannot cleanup queue directory on node %s: %s",
1147
                      node_name, msg)
1148

    
1149
    if not node.master_candidate:
1150
      # remove if existing, ignoring errors
1151
      self._nodes.pop(node_name, None)
1152
      # and skip the replication of the job ids
1153
      return
1154

    
1155
    # Upload the whole queue excluding archived jobs
1156
    files = [self._GetJobPath(job_id) for job_id in self._GetJobIDsUnlocked()]
1157

    
1158
    # Upload current serial file
1159
    files.append(constants.JOB_QUEUE_SERIAL_FILE)
1160

    
1161
    for file_name in files:
1162
      # Read file content
1163
      content = utils.ReadFile(file_name)
1164

    
1165
      result = rpc.RpcRunner.call_jobqueue_update([node_name],
1166
                                                  [node.primary_ip],
1167
                                                  file_name, content)
1168
      msg = result[node_name].fail_msg
1169
      if msg:
1170
        logging.error("Failed to upload file %s to node %s: %s",
1171
                      file_name, node_name, msg)
1172

    
1173
    self._nodes[node_name] = node.primary_ip
1174

    
1175
  @locking.ssynchronized(_LOCK)
1176
  @_RequireOpenQueue
1177
  def RemoveNode(self, node_name):
1178
    """Callback called when removing nodes from the cluster.
1179

1180
    @type node_name: str
1181
    @param node_name: the name of the node to remove
1182

1183
    """
1184
    self._nodes.pop(node_name, None)
1185

    
1186
  @staticmethod
1187
  def _CheckRpcResult(result, nodes, failmsg):
1188
    """Verifies the status of an RPC call.
1189

1190
    Since we aim to keep consistency should this node (the current
1191
    master) fail, we will log errors if our rpc fail, and especially
1192
    log the case when more than half of the nodes fails.
1193

1194
    @param result: the data as returned from the rpc call
1195
    @type nodes: list
1196
    @param nodes: the list of nodes we made the call to
1197
    @type failmsg: str
1198
    @param failmsg: the identifier to be used for logging
1199

1200
    """
1201
    failed = []
1202
    success = []
1203

    
1204
    for node in nodes:
1205
      msg = result[node].fail_msg
1206
      if msg:
1207
        failed.append(node)
1208
        logging.error("RPC call %s (%s) failed on node %s: %s",
1209
                      result[node].call, failmsg, node, msg)
1210
      else:
1211
        success.append(node)
1212

    
1213
    # +1 for the master node
1214
    if (len(success) + 1) < len(failed):
1215
      # TODO: Handle failing nodes
1216
      logging.error("More than half of the nodes failed")
1217

    
1218
  def _GetNodeIp(self):
1219
    """Helper for returning the node name/ip list.
1220

1221
    @rtype: (list, list)
1222
    @return: a tuple of two lists, the first one with the node
1223
        names and the second one with the node addresses
1224

1225
    """
1226
    # TODO: Change to "tuple(map(list, zip(*self._nodes.items())))"?
1227
    name_list = self._nodes.keys()
1228
    addr_list = [self._nodes[name] for name in name_list]
1229
    return name_list, addr_list
1230

    
1231
  def _UpdateJobQueueFile(self, file_name, data, replicate):
1232
    """Writes a file locally and then replicates it to all nodes.
1233

1234
    This function will replace the contents of a file on the local
1235
    node and then replicate it to all the other nodes we have.
1236

1237
    @type file_name: str
1238
    @param file_name: the path of the file to be replicated
1239
    @type data: str
1240
    @param data: the new contents of the file
1241
    @type replicate: boolean
1242
    @param replicate: whether to spread the changes to the remote nodes
1243

1244
    """
1245
    getents = runtime.GetEnts()
1246
    utils.WriteFile(file_name, data=data, uid=getents.masterd_uid,
1247
                    gid=getents.masterd_gid)
1248

    
1249
    if replicate:
1250
      names, addrs = self._GetNodeIp()
1251
      result = rpc.RpcRunner.call_jobqueue_update(names, addrs, file_name, data)
1252
      self._CheckRpcResult(result, self._nodes, "Updating %s" % file_name)
1253

    
1254
  def _RenameFilesUnlocked(self, rename):
1255
    """Renames a file locally and then replicate the change.
1256

1257
    This function will rename a file in the local queue directory
1258
    and then replicate this rename to all the other nodes we have.
1259

1260
    @type rename: list of (old, new)
1261
    @param rename: List containing tuples mapping old to new names
1262

1263
    """
1264
    # Rename them locally
1265
    for old, new in rename:
1266
      utils.RenameFile(old, new, mkdir=True)
1267

    
1268
    # ... and on all nodes
1269
    names, addrs = self._GetNodeIp()
1270
    result = rpc.RpcRunner.call_jobqueue_rename(names, addrs, rename)
1271
    self._CheckRpcResult(result, self._nodes, "Renaming files (%r)" % rename)
1272

    
1273
  @staticmethod
1274
  def _FormatJobID(job_id):
1275
    """Convert a job ID to string format.
1276

1277
    Currently this just does C{str(job_id)} after performing some
1278
    checks, but if we want to change the job id format this will
1279
    abstract this change.
1280

1281
    @type job_id: int or long
1282
    @param job_id: the numeric job id
1283
    @rtype: str
1284
    @return: the formatted job id
1285

1286
    """
1287
    if not isinstance(job_id, (int, long)):
1288
      raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id)
1289
    if job_id < 0:
1290
      raise errors.ProgrammerError("Job ID %s is negative" % job_id)
1291

    
1292
    return str(job_id)
1293

    
1294
  @classmethod
1295
  def _GetArchiveDirectory(cls, job_id):
1296
    """Returns the archive directory for a job.
1297

1298
    @type job_id: str
1299
    @param job_id: Job identifier
1300
    @rtype: str
1301
    @return: Directory name
1302

1303
    """
1304
    return str(int(job_id) / JOBS_PER_ARCHIVE_DIRECTORY)
1305

    
1306
  def _NewSerialsUnlocked(self, count):
1307
    """Generates a new job identifier.
1308

1309
    Job identifiers are unique during the lifetime of a cluster.
1310

1311
    @type count: integer
1312
    @param count: how many serials to return
1313
    @rtype: str
1314
    @return: a string representing the job identifier.
1315

1316
    """
1317
    assert count > 0
1318
    # New number
1319
    serial = self._last_serial + count
1320

    
1321
    # Write to file
1322
    self._UpdateJobQueueFile(constants.JOB_QUEUE_SERIAL_FILE,
1323
                             "%s\n" % serial, True)
1324

    
1325
    result = [self._FormatJobID(v)
1326
              for v in range(self._last_serial, serial + 1)]
1327
    # Keep it only if we were able to write the file
1328
    self._last_serial = serial
1329

    
1330
    return result
1331

    
1332
  @staticmethod
1333
  def _GetJobPath(job_id):
1334
    """Returns the job file for a given job id.
1335

1336
    @type job_id: str
1337
    @param job_id: the job identifier
1338
    @rtype: str
1339
    @return: the path to the job file
1340

1341
    """
1342
    return utils.PathJoin(constants.QUEUE_DIR, "job-%s" % job_id)
1343

    
1344
  @classmethod
1345
  def _GetArchivedJobPath(cls, job_id):
1346
    """Returns the archived job file for a give job id.
1347

1348
    @type job_id: str
1349
    @param job_id: the job identifier
1350
    @rtype: str
1351
    @return: the path to the archived job file
1352

1353
    """
1354
    return utils.PathJoin(constants.JOB_QUEUE_ARCHIVE_DIR,
1355
                          cls._GetArchiveDirectory(job_id), "job-%s" % job_id)
1356

    
1357
  def _GetJobIDsUnlocked(self, sort=True):
1358
    """Return all known job IDs.
1359

1360
    The method only looks at disk because it's a requirement that all
1361
    jobs are present on disk (so in the _memcache we don't have any
1362
    extra IDs).
1363

1364
    @type sort: boolean
1365
    @param sort: perform sorting on the returned job ids
1366
    @rtype: list
1367
    @return: the list of job IDs
1368

1369
    """
1370
    jlist = []
1371
    for filename in utils.ListVisibleFiles(constants.QUEUE_DIR):
1372
      m = self._RE_JOB_FILE.match(filename)
1373
      if m:
1374
        jlist.append(m.group(1))
1375
    if sort:
1376
      jlist = utils.NiceSort(jlist)
1377
    return jlist
1378

    
1379
  def _LoadJobUnlocked(self, job_id):
1380
    """Loads a job from the disk or memory.
1381

1382
    Given a job id, this will return the cached job object if
1383
    existing, or try to load the job from the disk. If loading from
1384
    disk, it will also add the job to the cache.
1385

1386
    @param job_id: the job id
1387
    @rtype: L{_QueuedJob} or None
1388
    @return: either None or the job object
1389

1390
    """
1391
    job = self._memcache.get(job_id, None)
1392
    if job:
1393
      logging.debug("Found job %s in memcache", job_id)
1394
      return job
1395

    
1396
    try:
1397
      job = self._LoadJobFromDisk(job_id)
1398
      if job is None:
1399
        return job
1400
    except errors.JobFileCorrupted:
1401
      old_path = self._GetJobPath(job_id)
1402
      new_path = self._GetArchivedJobPath(job_id)
1403
      if old_path == new_path:
1404
        # job already archived (future case)
1405
        logging.exception("Can't parse job %s", job_id)
1406
      else:
1407
        # non-archived case
1408
        logging.exception("Can't parse job %s, will archive.", job_id)
1409
        self._RenameFilesUnlocked([(old_path, new_path)])
1410
      return None
1411

    
1412
    self._memcache[job_id] = job
1413
    logging.debug("Added job %s to the cache", job_id)
1414
    return job
1415

    
1416
  def _LoadJobFromDisk(self, job_id):
1417
    """Load the given job file from disk.
1418

1419
    Given a job file, read, load and restore it in a _QueuedJob format.
1420

1421
    @type job_id: string
1422
    @param job_id: job identifier
1423
    @rtype: L{_QueuedJob} or None
1424
    @return: either None or the job object
1425

1426
    """
1427
    filepath = self._GetJobPath(job_id)
1428
    logging.debug("Loading job from %s", filepath)
1429
    try:
1430
      raw_data = utils.ReadFile(filepath)
1431
    except EnvironmentError, err:
1432
      if err.errno in (errno.ENOENT, ):
1433
        return None
1434
      raise
1435

    
1436
    try:
1437
      data = serializer.LoadJson(raw_data)
1438
      job = _QueuedJob.Restore(self, data)
1439
    except Exception, err: # pylint: disable-msg=W0703
1440
      raise errors.JobFileCorrupted(err)
1441

    
1442
    return job
1443

    
1444
  def SafeLoadJobFromDisk(self, job_id):
1445
    """Load the given job file from disk.
1446

1447
    Given a job file, read, load and restore it in a _QueuedJob format.
1448
    In case of error reading the job, it gets returned as None, and the
1449
    exception is logged.
1450

1451
    @type job_id: string
1452
    @param job_id: job identifier
1453
    @rtype: L{_QueuedJob} or None
1454
    @return: either None or the job object
1455

1456
    """
1457
    try:
1458
      return self._LoadJobFromDisk(job_id)
1459
    except (errors.JobFileCorrupted, EnvironmentError):
1460
      logging.exception("Can't load/parse job %s", job_id)
1461
      return None
1462

    
1463
  @staticmethod
1464
  def _IsQueueMarkedDrain():
1465
    """Check if the queue is marked from drain.
1466

1467
    This currently uses the queue drain file, which makes it a
1468
    per-node flag. In the future this can be moved to the config file.
1469

1470
    @rtype: boolean
1471
    @return: True of the job queue is marked for draining
1472

1473
    """
1474
    return os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
1475

    
1476
  def _UpdateQueueSizeUnlocked(self):
1477
    """Update the queue size.
1478

1479
    """
1480
    self._queue_size = len(self._GetJobIDsUnlocked(sort=False))
1481

    
1482
  @locking.ssynchronized(_LOCK)
1483
  @_RequireOpenQueue
1484
  def SetDrainFlag(self, drain_flag):
1485
    """Sets the drain flag for the queue.
1486

1487
    @type drain_flag: boolean
1488
    @param drain_flag: Whether to set or unset the drain flag
1489

1490
    """
1491
    getents = runtime.GetEnts()
1492

    
1493
    if drain_flag:
1494
      utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True,
1495
                      uid=getents.masterd_uid, gid=getents.masterd_gid)
1496
    else:
1497
      utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
1498

    
1499
    self._drained = drain_flag
1500

    
1501
    return True
1502

    
1503
  @_RequireOpenQueue
1504
  def _SubmitJobUnlocked(self, job_id, ops):
1505
    """Create and store a new job.
1506

1507
    This enters the job into our job queue and also puts it on the new
1508
    queue, in order for it to be picked up by the queue processors.
1509

1510
    @type job_id: job ID
1511
    @param job_id: the job ID for the new job
1512
    @type ops: list
1513
    @param ops: The list of OpCodes that will become the new job.
1514
    @rtype: L{_QueuedJob}
1515
    @return: the job object to be queued
1516
    @raise errors.JobQueueDrainError: if the job queue is marked for draining
1517
    @raise errors.JobQueueFull: if the job queue has too many jobs in it
1518
    @raise errors.GenericError: If an opcode is not valid
1519

1520
    """
1521
    # Ok when sharing the big job queue lock, as the drain file is created when
1522
    # the lock is exclusive.
1523
    if self._drained:
1524
      raise errors.JobQueueDrainError("Job queue is drained, refusing job")
1525

    
1526
    if self._queue_size >= constants.JOB_QUEUE_SIZE_HARD_LIMIT:
1527
      raise errors.JobQueueFull()
1528

    
1529
    job = _QueuedJob(self, job_id, ops)
1530

    
1531
    # Check priority
1532
    for idx, op in enumerate(job.ops):
1533
      if op.priority not in constants.OP_PRIO_SUBMIT_VALID:
1534
        allowed = utils.CommaJoin(constants.OP_PRIO_SUBMIT_VALID)
1535
        raise errors.GenericError("Opcode %s has invalid priority %s, allowed"
1536
                                  " are %s" % (idx, op.priority, allowed))
1537

    
1538
    # Write to disk
1539
    self.UpdateJobUnlocked(job)
1540

    
1541
    self._queue_size += 1
1542

    
1543
    logging.debug("Adding new job %s to the cache", job_id)
1544
    self._memcache[job_id] = job
1545

    
1546
    return job
1547

    
1548
  @locking.ssynchronized(_LOCK)
1549
  @_RequireOpenQueue
1550
  def SubmitJob(self, ops):
1551
    """Create and store a new job.
1552

1553
    @see: L{_SubmitJobUnlocked}
1554

1555
    """
1556
    job_id = self._NewSerialsUnlocked(1)[0]
1557
    self._EnqueueJobs([self._SubmitJobUnlocked(job_id, ops)])
1558
    return job_id
1559

    
1560
  @locking.ssynchronized(_LOCK)
1561
  @_RequireOpenQueue
1562
  def SubmitManyJobs(self, jobs):
1563
    """Create and store multiple jobs.
1564

1565
    @see: L{_SubmitJobUnlocked}
1566

1567
    """
1568
    results = []
1569
    added_jobs = []
1570
    all_job_ids = self._NewSerialsUnlocked(len(jobs))
1571
    for job_id, ops in zip(all_job_ids, jobs):
1572
      try:
1573
        added_jobs.append(self._SubmitJobUnlocked(job_id, ops))
1574
        status = True
1575
        data = job_id
1576
      except errors.GenericError, err:
1577
        data = str(err)
1578
        status = False
1579
      results.append((status, data))
1580

    
1581
    self._EnqueueJobs(added_jobs)
1582

    
1583
    return results
1584

    
1585
  def _EnqueueJobs(self, jobs):
1586
    """Helper function to add jobs to worker pool's queue.
1587

1588
    @type jobs: list
1589
    @param jobs: List of all jobs
1590

1591
    """
1592
    self._wpool.AddManyTasks([(job, ) for job in jobs],
1593
                             priority=[job.CalcPriority() for job in jobs])
1594

    
1595
  @_RequireOpenQueue
1596
  def UpdateJobUnlocked(self, job, replicate=True):
1597
    """Update a job's on disk storage.
1598

1599
    After a job has been modified, this function needs to be called in
1600
    order to write the changes to disk and replicate them to the other
1601
    nodes.
1602

1603
    @type job: L{_QueuedJob}
1604
    @param job: the changed job
1605
    @type replicate: boolean
1606
    @param replicate: whether to replicate the change to remote nodes
1607

1608
    """
1609
    filename = self._GetJobPath(job.id)
1610
    data = serializer.DumpJson(job.Serialize(), indent=False)
1611
    logging.debug("Writing job %s to %s", job.id, filename)
1612
    self._UpdateJobQueueFile(filename, data, replicate)
1613

    
1614
  def WaitForJobChanges(self, job_id, fields, prev_job_info, prev_log_serial,
1615
                        timeout):
1616
    """Waits for changes in a job.
1617

1618
    @type job_id: string
1619
    @param job_id: Job identifier
1620
    @type fields: list of strings
1621
    @param fields: Which fields to check for changes
1622
    @type prev_job_info: list or None
1623
    @param prev_job_info: Last job information returned
1624
    @type prev_log_serial: int
1625
    @param prev_log_serial: Last job message serial number
1626
    @type timeout: float
1627
    @param timeout: maximum time to wait in seconds
1628
    @rtype: tuple (job info, log entries)
1629
    @return: a tuple of the job information as required via
1630
        the fields parameter, and the log entries as a list
1631

1632
        if the job has not changed and the timeout has expired,
1633
        we instead return a special value,
1634
        L{constants.JOB_NOTCHANGED}, which should be interpreted
1635
        as such by the clients
1636

1637
    """
1638
    load_fn = compat.partial(self.SafeLoadJobFromDisk, job_id)
1639

    
1640
    helper = _WaitForJobChangesHelper()
1641

    
1642
    return helper(self._GetJobPath(job_id), load_fn,
1643
                  fields, prev_job_info, prev_log_serial, timeout)
1644

    
1645
  @locking.ssynchronized(_LOCK)
1646
  @_RequireOpenQueue
1647
  def CancelJob(self, job_id):
1648
    """Cancels a job.
1649

1650
    This will only succeed if the job has not started yet.
1651

1652
    @type job_id: string
1653
    @param job_id: job ID of job to be cancelled.
1654

1655
    """
1656
    logging.info("Cancelling job %s", job_id)
1657

    
1658
    job = self._LoadJobUnlocked(job_id)
1659
    if not job:
1660
      logging.debug("Job %s not found", job_id)
1661
      return (False, "Job %s not found" % job_id)
1662

    
1663
    (success, msg) = job.Cancel()
1664

    
1665
    if success:
1666
      self.UpdateJobUnlocked(job)
1667

    
1668
    return (success, msg)
1669

    
1670
  @_RequireOpenQueue
1671
  def _ArchiveJobsUnlocked(self, jobs):
1672
    """Archives jobs.
1673

1674
    @type jobs: list of L{_QueuedJob}
1675
    @param jobs: Job objects
1676
    @rtype: int
1677
    @return: Number of archived jobs
1678

1679
    """
1680
    archive_jobs = []
1681
    rename_files = []
1682
    for job in jobs:
1683
      if job.CalcStatus() not in constants.JOBS_FINALIZED:
1684
        logging.debug("Job %s is not yet done", job.id)
1685
        continue
1686

    
1687
      archive_jobs.append(job)
1688

    
1689
      old = self._GetJobPath(job.id)
1690
      new = self._GetArchivedJobPath(job.id)
1691
      rename_files.append((old, new))
1692

    
1693
    # TODO: What if 1..n files fail to rename?
1694
    self._RenameFilesUnlocked(rename_files)
1695

    
1696
    logging.debug("Successfully archived job(s) %s",
1697
                  utils.CommaJoin(job.id for job in archive_jobs))
1698

    
1699
    # Since we haven't quite checked, above, if we succeeded or failed renaming
1700
    # the files, we update the cached queue size from the filesystem. When we
1701
    # get around to fix the TODO: above, we can use the number of actually
1702
    # archived jobs to fix this.
1703
    self._UpdateQueueSizeUnlocked()
1704
    return len(archive_jobs)
1705

    
1706
  @locking.ssynchronized(_LOCK)
1707
  @_RequireOpenQueue
1708
  def ArchiveJob(self, job_id):
1709
    """Archives a job.
1710

1711
    This is just a wrapper over L{_ArchiveJobsUnlocked}.
1712

1713
    @type job_id: string
1714
    @param job_id: Job ID of job to be archived.
1715
    @rtype: bool
1716
    @return: Whether job was archived
1717

1718
    """
1719
    logging.info("Archiving job %s", job_id)
1720

    
1721
    job = self._LoadJobUnlocked(job_id)
1722
    if not job:
1723
      logging.debug("Job %s not found", job_id)
1724
      return False
1725

    
1726
    return self._ArchiveJobsUnlocked([job]) == 1
1727

    
1728
  @locking.ssynchronized(_LOCK)
1729
  @_RequireOpenQueue
1730
  def AutoArchiveJobs(self, age, timeout):
1731
    """Archives all jobs based on age.
1732

1733
    The method will archive all jobs which are older than the age
1734
    parameter. For jobs that don't have an end timestamp, the start
1735
    timestamp will be considered. The special '-1' age will cause
1736
    archival of all jobs (that are not running or queued).
1737

1738
    @type age: int
1739
    @param age: the minimum age in seconds
1740

1741
    """
1742
    logging.info("Archiving jobs with age more than %s seconds", age)
1743

    
1744
    now = time.time()
1745
    end_time = now + timeout
1746
    archived_count = 0
1747
    last_touched = 0
1748

    
1749
    all_job_ids = self._GetJobIDsUnlocked()
1750
    pending = []
1751
    for idx, job_id in enumerate(all_job_ids):
1752
      last_touched = idx + 1
1753

    
1754
      # Not optimal because jobs could be pending
1755
      # TODO: Measure average duration for job archival and take number of
1756
      # pending jobs into account.
1757
      if time.time() > end_time:
1758
        break
1759

    
1760
      # Returns None if the job failed to load
1761
      job = self._LoadJobUnlocked(job_id)
1762
      if job:
1763
        if job.end_timestamp is None:
1764
          if job.start_timestamp is None:
1765
            job_age = job.received_timestamp
1766
          else:
1767
            job_age = job.start_timestamp
1768
        else:
1769
          job_age = job.end_timestamp
1770

    
1771
        if age == -1 or now - job_age[0] > age:
1772
          pending.append(job)
1773

    
1774
          # Archive 10 jobs at a time
1775
          if len(pending) >= 10:
1776
            archived_count += self._ArchiveJobsUnlocked(pending)
1777
            pending = []
1778

    
1779
    if pending:
1780
      archived_count += self._ArchiveJobsUnlocked(pending)
1781

    
1782
    return (archived_count, len(all_job_ids) - last_touched)
1783

    
1784
  def QueryJobs(self, job_ids, fields):
1785
    """Returns a list of jobs in queue.
1786

1787
    @type job_ids: list
1788
    @param job_ids: sequence of job identifiers or None for all
1789
    @type fields: list
1790
    @param fields: names of fields to return
1791
    @rtype: list
1792
    @return: list one element per job, each element being list with
1793
        the requested fields
1794

1795
    """
1796
    jobs = []
1797
    list_all = False
1798
    if not job_ids:
1799
      # Since files are added to/removed from the queue atomically, there's no
1800
      # risk of getting the job ids in an inconsistent state.
1801
      job_ids = self._GetJobIDsUnlocked()
1802
      list_all = True
1803

    
1804
    for job_id in job_ids:
1805
      job = self.SafeLoadJobFromDisk(job_id)
1806
      if job is not None:
1807
        jobs.append(job.GetInfo(fields))
1808
      elif not list_all:
1809
        jobs.append(None)
1810

    
1811
    return jobs
1812

    
1813
  @locking.ssynchronized(_LOCK)
1814
  @_RequireOpenQueue
1815
  def Shutdown(self):
1816
    """Stops the job queue.
1817

1818
    This shutdowns all the worker threads an closes the queue.
1819

1820
    """
1821
    self._wpool.TerminateWorkers()
1822

    
1823
    self._queue_filelock.Close()
1824
    self._queue_filelock = None