Statistics
| Branch: | Tag: | Revision:

root / lib / jqueue.py @ a0d2fe2c

History | View | Annotate | Download (50.5 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",
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
  def __repr__(self):
207
    status = ["%s.%s" % (self.__class__.__module__, self.__class__.__name__),
208
              "id=%s" % self.id,
209
              "ops=%s" % ",".join([op.input.Summary() for op in self.ops])]
210

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

    
213
  @classmethod
214
  def Restore(cls, queue, state):
215
    """Restore a _QueuedJob from serialized state:
216

217
    @type queue: L{JobQueue}
218
    @param queue: to which queue the restored job belongs
219
    @type state: dict
220
    @param state: the serialized state
221
    @rtype: _JobQueue
222
    @return: the restored _JobQueue instance
223

224
    """
225
    obj = _QueuedJob.__new__(cls)
226
    obj.queue = queue
227
    obj.id = state["id"]
228
    obj.received_timestamp = state.get("received_timestamp", None)
229
    obj.start_timestamp = state.get("start_timestamp", None)
230
    obj.end_timestamp = state.get("end_timestamp", None)
231

    
232
    obj.ops = []
233
    obj.log_serial = 0
234
    for op_state in state["ops"]:
235
      op = _QueuedOpCode.Restore(op_state)
236
      for log_entry in op.log:
237
        obj.log_serial = max(obj.log_serial, log_entry[0])
238
      obj.ops.append(op)
239

    
240
    return obj
241

    
242
  def Serialize(self):
243
    """Serialize the _JobQueue instance.
244

245
    @rtype: dict
246
    @return: the serialized state
247

248
    """
249
    return {
250
      "id": self.id,
251
      "ops": [op.Serialize() for op in self.ops],
252
      "start_timestamp": self.start_timestamp,
253
      "end_timestamp": self.end_timestamp,
254
      "received_timestamp": self.received_timestamp,
255
      }
256

    
257
  def CalcStatus(self):
258
    """Compute the status of this job.
259

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

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

271
        will determine the job status
272

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

276
    @return: the job status
277

278
    """
279
    status = constants.JOB_STATUS_QUEUED
280

    
281
    all_success = True
282
    for op in self.ops:
283
      if op.status == constants.OP_STATUS_SUCCESS:
284
        continue
285

    
286
      all_success = False
287

    
288
      if op.status == constants.OP_STATUS_QUEUED:
289
        pass
290
      elif op.status == constants.OP_STATUS_WAITLOCK:
291
        status = constants.JOB_STATUS_WAITLOCK
292
      elif op.status == constants.OP_STATUS_RUNNING:
293
        status = constants.JOB_STATUS_RUNNING
294
      elif op.status == constants.OP_STATUS_CANCELING:
295
        status = constants.JOB_STATUS_CANCELING
296
        break
297
      elif op.status == constants.OP_STATUS_ERROR:
298
        status = constants.JOB_STATUS_ERROR
299
        # The whole job fails if one opcode failed
300
        break
301
      elif op.status == constants.OP_STATUS_CANCELED:
302
        status = constants.OP_STATUS_CANCELED
303
        break
304

    
305
    if all_success:
306
      status = constants.JOB_STATUS_SUCCESS
307

    
308
    return status
309

    
310
  def CalcPriority(self):
311
    """Gets the current priority for this job.
312

313
    Only unfinished opcodes are considered. When all are done, the default
314
    priority is used.
315

316
    @rtype: int
317

318
    """
319
    priorities = [op.priority for op in self.ops
320
                  if op.status not in constants.OPS_FINALIZED]
321

    
322
    if not priorities:
323
      # All opcodes are done, assume default priority
324
      return constants.OP_PRIO_DEFAULT
325

    
326
    return min(priorities)
327

    
328
  def GetLogEntries(self, newer_than):
329
    """Selectively returns the log entries.
330

331
    @type newer_than: None or int
332
    @param newer_than: if this is None, return all log entries,
333
        otherwise return only the log entries with serial higher
334
        than this value
335
    @rtype: list
336
    @return: the list of the log entries selected
337

338
    """
339
    if newer_than is None:
340
      serial = -1
341
    else:
342
      serial = newer_than
343

    
344
    entries = []
345
    for op in self.ops:
346
      entries.extend(filter(lambda entry: entry[0] > serial, op.log))
347

    
348
    return entries
349

    
350
  def GetInfo(self, fields):
351
    """Returns information about a job.
352

353
    @type fields: list
354
    @param fields: names of fields to return
355
    @rtype: list
356
    @return: list with one element for each field
357
    @raise errors.OpExecError: when an invalid field
358
        has been passed
359

360
    """
361
    row = []
362
    for fname in fields:
363
      if fname == "id":
364
        row.append(self.id)
365
      elif fname == "status":
366
        row.append(self.CalcStatus())
367
      elif fname == "ops":
368
        row.append([op.input.__getstate__() for op in self.ops])
369
      elif fname == "opresult":
370
        row.append([op.result for op in self.ops])
371
      elif fname == "opstatus":
372
        row.append([op.status for op in self.ops])
373
      elif fname == "oplog":
374
        row.append([op.log for op in self.ops])
375
      elif fname == "opstart":
376
        row.append([op.start_timestamp for op in self.ops])
377
      elif fname == "opexec":
378
        row.append([op.exec_timestamp for op in self.ops])
379
      elif fname == "opend":
380
        row.append([op.end_timestamp for op in self.ops])
381
      elif fname == "received_ts":
382
        row.append(self.received_timestamp)
383
      elif fname == "start_ts":
384
        row.append(self.start_timestamp)
385
      elif fname == "end_ts":
386
        row.append(self.end_timestamp)
387
      elif fname == "summary":
388
        row.append([op.input.Summary() for op in self.ops])
389
      else:
390
        raise errors.OpExecError("Invalid self query field '%s'" % fname)
391
    return row
392

    
393
  def MarkUnfinishedOps(self, status, result):
394
    """Mark unfinished opcodes with a given status and result.
395

396
    This is an utility function for marking all running or waiting to
397
    be run opcodes with a given status. Opcodes which are already
398
    finalised are not changed.
399

400
    @param status: a given opcode status
401
    @param result: the opcode result
402

403
    """
404
    not_marked = True
405
    for op in self.ops:
406
      if op.status in constants.OPS_FINALIZED:
407
        assert not_marked, "Finalized opcodes found after non-finalized ones"
408
        continue
409
      op.status = status
410
      op.result = result
411
      not_marked = False
412

    
413
  def Cancel(self):
414
    """Marks job as canceled/-ing if possible.
415

416
    @rtype: tuple; (bool, string)
417
    @return: Boolean describing whether job was successfully canceled or marked
418
      as canceling and a text message
419

420
    """
421
    status = self.CalcStatus()
422

    
423
    if status not in (constants.JOB_STATUS_QUEUED,
424
                      constants.JOB_STATUS_WAITLOCK):
425
      logging.debug("Job %s is no longer waiting in the queue", self.id)
426
      return (False, "Job %s is no longer waiting in the queue" % self.id)
427

    
428
    if status == constants.JOB_STATUS_QUEUED:
429
      self.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
430
                             "Job canceled by request")
431
      msg = "Job %s canceled" % self.id
432

    
433
    elif status == constants.JOB_STATUS_WAITLOCK:
434
      # The worker will notice the new status and cancel the job
435
      self.MarkUnfinishedOps(constants.OP_STATUS_CANCELING, None)
436
      msg = "Job %s will be canceled" % self.id
437

    
438
    return (True, msg)
439

    
440

    
441
class _OpExecCallbacks(mcpu.OpExecCbBase):
442
  def __init__(self, queue, job, op):
443
    """Initializes this class.
444

445
    @type queue: L{JobQueue}
446
    @param queue: Job queue
447
    @type job: L{_QueuedJob}
448
    @param job: Job object
449
    @type op: L{_QueuedOpCode}
450
    @param op: OpCode
451

452
    """
453
    assert queue, "Queue is missing"
454
    assert job, "Job is missing"
455
    assert op, "Opcode is missing"
456

    
457
    self._queue = queue
458
    self._job = job
459
    self._op = op
460

    
461
  def _CheckCancel(self):
462
    """Raises an exception to cancel the job if asked to.
463

464
    """
465
    # Cancel here if we were asked to
466
    if self._op.status == constants.OP_STATUS_CANCELING:
467
      logging.debug("Canceling opcode")
468
      raise CancelJob()
469

    
470
  @locking.ssynchronized(_QUEUE, shared=1)
471
  def NotifyStart(self):
472
    """Mark the opcode as running, not lock-waiting.
473

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

479
    """
480
    assert self._op in self._job.ops
481
    assert self._op.status in (constants.OP_STATUS_WAITLOCK,
482
                               constants.OP_STATUS_CANCELING)
483

    
484
    # Cancel here if we were asked to
485
    self._CheckCancel()
486

    
487
    logging.debug("Opcode is now running")
488

    
489
    self._op.status = constants.OP_STATUS_RUNNING
490
    self._op.exec_timestamp = TimeStampNow()
491

    
492
    # And finally replicate the job status
493
    self._queue.UpdateJobUnlocked(self._job)
494

    
495
  @locking.ssynchronized(_QUEUE, shared=1)
496
  def _AppendFeedback(self, timestamp, log_type, log_msg):
497
    """Internal feedback append function, with locks
498

499
    """
500
    self._job.log_serial += 1
501
    self._op.log.append((self._job.log_serial, timestamp, log_type, log_msg))
502
    self._queue.UpdateJobUnlocked(self._job, replicate=False)
503

    
504
  def Feedback(self, *args):
505
    """Append a log entry.
506

507
    """
508
    assert len(args) < 3
509

    
510
    if len(args) == 1:
511
      log_type = constants.ELOG_MESSAGE
512
      log_msg = args[0]
513
    else:
514
      (log_type, log_msg) = args
515

    
516
    # The time is split to make serialization easier and not lose
517
    # precision.
518
    timestamp = utils.SplitTime(time.time())
519
    self._AppendFeedback(timestamp, log_type, log_msg)
520

    
521
  def CheckCancel(self):
522
    """Check whether job has been cancelled.
523

524
    """
525
    assert self._op.status in (constants.OP_STATUS_WAITLOCK,
526
                               constants.OP_STATUS_CANCELING)
527

    
528
    # Cancel here if we were asked to
529
    self._CheckCancel()
530

    
531

    
532
class _JobChangesChecker(object):
533
  def __init__(self, fields, prev_job_info, prev_log_serial):
534
    """Initializes this class.
535

536
    @type fields: list of strings
537
    @param fields: Fields requested by LUXI client
538
    @type prev_job_info: string
539
    @param prev_job_info: previous job info, as passed by the LUXI client
540
    @type prev_log_serial: string
541
    @param prev_log_serial: previous job serial, as passed by the LUXI client
542

543
    """
544
    self._fields = fields
545
    self._prev_job_info = prev_job_info
546
    self._prev_log_serial = prev_log_serial
547

    
548
  def __call__(self, job):
549
    """Checks whether job has changed.
550

551
    @type job: L{_QueuedJob}
552
    @param job: Job object
553

554
    """
555
    status = job.CalcStatus()
556
    job_info = job.GetInfo(self._fields)
557
    log_entries = job.GetLogEntries(self._prev_log_serial)
558

    
559
    # Serializing and deserializing data can cause type changes (e.g. from
560
    # tuple to list) or precision loss. We're doing it here so that we get
561
    # the same modifications as the data received from the client. Without
562
    # this, the comparison afterwards might fail without the data being
563
    # significantly different.
564
    # TODO: we just deserialized from disk, investigate how to make sure that
565
    # the job info and log entries are compatible to avoid this further step.
566
    # TODO: Doing something like in testutils.py:UnifyValueType might be more
567
    # efficient, though floats will be tricky
568
    job_info = serializer.LoadJson(serializer.DumpJson(job_info))
569
    log_entries = serializer.LoadJson(serializer.DumpJson(log_entries))
570

    
571
    # Don't even try to wait if the job is no longer running, there will be
572
    # no changes.
573
    if (status not in (constants.JOB_STATUS_QUEUED,
574
                       constants.JOB_STATUS_RUNNING,
575
                       constants.JOB_STATUS_WAITLOCK) or
576
        job_info != self._prev_job_info or
577
        (log_entries and self._prev_log_serial != log_entries[0][0])):
578
      logging.debug("Job %s changed", job.id)
579
      return (job_info, log_entries)
580

    
581
    return None
582

    
583

    
584
class _JobFileChangesWaiter(object):
585
  def __init__(self, filename):
586
    """Initializes this class.
587

588
    @type filename: string
589
    @param filename: Path to job file
590
    @raises errors.InotifyError: if the notifier cannot be setup
591

592
    """
593
    self._wm = pyinotify.WatchManager()
594
    self._inotify_handler = \
595
      asyncnotifier.SingleFileEventHandler(self._wm, self._OnInotify, filename)
596
    self._notifier = \
597
      pyinotify.Notifier(self._wm, default_proc_fun=self._inotify_handler)
598
    try:
599
      self._inotify_handler.enable()
600
    except Exception:
601
      # pyinotify doesn't close file descriptors automatically
602
      self._notifier.stop()
603
      raise
604

    
605
  def _OnInotify(self, notifier_enabled):
606
    """Callback for inotify.
607

608
    """
609
    if not notifier_enabled:
610
      self._inotify_handler.enable()
611

    
612
  def Wait(self, timeout):
613
    """Waits for the job file to change.
614

615
    @type timeout: float
616
    @param timeout: Timeout in seconds
617
    @return: Whether there have been events
618

619
    """
620
    assert timeout >= 0
621
    have_events = self._notifier.check_events(timeout * 1000)
622
    if have_events:
623
      self._notifier.read_events()
624
    self._notifier.process_events()
625
    return have_events
626

    
627
  def Close(self):
628
    """Closes underlying notifier and its file descriptor.
629

630
    """
631
    self._notifier.stop()
632

    
633

    
634
class _JobChangesWaiter(object):
635
  def __init__(self, filename):
636
    """Initializes this class.
637

638
    @type filename: string
639
    @param filename: Path to job file
640

641
    """
642
    self._filewaiter = None
643
    self._filename = filename
644

    
645
  def Wait(self, timeout):
646
    """Waits for a job to change.
647

648
    @type timeout: float
649
    @param timeout: Timeout in seconds
650
    @return: Whether there have been events
651

652
    """
653
    if self._filewaiter:
654
      return self._filewaiter.Wait(timeout)
655

    
656
    # Lazy setup: Avoid inotify setup cost when job file has already changed.
657
    # If this point is reached, return immediately and let caller check the job
658
    # file again in case there were changes since the last check. This avoids a
659
    # race condition.
660
    self._filewaiter = _JobFileChangesWaiter(self._filename)
661

    
662
    return True
663

    
664
  def Close(self):
665
    """Closes underlying waiter.
666

667
    """
668
    if self._filewaiter:
669
      self._filewaiter.Close()
670

    
671

    
672
class _WaitForJobChangesHelper(object):
673
  """Helper class using inotify to wait for changes in a job file.
674

675
  This class takes a previous job status and serial, and alerts the client when
676
  the current job status has changed.
677

678
  """
679
  @staticmethod
680
  def _CheckForChanges(job_load_fn, check_fn):
681
    job = job_load_fn()
682
    if not job:
683
      raise errors.JobLost()
684

    
685
    result = check_fn(job)
686
    if result is None:
687
      raise utils.RetryAgain()
688

    
689
    return result
690

    
691
  def __call__(self, filename, job_load_fn,
692
               fields, prev_job_info, prev_log_serial, timeout):
693
    """Waits for changes on a job.
694

695
    @type filename: string
696
    @param filename: File on which to wait for changes
697
    @type job_load_fn: callable
698
    @param job_load_fn: Function to load job
699
    @type fields: list of strings
700
    @param fields: Which fields to check for changes
701
    @type prev_job_info: list or None
702
    @param prev_job_info: Last job information returned
703
    @type prev_log_serial: int
704
    @param prev_log_serial: Last job message serial number
705
    @type timeout: float
706
    @param timeout: maximum time to wait in seconds
707

708
    """
709
    try:
710
      check_fn = _JobChangesChecker(fields, prev_job_info, prev_log_serial)
711
      waiter = _JobChangesWaiter(filename)
712
      try:
713
        return utils.Retry(compat.partial(self._CheckForChanges,
714
                                          job_load_fn, check_fn),
715
                           utils.RETRY_REMAINING_TIME, timeout,
716
                           wait_fn=waiter.Wait)
717
      finally:
718
        waiter.Close()
719
    except (errors.InotifyError, errors.JobLost):
720
      return None
721
    except utils.RetryTimeout:
722
      return constants.JOB_NOTCHANGED
723

    
724

    
725
def _EncodeOpError(err):
726
  """Encodes an error which occurred while processing an opcode.
727

728
  """
729
  if isinstance(err, errors.GenericError):
730
    to_encode = err
731
  else:
732
    to_encode = errors.OpExecError(str(err))
733

    
734
  return errors.EncodeException(to_encode)
735

    
736

    
737
class _JobQueueWorker(workerpool.BaseWorker):
738
  """The actual job workers.
739

740
  """
741
  def RunTask(self, job): # pylint: disable-msg=W0221
742
    """Job executor.
743

744
    This functions processes a job. It is closely tied to the _QueuedJob and
745
    _QueuedOpCode classes.
746

747
    @type job: L{_QueuedJob}
748
    @param job: the job to be processed
749

750
    """
751
    self.SetTaskName("Job%s" % job.id)
752

    
753
    logging.info("Processing job %s", job.id)
754
    proc = mcpu.Processor(self.pool.queue.context, job.id)
755
    queue = job.queue
756
    try:
757
      try:
758
        count = len(job.ops)
759
        for idx, op in enumerate(job.ops):
760
          op_summary = op.input.Summary()
761
          if op.status == constants.OP_STATUS_SUCCESS:
762
            # this is a job that was partially completed before master
763
            # daemon shutdown, so it can be expected that some opcodes
764
            # are already completed successfully (if any did error
765
            # out, then the whole job should have been aborted and not
766
            # resubmitted for processing)
767
            logging.info("Op %s/%s: opcode %s already processed, skipping",
768
                         idx + 1, count, op_summary)
769
            continue
770
          try:
771
            logging.info("Op %s/%s: Starting opcode %s", idx + 1, count,
772
                         op_summary)
773

    
774
            queue.acquire(shared=1)
775
            try:
776
              if op.status == constants.OP_STATUS_CANCELED:
777
                logging.debug("Canceling opcode")
778
                raise CancelJob()
779
              assert op.status == constants.OP_STATUS_QUEUED
780
              logging.debug("Opcode %s/%s waiting for locks",
781
                            idx + 1, count)
782
              op.status = constants.OP_STATUS_WAITLOCK
783
              op.result = None
784
              op.start_timestamp = TimeStampNow()
785
              if idx == 0: # first opcode
786
                job.start_timestamp = op.start_timestamp
787
              queue.UpdateJobUnlocked(job)
788

    
789
              input_opcode = op.input
790
            finally:
791
              queue.release()
792

    
793
            # Make sure not to hold queue lock while calling ExecOpCode
794
            result = proc.ExecOpCode(input_opcode,
795
                                     _OpExecCallbacks(queue, job, op))
796

    
797
            queue.acquire(shared=1)
798
            try:
799
              logging.debug("Opcode %s/%s succeeded", idx + 1, count)
800
              op.status = constants.OP_STATUS_SUCCESS
801
              op.result = result
802
              op.end_timestamp = TimeStampNow()
803
              if idx == count - 1:
804
                job.end_timestamp = TimeStampNow()
805

    
806
                # Consistency check
807
                assert compat.all(i.status == constants.OP_STATUS_SUCCESS
808
                                  for i in job.ops)
809

    
810
              queue.UpdateJobUnlocked(job)
811
            finally:
812
              queue.release()
813

    
814
            logging.info("Op %s/%s: Successfully finished opcode %s",
815
                         idx + 1, count, op_summary)
816
          except CancelJob:
817
            # Will be handled further up
818
            raise
819
          except Exception, err:
820
            queue.acquire(shared=1)
821
            try:
822
              try:
823
                logging.debug("Opcode %s/%s failed", idx + 1, count)
824
                op.status = constants.OP_STATUS_ERROR
825
                op.result = _EncodeOpError(err)
826
                op.end_timestamp = TimeStampNow()
827
                logging.info("Op %s/%s: Error in opcode %s: %s",
828
                             idx + 1, count, op_summary, err)
829

    
830
                to_encode = errors.OpExecError("Preceding opcode failed")
831
                job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
832
                                      _EncodeOpError(to_encode))
833

    
834
                # Consistency check
835
                assert compat.all(i.status == constants.OP_STATUS_SUCCESS
836
                                  for i in job.ops[:idx])
837
                assert compat.all(i.status == constants.OP_STATUS_ERROR and
838
                                  errors.GetEncodedError(i.result)
839
                                  for i in job.ops[idx:])
840
              finally:
841
                job.end_timestamp = TimeStampNow()
842
                queue.UpdateJobUnlocked(job)
843
            finally:
844
              queue.release()
845
            raise
846

    
847
      except CancelJob:
848
        queue.acquire(shared=1)
849
        try:
850
          job.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
851
                                "Job canceled by request")
852
          job.end_timestamp = TimeStampNow()
853
          queue.UpdateJobUnlocked(job)
854
        finally:
855
          queue.release()
856
      except errors.GenericError, err:
857
        logging.exception("Ganeti exception")
858
      except:
859
        logging.exception("Unhandled exception")
860
    finally:
861
      status = job.CalcStatus()
862
      logging.info("Finished job %s, status = %s", job.id, status)
863

    
864

    
865
class _JobQueueWorkerPool(workerpool.WorkerPool):
866
  """Simple class implementing a job-processing workerpool.
867

868
  """
869
  def __init__(self, queue):
870
    super(_JobQueueWorkerPool, self).__init__("JobQueue",
871
                                              JOBQUEUE_THREADS,
872
                                              _JobQueueWorker)
873
    self.queue = queue
874

    
875

    
876
def _RequireOpenQueue(fn):
877
  """Decorator for "public" functions.
878

879
  This function should be used for all 'public' functions. That is,
880
  functions usually called from other classes. Note that this should
881
  be applied only to methods (not plain functions), since it expects
882
  that the decorated function is called with a first argument that has
883
  a '_queue_filelock' argument.
884

885
  @warning: Use this decorator only after locking.ssynchronized
886

887
  Example::
888
    @locking.ssynchronized(_LOCK)
889
    @_RequireOpenQueue
890
    def Example(self):
891
      pass
892

893
  """
894
  def wrapper(self, *args, **kwargs):
895
    # pylint: disable-msg=W0212
896
    assert self._queue_filelock is not None, "Queue should be open"
897
    return fn(self, *args, **kwargs)
898
  return wrapper
899

    
900

    
901
class JobQueue(object):
902
  """Queue used to manage the jobs.
903

904
  @cvar _RE_JOB_FILE: regex matching the valid job file names
905

906
  """
907
  _RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
908

    
909
  def __init__(self, context):
910
    """Constructor for JobQueue.
911

912
    The constructor will initialize the job queue object and then
913
    start loading the current jobs from disk, either for starting them
914
    (if they were queue) or for aborting them (if they were already
915
    running).
916

917
    @type context: GanetiContext
918
    @param context: the context object for access to the configuration
919
        data and other ganeti objects
920

921
    """
922
    self.context = context
923
    self._memcache = weakref.WeakValueDictionary()
924
    self._my_hostname = netutils.Hostname.GetSysName()
925

    
926
    # The Big JobQueue lock. If a code block or method acquires it in shared
927
    # mode safe it must guarantee concurrency with all the code acquiring it in
928
    # shared mode, including itself. In order not to acquire it at all
929
    # concurrency must be guaranteed with all code acquiring it in shared mode
930
    # and all code acquiring it exclusively.
931
    self._lock = locking.SharedLock("JobQueue")
932

    
933
    self.acquire = self._lock.acquire
934
    self.release = self._lock.release
935

    
936
    # Initialize the queue, and acquire the filelock.
937
    # This ensures no other process is working on the job queue.
938
    self._queue_filelock = jstore.InitAndVerifyQueue(must_lock=True)
939

    
940
    # Read serial file
941
    self._last_serial = jstore.ReadSerial()
942
    assert self._last_serial is not None, ("Serial file was modified between"
943
                                           " check in jstore and here")
944

    
945
    # Get initial list of nodes
946
    self._nodes = dict((n.name, n.primary_ip)
947
                       for n in self.context.cfg.GetAllNodesInfo().values()
948
                       if n.master_candidate)
949

    
950
    # Remove master node
951
    self._nodes.pop(self._my_hostname, None)
952

    
953
    # TODO: Check consistency across nodes
954

    
955
    self._queue_size = 0
956
    self._UpdateQueueSizeUnlocked()
957
    self._drained = self._IsQueueMarkedDrain()
958

    
959
    # Setup worker pool
960
    self._wpool = _JobQueueWorkerPool(self)
961
    try:
962
      self._InspectQueue()
963
    except:
964
      self._wpool.TerminateWorkers()
965
      raise
966

    
967
  @locking.ssynchronized(_LOCK)
968
  @_RequireOpenQueue
969
  def _InspectQueue(self):
970
    """Loads the whole job queue and resumes unfinished jobs.
971

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

975
    """
976
    logging.info("Inspecting job queue")
977

    
978
    all_job_ids = self._GetJobIDsUnlocked()
979
    jobs_count = len(all_job_ids)
980
    lastinfo = time.time()
981
    for idx, job_id in enumerate(all_job_ids):
982
      # Give an update every 1000 jobs or 10 seconds
983
      if (idx % 1000 == 0 or time.time() >= (lastinfo + 10.0) or
984
          idx == (jobs_count - 1)):
985
        logging.info("Job queue inspection: %d/%d (%0.1f %%)",
986
                     idx, jobs_count - 1, 100.0 * (idx + 1) / jobs_count)
987
        lastinfo = time.time()
988

    
989
      job = self._LoadJobUnlocked(job_id)
990

    
991
      # a failure in loading the job can cause 'None' to be returned
992
      if job is None:
993
        continue
994

    
995
      status = job.CalcStatus()
996

    
997
      if status in (constants.JOB_STATUS_QUEUED, ):
998
        self._wpool.AddTask((job, ))
999

    
1000
      elif status in (constants.JOB_STATUS_RUNNING,
1001
                      constants.JOB_STATUS_WAITLOCK,
1002
                      constants.JOB_STATUS_CANCELING):
1003
        logging.warning("Unfinished job %s found: %s", job.id, job)
1004
        job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
1005
                              "Unclean master daemon shutdown")
1006
        self.UpdateJobUnlocked(job)
1007

    
1008
    logging.info("Job queue inspection finished")
1009

    
1010
  @locking.ssynchronized(_LOCK)
1011
  @_RequireOpenQueue
1012
  def AddNode(self, node):
1013
    """Register a new node with the queue.
1014

1015
    @type node: L{objects.Node}
1016
    @param node: the node object to be added
1017

1018
    """
1019
    node_name = node.name
1020
    assert node_name != self._my_hostname
1021

    
1022
    # Clean queue directory on added node
1023
    result = rpc.RpcRunner.call_jobqueue_purge(node_name)
1024
    msg = result.fail_msg
1025
    if msg:
1026
      logging.warning("Cannot cleanup queue directory on node %s: %s",
1027
                      node_name, msg)
1028

    
1029
    if not node.master_candidate:
1030
      # remove if existing, ignoring errors
1031
      self._nodes.pop(node_name, None)
1032
      # and skip the replication of the job ids
1033
      return
1034

    
1035
    # Upload the whole queue excluding archived jobs
1036
    files = [self._GetJobPath(job_id) for job_id in self._GetJobIDsUnlocked()]
1037

    
1038
    # Upload current serial file
1039
    files.append(constants.JOB_QUEUE_SERIAL_FILE)
1040

    
1041
    for file_name in files:
1042
      # Read file content
1043
      content = utils.ReadFile(file_name)
1044

    
1045
      result = rpc.RpcRunner.call_jobqueue_update([node_name],
1046
                                                  [node.primary_ip],
1047
                                                  file_name, content)
1048
      msg = result[node_name].fail_msg
1049
      if msg:
1050
        logging.error("Failed to upload file %s to node %s: %s",
1051
                      file_name, node_name, msg)
1052

    
1053
    self._nodes[node_name] = node.primary_ip
1054

    
1055
  @locking.ssynchronized(_LOCK)
1056
  @_RequireOpenQueue
1057
  def RemoveNode(self, node_name):
1058
    """Callback called when removing nodes from the cluster.
1059

1060
    @type node_name: str
1061
    @param node_name: the name of the node to remove
1062

1063
    """
1064
    self._nodes.pop(node_name, None)
1065

    
1066
  @staticmethod
1067
  def _CheckRpcResult(result, nodes, failmsg):
1068
    """Verifies the status of an RPC call.
1069

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

1074
    @param result: the data as returned from the rpc call
1075
    @type nodes: list
1076
    @param nodes: the list of nodes we made the call to
1077
    @type failmsg: str
1078
    @param failmsg: the identifier to be used for logging
1079

1080
    """
1081
    failed = []
1082
    success = []
1083

    
1084
    for node in nodes:
1085
      msg = result[node].fail_msg
1086
      if msg:
1087
        failed.append(node)
1088
        logging.error("RPC call %s (%s) failed on node %s: %s",
1089
                      result[node].call, failmsg, node, msg)
1090
      else:
1091
        success.append(node)
1092

    
1093
    # +1 for the master node
1094
    if (len(success) + 1) < len(failed):
1095
      # TODO: Handle failing nodes
1096
      logging.error("More than half of the nodes failed")
1097

    
1098
  def _GetNodeIp(self):
1099
    """Helper for returning the node name/ip list.
1100

1101
    @rtype: (list, list)
1102
    @return: a tuple of two lists, the first one with the node
1103
        names and the second one with the node addresses
1104

1105
    """
1106
    # TODO: Change to "tuple(map(list, zip(*self._nodes.items())))"?
1107
    name_list = self._nodes.keys()
1108
    addr_list = [self._nodes[name] for name in name_list]
1109
    return name_list, addr_list
1110

    
1111
  def _UpdateJobQueueFile(self, file_name, data, replicate):
1112
    """Writes a file locally and then replicates it to all nodes.
1113

1114
    This function will replace the contents of a file on the local
1115
    node and then replicate it to all the other nodes we have.
1116

1117
    @type file_name: str
1118
    @param file_name: the path of the file to be replicated
1119
    @type data: str
1120
    @param data: the new contents of the file
1121
    @type replicate: boolean
1122
    @param replicate: whether to spread the changes to the remote nodes
1123

1124
    """
1125
    getents = runtime.GetEnts()
1126
    utils.WriteFile(file_name, data=data, uid=getents.masterd_uid,
1127
                    gid=getents.masterd_gid)
1128

    
1129
    if replicate:
1130
      names, addrs = self._GetNodeIp()
1131
      result = rpc.RpcRunner.call_jobqueue_update(names, addrs, file_name, data)
1132
      self._CheckRpcResult(result, self._nodes, "Updating %s" % file_name)
1133

    
1134
  def _RenameFilesUnlocked(self, rename):
1135
    """Renames a file locally and then replicate the change.
1136

1137
    This function will rename a file in the local queue directory
1138
    and then replicate this rename to all the other nodes we have.
1139

1140
    @type rename: list of (old, new)
1141
    @param rename: List containing tuples mapping old to new names
1142

1143
    """
1144
    # Rename them locally
1145
    for old, new in rename:
1146
      utils.RenameFile(old, new, mkdir=True)
1147

    
1148
    # ... and on all nodes
1149
    names, addrs = self._GetNodeIp()
1150
    result = rpc.RpcRunner.call_jobqueue_rename(names, addrs, rename)
1151
    self._CheckRpcResult(result, self._nodes, "Renaming files (%r)" % rename)
1152

    
1153
  @staticmethod
1154
  def _FormatJobID(job_id):
1155
    """Convert a job ID to string format.
1156

1157
    Currently this just does C{str(job_id)} after performing some
1158
    checks, but if we want to change the job id format this will
1159
    abstract this change.
1160

1161
    @type job_id: int or long
1162
    @param job_id: the numeric job id
1163
    @rtype: str
1164
    @return: the formatted job id
1165

1166
    """
1167
    if not isinstance(job_id, (int, long)):
1168
      raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id)
1169
    if job_id < 0:
1170
      raise errors.ProgrammerError("Job ID %s is negative" % job_id)
1171

    
1172
    return str(job_id)
1173

    
1174
  @classmethod
1175
  def _GetArchiveDirectory(cls, job_id):
1176
    """Returns the archive directory for a job.
1177

1178
    @type job_id: str
1179
    @param job_id: Job identifier
1180
    @rtype: str
1181
    @return: Directory name
1182

1183
    """
1184
    return str(int(job_id) / JOBS_PER_ARCHIVE_DIRECTORY)
1185

    
1186
  def _NewSerialsUnlocked(self, count):
1187
    """Generates a new job identifier.
1188

1189
    Job identifiers are unique during the lifetime of a cluster.
1190

1191
    @type count: integer
1192
    @param count: how many serials to return
1193
    @rtype: str
1194
    @return: a string representing the job identifier.
1195

1196
    """
1197
    assert count > 0
1198
    # New number
1199
    serial = self._last_serial + count
1200

    
1201
    # Write to file
1202
    self._UpdateJobQueueFile(constants.JOB_QUEUE_SERIAL_FILE,
1203
                             "%s\n" % serial, True)
1204

    
1205
    result = [self._FormatJobID(v)
1206
              for v in range(self._last_serial, serial + 1)]
1207
    # Keep it only if we were able to write the file
1208
    self._last_serial = serial
1209

    
1210
    return result
1211

    
1212
  @staticmethod
1213
  def _GetJobPath(job_id):
1214
    """Returns the job file for a given job id.
1215

1216
    @type job_id: str
1217
    @param job_id: the job identifier
1218
    @rtype: str
1219
    @return: the path to the job file
1220

1221
    """
1222
    return utils.PathJoin(constants.QUEUE_DIR, "job-%s" % job_id)
1223

    
1224
  @classmethod
1225
  def _GetArchivedJobPath(cls, job_id):
1226
    """Returns the archived job file for a give job id.
1227

1228
    @type job_id: str
1229
    @param job_id: the job identifier
1230
    @rtype: str
1231
    @return: the path to the archived job file
1232

1233
    """
1234
    return utils.PathJoin(constants.JOB_QUEUE_ARCHIVE_DIR,
1235
                          cls._GetArchiveDirectory(job_id), "job-%s" % job_id)
1236

    
1237
  def _GetJobIDsUnlocked(self, sort=True):
1238
    """Return all known job IDs.
1239

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

1244
    @type sort: boolean
1245
    @param sort: perform sorting on the returned job ids
1246
    @rtype: list
1247
    @return: the list of job IDs
1248

1249
    """
1250
    jlist = []
1251
    for filename in utils.ListVisibleFiles(constants.QUEUE_DIR):
1252
      m = self._RE_JOB_FILE.match(filename)
1253
      if m:
1254
        jlist.append(m.group(1))
1255
    if sort:
1256
      jlist = utils.NiceSort(jlist)
1257
    return jlist
1258

    
1259
  def _LoadJobUnlocked(self, job_id):
1260
    """Loads a job from the disk or memory.
1261

1262
    Given a job id, this will return the cached job object if
1263
    existing, or try to load the job from the disk. If loading from
1264
    disk, it will also add the job to the cache.
1265

1266
    @param job_id: the job id
1267
    @rtype: L{_QueuedJob} or None
1268
    @return: either None or the job object
1269

1270
    """
1271
    job = self._memcache.get(job_id, None)
1272
    if job:
1273
      logging.debug("Found job %s in memcache", job_id)
1274
      return job
1275

    
1276
    try:
1277
      job = self._LoadJobFromDisk(job_id)
1278
      if job is None:
1279
        return job
1280
    except errors.JobFileCorrupted:
1281
      old_path = self._GetJobPath(job_id)
1282
      new_path = self._GetArchivedJobPath(job_id)
1283
      if old_path == new_path:
1284
        # job already archived (future case)
1285
        logging.exception("Can't parse job %s", job_id)
1286
      else:
1287
        # non-archived case
1288
        logging.exception("Can't parse job %s, will archive.", job_id)
1289
        self._RenameFilesUnlocked([(old_path, new_path)])
1290
      return None
1291

    
1292
    self._memcache[job_id] = job
1293
    logging.debug("Added job %s to the cache", job_id)
1294
    return job
1295

    
1296
  def _LoadJobFromDisk(self, job_id):
1297
    """Load the given job file from disk.
1298

1299
    Given a job file, read, load and restore it in a _QueuedJob format.
1300

1301
    @type job_id: string
1302
    @param job_id: job identifier
1303
    @rtype: L{_QueuedJob} or None
1304
    @return: either None or the job object
1305

1306
    """
1307
    filepath = self._GetJobPath(job_id)
1308
    logging.debug("Loading job from %s", filepath)
1309
    try:
1310
      raw_data = utils.ReadFile(filepath)
1311
    except EnvironmentError, err:
1312
      if err.errno in (errno.ENOENT, ):
1313
        return None
1314
      raise
1315

    
1316
    try:
1317
      data = serializer.LoadJson(raw_data)
1318
      job = _QueuedJob.Restore(self, data)
1319
    except Exception, err: # pylint: disable-msg=W0703
1320
      raise errors.JobFileCorrupted(err)
1321

    
1322
    return job
1323

    
1324
  def SafeLoadJobFromDisk(self, job_id):
1325
    """Load the given job file from disk.
1326

1327
    Given a job file, read, load and restore it in a _QueuedJob format.
1328
    In case of error reading the job, it gets returned as None, and the
1329
    exception is logged.
1330

1331
    @type job_id: string
1332
    @param job_id: job identifier
1333
    @rtype: L{_QueuedJob} or None
1334
    @return: either None or the job object
1335

1336
    """
1337
    try:
1338
      return self._LoadJobFromDisk(job_id)
1339
    except (errors.JobFileCorrupted, EnvironmentError):
1340
      logging.exception("Can't load/parse job %s", job_id)
1341
      return None
1342

    
1343
  @staticmethod
1344
  def _IsQueueMarkedDrain():
1345
    """Check if the queue is marked from drain.
1346

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

1350
    @rtype: boolean
1351
    @return: True of the job queue is marked for draining
1352

1353
    """
1354
    return os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
1355

    
1356
  def _UpdateQueueSizeUnlocked(self):
1357
    """Update the queue size.
1358

1359
    """
1360
    self._queue_size = len(self._GetJobIDsUnlocked(sort=False))
1361

    
1362
  @locking.ssynchronized(_LOCK)
1363
  @_RequireOpenQueue
1364
  def SetDrainFlag(self, drain_flag):
1365
    """Sets the drain flag for the queue.
1366

1367
    @type drain_flag: boolean
1368
    @param drain_flag: Whether to set or unset the drain flag
1369

1370
    """
1371
    getents = runtime.GetEnts()
1372

    
1373
    if drain_flag:
1374
      utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True,
1375
                      uid=getents.masterd_uid, gid=getents.masterd_gid)
1376
    else:
1377
      utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
1378

    
1379
    self._drained = drain_flag
1380

    
1381
    return True
1382

    
1383
  @_RequireOpenQueue
1384
  def _SubmitJobUnlocked(self, job_id, ops):
1385
    """Create and store a new job.
1386

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

1390
    @type job_id: job ID
1391
    @param job_id: the job ID for the new job
1392
    @type ops: list
1393
    @param ops: The list of OpCodes that will become the new job.
1394
    @rtype: L{_QueuedJob}
1395
    @return: the job object to be queued
1396
    @raise errors.JobQueueDrainError: if the job queue is marked for draining
1397
    @raise errors.JobQueueFull: if the job queue has too many jobs in it
1398
    @raise errors.GenericError: If an opcode is not valid
1399

1400
    """
1401
    # Ok when sharing the big job queue lock, as the drain file is created when
1402
    # the lock is exclusive.
1403
    if self._drained:
1404
      raise errors.JobQueueDrainError("Job queue is drained, refusing job")
1405

    
1406
    if self._queue_size >= constants.JOB_QUEUE_SIZE_HARD_LIMIT:
1407
      raise errors.JobQueueFull()
1408

    
1409
    job = _QueuedJob(self, job_id, ops)
1410

    
1411
    # Check priority
1412
    for idx, op in enumerate(job.ops):
1413
      if op.priority not in constants.OP_PRIO_SUBMIT_VALID:
1414
        allowed = utils.CommaJoin(constants.OP_PRIO_SUBMIT_VALID)
1415
        raise errors.GenericError("Opcode %s has invalid priority %s, allowed"
1416
                                  " are %s" % (idx, op.priority, allowed))
1417

    
1418
    # Write to disk
1419
    self.UpdateJobUnlocked(job)
1420

    
1421
    self._queue_size += 1
1422

    
1423
    logging.debug("Adding new job %s to the cache", job_id)
1424
    self._memcache[job_id] = job
1425

    
1426
    return job
1427

    
1428
  @locking.ssynchronized(_LOCK)
1429
  @_RequireOpenQueue
1430
  def SubmitJob(self, ops):
1431
    """Create and store a new job.
1432

1433
    @see: L{_SubmitJobUnlocked}
1434

1435
    """
1436
    job_id = self._NewSerialsUnlocked(1)[0]
1437
    self._wpool.AddTask((self._SubmitJobUnlocked(job_id, ops), ))
1438
    return job_id
1439

    
1440
  @locking.ssynchronized(_LOCK)
1441
  @_RequireOpenQueue
1442
  def SubmitManyJobs(self, jobs):
1443
    """Create and store multiple jobs.
1444

1445
    @see: L{_SubmitJobUnlocked}
1446

1447
    """
1448
    results = []
1449
    tasks = []
1450
    all_job_ids = self._NewSerialsUnlocked(len(jobs))
1451
    for job_id, ops in zip(all_job_ids, jobs):
1452
      try:
1453
        tasks.append((self._SubmitJobUnlocked(job_id, ops), ))
1454
        status = True
1455
        data = job_id
1456
      except errors.GenericError, err:
1457
        data = str(err)
1458
        status = False
1459
      results.append((status, data))
1460
    self._wpool.AddManyTasks(tasks)
1461

    
1462
    return results
1463

    
1464
  @_RequireOpenQueue
1465
  def UpdateJobUnlocked(self, job, replicate=True):
1466
    """Update a job's on disk storage.
1467

1468
    After a job has been modified, this function needs to be called in
1469
    order to write the changes to disk and replicate them to the other
1470
    nodes.
1471

1472
    @type job: L{_QueuedJob}
1473
    @param job: the changed job
1474
    @type replicate: boolean
1475
    @param replicate: whether to replicate the change to remote nodes
1476

1477
    """
1478
    filename = self._GetJobPath(job.id)
1479
    data = serializer.DumpJson(job.Serialize(), indent=False)
1480
    logging.debug("Writing job %s to %s", job.id, filename)
1481
    self._UpdateJobQueueFile(filename, data, replicate)
1482

    
1483
  def WaitForJobChanges(self, job_id, fields, prev_job_info, prev_log_serial,
1484
                        timeout):
1485
    """Waits for changes in a job.
1486

1487
    @type job_id: string
1488
    @param job_id: Job identifier
1489
    @type fields: list of strings
1490
    @param fields: Which fields to check for changes
1491
    @type prev_job_info: list or None
1492
    @param prev_job_info: Last job information returned
1493
    @type prev_log_serial: int
1494
    @param prev_log_serial: Last job message serial number
1495
    @type timeout: float
1496
    @param timeout: maximum time to wait in seconds
1497
    @rtype: tuple (job info, log entries)
1498
    @return: a tuple of the job information as required via
1499
        the fields parameter, and the log entries as a list
1500

1501
        if the job has not changed and the timeout has expired,
1502
        we instead return a special value,
1503
        L{constants.JOB_NOTCHANGED}, which should be interpreted
1504
        as such by the clients
1505

1506
    """
1507
    load_fn = compat.partial(self.SafeLoadJobFromDisk, job_id)
1508

    
1509
    helper = _WaitForJobChangesHelper()
1510

    
1511
    return helper(self._GetJobPath(job_id), load_fn,
1512
                  fields, prev_job_info, prev_log_serial, timeout)
1513

    
1514
  @locking.ssynchronized(_LOCK)
1515
  @_RequireOpenQueue
1516
  def CancelJob(self, job_id):
1517
    """Cancels a job.
1518

1519
    This will only succeed if the job has not started yet.
1520

1521
    @type job_id: string
1522
    @param job_id: job ID of job to be cancelled.
1523

1524
    """
1525
    logging.info("Cancelling job %s", job_id)
1526

    
1527
    job = self._LoadJobUnlocked(job_id)
1528
    if not job:
1529
      logging.debug("Job %s not found", job_id)
1530
      return (False, "Job %s not found" % job_id)
1531

    
1532
    (success, msg) = job.Cancel()
1533

    
1534
    if success:
1535
      self.UpdateJobUnlocked(job)
1536

    
1537
    return (success, msg)
1538

    
1539
  @_RequireOpenQueue
1540
  def _ArchiveJobsUnlocked(self, jobs):
1541
    """Archives jobs.
1542

1543
    @type jobs: list of L{_QueuedJob}
1544
    @param jobs: Job objects
1545
    @rtype: int
1546
    @return: Number of archived jobs
1547

1548
    """
1549
    archive_jobs = []
1550
    rename_files = []
1551
    for job in jobs:
1552
      if job.CalcStatus() not in constants.JOBS_FINALIZED:
1553
        logging.debug("Job %s is not yet done", job.id)
1554
        continue
1555

    
1556
      archive_jobs.append(job)
1557

    
1558
      old = self._GetJobPath(job.id)
1559
      new = self._GetArchivedJobPath(job.id)
1560
      rename_files.append((old, new))
1561

    
1562
    # TODO: What if 1..n files fail to rename?
1563
    self._RenameFilesUnlocked(rename_files)
1564

    
1565
    logging.debug("Successfully archived job(s) %s",
1566
                  utils.CommaJoin(job.id for job in archive_jobs))
1567

    
1568
    # Since we haven't quite checked, above, if we succeeded or failed renaming
1569
    # the files, we update the cached queue size from the filesystem. When we
1570
    # get around to fix the TODO: above, we can use the number of actually
1571
    # archived jobs to fix this.
1572
    self._UpdateQueueSizeUnlocked()
1573
    return len(archive_jobs)
1574

    
1575
  @locking.ssynchronized(_LOCK)
1576
  @_RequireOpenQueue
1577
  def ArchiveJob(self, job_id):
1578
    """Archives a job.
1579

1580
    This is just a wrapper over L{_ArchiveJobsUnlocked}.
1581

1582
    @type job_id: string
1583
    @param job_id: Job ID of job to be archived.
1584
    @rtype: bool
1585
    @return: Whether job was archived
1586

1587
    """
1588
    logging.info("Archiving job %s", job_id)
1589

    
1590
    job = self._LoadJobUnlocked(job_id)
1591
    if not job:
1592
      logging.debug("Job %s not found", job_id)
1593
      return False
1594

    
1595
    return self._ArchiveJobsUnlocked([job]) == 1
1596

    
1597
  @locking.ssynchronized(_LOCK)
1598
  @_RequireOpenQueue
1599
  def AutoArchiveJobs(self, age, timeout):
1600
    """Archives all jobs based on age.
1601

1602
    The method will archive all jobs which are older than the age
1603
    parameter. For jobs that don't have an end timestamp, the start
1604
    timestamp will be considered. The special '-1' age will cause
1605
    archival of all jobs (that are not running or queued).
1606

1607
    @type age: int
1608
    @param age: the minimum age in seconds
1609

1610
    """
1611
    logging.info("Archiving jobs with age more than %s seconds", age)
1612

    
1613
    now = time.time()
1614
    end_time = now + timeout
1615
    archived_count = 0
1616
    last_touched = 0
1617

    
1618
    all_job_ids = self._GetJobIDsUnlocked()
1619
    pending = []
1620
    for idx, job_id in enumerate(all_job_ids):
1621
      last_touched = idx + 1
1622

    
1623
      # Not optimal because jobs could be pending
1624
      # TODO: Measure average duration for job archival and take number of
1625
      # pending jobs into account.
1626
      if time.time() > end_time:
1627
        break
1628

    
1629
      # Returns None if the job failed to load
1630
      job = self._LoadJobUnlocked(job_id)
1631
      if job:
1632
        if job.end_timestamp is None:
1633
          if job.start_timestamp is None:
1634
            job_age = job.received_timestamp
1635
          else:
1636
            job_age = job.start_timestamp
1637
        else:
1638
          job_age = job.end_timestamp
1639

    
1640
        if age == -1 or now - job_age[0] > age:
1641
          pending.append(job)
1642

    
1643
          # Archive 10 jobs at a time
1644
          if len(pending) >= 10:
1645
            archived_count += self._ArchiveJobsUnlocked(pending)
1646
            pending = []
1647

    
1648
    if pending:
1649
      archived_count += self._ArchiveJobsUnlocked(pending)
1650

    
1651
    return (archived_count, len(all_job_ids) - last_touched)
1652

    
1653
  def QueryJobs(self, job_ids, fields):
1654
    """Returns a list of jobs in queue.
1655

1656
    @type job_ids: list
1657
    @param job_ids: sequence of job identifiers or None for all
1658
    @type fields: list
1659
    @param fields: names of fields to return
1660
    @rtype: list
1661
    @return: list one element per job, each element being list with
1662
        the requested fields
1663

1664
    """
1665
    jobs = []
1666
    list_all = False
1667
    if not job_ids:
1668
      # Since files are added to/removed from the queue atomically, there's no
1669
      # risk of getting the job ids in an inconsistent state.
1670
      job_ids = self._GetJobIDsUnlocked()
1671
      list_all = True
1672

    
1673
    for job_id in job_ids:
1674
      job = self.SafeLoadJobFromDisk(job_id)
1675
      if job is not None:
1676
        jobs.append(job.GetInfo(fields))
1677
      elif not list_all:
1678
        jobs.append(None)
1679

    
1680
    return jobs
1681

    
1682
  @locking.ssynchronized(_LOCK)
1683
  @_RequireOpenQueue
1684
  def Shutdown(self):
1685
    """Stops the job queue.
1686

1687
    This shutdowns all the worker threads an closes the queue.
1688

1689
    """
1690
    self._wpool.TerminateWorkers()
1691

    
1692
    self._queue_filelock.Close()
1693
    self._queue_filelock = None