jqueue.py 6.52 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."""

Michael Hanselmann's avatar
Michael Hanselmann committed
24 25
import logging
import threading
Iustin Pop's avatar
Iustin Pop committed
26

Michael Hanselmann's avatar
Michael Hanselmann committed
27 28
from ganeti import constants
from ganeti import workerpool
Iustin Pop's avatar
Iustin Pop committed
29
from ganeti import errors
Michael Hanselmann's avatar
Michael Hanselmann committed
30
from ganeti import mcpu
31
from ganeti import utils
Michael Hanselmann's avatar
Michael Hanselmann committed
32 33 34 35


JOBQUEUE_THREADS = 5

Iustin Pop's avatar
Iustin Pop committed
36

Michael Hanselmann's avatar
Michael Hanselmann committed
37 38 39
class _QueuedOpCode(object):
  """Encasulates an opcode object.

40
  Access is synchronized by the '_lock' attribute.
Michael Hanselmann's avatar
Michael Hanselmann committed
41 42 43 44 45 46

  """
  def __init__(self, op):
    self.input = op
    self.status = constants.OP_STATUS_QUEUED
    self.result = None
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
    self._lock = threading.Lock()

  @utils.LockedMethod
  def SetStatus(self, status, result):
    """Update the opcode status and result.

    """
    self.status = status
    self.result = result

  @utils.LockedMethod
  def GetStatus(self):
    """Get the opcode status.

    """
    return self.status

  @utils.LockedMethod
  def GetResult(self):
    """Get the opcode result.

    """
    return self.result
Michael Hanselmann's avatar
Michael Hanselmann committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89


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

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

  """
  def __init__(self, ops, job_id):
    if not ops:
      # TODO
      raise Exception("No opcodes")

    self.id = job_id
    self._lock = threading.Lock()

    # _ops should not be modified again because we don't acquire the lock
    # to use it.
    self._ops = [_QueuedOpCode(op) for op in ops]

90
  def GetStatus(self):
Michael Hanselmann's avatar
Michael Hanselmann committed
91 92 93 94
    status = constants.JOB_STATUS_QUEUED

    all_success = True
    for op in self._ops:
95 96
      op_status = op.GetStatus()
      if op_status == constants.OP_STATUS_SUCCESS:
Michael Hanselmann's avatar
Michael Hanselmann committed
97 98 99 100
        continue

      all_success = False

101
      if op_status == constants.OP_STATUS_QUEUED:
Michael Hanselmann's avatar
Michael Hanselmann committed
102
        pass
103
      elif op_status == constants.OP_STATUS_ERROR:
Michael Hanselmann's avatar
Michael Hanselmann committed
104
        status = constants.JOB_STATUS_ERROR
105
      elif op_status == constants.OP_STATUS_RUNNING:
Michael Hanselmann's avatar
Michael Hanselmann committed
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
        status = constants.JOB_STATUS_RUNNING

    if all_success:
      status = constants.JOB_STATUS_SUCCESS

    return status

  def Run(self, proc):
    """Job executor.

    This functions processes a this job in the context of given processor
    instance.

    Args:
    - proc: Ganeti Processor to run the job with

    """
    try:
124 125
      count = len(self._ops)
      for idx, op in enumerate(self._ops):
Michael Hanselmann's avatar
Michael Hanselmann committed
126
        try:
127 128
          logging.debug("Op %s/%s: Starting %s", idx + 1, count, op)
          op.SetStatus(constants.OP_STATUS_RUNNING, None)
Michael Hanselmann's avatar
Michael Hanselmann committed
129 130 131

          result = proc.ExecOpCode(op.input)

132 133 134
          op.SetStatus(constants.OP_STATUS_SUCCESS, result)
          logging.debug("Op %s/%s: Successfully finished %s",
                        idx + 1, count, op)
Michael Hanselmann's avatar
Michael Hanselmann committed
135
        except Exception, err:
136 137
          op.SetStatus(constants.OP_STATUS_ERROR, str(err))
          logging.debug("Op %s/%s: Error in %s", idx + 1, count, op)
Michael Hanselmann's avatar
Michael Hanselmann committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 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
          raise

    except errors.GenericError, err:
      logging.error("ganeti exception %s", exc_info=err)
    except Exception, err:
      logging.error("unhandled exception %s", exc_info=err)
    except:
      logging.error("unhandled unknown exception %s", exc_info=err)


class _JobQueueWorker(workerpool.BaseWorker):
  def RunTask(self, job):
    logging.debug("Worker %s processing job %s",
                  self.worker_id, job.id)
    # TODO: feedback function
    proc = mcpu.Processor(self.pool.context, feedback=lambda x: None)
    try:
      job.Run(proc)
    finally:
      logging.debug("Worker %s finished job %s, status = %s",
                    self.worker_id, job.id, job.GetStatus())


class _JobQueueWorkerPool(workerpool.WorkerPool):
  def __init__(self, context):
    super(_JobQueueWorkerPool, self).__init__(JOBQUEUE_THREADS,
                                              _JobQueueWorker)
    self.context = context


class JobQueue:
  """The job queue.

   """
  def __init__(self, context):
    self._lock = threading.Lock()
    self._last_job_id = 0
    self._jobs = {}
    self._wpool = _JobQueueWorkerPool(context)

  def _NewJobIdUnlocked(self):
    """Generates a new job identifier.

    Returns: A string representing the job identifier.

    """
    self._last_job_id += 1
    return str(self._last_job_id)

  def SubmitJob(self, ops):
    """Add a new job to the queue.

    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.

    Args:
    - ops: Sequence of opcodes

    """
    # Get job identifier
    self._lock.acquire()
    try:
      job_id = self._NewJobIdUnlocked()
    finally:
      self._lock.release()

    job = _QueuedJob(ops, job_id)

    # Add it to our internal queue
    self._lock.acquire()
    try:
      self._jobs[job_id] = job
    finally:
      self._lock.release()

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

    return job_id

  def ArchiveJob(self, job_id):
    raise NotImplementedError()

  def CancelJob(self, job_id):
    raise NotImplementedError()

  def _GetJobInfo(self, job, fields):
    row = []
    for fname in fields:
      if fname == "id":
        row.append(job.id)
      elif fname == "status":
        row.append(job.GetStatus())
      elif fname == "result":
        # TODO
233
        row.append([op.GetResult() for op in job._ops])
Michael Hanselmann's avatar
Michael Hanselmann committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
      else:
        raise errors.OpExecError("Invalid job query field '%s'" % fname)
    return row

  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

    """
    self._lock.acquire()
    try:
      if not job_ids:
        job_ids = self._jobs.keys()

      # TODO: define sort order?
      job_ids.sort()

      jobs = []

      for job_id in job_ids:
        job = self._jobs.get(job_id, None)
        if job is None:
          jobs.append(None)
        else:
          jobs.append(self._GetJobInfo(job, fields))

      return jobs
    finally:
      self._lock.release()

  def Shutdown(self):
    """Stops the job queue.

    """
    self._wpool.TerminateWorkers()