Statistics
| Branch: | Tag: | Revision:

root / lib / jqueue.py @ 04ab05ce

History | View | Annotate | Download (15.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007 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
import os
25
import logging
26
import threading
27
import errno
28
import re
29
import time
30

    
31
from ganeti import constants
32
from ganeti import serializer
33
from ganeti import workerpool
34
from ganeti import opcodes
35
from ganeti import errors
36
from ganeti import mcpu
37
from ganeti import utils
38
from ganeti import jstore
39
from ganeti import rpc
40

    
41

    
42
JOBQUEUE_THREADS = 5
43

    
44

    
45
class _QueuedOpCode(object):
46
  """Encasulates an opcode object.
47

48
  Access is synchronized by the '_lock' attribute.
49

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

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

    
60
  def __init__(self, op):
61
    self.input = op
62
    self.status = constants.OP_STATUS_QUEUED
63
    self.result = None
64
    self.log = []
65

    
66
  @classmethod
67
  def Restore(cls, state):
68
    obj = _QueuedOpCode.__new__(cls)
69
    obj.input = opcodes.OpCode.LoadOpCode(state["input"])
70
    obj.status = state["status"]
71
    obj.result = state["result"]
72
    obj.log = state["log"]
73
    return obj
74

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

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

90
    """
91
    assert len(args) < 3
92

    
93
    if len(args) == 1:
94
      log_type = constants.ELOG_MESSAGE
95
      log_msg = args[0]
96
    else:
97
      log_type, log_msg = args
98

    
99
    self._log_lock.acquire()
100
    try:
101
      self.log.append((time.time(), log_type, log_msg))
102
    finally:
103
      self._log_lock.release()
104

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

108
    """
109
    self._log_lock.acquire()
110
    try:
111
      return self.log[start_at:]
112
    finally:
113
      self._log_lock.release()
114

    
115

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

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

121
  """
122
  def __init__(self, queue, job_id, ops):
123
    if not ops:
124
      # TODO
125
      raise Exception("No opcodes")
126

    
127
    self.queue = queue
128
    self.id = job_id
129
    self.ops = [_QueuedOpCode(op) for op in ops]
130
    self.run_op_index = -1
131

    
132
  @classmethod
133
  def Restore(cls, queue, state):
134
    obj = _QueuedJob.__new__(cls)
135
    obj.queue = queue
136
    obj.id = state["id"]
137
    obj.ops = [_QueuedOpCode.Restore(op_state) for op_state in state["ops"]]
138
    obj.run_op_index = state["run_op_index"]
139
    return obj
140

    
141
  def Serialize(self):
142
    return {
143
      "id": self.id,
144
      "ops": [op.Serialize() for op in self.ops],
145
      "run_op_index": self.run_op_index,
146
      }
147

    
148
  def CalcStatus(self):
149
    status = constants.JOB_STATUS_QUEUED
150

    
151
    all_success = True
152
    for op in self.ops:
153
      if op.status == constants.OP_STATUS_SUCCESS:
154
        continue
155

    
156
      all_success = False
157

    
158
      if op.status == constants.OP_STATUS_QUEUED:
159
        pass
160
      elif op.status == constants.OP_STATUS_RUNNING:
161
        status = constants.JOB_STATUS_RUNNING
162
      elif op.status == constants.OP_STATUS_ERROR:
163
        status = constants.JOB_STATUS_ERROR
164
        # The whole job fails if one opcode failed
165
        break
166
      elif op.status == constants.OP_STATUS_CANCELED:
167
        status = constants.OP_STATUS_CANCELED
168
        break
169

    
170
    if all_success:
171
      status = constants.JOB_STATUS_SUCCESS
172

    
173
    return status
174

    
175

    
176
class _JobQueueWorker(workerpool.BaseWorker):
177
  def RunTask(self, job):
178
    """Job executor.
179

180
    This functions processes a job.
181

182
    """
183
    logging.debug("Worker %s processing job %s",
184
                  self.worker_id, job.id)
185
    proc = mcpu.Processor(self.pool.queue.context)
186
    queue = job.queue
187
    try:
188
      try:
189
        count = len(job.ops)
190
        for idx, op in enumerate(job.ops):
191
          try:
192
            logging.debug("Op %s/%s: Starting %s", idx + 1, count, op)
193

    
194
            queue.acquire()
195
            try:
196
              job.run_op_index = idx
197
              op.status = constants.OP_STATUS_RUNNING
198
              op.result = None
199
              queue.UpdateJobUnlocked(job)
200

    
201
              input_opcode = op.input
202
            finally:
203
              queue.release()
204

    
205
            result = proc.ExecOpCode(input_opcode, op.Log)
206

    
207
            queue.acquire()
208
            try:
209
              op.status = constants.OP_STATUS_SUCCESS
210
              op.result = result
211
              queue.UpdateJobUnlocked(job)
212
            finally:
213
              queue.release()
214

    
215
            logging.debug("Op %s/%s: Successfully finished %s",
216
                          idx + 1, count, op)
217
          except Exception, err:
218
            queue.acquire()
219
            try:
220
              try:
221
                op.status = constants.OP_STATUS_ERROR
222
                op.result = str(err)
223
                logging.debug("Op %s/%s: Error in %s", idx + 1, count, op)
224
              finally:
225
                queue.UpdateJobUnlocked(job)
226
            finally:
227
              queue.release()
228
            raise
229

    
230
      except errors.GenericError, err:
231
        logging.exception("Ganeti exception")
232
      except:
233
        logging.exception("Unhandled exception")
234
    finally:
235
      queue.acquire()
236
      try:
237
        job_id = job.id
238
        status = job.CalcStatus()
239
      finally:
240
        queue.release()
241
      logging.debug("Worker %s finished job %s, status = %s",
242
                    self.worker_id, job_id, status)
243

    
244

    
245
class _JobQueueWorkerPool(workerpool.WorkerPool):
246
  def __init__(self, queue):
247
    super(_JobQueueWorkerPool, self).__init__(JOBQUEUE_THREADS,
248
                                              _JobQueueWorker)
249
    self.queue = queue
250

    
251

    
252
class JobQueue(object):
253
  _RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
254

    
255
  def _RequireOpenQueue(fn):
256
    """Decorator for "public" functions.
257

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

261
    Important: Use this decorator only after utils.LockedMethod!
262

263
    Example:
264
      @utils.LockedMethod
265
      @_RequireOpenQueue
266
      def Example(self):
267
        pass
268

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

    
275
  def __init__(self, context):
276
    self.context = context
277
    self._memcache = {}
278
    self._my_hostname = utils.HostInfo().name
279

    
280
    # Locking
281
    self._lock = threading.Lock()
282
    self.acquire = self._lock.acquire
283
    self.release = self._lock.release
284

    
285
    # Initialize
286
    self._queue_lock = jstore.InitAndVerifyQueue(exclusive=True)
287

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

    
293
    # Setup worker pool
294
    self._wpool = _JobQueueWorkerPool(self)
295

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

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

    
306
        elif status in (constants.JOB_STATUS_RUNNING, ):
307
          logging.warning("Unfinished job %s found: %s", job.id, job)
308
          try:
309
            for op in job.ops:
310
              op.status = constants.OP_STATUS_ERROR
311
              op.result = "Unclean master daemon shutdown"
312
          finally:
313
            self.UpdateJobUnlocked(job)
314
    finally:
315
      self.release()
316

    
317
  def _FormatJobID(self, job_id):
318
    if not isinstance(job_id, (int, long)):
319
      raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id)
320
    if job_id < 0:
321
      raise errors.ProgrammerError("Job ID %s is negative" % job_id)
322

    
323
    return str(job_id)
324

    
325
  def _NewSerialUnlocked(self, nodes):
326
    """Generates a new job identifier.
327

328
    Job identifiers are unique during the lifetime of a cluster.
329

330
    Returns: A string representing the job identifier.
331

332
    """
333
    # New number
334
    serial = self._last_serial + 1
335

    
336
    # Write to file
337
    utils.WriteFile(constants.JOB_QUEUE_SERIAL_FILE,
338
                    data="%s\n" % serial)
339

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

    
343
    # Distribute the serial to the other nodes
344
    try:
345
      nodes.remove(self._my_hostname)
346
    except ValueError:
347
      pass
348

    
349
    result = rpc.call_upload_file(nodes, constants.JOB_QUEUE_SERIAL_FILE)
350
    for node in nodes:
351
      if not result[node]:
352
        logging.error("copy of job queue file to node %s failed", node)
353

    
354
    return self._FormatJobID(serial)
355

    
356
  @staticmethod
357
  def _GetJobPath(job_id):
358
    return os.path.join(constants.QUEUE_DIR, "job-%s" % job_id)
359

    
360
  @staticmethod
361
  def _GetArchivedJobPath(job_id):
362
    return os.path.join(constants.JOB_QUEUE_ARCHIVE_DIR, "job-%s" % job_id)
363

    
364
  @classmethod
365
  def _ExtractJobID(cls, name):
366
    m = cls._RE_JOB_FILE.match(name)
367
    if m:
368
      return m.group(1)
369
    else:
370
      return None
371

    
372
  def _GetJobIDsUnlocked(self, archived=False):
373
    """Return all known job IDs.
374

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

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

382
    """
383
    jlist = [self._ExtractJobID(name) for name in self._ListJobFiles()]
384
    jlist.sort()
385
    return jlist
386

    
387
  def _ListJobFiles(self):
388
    return [name for name in utils.ListVisibleFiles(constants.QUEUE_DIR)
389
            if self._RE_JOB_FILE.match(name)]
390

    
391
  def _LoadJobUnlocked(self, job_id):
392
    if job_id in self._memcache:
393
      logging.debug("Found job %s in memcache", job_id)
394
      return self._memcache[job_id]
395

    
396
    filepath = self._GetJobPath(job_id)
397
    logging.debug("Loading job from %s", filepath)
398
    try:
399
      fd = open(filepath, "r")
400
    except IOError, err:
401
      if err.errno in (errno.ENOENT, ):
402
        return None
403
      raise
404
    try:
405
      data = serializer.LoadJson(fd.read())
406
    finally:
407
      fd.close()
408

    
409
    job = _QueuedJob.Restore(self, data)
410
    self._memcache[job_id] = job
411
    logging.debug("Added job %s to the cache", job_id)
412
    return job
413

    
414
  def _GetJobsUnlocked(self, job_ids):
415
    if not job_ids:
416
      job_ids = self._GetJobIDsUnlocked()
417

    
418
    return [self._LoadJobUnlocked(job_id) for job_id in job_ids]
419

    
420
  @utils.LockedMethod
421
  @_RequireOpenQueue
422
  def SubmitJob(self, ops, nodes):
423
    """Create and store a new job.
424

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

428
    @type ops: list
429
    @param ops: The list of OpCodes that will become the new job.
430
    @type nodes: list
431
    @param nodes: The list of nodes to which the new job serial will be
432
                  distributed.
433

434
    """
435
    # Get job identifier
436
    job_id = self._NewSerialUnlocked(nodes)
437
    job = _QueuedJob(self, job_id, ops)
438

    
439
    # Write to disk
440
    self.UpdateJobUnlocked(job)
441

    
442
    logging.debug("Added new job %s to the cache", job_id)
443
    self._memcache[job_id] = job
444

    
445
    # Add to worker pool
446
    self._wpool.AddTask(job)
447

    
448
    return job.id
449

    
450
  @_RequireOpenQueue
451
  def UpdateJobUnlocked(self, job):
452
    filename = self._GetJobPath(job.id)
453
    logging.debug("Writing job %s to %s", job.id, filename)
454
    utils.WriteFile(filename,
455
                    data=serializer.DumpJson(job.Serialize(), indent=False))
456
    self._CleanCacheUnlocked([job.id])
457

    
458
  def _CleanCacheUnlocked(self, exclude):
459
    """Clean the memory cache.
460

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

464
    """
465
    assert isinstance(exclude, list)
466

    
467
    for job in self._memcache.values():
468
      if job.id in exclude:
469
        continue
470
      if job.CalcStatus() not in (constants.JOB_STATUS_QUEUED,
471
                                  constants.JOB_STATUS_RUNNING):
472
        logging.debug("Cleaning job %s from the cache", job.id)
473
        try:
474
          del self._memcache[job.id]
475
        except KeyError:
476
          pass
477

    
478
  @utils.LockedMethod
479
  @_RequireOpenQueue
480
  def CancelJob(self, job_id):
481
    """Cancels a job.
482

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

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

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

    
494
    if job.CalcStatus() not in (constants.JOB_STATUS_QUEUED,):
495
      logging.debug("Job %s is no longer in the queue", job.id)
496
      return
497

    
498
    try:
499
      for op in job.ops:
500
        op.status = constants.OP_STATUS_ERROR
501
        op.result = "Job cancelled by request"
502
    finally:
503
      self.UpdateJobUnlocked(job)
504

    
505
  @utils.LockedMethod
506
  @_RequireOpenQueue
507
  def ArchiveJob(self, job_id):
508
    """Archives a job.
509

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

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

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

    
521
    if job.CalcStatus() not in (constants.JOB_STATUS_CANCELED,
522
                                constants.JOB_STATUS_SUCCESS,
523
                                constants.JOB_STATUS_ERROR):
524
      logging.debug("Job %s is not yet done", job.id)
525
      return
526

    
527
    try:
528
      old = self._GetJobPath(job.id)
529
      new = self._GetArchivedJobPath(job.id)
530

    
531
      os.rename(old, new)
532

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

    
539
  def _GetJobInfoUnlocked(self, job, fields):
540
    row = []
541
    for fname in fields:
542
      if fname == "id":
543
        row.append(job.id)
544
      elif fname == "status":
545
        row.append(job.CalcStatus())
546
      elif fname == "ops":
547
        row.append([op.input.__getstate__() for op in job.ops])
548
      elif fname == "opresult":
549
        row.append([op.result for op in job.ops])
550
      elif fname == "opstatus":
551
        row.append([op.status for op in job.ops])
552
      elif fname == "ticker":
553
        ji = job.run_op_index
554
        if ji < 0:
555
          lmsg = None
556
        else:
557
          lmsg = job.ops[ji].RetrieveLog(-1)
558
          # message might be empty here
559
          if lmsg:
560
            lmsg = lmsg[0]
561
          else:
562
            lmsg = None
563
        row.append(lmsg)
564
      else:
565
        raise errors.OpExecError("Invalid job query field '%s'" % fname)
566
    return row
567

    
568
  @utils.LockedMethod
569
  @_RequireOpenQueue
570
  def QueryJobs(self, job_ids, fields):
571
    """Returns a list of jobs in queue.
572

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

577
    """
578
    jobs = []
579

    
580
    for job in self._GetJobsUnlocked(job_ids):
581
      if job is None:
582
        jobs.append(None)
583
      else:
584
        jobs.append(self._GetJobInfoUnlocked(job, fields))
585

    
586
    return jobs
587

    
588
  @utils.LockedMethod
589
  @_RequireOpenQueue
590
  def Shutdown(self):
591
    """Stops the job queue.
592

593
    """
594
    self._wpool.TerminateWorkers()
595

    
596
    self._queue_lock.Close()
597
    self._queue_lock = None