Statistics
| Branch: | Tag: | Revision:

root / lib / jqueue.py @ 2d3ed64b

History | View | Annotate | Download (40.4 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008 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 threading
35
import errno
36
import re
37
import time
38
import weakref
39

    
40
from ganeti import constants
41
from ganeti import serializer
42
from ganeti import workerpool
43
from ganeti import opcodes
44
from ganeti import errors
45
from ganeti import mcpu
46
from ganeti import utils
47
from ganeti import jstore
48
from ganeti import rpc
49

    
50

    
51
JOBQUEUE_THREADS = 25
52
JOBS_PER_ARCHIVE_DIRECTORY = 10000
53

    
54

    
55
class CancelJob(Exception):
56
  """Special exception to cancel a job.
57

58
  """
59

    
60

    
61
def TimeStampNow():
62
  """Returns the current timestamp.
63

64
  @rtype: tuple
65
  @return: the current time in the (seconds, microseconds) format
66

67
  """
68
  return utils.SplitTime(time.time())
69

    
70

    
71
class _QueuedOpCode(object):
72
  """Encapsulates an opcode object.
73

74
  @ivar log: holds the execution log and consists of tuples
75
  of the form C{(log_serial, timestamp, level, message)}
76
  @ivar input: the OpCode we encapsulate
77
  @ivar status: the current status
78
  @ivar result: the result of the LU execution
79
  @ivar start_timestamp: timestamp for the start of the execution
80
  @ivar stop_timestamp: timestamp for the end of the execution
81

82
  """
83
  __slots__ = ["input", "status", "result", "log",
84
               "start_timestamp", "end_timestamp",
85
               "__weakref__"]
86

    
87
  def __init__(self, op):
88
    """Constructor for the _QuededOpCode.
89

90
    @type op: L{opcodes.OpCode}
91
    @param op: the opcode we encapsulate
92

93
    """
94
    self.input = op
95
    self.status = constants.OP_STATUS_QUEUED
96
    self.result = None
97
    self.log = []
98
    self.start_timestamp = None
99
    self.end_timestamp = None
100

    
101
  @classmethod
102
  def Restore(cls, state):
103
    """Restore the _QueuedOpCode from the serialized form.
104

105
    @type state: dict
106
    @param state: the serialized state
107
    @rtype: _QueuedOpCode
108
    @return: a new _QueuedOpCode instance
109

110
    """
111
    obj = _QueuedOpCode.__new__(cls)
112
    obj.input = opcodes.OpCode.LoadOpCode(state["input"])
113
    obj.status = state["status"]
114
    obj.result = state["result"]
115
    obj.log = state["log"]
116
    obj.start_timestamp = state.get("start_timestamp", None)
117
    obj.end_timestamp = state.get("end_timestamp", None)
118
    return obj
119

    
120
  def Serialize(self):
121
    """Serializes this _QueuedOpCode.
122

123
    @rtype: dict
124
    @return: the dictionary holding the serialized state
125

126
    """
127
    return {
128
      "input": self.input.__getstate__(),
129
      "status": self.status,
130
      "result": self.result,
131
      "log": self.log,
132
      "start_timestamp": self.start_timestamp,
133
      "end_timestamp": self.end_timestamp,
134
      }
135

    
136

    
137
class _QueuedJob(object):
138
  """In-memory job representation.
139

140
  This is what we use to track the user-submitted jobs. Locking must
141
  be taken care of by users of this class.
142

143
  @type queue: L{JobQueue}
144
  @ivar queue: the parent queue
145
  @ivar id: the job ID
146
  @type ops: list
147
  @ivar ops: the list of _QueuedOpCode that constitute the job
148
  @type run_op_index: int
149
  @ivar run_op_index: the currently executing opcode, or -1 if
150
      we didn't yet start executing
151
  @type log_serial: int
152
  @ivar log_serial: holds the index for the next log entry
153
  @ivar received_timestamp: the timestamp for when the job was received
154
  @ivar start_timestmap: the timestamp for start of execution
155
  @ivar end_timestamp: the timestamp for end of execution
156
  @ivar change: a Condition variable we use for waiting for job changes
157

158
  """
159
  __slots__ = ["queue", "id", "ops", "run_op_index", "log_serial",
160
               "received_timestamp", "start_timestamp", "end_timestamp",
161
               "change",
162
               "__weakref__"]
163

    
164
  def __init__(self, queue, job_id, ops):
165
    """Constructor for the _QueuedJob.
166

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

175
    """
176
    if not ops:
177
      # TODO: use a better exception
178
      raise Exception("No opcodes")
179

    
180
    self.queue = queue
181
    self.id = job_id
182
    self.ops = [_QueuedOpCode(op) for op in ops]
183
    self.run_op_index = -1
184
    self.log_serial = 0
185
    self.received_timestamp = TimeStampNow()
186
    self.start_timestamp = None
187
    self.end_timestamp = None
188

    
189
    # Condition to wait for changes
190
    self.change = threading.Condition(self.queue._lock)
191

    
192
  @classmethod
193
  def Restore(cls, queue, state):
194
    """Restore a _QueuedJob from serialized state:
195

196
    @type queue: L{JobQueue}
197
    @param queue: to which queue the restored job belongs
198
    @type state: dict
199
    @param state: the serialized state
200
    @rtype: _JobQueue
201
    @return: the restored _JobQueue instance
202

203
    """
204
    obj = _QueuedJob.__new__(cls)
205
    obj.queue = queue
206
    obj.id = state["id"]
207
    obj.run_op_index = state["run_op_index"]
208
    obj.received_timestamp = state.get("received_timestamp", None)
209
    obj.start_timestamp = state.get("start_timestamp", None)
210
    obj.end_timestamp = state.get("end_timestamp", None)
211

    
212
    obj.ops = []
213
    obj.log_serial = 0
214
    for op_state in state["ops"]:
215
      op = _QueuedOpCode.Restore(op_state)
216
      for log_entry in op.log:
217
        obj.log_serial = max(obj.log_serial, log_entry[0])
218
      obj.ops.append(op)
219

    
220
    # Condition to wait for changes
221
    obj.change = threading.Condition(obj.queue._lock)
222

    
223
    return obj
224

    
225
  def Serialize(self):
226
    """Serialize the _JobQueue instance.
227

228
    @rtype: dict
229
    @return: the serialized state
230

231
    """
232
    return {
233
      "id": self.id,
234
      "ops": [op.Serialize() for op in self.ops],
235
      "run_op_index": self.run_op_index,
236
      "start_timestamp": self.start_timestamp,
237
      "end_timestamp": self.end_timestamp,
238
      "received_timestamp": self.received_timestamp,
239
      }
240

    
241
  def CalcStatus(self):
242
    """Compute the status of this job.
243

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

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

255
        will determine the job status
256

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

260
    @return: the job status
261

262
    """
263
    status = constants.JOB_STATUS_QUEUED
264

    
265
    all_success = True
266
    for op in self.ops:
267
      if op.status == constants.OP_STATUS_SUCCESS:
268
        continue
269

    
270
      all_success = False
271

    
272
      if op.status == constants.OP_STATUS_QUEUED:
273
        pass
274
      elif op.status == constants.OP_STATUS_WAITLOCK:
275
        status = constants.JOB_STATUS_WAITLOCK
276
      elif op.status == constants.OP_STATUS_RUNNING:
277
        status = constants.JOB_STATUS_RUNNING
278
      elif op.status == constants.OP_STATUS_CANCELING:
279
        status = constants.JOB_STATUS_CANCELING
280
        break
281
      elif op.status == constants.OP_STATUS_ERROR:
282
        status = constants.JOB_STATUS_ERROR
283
        # The whole job fails if one opcode failed
284
        break
285
      elif op.status == constants.OP_STATUS_CANCELED:
286
        status = constants.OP_STATUS_CANCELED
287
        break
288

    
289
    if all_success:
290
      status = constants.JOB_STATUS_SUCCESS
291

    
292
    return status
293

    
294
  def GetLogEntries(self, newer_than):
295
    """Selectively returns the log entries.
296

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

304
    """
305
    if newer_than is None:
306
      serial = -1
307
    else:
308
      serial = newer_than
309

    
310
    entries = []
311
    for op in self.ops:
312
      entries.extend(filter(lambda entry: entry[0] > serial, op.log))
313

    
314
    return entries
315

    
316
  def MarkUnfinishedOps(self, status, result):
317
    """Mark unfinished opcodes with a given status and result.
318

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

323
    @param status: a given opcode status
324
    @param result: the opcode result
325

326
    """
327
    not_marked = True
328
    for op in self.ops:
329
      if op.status in constants.OPS_FINALIZED:
330
        assert not_marked, "Finalized opcodes found after non-finalized ones"
331
        continue
332
      op.status = status
333
      op.result = result
334
      not_marked = False
335

    
336

    
337
class _JobQueueWorker(workerpool.BaseWorker):
338
  """The actual job workers.
339

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

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

349
    """
350
    assert self.queue, "Queue attribute is missing"
351
    assert self.opcode, "Opcode attribute is missing"
352

    
353
    self.queue.acquire()
354
    try:
355
      assert self.opcode.status in (constants.OP_STATUS_WAITLOCK,
356
                                    constants.OP_STATUS_CANCELING)
357

    
358
      # Cancel here if we were asked to
359
      if self.opcode.status == constants.OP_STATUS_CANCELING:
360
        raise CancelJob()
361

    
362
      self.opcode.status = constants.OP_STATUS_RUNNING
363
    finally:
364
      self.queue.release()
365

    
366
  def RunTask(self, job):
367
    """Job executor.
368

369
    This functions processes a job. It is closely tied to the _QueuedJob and
370
    _QueuedOpCode classes.
371

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

375
    """
376
    logging.info("Worker %s processing job %s",
377
                  self.worker_id, job.id)
378
    proc = mcpu.Processor(self.pool.queue.context)
379
    self.queue = queue = job.queue
380
    try:
381
      try:
382
        count = len(job.ops)
383
        for idx, op in enumerate(job.ops):
384
          op_summary = op.input.Summary()
385
          if op.status == constants.OP_STATUS_SUCCESS:
386
            # this is a job that was partially completed before master
387
            # daemon shutdown, so it can be expected that some opcodes
388
            # are already completed successfully (if any did error
389
            # out, then the whole job should have been aborted and not
390
            # resubmitted for processing)
391
            logging.info("Op %s/%s: opcode %s already processed, skipping",
392
                         idx + 1, count, op_summary)
393
            continue
394
          try:
395
            logging.info("Op %s/%s: Starting opcode %s", idx + 1, count,
396
                         op_summary)
397

    
398
            queue.acquire()
399
            try:
400
              if op.status == constants.OP_STATUS_CANCELED:
401
                raise CancelJob()
402
              assert op.status == constants.OP_STATUS_QUEUED
403
              job.run_op_index = idx
404
              op.status = constants.OP_STATUS_WAITLOCK
405
              op.result = None
406
              op.start_timestamp = TimeStampNow()
407
              if idx == 0: # first opcode
408
                job.start_timestamp = op.start_timestamp
409
              queue.UpdateJobUnlocked(job)
410

    
411
              input_opcode = op.input
412
            finally:
413
              queue.release()
414

    
415
            def _Log(*args):
416
              """Append a log entry.
417

418
              """
419
              assert len(args) < 3
420

    
421
              if len(args) == 1:
422
                log_type = constants.ELOG_MESSAGE
423
                log_msg = args[0]
424
              else:
425
                log_type, log_msg = args
426

    
427
              # The time is split to make serialization easier and not lose
428
              # precision.
429
              timestamp = utils.SplitTime(time.time())
430

    
431
              queue.acquire()
432
              try:
433
                job.log_serial += 1
434
                op.log.append((job.log_serial, timestamp, log_type, log_msg))
435

    
436
                job.change.notifyAll()
437
              finally:
438
                queue.release()
439

    
440
            # Make sure not to hold lock while _Log is called
441
            self.opcode = op
442
            result = proc.ExecOpCode(input_opcode, _Log, self._NotifyStart)
443

    
444
            queue.acquire()
445
            try:
446
              op.status = constants.OP_STATUS_SUCCESS
447
              op.result = result
448
              op.end_timestamp = TimeStampNow()
449
              queue.UpdateJobUnlocked(job)
450
            finally:
451
              queue.release()
452

    
453
            logging.info("Op %s/%s: Successfully finished opcode %s",
454
                         idx + 1, count, op_summary)
455
          except CancelJob:
456
            # Will be handled further up
457
            raise
458
          except Exception, err:
459
            queue.acquire()
460
            try:
461
              try:
462
                op.status = constants.OP_STATUS_ERROR
463
                if isinstance(err, errors.GenericError):
464
                  op.result = errors.EncodeException(err)
465
                else:
466
                  op.result = str(err)
467
                op.end_timestamp = TimeStampNow()
468
                logging.info("Op %s/%s: Error in opcode %s: %s",
469
                             idx + 1, count, op_summary, err)
470
              finally:
471
                queue.UpdateJobUnlocked(job)
472
            finally:
473
              queue.release()
474
            raise
475

    
476
      except CancelJob:
477
        queue.acquire()
478
        try:
479
          queue.CancelJobUnlocked(job)
480
        finally:
481
          queue.release()
482
      except errors.GenericError, err:
483
        logging.exception("Ganeti exception")
484
      except:
485
        logging.exception("Unhandled exception")
486
    finally:
487
      queue.acquire()
488
      try:
489
        try:
490
          job.run_op_index = -1
491
          job.end_timestamp = TimeStampNow()
492
          queue.UpdateJobUnlocked(job)
493
        finally:
494
          job_id = job.id
495
          status = job.CalcStatus()
496
      finally:
497
        queue.release()
498
      logging.info("Worker %s finished job %s, status = %s",
499
                   self.worker_id, job_id, status)
500

    
501

    
502
class _JobQueueWorkerPool(workerpool.WorkerPool):
503
  """Simple class implementing a job-processing workerpool.
504

505
  """
506
  def __init__(self, queue):
507
    super(_JobQueueWorkerPool, self).__init__(JOBQUEUE_THREADS,
508
                                              _JobQueueWorker)
509
    self.queue = queue
510

    
511

    
512
class JobQueue(object):
513
  """Queue used to manage the jobs.
514

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

517
  """
518
  _RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
519

    
520
  def _RequireOpenQueue(fn):
521
    """Decorator for "public" functions.
522

523
    This function should be used for all 'public' functions. That is,
524
    functions usually called from other classes.
525

526
    @warning: Use this decorator only after utils.LockedMethod!
527

528
    Example::
529
      @utils.LockedMethod
530
      @_RequireOpenQueue
531
      def Example(self):
532
        pass
533

534
    """
535
    def wrapper(self, *args, **kwargs):
536
      assert self._queue_lock is not None, "Queue should be open"
537
      return fn(self, *args, **kwargs)
538
    return wrapper
539

    
540
  def __init__(self, context):
541
    """Constructor for JobQueue.
542

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

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

552
    """
553
    self.context = context
554
    self._memcache = weakref.WeakValueDictionary()
555
    self._my_hostname = utils.HostInfo().name
556

    
557
    # Locking
558
    self._lock = threading.Lock()
559
    self.acquire = self._lock.acquire
560
    self.release = self._lock.release
561

    
562
    # Initialize
563
    self._queue_lock = jstore.InitAndVerifyQueue(must_lock=True)
564

    
565
    # Read serial file
566
    self._last_serial = jstore.ReadSerial()
567
    assert self._last_serial is not None, ("Serial file was modified between"
568
                                           " check in jstore and here")
569

    
570
    # Get initial list of nodes
571
    self._nodes = dict((n.name, n.primary_ip)
572
                       for n in self.context.cfg.GetAllNodesInfo().values()
573
                       if n.master_candidate)
574

    
575
    # Remove master node
576
    try:
577
      del self._nodes[self._my_hostname]
578
    except KeyError:
579
      pass
580

    
581
    # TODO: Check consistency across nodes
582

    
583
    # Setup worker pool
584
    self._wpool = _JobQueueWorkerPool(self)
585
    try:
586
      # We need to lock here because WorkerPool.AddTask() may start a job while
587
      # we're still doing our work.
588
      self.acquire()
589
      try:
590
        logging.info("Inspecting job queue")
591

    
592
        all_job_ids = self._GetJobIDsUnlocked()
593
        jobs_count = len(all_job_ids)
594
        lastinfo = time.time()
595
        for idx, job_id in enumerate(all_job_ids):
596
          # Give an update every 1000 jobs or 10 seconds
597
          if (idx % 1000 == 0 or time.time() >= (lastinfo + 10.0) or
598
              idx == (jobs_count - 1)):
599
            logging.info("Job queue inspection: %d/%d (%0.1f %%)",
600
                         idx, jobs_count - 1, 100.0 * (idx + 1) / jobs_count)
601
            lastinfo = time.time()
602

    
603
          job = self._LoadJobUnlocked(job_id)
604

    
605
          # a failure in loading the job can cause 'None' to be returned
606
          if job is None:
607
            continue
608

    
609
          status = job.CalcStatus()
610

    
611
          if status in (constants.JOB_STATUS_QUEUED, ):
612
            self._wpool.AddTask(job)
613

    
614
          elif status in (constants.JOB_STATUS_RUNNING,
615
                          constants.JOB_STATUS_WAITLOCK,
616
                          constants.JOB_STATUS_CANCELING):
617
            logging.warning("Unfinished job %s found: %s", job.id, job)
618
            try:
619
              job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
620
                                    "Unclean master daemon shutdown")
621
            finally:
622
              self.UpdateJobUnlocked(job)
623

    
624
        logging.info("Job queue inspection finished")
625
      finally:
626
        self.release()
627
    except:
628
      self._wpool.TerminateWorkers()
629
      raise
630

    
631
  @utils.LockedMethod
632
  @_RequireOpenQueue
633
  def AddNode(self, node):
634
    """Register a new node with the queue.
635

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

639
    """
640
    node_name = node.name
641
    assert node_name != self._my_hostname
642

    
643
    # Clean queue directory on added node
644
    result = rpc.RpcRunner.call_jobqueue_purge(node_name)
645
    msg = result.RemoteFailMsg()
646
    if msg:
647
      logging.warning("Cannot cleanup queue directory on node %s: %s",
648
                      node_name, msg)
649

    
650
    if not node.master_candidate:
651
      # remove if existing, ignoring errors
652
      self._nodes.pop(node_name, None)
653
      # and skip the replication of the job ids
654
      return
655

    
656
    # Upload the whole queue excluding archived jobs
657
    files = [self._GetJobPath(job_id) for job_id in self._GetJobIDsUnlocked()]
658

    
659
    # Upload current serial file
660
    files.append(constants.JOB_QUEUE_SERIAL_FILE)
661

    
662
    for file_name in files:
663
      # Read file content
664
      content = utils.ReadFile(file_name)
665

    
666
      result = rpc.RpcRunner.call_jobqueue_update([node_name],
667
                                                  [node.primary_ip],
668
                                                  file_name, content)
669
      msg = result[node_name].RemoteFailMsg()
670
      if msg:
671
        logging.error("Failed to upload file %s to node %s: %s",
672
                      file_name, node_name, msg)
673

    
674
    self._nodes[node_name] = node.primary_ip
675

    
676
  @utils.LockedMethod
677
  @_RequireOpenQueue
678
  def RemoveNode(self, node_name):
679
    """Callback called when removing nodes from the cluster.
680

681
    @type node_name: str
682
    @param node_name: the name of the node to remove
683

684
    """
685
    try:
686
      # The queue is removed by the "leave node" RPC call.
687
      del self._nodes[node_name]
688
    except KeyError:
689
      pass
690

    
691
  def _CheckRpcResult(self, result, nodes, failmsg):
692
    """Verifies the status of an RPC call.
693

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

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

704
    """
705
    failed = []
706
    success = []
707

    
708
    for node in nodes:
709
      msg = result[node].RemoteFailMsg()
710
      if msg:
711
        failed.append(node)
712
        logging.error("RPC call %s failed on node %s: %s",
713
                      result[node].call, node, msg)
714
      else:
715
        success.append(node)
716

    
717
    # +1 for the master node
718
    if (len(success) + 1) < len(failed):
719
      # TODO: Handle failing nodes
720
      logging.error("More than half of the nodes failed")
721

    
722
  def _GetNodeIp(self):
723
    """Helper for returning the node name/ip list.
724

725
    @rtype: (list, list)
726
    @return: a tuple of two lists, the first one with the node
727
        names and the second one with the node addresses
728

729
    """
730
    name_list = self._nodes.keys()
731
    addr_list = [self._nodes[name] for name in name_list]
732
    return name_list, addr_list
733

    
734
  def _WriteAndReplicateFileUnlocked(self, file_name, data):
735
    """Writes a file locally and then replicates it to all nodes.
736

737
    This function will replace the contents of a file on the local
738
    node and then replicate it to all the other nodes we have.
739

740
    @type file_name: str
741
    @param file_name: the path of the file to be replicated
742
    @type data: str
743
    @param data: the new contents of the file
744

745
    """
746
    utils.WriteFile(file_name, data=data)
747

    
748
    names, addrs = self._GetNodeIp()
749
    result = rpc.RpcRunner.call_jobqueue_update(names, addrs, file_name, data)
750
    self._CheckRpcResult(result, self._nodes,
751
                         "Updating %s" % file_name)
752

    
753
  def _RenameFilesUnlocked(self, rename):
754
    """Renames a file locally and then replicate the change.
755

756
    This function will rename a file in the local queue directory
757
    and then replicate this rename to all the other nodes we have.
758

759
    @type rename: list of (old, new)
760
    @param rename: List containing tuples mapping old to new names
761

762
    """
763
    # Rename them locally
764
    for old, new in rename:
765
      utils.RenameFile(old, new, mkdir=True)
766

    
767
    # ... and on all nodes
768
    names, addrs = self._GetNodeIp()
769
    result = rpc.RpcRunner.call_jobqueue_rename(names, addrs, rename)
770
    self._CheckRpcResult(result, self._nodes, "Renaming files (%r)" % rename)
771

    
772
  def _FormatJobID(self, job_id):
773
    """Convert a job ID to string format.
774

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

779
    @type job_id: int or long
780
    @param job_id: the numeric job id
781
    @rtype: str
782
    @return: the formatted job id
783

784
    """
785
    if not isinstance(job_id, (int, long)):
786
      raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id)
787
    if job_id < 0:
788
      raise errors.ProgrammerError("Job ID %s is negative" % job_id)
789

    
790
    return str(job_id)
791

    
792
  @classmethod
793
  def _GetArchiveDirectory(cls, job_id):
794
    """Returns the archive directory for a job.
795

796
    @type job_id: str
797
    @param job_id: Job identifier
798
    @rtype: str
799
    @return: Directory name
800

801
    """
802
    return str(int(job_id) / JOBS_PER_ARCHIVE_DIRECTORY)
803

    
804
  def _NewSerialUnlocked(self):
805
    """Generates a new job identifier.
806

807
    Job identifiers are unique during the lifetime of a cluster.
808

809
    @rtype: str
810
    @return: a string representing the job identifier.
811

812
    """
813
    # New number
814
    serial = self._last_serial + 1
815

    
816
    # Write to file
817
    self._WriteAndReplicateFileUnlocked(constants.JOB_QUEUE_SERIAL_FILE,
818
                                        "%s\n" % serial)
819

    
820
    # Keep it only if we were able to write the file
821
    self._last_serial = serial
822

    
823
    return self._FormatJobID(serial)
824

    
825
  @staticmethod
826
  def _GetJobPath(job_id):
827
    """Returns the job file for a given job id.
828

829
    @type job_id: str
830
    @param job_id: the job identifier
831
    @rtype: str
832
    @return: the path to the job file
833

834
    """
835
    return os.path.join(constants.QUEUE_DIR, "job-%s" % job_id)
836

    
837
  @classmethod
838
  def _GetArchivedJobPath(cls, job_id):
839
    """Returns the archived job file for a give job id.
840

841
    @type job_id: str
842
    @param job_id: the job identifier
843
    @rtype: str
844
    @return: the path to the archived job file
845

846
    """
847
    path = "%s/job-%s" % (cls._GetArchiveDirectory(job_id), job_id)
848
    return os.path.join(constants.JOB_QUEUE_ARCHIVE_DIR, path)
849

    
850
  @classmethod
851
  def _ExtractJobID(cls, name):
852
    """Extract the job id from a filename.
853

854
    @type name: str
855
    @param name: the job filename
856
    @rtype: job id or None
857
    @return: the job id corresponding to the given filename,
858
        or None if the filename does not represent a valid
859
        job file
860

861
    """
862
    m = cls._RE_JOB_FILE.match(name)
863
    if m:
864
      return m.group(1)
865
    else:
866
      return None
867

    
868
  def _GetJobIDsUnlocked(self, archived=False):
869
    """Return all known job IDs.
870

871
    If the parameter archived is True, archived jobs IDs will be
872
    included. Currently this argument is unused.
873

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

878
    @rtype: list
879
    @return: the list of job IDs
880

881
    """
882
    jlist = [self._ExtractJobID(name) for name in self._ListJobFiles()]
883
    jlist = utils.NiceSort(jlist)
884
    return jlist
885

    
886
  def _ListJobFiles(self):
887
    """Returns the list of current job files.
888

889
    @rtype: list
890
    @return: the list of job file names
891

892
    """
893
    return [name for name in utils.ListVisibleFiles(constants.QUEUE_DIR)
894
            if self._RE_JOB_FILE.match(name)]
895

    
896
  def _LoadJobUnlocked(self, job_id):
897
    """Loads a job from the disk or memory.
898

899
    Given a job id, this will return the cached job object if
900
    existing, or try to load the job from the disk. If loading from
901
    disk, it will also add the job to the cache.
902

903
    @param job_id: the job id
904
    @rtype: L{_QueuedJob} or None
905
    @return: either None or the job object
906

907
    """
908
    job = self._memcache.get(job_id, None)
909
    if job:
910
      logging.debug("Found job %s in memcache", job_id)
911
      return job
912

    
913
    filepath = self._GetJobPath(job_id)
914
    logging.debug("Loading job from %s", filepath)
915
    try:
916
      raw_data = utils.ReadFile(filepath)
917
    except IOError, err:
918
      if err.errno in (errno.ENOENT, ):
919
        return None
920
      raise
921

    
922
    data = serializer.LoadJson(raw_data)
923

    
924
    try:
925
      job = _QueuedJob.Restore(self, data)
926
    except Exception, err:
927
      new_path = self._GetArchivedJobPath(job_id)
928
      if filepath == new_path:
929
        # job already archived (future case)
930
        logging.exception("Can't parse job %s", job_id)
931
      else:
932
        # non-archived case
933
        logging.exception("Can't parse job %s, will archive.", job_id)
934
        self._RenameFilesUnlocked([(filepath, new_path)])
935
      return None
936

    
937
    self._memcache[job_id] = job
938
    logging.debug("Added job %s to the cache", job_id)
939
    return job
940

    
941
  def _GetJobsUnlocked(self, job_ids):
942
    """Return a list of jobs based on their IDs.
943

944
    @type job_ids: list
945
    @param job_ids: either an empty list (meaning all jobs),
946
        or a list of job IDs
947
    @rtype: list
948
    @return: the list of job objects
949

950
    """
951
    if not job_ids:
952
      job_ids = self._GetJobIDsUnlocked()
953

    
954
    return [self._LoadJobUnlocked(job_id) for job_id in job_ids]
955

    
956
  @staticmethod
957
  def _IsQueueMarkedDrain():
958
    """Check if the queue is marked from drain.
959

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

963
    @rtype: boolean
964
    @return: True of the job queue is marked for draining
965

966
    """
967
    return os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
968

    
969
  @staticmethod
970
  def SetDrainFlag(drain_flag):
971
    """Sets the drain flag for the queue.
972

973
    This is similar to the function L{backend.JobQueueSetDrainFlag},
974
    and in the future we might merge them.
975

976
    @type drain_flag: boolean
977
    @param drain_flag: Whether to set or unset the drain flag
978

979
    """
980
    if drain_flag:
981
      utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
982
    else:
983
      utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
984
    return True
985

    
986
  @_RequireOpenQueue
987
  def _SubmitJobUnlocked(self, ops):
988
    """Create and store a new job.
989

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

993
    @type ops: list
994
    @param ops: The list of OpCodes that will become the new job.
995
    @rtype: job ID
996
    @return: the job ID of the newly created job
997
    @raise errors.JobQueueDrainError: if the job is marked for draining
998

999
    """
1000
    if self._IsQueueMarkedDrain():
1001
      raise errors.JobQueueDrainError("Job queue is drained, refusing job")
1002

    
1003
    # Check job queue size
1004
    size = len(self._ListJobFiles())
1005
    if size >= constants.JOB_QUEUE_SIZE_SOFT_LIMIT:
1006
      # TODO: Autoarchive jobs. Make sure it's not done on every job
1007
      # submission, though.
1008
      #size = ...
1009
      pass
1010

    
1011
    if size >= constants.JOB_QUEUE_SIZE_HARD_LIMIT:
1012
      raise errors.JobQueueFull()
1013

    
1014
    # Get job identifier
1015
    job_id = self._NewSerialUnlocked()
1016
    job = _QueuedJob(self, job_id, ops)
1017

    
1018
    # Write to disk
1019
    self.UpdateJobUnlocked(job)
1020

    
1021
    logging.debug("Adding new job %s to the cache", job_id)
1022
    self._memcache[job_id] = job
1023

    
1024
    # Add to worker pool
1025
    self._wpool.AddTask(job)
1026

    
1027
    return job.id
1028

    
1029
  @utils.LockedMethod
1030
  @_RequireOpenQueue
1031
  def SubmitJob(self, ops):
1032
    """Create and store a new job.
1033

1034
    @see: L{_SubmitJobUnlocked}
1035

1036
    """
1037
    return self._SubmitJobUnlocked(ops)
1038

    
1039
  @utils.LockedMethod
1040
  @_RequireOpenQueue
1041
  def SubmitManyJobs(self, jobs):
1042
    """Create and store multiple jobs.
1043

1044
    @see: L{_SubmitJobUnlocked}
1045

1046
    """
1047
    results = []
1048
    for ops in jobs:
1049
      try:
1050
        data = self._SubmitJobUnlocked(ops)
1051
        status = True
1052
      except errors.GenericError, err:
1053
        data = str(err)
1054
        status = False
1055
      results.append((status, data))
1056

    
1057
    return results
1058

    
1059

    
1060
  @_RequireOpenQueue
1061
  def UpdateJobUnlocked(self, job):
1062
    """Update a job's on disk storage.
1063

1064
    After a job has been modified, this function needs to be called in
1065
    order to write the changes to disk and replicate them to the other
1066
    nodes.
1067

1068
    @type job: L{_QueuedJob}
1069
    @param job: the changed job
1070

1071
    """
1072
    filename = self._GetJobPath(job.id)
1073
    data = serializer.DumpJson(job.Serialize(), indent=False)
1074
    logging.debug("Writing job %s to %s", job.id, filename)
1075
    self._WriteAndReplicateFileUnlocked(filename, data)
1076

    
1077
    # Notify waiters about potential changes
1078
    job.change.notifyAll()
1079

    
1080
  @utils.LockedMethod
1081
  @_RequireOpenQueue
1082
  def WaitForJobChanges(self, job_id, fields, prev_job_info, prev_log_serial,
1083
                        timeout):
1084
    """Waits for changes in a job.
1085

1086
    @type job_id: string
1087
    @param job_id: Job identifier
1088
    @type fields: list of strings
1089
    @param fields: Which fields to check for changes
1090
    @type prev_job_info: list or None
1091
    @param prev_job_info: Last job information returned
1092
    @type prev_log_serial: int
1093
    @param prev_log_serial: Last job message serial number
1094
    @type timeout: float
1095
    @param timeout: maximum time to wait
1096
    @rtype: tuple (job info, log entries)
1097
    @return: a tuple of the job information as required via
1098
        the fields parameter, and the log entries as a list
1099

1100
        if the job has not changed and the timeout has expired,
1101
        we instead return a special value,
1102
        L{constants.JOB_NOTCHANGED}, which should be interpreted
1103
        as such by the clients
1104

1105
    """
1106
    logging.debug("Waiting for changes in job %s", job_id)
1107

    
1108
    job_info = None
1109
    log_entries = None
1110

    
1111
    end_time = time.time() + timeout
1112
    while True:
1113
      delta_time = end_time - time.time()
1114
      if delta_time < 0:
1115
        return constants.JOB_NOTCHANGED
1116

    
1117
      job = self._LoadJobUnlocked(job_id)
1118
      if not job:
1119
        logging.debug("Job %s not found", job_id)
1120
        break
1121

    
1122
      status = job.CalcStatus()
1123
      job_info = self._GetJobInfoUnlocked(job, fields)
1124
      log_entries = job.GetLogEntries(prev_log_serial)
1125

    
1126
      # Serializing and deserializing data can cause type changes (e.g. from
1127
      # tuple to list) or precision loss. We're doing it here so that we get
1128
      # the same modifications as the data received from the client. Without
1129
      # this, the comparison afterwards might fail without the data being
1130
      # significantly different.
1131
      job_info = serializer.LoadJson(serializer.DumpJson(job_info))
1132
      log_entries = serializer.LoadJson(serializer.DumpJson(log_entries))
1133

    
1134
      if status not in (constants.JOB_STATUS_QUEUED,
1135
                        constants.JOB_STATUS_RUNNING,
1136
                        constants.JOB_STATUS_WAITLOCK):
1137
        # Don't even try to wait if the job is no longer running, there will be
1138
        # no changes.
1139
        break
1140

    
1141
      if (prev_job_info != job_info or
1142
          (log_entries and prev_log_serial != log_entries[0][0])):
1143
        break
1144

    
1145
      logging.debug("Waiting again")
1146

    
1147
      # Release the queue lock while waiting
1148
      job.change.wait(delta_time)
1149

    
1150
    logging.debug("Job %s changed", job_id)
1151

    
1152
    if job_info is None and log_entries is None:
1153
      return None
1154
    else:
1155
      return (job_info, log_entries)
1156

    
1157
  @utils.LockedMethod
1158
  @_RequireOpenQueue
1159
  def CancelJob(self, job_id):
1160
    """Cancels a job.
1161

1162
    This will only succeed if the job has not started yet.
1163

1164
    @type job_id: string
1165
    @param job_id: job ID of job to be cancelled.
1166

1167
    """
1168
    logging.info("Cancelling job %s", job_id)
1169

    
1170
    job = self._LoadJobUnlocked(job_id)
1171
    if not job:
1172
      logging.debug("Job %s not found", job_id)
1173
      return (False, "Job %s not found" % job_id)
1174

    
1175
    job_status = job.CalcStatus()
1176

    
1177
    if job_status not in (constants.JOB_STATUS_QUEUED,
1178
                          constants.JOB_STATUS_WAITLOCK):
1179
      logging.debug("Job %s is no longer waiting in the queue", job.id)
1180
      return (False, "Job %s is no longer waiting in the queue" % job.id)
1181

    
1182
    if job_status == constants.JOB_STATUS_QUEUED:
1183
      self.CancelJobUnlocked(job)
1184
      return (True, "Job %s canceled" % job.id)
1185

    
1186
    elif job_status == constants.JOB_STATUS_WAITLOCK:
1187
      # The worker will notice the new status and cancel the job
1188
      try:
1189
        job.MarkUnfinishedOps(constants.OP_STATUS_CANCELING, None)
1190
      finally:
1191
        self.UpdateJobUnlocked(job)
1192
      return (True, "Job %s will be canceled" % job.id)
1193

    
1194
  @_RequireOpenQueue
1195
  def CancelJobUnlocked(self, job):
1196
    """Marks a job as canceled.
1197

1198
    """
1199
    try:
1200
      job.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
1201
                            "Job canceled by request")
1202
    finally:
1203
      self.UpdateJobUnlocked(job)
1204

    
1205
  @_RequireOpenQueue
1206
  def _ArchiveJobsUnlocked(self, jobs):
1207
    """Archives jobs.
1208

1209
    @type jobs: list of L{_QueuedJob}
1210
    @param jobs: Job objects
1211
    @rtype: int
1212
    @return: Number of archived jobs
1213

1214
    """
1215
    archive_jobs = []
1216
    rename_files = []
1217
    for job in jobs:
1218
      if job.CalcStatus() not in (constants.JOB_STATUS_CANCELED,
1219
                                  constants.JOB_STATUS_SUCCESS,
1220
                                  constants.JOB_STATUS_ERROR):
1221
        logging.debug("Job %s is not yet done", job.id)
1222
        continue
1223

    
1224
      archive_jobs.append(job)
1225

    
1226
      old = self._GetJobPath(job.id)
1227
      new = self._GetArchivedJobPath(job.id)
1228
      rename_files.append((old, new))
1229

    
1230
    # TODO: What if 1..n files fail to rename?
1231
    self._RenameFilesUnlocked(rename_files)
1232

    
1233
    logging.debug("Successfully archived job(s) %s",
1234
                  ", ".join(job.id for job in archive_jobs))
1235

    
1236
    return len(archive_jobs)
1237

    
1238
  @utils.LockedMethod
1239
  @_RequireOpenQueue
1240
  def ArchiveJob(self, job_id):
1241
    """Archives a job.
1242

1243
    This is just a wrapper over L{_ArchiveJobsUnlocked}.
1244

1245
    @type job_id: string
1246
    @param job_id: Job ID of job to be archived.
1247
    @rtype: bool
1248
    @return: Whether job was archived
1249

1250
    """
1251
    logging.info("Archiving job %s", job_id)
1252

    
1253
    job = self._LoadJobUnlocked(job_id)
1254
    if not job:
1255
      logging.debug("Job %s not found", job_id)
1256
      return False
1257

    
1258
    return self._ArchiveJobsUnlocked([job]) == 1
1259

    
1260
  @utils.LockedMethod
1261
  @_RequireOpenQueue
1262
  def AutoArchiveJobs(self, age, timeout):
1263
    """Archives all jobs based on age.
1264

1265
    The method will archive all jobs which are older than the age
1266
    parameter. For jobs that don't have an end timestamp, the start
1267
    timestamp will be considered. The special '-1' age will cause
1268
    archival of all jobs (that are not running or queued).
1269

1270
    @type age: int
1271
    @param age: the minimum age in seconds
1272

1273
    """
1274
    logging.info("Archiving jobs with age more than %s seconds", age)
1275

    
1276
    now = time.time()
1277
    end_time = now + timeout
1278
    archived_count = 0
1279
    last_touched = 0
1280

    
1281
    all_job_ids = self._GetJobIDsUnlocked(archived=False)
1282
    pending = []
1283
    for idx, job_id in enumerate(all_job_ids):
1284
      last_touched = idx
1285

    
1286
      # Not optimal because jobs could be pending
1287
      # TODO: Measure average duration for job archival and take number of
1288
      # pending jobs into account.
1289
      if time.time() > end_time:
1290
        break
1291

    
1292
      # Returns None if the job failed to load
1293
      job = self._LoadJobUnlocked(job_id)
1294
      if job:
1295
        if job.end_timestamp is None:
1296
          if job.start_timestamp is None:
1297
            job_age = job.received_timestamp
1298
          else:
1299
            job_age = job.start_timestamp
1300
        else:
1301
          job_age = job.end_timestamp
1302

    
1303
        if age == -1 or now - job_age[0] > age:
1304
          pending.append(job)
1305

    
1306
          # Archive 10 jobs at a time
1307
          if len(pending) >= 10:
1308
            archived_count += self._ArchiveJobsUnlocked(pending)
1309
            pending = []
1310

    
1311
    if pending:
1312
      archived_count += self._ArchiveJobsUnlocked(pending)
1313

    
1314
    return (archived_count, len(all_job_ids) - last_touched - 1)
1315

    
1316
  def _GetJobInfoUnlocked(self, job, fields):
1317
    """Returns information about a job.
1318

1319
    @type job: L{_QueuedJob}
1320
    @param job: the job which we query
1321
    @type fields: list
1322
    @param fields: names of fields to return
1323
    @rtype: list
1324
    @return: list with one element for each field
1325
    @raise errors.OpExecError: when an invalid field
1326
        has been passed
1327

1328
    """
1329
    row = []
1330
    for fname in fields:
1331
      if fname == "id":
1332
        row.append(job.id)
1333
      elif fname == "status":
1334
        row.append(job.CalcStatus())
1335
      elif fname == "ops":
1336
        row.append([op.input.__getstate__() for op in job.ops])
1337
      elif fname == "opresult":
1338
        row.append([op.result for op in job.ops])
1339
      elif fname == "opstatus":
1340
        row.append([op.status for op in job.ops])
1341
      elif fname == "oplog":
1342
        row.append([op.log for op in job.ops])
1343
      elif fname == "opstart":
1344
        row.append([op.start_timestamp for op in job.ops])
1345
      elif fname == "opend":
1346
        row.append([op.end_timestamp for op in job.ops])
1347
      elif fname == "received_ts":
1348
        row.append(job.received_timestamp)
1349
      elif fname == "start_ts":
1350
        row.append(job.start_timestamp)
1351
      elif fname == "end_ts":
1352
        row.append(job.end_timestamp)
1353
      elif fname == "summary":
1354
        row.append([op.input.Summary() for op in job.ops])
1355
      else:
1356
        raise errors.OpExecError("Invalid job query field '%s'" % fname)
1357
    return row
1358

    
1359
  @utils.LockedMethod
1360
  @_RequireOpenQueue
1361
  def QueryJobs(self, job_ids, fields):
1362
    """Returns a list of jobs in queue.
1363

1364
    This is a wrapper of L{_GetJobsUnlocked}, which actually does the
1365
    processing for each job.
1366

1367
    @type job_ids: list
1368
    @param job_ids: sequence of job identifiers or None for all
1369
    @type fields: list
1370
    @param fields: names of fields to return
1371
    @rtype: list
1372
    @return: list one element per job, each element being list with
1373
        the requested fields
1374

1375
    """
1376
    jobs = []
1377

    
1378
    for job in self._GetJobsUnlocked(job_ids):
1379
      if job is None:
1380
        jobs.append(None)
1381
      else:
1382
        jobs.append(self._GetJobInfoUnlocked(job, fields))
1383

    
1384
    return jobs
1385

    
1386
  @utils.LockedMethod
1387
  @_RequireOpenQueue
1388
  def Shutdown(self):
1389
    """Stops the job queue.
1390

1391
    This shutdowns all the worker threads an closes the queue.
1392

1393
    """
1394
    self._wpool.TerminateWorkers()
1395

    
1396
    self._queue_lock.Close()
1397
    self._queue_lock = None