jqueue.py 17.4 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
#

# Copyright (C) 2006, 2007 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Module implementing the job queue handling."""

24
import os
Michael Hanselmann's avatar
Michael Hanselmann committed
25 26
import logging
import threading
27 28
import errno
import re
29
import time
Iustin Pop's avatar
Iustin Pop committed
30

Michael Hanselmann's avatar
Michael Hanselmann committed
31
from ganeti import constants
32
from ganeti import serializer
Michael Hanselmann's avatar
Michael Hanselmann committed
33
from ganeti import workerpool
34
from ganeti import opcodes
Iustin Pop's avatar
Iustin Pop committed
35
from ganeti import errors
Michael Hanselmann's avatar
Michael Hanselmann committed
36
from ganeti import mcpu
37
from ganeti import utils
38
from ganeti import jstore
39
from ganeti import rpc
Michael Hanselmann's avatar
Michael Hanselmann committed
40 41 42 43


JOBQUEUE_THREADS = 5

Iustin Pop's avatar
Iustin Pop committed
44

Michael Hanselmann's avatar
Michael Hanselmann committed
45 46 47
class _QueuedOpCode(object):
  """Encasulates an opcode object.

48
  Access is synchronized by the '_lock' attribute.
Michael Hanselmann's avatar
Michael Hanselmann committed
49

50 51 52
  The 'log' attribute holds the execution log and consists of tuples
  of the form (timestamp, level, message).

Michael Hanselmann's avatar
Michael Hanselmann committed
53
  """
Michael Hanselmann's avatar
Michael Hanselmann committed
54 55 56 57 58
  def __new__(cls, *args, **kwargs):
    obj = object.__new__(cls, *args, **kwargs)
    # Create a special lock for logging
    obj._log_lock = threading.Lock()
    return obj
59

Michael Hanselmann's avatar
Michael Hanselmann committed
60 61 62 63 64
  def __init__(self, op):
    self.input = op
    self.status = constants.OP_STATUS_QUEUED
    self.result = None
    self.log = []
65 66 67

  @classmethod
  def Restore(cls, state):
Michael Hanselmann's avatar
Michael Hanselmann committed
68 69 70 71 72
    obj = _QueuedOpCode.__new__(cls)
    obj.input = opcodes.OpCode.LoadOpCode(state["input"])
    obj.status = state["status"]
    obj.result = state["result"]
    obj.log = state["log"]
73 74 75
    return obj

  def Serialize(self):
Michael Hanselmann's avatar
Michael Hanselmann committed
76 77 78 79 80 81 82 83 84 85
    self._log_lock.acquire()
    try:
      return {
        "input": self.input.__getstate__(),
        "status": self.status,
        "result": self.result,
        "log": self.log,
        }
    finally:
      self._log_lock.release()
Michael Hanselmann's avatar
Michael Hanselmann committed
86

87 88 89 90
  def Log(self, *args):
    """Append a log entry.

    """
Michael Hanselmann's avatar
Michael Hanselmann committed
91
    assert len(args) < 3
92 93 94 95 96 97 98

    if len(args) == 1:
      log_type = constants.ELOG_MESSAGE
      log_msg = args[0]
    else:
      log_type, log_msg = args

Michael Hanselmann's avatar
Michael Hanselmann committed
99 100
    self._log_lock.acquire()
    try:
101 102 103
      # The time is split to make serialization easier and not lose more
      # precision.
      self.log.append((utils.SplitTime(time.time()), log_type, log_msg))
Michael Hanselmann's avatar
Michael Hanselmann committed
104 105 106
    finally:
      self._log_lock.release()

107 108 109 110
  def RetrieveLog(self, start_at=0):
    """Retrieve (a part of) the execution log.

    """
Michael Hanselmann's avatar
Michael Hanselmann committed
111 112 113 114 115
    self._log_lock.acquire()
    try:
      return self.log[start_at:]
    finally:
      self._log_lock.release()
116

Michael Hanselmann's avatar
Michael Hanselmann committed
117 118 119 120 121 122 123

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

  This is what we use to track the user-submitted jobs.

  """
Michael Hanselmann's avatar
Michael Hanselmann committed
124
  def __init__(self, queue, job_id, ops):
Michael Hanselmann's avatar
Michael Hanselmann committed
125 126 127 128
    if not ops:
      # TODO
      raise Exception("No opcodes")

Michael Hanselmann's avatar
Michael Hanselmann committed
129
    self.queue = queue
130
    self.id = job_id
Michael Hanselmann's avatar
Michael Hanselmann committed
131 132
    self.ops = [_QueuedOpCode(op) for op in ops]
    self.run_op_index = -1
133 134

  @classmethod
Michael Hanselmann's avatar
Michael Hanselmann committed
135 136 137 138 139 140
  def Restore(cls, queue, state):
    obj = _QueuedJob.__new__(cls)
    obj.queue = queue
    obj.id = state["id"]
    obj.ops = [_QueuedOpCode.Restore(op_state) for op_state in state["ops"]]
    obj.run_op_index = state["run_op_index"]
141 142 143 144 145
    return obj

  def Serialize(self):
    return {
      "id": self.id,
Michael Hanselmann's avatar
Michael Hanselmann committed
146
      "ops": [op.Serialize() for op in self.ops],
147
      "run_op_index": self.run_op_index,
148 149
      }

Michael Hanselmann's avatar
Michael Hanselmann committed
150
  def CalcStatus(self):
Michael Hanselmann's avatar
Michael Hanselmann committed
151 152 153
    status = constants.JOB_STATUS_QUEUED

    all_success = True
Michael Hanselmann's avatar
Michael Hanselmann committed
154 155
    for op in self.ops:
      if op.status == constants.OP_STATUS_SUCCESS:
Michael Hanselmann's avatar
Michael Hanselmann committed
156 157 158 159
        continue

      all_success = False

Michael Hanselmann's avatar
Michael Hanselmann committed
160
      if op.status == constants.OP_STATUS_QUEUED:
Michael Hanselmann's avatar
Michael Hanselmann committed
161
        pass
Michael Hanselmann's avatar
Michael Hanselmann committed
162
      elif op.status == constants.OP_STATUS_RUNNING:
Michael Hanselmann's avatar
Michael Hanselmann committed
163
        status = constants.JOB_STATUS_RUNNING
Michael Hanselmann's avatar
Michael Hanselmann committed
164
      elif op.status == constants.OP_STATUS_ERROR:
165 166 167
        status = constants.JOB_STATUS_ERROR
        # The whole job fails if one opcode failed
        break
Michael Hanselmann's avatar
Michael Hanselmann committed
168
      elif op.status == constants.OP_STATUS_CANCELED:
169 170
        status = constants.OP_STATUS_CANCELED
        break
Michael Hanselmann's avatar
Michael Hanselmann committed
171 172 173 174 175 176

    if all_success:
      status = constants.JOB_STATUS_SUCCESS

    return status

177

Michael Hanselmann's avatar
Michael Hanselmann committed
178 179
class _JobQueueWorker(workerpool.BaseWorker):
  def RunTask(self, job):
Michael Hanselmann's avatar
Michael Hanselmann committed
180 181
    """Job executor.

Michael Hanselmann's avatar
Michael Hanselmann committed
182
    This functions processes a job.
Michael Hanselmann's avatar
Michael Hanselmann committed
183 184 185 186

    """
    logging.debug("Worker %s processing job %s",
                  self.worker_id, job.id)
187
    proc = mcpu.Processor(self.pool.queue.context)
Michael Hanselmann's avatar
Michael Hanselmann committed
188
    queue = job.queue
Michael Hanselmann's avatar
Michael Hanselmann committed
189
    try:
Michael Hanselmann's avatar
Michael Hanselmann committed
190 191 192 193 194 195 196 197 198 199 200 201 202
      try:
        count = len(job.ops)
        for idx, op in enumerate(job.ops):
          try:
            logging.debug("Op %s/%s: Starting %s", idx + 1, count, op)

            queue.acquire()
            try:
              job.run_op_index = idx
              op.status = constants.OP_STATUS_RUNNING
              op.result = None
              queue.UpdateJobUnlocked(job)

Iustin Pop's avatar
Iustin Pop committed
203
              input_opcode = op.input
Michael Hanselmann's avatar
Michael Hanselmann committed
204 205 206
            finally:
              queue.release()

Iustin Pop's avatar
Iustin Pop committed
207
            result = proc.ExecOpCode(input_opcode, op.Log)
Michael Hanselmann's avatar
Michael Hanselmann committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

            queue.acquire()
            try:
              op.status = constants.OP_STATUS_SUCCESS
              op.result = result
              queue.UpdateJobUnlocked(job)
            finally:
              queue.release()

            logging.debug("Op %s/%s: Successfully finished %s",
                          idx + 1, count, op)
          except Exception, err:
            queue.acquire()
            try:
              try:
                op.status = constants.OP_STATUS_ERROR
                op.result = str(err)
                logging.debug("Op %s/%s: Error in %s", idx + 1, count, op)
              finally:
                queue.UpdateJobUnlocked(job)
            finally:
              queue.release()
            raise

      except errors.GenericError, err:
        logging.exception("Ganeti exception")
      except:
        logging.exception("Unhandled exception")
Michael Hanselmann's avatar
Michael Hanselmann committed
236
    finally:
Michael Hanselmann's avatar
Michael Hanselmann committed
237 238 239 240 241 242
      queue.acquire()
      try:
        job_id = job.id
        status = job.CalcStatus()
      finally:
        queue.release()
Michael Hanselmann's avatar
Michael Hanselmann committed
243
      logging.debug("Worker %s finished job %s, status = %s",
Michael Hanselmann's avatar
Michael Hanselmann committed
244
                    self.worker_id, job_id, status)
Michael Hanselmann's avatar
Michael Hanselmann committed
245 246 247


class _JobQueueWorkerPool(workerpool.WorkerPool):
248
  def __init__(self, queue):
Michael Hanselmann's avatar
Michael Hanselmann committed
249 250
    super(_JobQueueWorkerPool, self).__init__(JOBQUEUE_THREADS,
                                              _JobQueueWorker)
251
    self.queue = queue
Michael Hanselmann's avatar
Michael Hanselmann committed
252 253


Michael Hanselmann's avatar
Michael Hanselmann committed
254
class JobQueue(object):
255
  _RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
256

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  def _RequireOpenQueue(fn):
    """Decorator for "public" functions.

    This function should be used for all "public" functions. That is, functions
    usually called from other classes.

    Important: Use this decorator only after utils.LockedMethod!

    Example:
      @utils.LockedMethod
      @_RequireOpenQueue
      def Example(self):
        pass

    """
    def wrapper(self, *args, **kwargs):
273
      assert self._queue_lock is not None, "Queue should be open"
274 275 276
      return fn(self, *args, **kwargs)
    return wrapper

Michael Hanselmann's avatar
Michael Hanselmann committed
277
  def __init__(self, context):
278
    self.context = context
Iustin Pop's avatar
Iustin Pop committed
279
    self._memcache = {}
280
    self._my_hostname = utils.HostInfo().name
281

Michael Hanselmann's avatar
Michael Hanselmann committed
282 283 284 285 286
    # Locking
    self._lock = threading.Lock()
    self.acquire = self._lock.acquire
    self.release = self._lock.release

287
    # Initialize
288
    self._queue_lock = jstore.InitAndVerifyQueue(must_lock=True)
289

290 291 292 293
    # Read serial file
    self._last_serial = jstore.ReadSerial()
    assert self._last_serial is not None, ("Serial file was modified between"
                                           " check in jstore and here")
294

295
    # Get initial list of nodes
296 297 298 299 300 301 302
    self._nodes = set(self.context.cfg.GetNodeList())

    # Remove master node
    try:
      self._nodes.remove(self._my_hostname)
    except ValueError:
      pass
303 304 305

    # TODO: Check consistency across nodes

Michael Hanselmann's avatar
Michael Hanselmann committed
306
    # Setup worker pool
307
    self._wpool = _JobQueueWorkerPool(self)
Michael Hanselmann's avatar
Michael Hanselmann committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329

    # We need to lock here because WorkerPool.AddTask() may start a job while
    # we're still doing our work.
    self.acquire()
    try:
      for job in self._GetJobsUnlocked(None):
        status = job.CalcStatus()

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

        elif status in (constants.JOB_STATUS_RUNNING, ):
          logging.warning("Unfinished job %s found: %s", job.id, job)
          try:
            for op in job.ops:
              op.status = constants.OP_STATUS_ERROR
              op.result = "Unclean master daemon shutdown"
          finally:
            self.UpdateJobUnlocked(job)
    finally:
      self.release()

330 331 332 333
  @utils.LockedMethod
  @_RequireOpenQueue
  def AddNode(self, node_name):
    assert node_name != self._my_hostname
334

335 336
    # Clean queue directory on added node
    rpc.call_jobqueue_purge(node_name)
337

338 339
    # Upload the whole queue excluding archived jobs
    files = [self._GetJobPath(job_id) for job_id in self._GetJobIDsUnlocked()]
340

341 342 343 344
    # Upload current serial file
    files.append(constants.JOB_QUEUE_SERIAL_FILE)

    for file_name in files:
345 346 347 348 349 350 351 352
      # Read file content
      fd = open(file_name, "r")
      try:
        content = fd.read()
      finally:
        fd.close()

      result = rpc.call_jobqueue_update([node_name], file_name, content)
353 354 355 356 357 358 359 360
      if not result[node_name]:
        logging.error("Failed to upload %s to %s", file_name, node_name)

    self._nodes.add(node_name)

  @utils.LockedMethod
  @_RequireOpenQueue
  def RemoveNode(self, node_name):
361
    try:
362 363 364
      # The queue is removed by the "leave node" RPC call.
      self._nodes.remove(node_name)
    except KeyError:
365 366
      pass

367 368 369 370 371 372
  def _WriteAndReplicateFileUnlocked(self, file_name, data):
    """Writes a file locally and then replicates it to all nodes.

    """
    utils.WriteFile(file_name, data=data)

373
    failed_nodes = 0
374
    result = rpc.call_jobqueue_update(self._nodes, file_name, data)
375
    for node in self._nodes:
376 377 378 379 380 381
      if not result[node]:
        failed_nodes += 1
        logging.error("Copy of job queue file to node %s failed", node)

    # TODO: check failed_nodes

382 383 384 385 386 387 388 389 390 391
  def _RenameFileUnlocked(self, old, new):
    os.rename(old, new)

    result = rpc.call_jobqueue_rename(self._nodes, old, new)
    for node in self._nodes:
      if not result[node]:
        logging.error("Moving %s to %s failed on %s", old, new, node)

    # TODO: check failed nodes

Michael Hanselmann's avatar
Michael Hanselmann committed
392 393 394 395 396 397 398 399
  def _FormatJobID(self, job_id):
    if not isinstance(job_id, (int, long)):
      raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id)
    if job_id < 0:
      raise errors.ProgrammerError("Job ID %s is negative" % job_id)

    return str(job_id)

400
  def _NewSerialUnlocked(self):
401 402 403 404 405 406 407 408 409 410 411
    """Generates a new job identifier.

    Job identifiers are unique during the lifetime of a cluster.

    Returns: A string representing the job identifier.

    """
    # New number
    serial = self._last_serial + 1

    # Write to file
412 413
    self._WriteAndReplicateFileUnlocked(constants.JOB_QUEUE_SERIAL_FILE,
                                        "%s\n" % serial)
414 415 416 417

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

Michael Hanselmann's avatar
Michael Hanselmann committed
418
    return self._FormatJobID(serial)
419

Michael Hanselmann's avatar
Michael Hanselmann committed
420 421
  @staticmethod
  def _GetJobPath(job_id):
422 423
    return os.path.join(constants.QUEUE_DIR, "job-%s" % job_id)

Michael Hanselmann's avatar
Michael Hanselmann committed
424 425
  @staticmethod
  def _GetArchivedJobPath(job_id):
426 427
    return os.path.join(constants.JOB_QUEUE_ARCHIVE_DIR, "job-%s" % job_id)

Michael Hanselmann's avatar
Michael Hanselmann committed
428 429 430
  @classmethod
  def _ExtractJobID(cls, name):
    m = cls._RE_JOB_FILE.match(name)
431 432 433 434 435
    if m:
      return m.group(1)
    else:
      return None

436 437 438 439 440 441
  def _GetJobIDsUnlocked(self, archived=False):
    """Return all known job IDs.

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

Iustin Pop's avatar
Iustin Pop committed
442 443 444 445
    The method only looks at disk because it's a requirement that all
    jobs are present on disk (so in the _memcache we don't have any
    extra IDs).

446
    """
447
    jlist = [self._ExtractJobID(name) for name in self._ListJobFiles()]
448 449
    jlist.sort()
    return jlist
450

451 452 453 454
  def _ListJobFiles(self):
    return [name for name in utils.ListVisibleFiles(constants.QUEUE_DIR)
            if self._RE_JOB_FILE.match(name)]

455
  def _LoadJobUnlocked(self, job_id):
Iustin Pop's avatar
Iustin Pop committed
456
    if job_id in self._memcache:
457
      logging.debug("Found job %s in memcache", job_id)
Iustin Pop's avatar
Iustin Pop committed
458 459
      return self._memcache[job_id]

460
    filepath = self._GetJobPath(job_id)
461 462 463 464 465 466 467 468 469 470 471 472
    logging.debug("Loading job from %s", filepath)
    try:
      fd = open(filepath, "r")
    except IOError, err:
      if err.errno in (errno.ENOENT, ):
        return None
      raise
    try:
      data = serializer.LoadJson(fd.read())
    finally:
      fd.close()

Iustin Pop's avatar
Iustin Pop committed
473 474
    job = _QueuedJob.Restore(self, data)
    self._memcache[job_id] = job
475
    logging.debug("Added job %s to the cache", job_id)
Iustin Pop's avatar
Iustin Pop committed
476
    return job
477 478

  def _GetJobsUnlocked(self, job_ids):
479 480
    if not job_ids:
      job_ids = self._GetJobIDsUnlocked()
481

482
    return [self._LoadJobUnlocked(job_id) for job_id in job_ids]
483 484

  @utils.LockedMethod
485
  @_RequireOpenQueue
486
  def SubmitJob(self, ops):
Michael Hanselmann's avatar
Michael Hanselmann committed
487
    """Create and store a new job.
488

Michael Hanselmann's avatar
Michael Hanselmann committed
489 490
    This enters the job into our job queue and also puts it on the new
    queue, in order for it to be picked up by the queue processors.
491 492

    @type ops: list
493
    @param ops: The list of OpCodes that will become the new job.
494 495

    """
496
    # Get job identifier
497
    job_id = self._NewSerialUnlocked()
498 499 500
    job = _QueuedJob(self, job_id, ops)

    # Write to disk
Michael Hanselmann's avatar
Michael Hanselmann committed
501
    self.UpdateJobUnlocked(job)
502

503
    logging.debug("Added new job %s to the cache", job_id)
Iustin Pop's avatar
Iustin Pop committed
504 505
    self._memcache[job_id] = job

Michael Hanselmann's avatar
Michael Hanselmann committed
506 507 508 509
    # Add to worker pool
    self._wpool.AddTask(job)

    return job.id
510

511
  @_RequireOpenQueue
Michael Hanselmann's avatar
Michael Hanselmann committed
512
  def UpdateJobUnlocked(self, job):
513
    filename = self._GetJobPath(job.id)
514
    data = serializer.DumpJson(job.Serialize(), indent=False)
515
    logging.debug("Writing job %s to %s", job.id, filename)
516
    self._WriteAndReplicateFileUnlocked(filename, data)
517
    self._CleanCacheUnlocked([job.id])
Iustin Pop's avatar
Iustin Pop committed
518

519
  def _CleanCacheUnlocked(self, exclude):
Iustin Pop's avatar
Iustin Pop committed
520 521 522 523 524 525
    """Clean the memory cache.

    The exceptions argument contains job IDs that should not be
    cleaned.

    """
526
    assert isinstance(exclude, list)
Michael Hanselmann's avatar
Michael Hanselmann committed
527

Iustin Pop's avatar
Iustin Pop committed
528
    for job in self._memcache.values():
529
      if job.id in exclude:
Iustin Pop's avatar
Iustin Pop committed
530
        continue
Michael Hanselmann's avatar
Michael Hanselmann committed
531 532
      if job.CalcStatus() not in (constants.JOB_STATUS_QUEUED,
                                  constants.JOB_STATUS_RUNNING):
533
        logging.debug("Cleaning job %s from the cache", job.id)
Iustin Pop's avatar
Iustin Pop committed
534 535 536 537
        try:
          del self._memcache[job.id]
        except KeyError:
          pass
538 539

  @utils.LockedMethod
540
  @_RequireOpenQueue
541 542 543 544 545 546 547 548 549
  def CancelJob(self, job_id):
    """Cancels a job.

    @type job_id: string
    @param job_id: Job ID of job to be cancelled.

    """
    logging.debug("Cancelling job %s", job_id)

Michael Hanselmann's avatar
Michael Hanselmann committed
550
    job = self._LoadJobUnlocked(job_id)
551 552 553 554
    if not job:
      logging.debug("Job %s not found", job_id)
      return

Michael Hanselmann's avatar
Michael Hanselmann committed
555
    if job.CalcStatus() not in (constants.JOB_STATUS_QUEUED,):
556 557 558
      logging.debug("Job %s is no longer in the queue", job.id)
      return

Michael Hanselmann's avatar
Michael Hanselmann committed
559 560 561 562 563 564
    try:
      for op in job.ops:
        op.status = constants.OP_STATUS_ERROR
        op.result = "Job cancelled by request"
    finally:
      self.UpdateJobUnlocked(job)
565

566
  @utils.LockedMethod
567
  @_RequireOpenQueue
568
  def ArchiveJob(self, job_id):
569 570 571 572 573 574 575 576 577 578 579 580 581
    """Archives a job.

    @type job_id: string
    @param job_id: Job ID of job to be archived.

    """
    logging.debug("Archiving job %s", job_id)

    job = self._LoadJobUnlocked(job_id)
    if not job:
      logging.debug("Job %s not found", job_id)
      return

Michael Hanselmann's avatar
Michael Hanselmann committed
582 583 584 585
    if job.CalcStatus() not in (constants.JOB_STATUS_CANCELED,
                                constants.JOB_STATUS_SUCCESS,
                                constants.JOB_STATUS_ERROR):
      logging.debug("Job %s is not yet done", job.id)
586 587 588 589 590 591
      return

    try:
      old = self._GetJobPath(job.id)
      new = self._GetArchivedJobPath(job.id)

592
      self._RenameFileUnlocked(old, new)
593 594 595 596 597 598

      logging.debug("Successfully archived job %s", job.id)
    finally:
      # Cleaning the cache because we don't know what os.rename actually did
      # and to be on the safe side.
      self._CleanCacheUnlocked([])
599

Michael Hanselmann's avatar
Michael Hanselmann committed
600
  def _GetJobInfoUnlocked(self, job, fields):
Michael Hanselmann's avatar
Michael Hanselmann committed
601 602 603 604 605
    row = []
    for fname in fields:
      if fname == "id":
        row.append(job.id)
      elif fname == "status":
Michael Hanselmann's avatar
Michael Hanselmann committed
606
        row.append(job.CalcStatus())
607
      elif fname == "ops":
Michael Hanselmann's avatar
Michael Hanselmann committed
608
        row.append([op.input.__getstate__() for op in job.ops])
609
      elif fname == "opresult":
Michael Hanselmann's avatar
Michael Hanselmann committed
610
        row.append([op.result for op in job.ops])
611
      elif fname == "opstatus":
Michael Hanselmann's avatar
Michael Hanselmann committed
612
        row.append([op.status for op in job.ops])
613
      elif fname == "ticker":
Michael Hanselmann's avatar
Michael Hanselmann committed
614
        ji = job.run_op_index
615 616 617
        if ji < 0:
          lmsg = None
        else:
Michael Hanselmann's avatar
Michael Hanselmann committed
618
          lmsg = job.ops[ji].RetrieveLog(-1)
619 620 621 622 623 624
          # message might be empty here
          if lmsg:
            lmsg = lmsg[0]
          else:
            lmsg = None
        row.append(lmsg)
Michael Hanselmann's avatar
Michael Hanselmann committed
625 626 627 628
      else:
        raise errors.OpExecError("Invalid job query field '%s'" % fname)
    return row

Michael Hanselmann's avatar
Michael Hanselmann committed
629
  @utils.LockedMethod
630
  @_RequireOpenQueue
Michael Hanselmann's avatar
Michael Hanselmann committed
631 632 633 634 635 636 637 638
  def QueryJobs(self, job_ids, fields):
    """Returns a list of jobs in queue.

    Args:
    - job_ids: Sequence of job identifiers or None for all
    - fields: Names of fields to return

    """
Michael Hanselmann's avatar
Michael Hanselmann committed
639
    jobs = []
Michael Hanselmann's avatar
Michael Hanselmann committed
640

Michael Hanselmann's avatar
Michael Hanselmann committed
641 642 643 644 645
    for job in self._GetJobsUnlocked(job_ids):
      if job is None:
        jobs.append(None)
      else:
        jobs.append(self._GetJobInfoUnlocked(job, fields))
Michael Hanselmann's avatar
Michael Hanselmann committed
646

Michael Hanselmann's avatar
Michael Hanselmann committed
647
    return jobs
Michael Hanselmann's avatar
Michael Hanselmann committed
648

649
  @utils.LockedMethod
650
  @_RequireOpenQueue
Michael Hanselmann's avatar
Michael Hanselmann committed
651 652 653 654 655
  def Shutdown(self):
    """Stops the job queue.

    """
    self._wpool.TerminateWorkers()
Michael Hanselmann's avatar
Michael Hanselmann committed
656

657 658
    self._queue_lock.Close()
    self._queue_lock = None