4 # Copyright (C) 2006, 2007, 2008 Google Inc.
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.
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.
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
22 """Module implementing the job queue handling.
24 Locking: there's a single, large lock in the L{JobQueue} class. It's
25 used by all other classes in this module.
27 @var JOBQUEUE_THREADS: the number of worker threads we start for
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
54 """Returns the current timestamp.
57 @return: the current time in the (seconds, microseconds) format
60 return utils.SplitTime(time.time())
63 class _QueuedOpCode(object):
64 """Encasulates an opcode object.
66 @ivar log: holds the execution log and consists of tuples
67 of the form C{(log_serial, timestamp, level, message)}
68 @ivar input: the OpCode we encapsulate
69 @ivar status: the current status
70 @ivar result: the result of the LU execution
71 @ivar start_timestamp: timestamp for the start of the execution
72 @ivar stop_timestamp: timestamp for the end of the execution
75 def __init__(self, op):
76 """Constructor for the _QuededOpCode.
78 @type op: L{opcodes.OpCode}
79 @param op: the opcode we encapsulate
83 self.status = constants.OP_STATUS_QUEUED
86 self.start_timestamp = None
87 self.end_timestamp = None
90 def Restore(cls, state):
91 """Restore the _QueuedOpCode from the serialized form.
94 @param state: the serialized state
96 @return: a new _QueuedOpCode instance
99 obj = _QueuedOpCode.__new__(cls)
100 obj.input = opcodes.OpCode.LoadOpCode(state["input"])
101 obj.status = state["status"]
102 obj.result = state["result"]
103 obj.log = state["log"]
104 obj.start_timestamp = state.get("start_timestamp", None)
105 obj.end_timestamp = state.get("end_timestamp", None)
109 """Serializes this _QueuedOpCode.
112 @return: the dictionary holding the serialized state
116 "input": self.input.__getstate__(),
117 "status": self.status,
118 "result": self.result,
120 "start_timestamp": self.start_timestamp,
121 "end_timestamp": self.end_timestamp,
125 class _QueuedJob(object):
126 """In-memory job representation.
128 This is what we use to track the user-submitted jobs. Locking must
129 be taken care of by users of this class.
131 @type queue: L{JobQueue}
132 @ivar queue: the parent queue
135 @ivar ops: the list of _QueuedOpCode that constitute the job
136 @type run_op_index: int
137 @ivar run_op_index: the currently executing opcode, or -1 if
138 we didn't yet start executing
139 @type log_serial: int
140 @ivar log_serial: holds the index for the next log entry
141 @ivar received_timestamp: the timestamp for when the job was received
142 @ivar start_timestmap: the timestamp for start of execution
143 @ivar end_timestamp: the timestamp for end of execution
144 @ivar change: a Condition variable we use for waiting for job changes
147 def __init__(self, queue, job_id, ops):
148 """Constructor for the _QueuedJob.
150 @type queue: L{JobQueue}
151 @param queue: our parent queue
153 @param job_id: our job id
155 @param ops: the list of opcodes we hold, which will be encapsulated
160 # TODO: use a better exception
161 raise Exception("No opcodes")
165 self.ops = [_QueuedOpCode(op) for op in ops]
166 self.run_op_index = -1
168 self.received_timestamp = TimeStampNow()
169 self.start_timestamp = None
170 self.end_timestamp = None
172 # Condition to wait for changes
173 self.change = threading.Condition(self.queue._lock)
176 def Restore(cls, queue, state):
177 """Restore a _QueuedJob from serialized state:
179 @type queue: L{JobQueue}
180 @param queue: to which queue the restored job belongs
182 @param state: the serialized state
184 @return: the restored _JobQueue instance
187 obj = _QueuedJob.__new__(cls)
190 obj.run_op_index = state["run_op_index"]
191 obj.received_timestamp = state.get("received_timestamp", None)
192 obj.start_timestamp = state.get("start_timestamp", None)
193 obj.end_timestamp = state.get("end_timestamp", None)
197 for op_state in state["ops"]:
198 op = _QueuedOpCode.Restore(op_state)
199 for log_entry in op.log:
200 obj.log_serial = max(obj.log_serial, log_entry[0])
203 # Condition to wait for changes
204 obj.change = threading.Condition(obj.queue._lock)
209 """Serialize the _JobQueue instance.
212 @return: the serialized state
217 "ops": [op.Serialize() for op in self.ops],
218 "run_op_index": self.run_op_index,
219 "start_timestamp": self.start_timestamp,
220 "end_timestamp": self.end_timestamp,
221 "received_timestamp": self.received_timestamp,
224 def CalcStatus(self):
225 """Compute the status of this job.
227 This function iterates over all the _QueuedOpCodes in the job and
228 based on their status, computes the job status.
231 - if we find a cancelled, or finished with error, the job
232 status will be the same
233 - otherwise, the last opcode with the status one of:
237 will determine the job status
239 - otherwise, it means either all opcodes are queued, or success,
240 and the job status will be the same
242 @return: the job status
245 status = constants.JOB_STATUS_QUEUED
249 if op.status == constants.OP_STATUS_SUCCESS:
254 if op.status == constants.OP_STATUS_QUEUED:
256 elif op.status == constants.OP_STATUS_WAITLOCK:
257 status = constants.JOB_STATUS_WAITLOCK
258 elif op.status == constants.OP_STATUS_RUNNING:
259 status = constants.JOB_STATUS_RUNNING
260 elif op.status == constants.OP_STATUS_ERROR:
261 status = constants.JOB_STATUS_ERROR
262 # The whole job fails if one opcode failed
264 elif op.status == constants.OP_STATUS_CANCELED:
265 status = constants.OP_STATUS_CANCELED
269 status = constants.JOB_STATUS_SUCCESS
273 def GetLogEntries(self, newer_than):
274 """Selectively returns the log entries.
276 @type newer_than: None or int
277 @param newer_than: if this is None, return all log enties,
278 otherwise return only the log entries with serial higher
281 @return: the list of the log entries selected
284 if newer_than is None:
291 entries.extend(filter(lambda entry: entry[0] > serial, op.log))
296 class _JobQueueWorker(workerpool.BaseWorker):
297 """The actual job workers.
300 def _NotifyStart(self):
301 """Mark the opcode as running, not lock-waiting.
303 This is called from the mcpu code as a notifier function, when the
304 LU is finally about to start the Exec() method. Of course, to have
305 end-user visible results, the opcode must be initially (before
306 calling into Processor.ExecOpCode) set to OP_STATUS_WAITLOCK.
309 assert self.queue, "Queue attribute is missing"
310 assert self.opcode, "Opcode attribute is missing"
314 self.opcode.status = constants.OP_STATUS_RUNNING
318 def RunTask(self, job):
321 This functions processes a job. It is closely tied to the _QueuedJob and
322 _QueuedOpCode classes.
324 @type job: L{_QueuedJob}
325 @param job: the job to be processed
328 logging.debug("Worker %s processing job %s",
329 self.worker_id, job.id)
330 proc = mcpu.Processor(self.pool.queue.context)
331 self.queue = queue = job.queue
335 for idx, op in enumerate(job.ops):
337 logging.debug("Op %s/%s: Starting %s", idx + 1, count, op)
341 job.run_op_index = idx
342 op.status = constants.OP_STATUS_WAITLOCK
344 op.start_timestamp = TimeStampNow()
345 if idx == 0: # first opcode
346 job.start_timestamp = op.start_timestamp
347 queue.UpdateJobUnlocked(job)
349 input_opcode = op.input
354 """Append a log entry.
360 log_type = constants.ELOG_MESSAGE
363 log_type, log_msg = args
365 # The time is split to make serialization easier and not lose
367 timestamp = utils.SplitTime(time.time())
372 op.log.append((job.log_serial, timestamp, log_type, log_msg))
374 job.change.notifyAll()
378 # Make sure not to hold lock while _Log is called
380 result = proc.ExecOpCode(input_opcode, _Log, self._NotifyStart)
384 op.status = constants.OP_STATUS_SUCCESS
386 op.end_timestamp = TimeStampNow()
387 queue.UpdateJobUnlocked(job)
391 logging.debug("Op %s/%s: Successfully finished %s",
393 except Exception, err:
397 op.status = constants.OP_STATUS_ERROR
399 op.end_timestamp = TimeStampNow()
400 logging.debug("Op %s/%s: Error in %s", idx + 1, count, op)
402 queue.UpdateJobUnlocked(job)
407 except errors.GenericError, err:
408 logging.exception("Ganeti exception")
410 logging.exception("Unhandled exception")
416 job.end_timestamp = TimeStampNow()
417 queue.UpdateJobUnlocked(job)
420 status = job.CalcStatus()
423 logging.debug("Worker %s finished job %s, status = %s",
424 self.worker_id, job_id, status)
427 class _JobQueueWorkerPool(workerpool.WorkerPool):
428 """Simple class implementing a job-processing workerpool.
431 def __init__(self, queue):
432 super(_JobQueueWorkerPool, self).__init__(JOBQUEUE_THREADS,
437 class JobQueue(object):
438 """Quue used to manaage the jobs.
440 @cvar _RE_JOB_FILE: regex matching the valid job file names
443 _RE_JOB_FILE = re.compile(r"^job-(%s)$" % constants.JOB_ID_TEMPLATE)
445 def _RequireOpenQueue(fn):
446 """Decorator for "public" functions.
448 This function should be used for all 'public' functions. That is,
449 functions usually called from other classes.
451 @warning: Use this decorator only after utils.LockedMethod!
460 def wrapper(self, *args, **kwargs):
461 assert self._queue_lock is not None, "Queue should be open"
462 return fn(self, *args, **kwargs)
465 def __init__(self, context):
466 """Constructor for JobQueue.
468 The constructor will initialize the job queue object and then
469 start loading the current jobs from disk, either for starting them
470 (if they were queue) or for aborting them (if they were already
473 @type context: GanetiContext
474 @param context: the context object for access to the configuration
475 data and other ganeti objects
478 self.context = context
479 self._memcache = weakref.WeakValueDictionary()
480 self._my_hostname = utils.HostInfo().name
483 self._lock = threading.Lock()
484 self.acquire = self._lock.acquire
485 self.release = self._lock.release
488 self._queue_lock = jstore.InitAndVerifyQueue(must_lock=True)
491 self._last_serial = jstore.ReadSerial()
492 assert self._last_serial is not None, ("Serial file was modified between"
493 " check in jstore and here")
495 # Get initial list of nodes
496 self._nodes = dict((n.name, n.primary_ip)
497 for n in self.context.cfg.GetAllNodesInfo().values())
501 del self._nodes[self._my_hostname]
505 # TODO: Check consistency across nodes
508 self._wpool = _JobQueueWorkerPool(self)
510 # We need to lock here because WorkerPool.AddTask() may start a job while
511 # we're still doing our work.
514 for job in self._GetJobsUnlocked(None):
515 # a failure in loading the job can cause 'None' to be returned
519 status = job.CalcStatus()
521 if status in (constants.JOB_STATUS_QUEUED, ):
522 self._wpool.AddTask(job)
524 elif status in (constants.JOB_STATUS_RUNNING,
525 constants.JOB_STATUS_WAITLOCK):
526 logging.warning("Unfinished job %s found: %s", job.id, job)
529 op.status = constants.OP_STATUS_ERROR
530 op.result = "Unclean master daemon shutdown"
532 self.UpdateJobUnlocked(job)
536 self._wpool.TerminateWorkers()
541 def AddNode(self, node):
542 """Register a new node with the queue.
544 @type node: L{objects.Node}
545 @param node: the node object to be added
548 node_name = node.name
549 assert node_name != self._my_hostname
551 # Clean queue directory on added node
552 rpc.RpcRunner.call_jobqueue_purge(node_name)
554 # Upload the whole queue excluding archived jobs
555 files = [self._GetJobPath(job_id) for job_id in self._GetJobIDsUnlocked()]
557 # Upload current serial file
558 files.append(constants.JOB_QUEUE_SERIAL_FILE)
560 for file_name in files:
562 fd = open(file_name, "r")
568 result = rpc.RpcRunner.call_jobqueue_update([node_name],
571 if not result[node_name]:
572 logging.error("Failed to upload %s to %s", file_name, node_name)
574 self._nodes[node_name] = node.primary_ip
578 def RemoveNode(self, node_name):
579 """Callback called when removing nodes from the cluster.
582 @param node_name: the name of the node to remove
586 # The queue is removed by the "leave node" RPC call.
587 del self._nodes[node_name]
591 def _CheckRpcResult(self, result, nodes, failmsg):
592 """Verifies the status of an RPC call.
594 Since we aim to keep consistency should this node (the current
595 master) fail, we will log errors if our rpc fail, and especially
596 log the case when more than half of the nodes failes.
598 @param result: the data as returned from the rpc call
600 @param nodes: the list of nodes we made the call to
602 @param failmsg: the identifier to be used for logging
615 logging.error("%s failed on %s", failmsg, ", ".join(failed))
617 # +1 for the master node
618 if (len(success) + 1) < len(failed):
619 # TODO: Handle failing nodes
620 logging.error("More than half of the nodes failed")
622 def _GetNodeIp(self):
623 """Helper for returning the node name/ip list.
626 @return: a tuple of two lists, the first one with the node
627 names and the second one with the node addresses
630 name_list = self._nodes.keys()
631 addr_list = [self._nodes[name] for name in name_list]
632 return name_list, addr_list
634 def _WriteAndReplicateFileUnlocked(self, file_name, data):
635 """Writes a file locally and then replicates it to all nodes.
637 This function will replace the contents of a file on the local
638 node and then replicate it to all the other nodes we have.
641 @param file_name: the path of the file to be replicated
643 @param data: the new contents of the file
646 utils.WriteFile(file_name, data=data)
648 names, addrs = self._GetNodeIp()
649 result = rpc.RpcRunner.call_jobqueue_update(names, addrs, file_name, data)
650 self._CheckRpcResult(result, self._nodes,
651 "Updating %s" % file_name)
653 def _RenameFileUnlocked(self, old, new):
654 """Renames a file locally and then replicate the change.
656 This function will rename a file in the local queue directory
657 and then replicate this rename to all the other nodes we have.
660 @param old: the current name of the file
662 @param new: the new name of the file
667 names, addrs = self._GetNodeIp()
668 result = rpc.RpcRunner.call_jobqueue_rename(names, addrs, old, new)
669 self._CheckRpcResult(result, self._nodes,
670 "Moving %s to %s" % (old, new))
672 def _FormatJobID(self, job_id):
673 """Convert a job ID to string format.
675 Currently this just does C{str(job_id)} after performing some
676 checks, but if we want to change the job id format this will
677 abstract this change.
679 @type job_id: int or long
680 @param job_id: the numeric job id
682 @return: the formatted job id
685 if not isinstance(job_id, (int, long)):
686 raise errors.ProgrammerError("Job ID '%s' not numeric" % job_id)
688 raise errors.ProgrammerError("Job ID %s is negative" % job_id)
692 def _NewSerialUnlocked(self):
693 """Generates a new job identifier.
695 Job identifiers are unique during the lifetime of a cluster.
698 @return: a string representing the job identifier.
702 serial = self._last_serial + 1
705 self._WriteAndReplicateFileUnlocked(constants.JOB_QUEUE_SERIAL_FILE,
708 # Keep it only if we were able to write the file
709 self._last_serial = serial
711 return self._FormatJobID(serial)
714 def _GetJobPath(job_id):
715 """Returns the job file for a given job id.
718 @param job_id: the job identifier
720 @return: the path to the job file
723 return os.path.join(constants.QUEUE_DIR, "job-%s" % job_id)
726 def _GetArchivedJobPath(job_id):
727 """Returns the archived job file for a give job id.
730 @param job_id: the job identifier
732 @return: the path to the archived job file
735 return os.path.join(constants.JOB_QUEUE_ARCHIVE_DIR, "job-%s" % job_id)
738 def _ExtractJobID(cls, name):
739 """Extract the job id from a filename.
742 @param name: the job filename
743 @rtype: job id or None
744 @return: the job id corresponding to the given filename,
745 or None if the filename does not represent a valid
749 m = cls._RE_JOB_FILE.match(name)
755 def _GetJobIDsUnlocked(self, archived=False):
756 """Return all known job IDs.
758 If the parameter archived is True, archived jobs IDs will be
759 included. Currently this argument is unused.
761 The method only looks at disk because it's a requirement that all
762 jobs are present on disk (so in the _memcache we don't have any
766 @return: the list of job IDs
769 jlist = [self._ExtractJobID(name) for name in self._ListJobFiles()]
770 jlist = utils.NiceSort(jlist)
773 def _ListJobFiles(self):
774 """Returns the list of current job files.
777 @return: the list of job file names
780 return [name for name in utils.ListVisibleFiles(constants.QUEUE_DIR)
781 if self._RE_JOB_FILE.match(name)]
783 def _LoadJobUnlocked(self, job_id):
784 """Loads a job from the disk or memory.
786 Given a job id, this will return the cached job object if
787 existing, or try to load the job from the disk. If loading from
788 disk, it will also add the job to the cache.
790 @param job_id: the job id
791 @rtype: L{_QueuedJob} or None
792 @return: either None or the job object
795 job = self._memcache.get(job_id, None)
797 logging.debug("Found job %s in memcache", job_id)
800 filepath = self._GetJobPath(job_id)
801 logging.debug("Loading job from %s", filepath)
803 fd = open(filepath, "r")
805 if err.errno in (errno.ENOENT, ):
809 data = serializer.LoadJson(fd.read())
814 job = _QueuedJob.Restore(self, data)
815 except Exception, err:
816 new_path = self._GetArchivedJobPath(job_id)
817 if filepath == new_path:
818 # job already archived (future case)
819 logging.exception("Can't parse job %s", job_id)
822 logging.exception("Can't parse job %s, will archive.", job_id)
823 self._RenameFileUnlocked(filepath, new_path)
826 self._memcache[job_id] = job
827 logging.debug("Added job %s to the cache", job_id)
830 def _GetJobsUnlocked(self, job_ids):
831 """Return a list of jobs based on their IDs.
834 @param job_ids: either an empty list (meaning all jobs),
837 @return: the list of job objects
841 job_ids = self._GetJobIDsUnlocked()
843 return [self._LoadJobUnlocked(job_id) for job_id in job_ids]
846 def _IsQueueMarkedDrain():
847 """Check if the queue is marked from drain.
849 This currently uses the queue drain file, which makes it a
850 per-node flag. In the future this can be moved to the config file.
853 @return: True of the job queue is marked for draining
856 return os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
859 def SetDrainFlag(drain_flag):
860 """Sets the drain flag for the queue.
862 This is similar to the function L{backend.JobQueueSetDrainFlag},
863 and in the future we might merge them.
865 @type drain_flag: boolean
866 @param drain_flag: wheter to set or unset the drain flag
870 utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
872 utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
877 def SubmitJob(self, ops):
878 """Create and store a new job.
880 This enters the job into our job queue and also puts it on the new
881 queue, in order for it to be picked up by the queue processors.
884 @param ops: The list of OpCodes that will become the new job.
886 @return: the job ID of the newly created job
887 @raise errors.JobQueueDrainError: if the job is marked for draining
890 if self._IsQueueMarkedDrain():
891 raise errors.JobQueueDrainError()
893 job_id = self._NewSerialUnlocked()
894 job = _QueuedJob(self, job_id, ops)
897 self.UpdateJobUnlocked(job)
899 logging.debug("Adding new job %s to the cache", job_id)
900 self._memcache[job_id] = job
903 self._wpool.AddTask(job)
908 def UpdateJobUnlocked(self, job):
909 """Update a job's on disk storage.
911 After a job has been modified, this function needs to be called in
912 order to write the changes to disk and replicate them to the other
915 @type job: L{_QueuedJob}
916 @param job: the changed job
919 filename = self._GetJobPath(job.id)
920 data = serializer.DumpJson(job.Serialize(), indent=False)
921 logging.debug("Writing job %s to %s", job.id, filename)
922 self._WriteAndReplicateFileUnlocked(filename, data)
924 # Notify waiters about potential changes
925 job.change.notifyAll()
929 def WaitForJobChanges(self, job_id, fields, prev_job_info, prev_log_serial,
931 """Waits for changes in a job.
934 @param job_id: Job identifier
935 @type fields: list of strings
936 @param fields: Which fields to check for changes
937 @type prev_job_info: list or None
938 @param prev_job_info: Last job information returned
939 @type prev_log_serial: int
940 @param prev_log_serial: Last job message serial number
942 @param timeout: maximum time to wait
943 @rtype: tuple (job info, log entries)
944 @return: a tuple of the job information as required via
945 the fields parameter, and the log entries as a list
947 if the job has not changed and the timeout has expired,
948 we instead return a special value,
949 L{constants.JOB_NOTCHANGED}, which should be interpreted
950 as such by the clients
953 logging.debug("Waiting for changes in job %s", job_id)
954 end_time = time.time() + timeout
956 delta_time = end_time - time.time()
958 return constants.JOB_NOTCHANGED
960 job = self._LoadJobUnlocked(job_id)
962 logging.debug("Job %s not found", job_id)
965 status = job.CalcStatus()
966 job_info = self._GetJobInfoUnlocked(job, fields)
967 log_entries = job.GetLogEntries(prev_log_serial)
969 # Serializing and deserializing data can cause type changes (e.g. from
970 # tuple to list) or precision loss. We're doing it here so that we get
971 # the same modifications as the data received from the client. Without
972 # this, the comparison afterwards might fail without the data being
973 # significantly different.
974 job_info = serializer.LoadJson(serializer.DumpJson(job_info))
975 log_entries = serializer.LoadJson(serializer.DumpJson(log_entries))
977 if status not in (constants.JOB_STATUS_QUEUED,
978 constants.JOB_STATUS_RUNNING,
979 constants.JOB_STATUS_WAITLOCK):
980 # Don't even try to wait if the job is no longer running, there will be
984 if (prev_job_info != job_info or
985 (log_entries and prev_log_serial != log_entries[0][0])):
988 logging.debug("Waiting again")
990 # Release the queue lock while waiting
991 job.change.wait(delta_time)
993 logging.debug("Job %s changed", job_id)
995 return (job_info, log_entries)
999 def CancelJob(self, job_id):
1002 This will only succeed if the job has not started yet.
1004 @type job_id: string
1005 @param job_id: job ID of job to be cancelled.
1008 logging.debug("Cancelling job %s", job_id)
1010 job = self._LoadJobUnlocked(job_id)
1012 logging.debug("Job %s not found", job_id)
1015 if job.CalcStatus() not in (constants.JOB_STATUS_QUEUED,):
1016 logging.debug("Job %s is no longer in the queue", job.id)
1021 op.status = constants.OP_STATUS_ERROR
1022 op.result = "Job cancelled by request"
1024 self.UpdateJobUnlocked(job)
1027 def _ArchiveJobUnlocked(self, job_id):
1030 @type job_id: string
1031 @param job_id: Job ID of job to be archived.
1034 logging.info("Archiving job %s", job_id)
1036 job = self._LoadJobUnlocked(job_id)
1038 logging.debug("Job %s not found", job_id)
1041 if job.CalcStatus() not in (constants.JOB_STATUS_CANCELED,
1042 constants.JOB_STATUS_SUCCESS,
1043 constants.JOB_STATUS_ERROR):
1044 logging.debug("Job %s is not yet done", job.id)
1047 old = self._GetJobPath(job.id)
1048 new = self._GetArchivedJobPath(job.id)
1050 self._RenameFileUnlocked(old, new)
1052 logging.debug("Successfully archived job %s", job.id)
1056 def ArchiveJob(self, job_id):
1059 This is just a wrapper over L{_ArchiveJobUnlocked}.
1061 @type job_id: string
1062 @param job_id: Job ID of job to be archived.
1065 return self._ArchiveJobUnlocked(job_id)
1069 def AutoArchiveJobs(self, age):
1070 """Archives all jobs based on age.
1072 The method will archive all jobs which are older than the age
1073 parameter. For jobs that don't have an end timestamp, the start
1074 timestamp will be considered. The special '-1' age will cause
1075 archival of all jobs (that are not running or queued).
1078 @param age: the minimum age in seconds
1081 logging.info("Archiving jobs with age more than %s seconds", age)
1084 for jid in self._GetJobIDsUnlocked(archived=False):
1085 job = self._LoadJobUnlocked(jid)
1086 if job.CalcStatus() not in (constants.OP_STATUS_SUCCESS,
1087 constants.OP_STATUS_ERROR,
1088 constants.OP_STATUS_CANCELED):
1090 if job.end_timestamp is None:
1091 if job.start_timestamp is None:
1092 job_age = job.received_timestamp
1094 job_age = job.start_timestamp
1096 job_age = job.end_timestamp
1098 if age == -1 or now - job_age[0] > age:
1099 self._ArchiveJobUnlocked(jid)
1101 def _GetJobInfoUnlocked(self, job, fields):
1102 """Returns information about a job.
1104 @type job: L{_QueuedJob}
1105 @param job: the job which we query
1107 @param fields: names of fields to return
1109 @return: list with one element for each field
1110 @raise errors.OpExecError: when an invalid field
1115 for fname in fields:
1118 elif fname == "status":
1119 row.append(job.CalcStatus())
1120 elif fname == "ops":
1121 row.append([op.input.__getstate__() for op in job.ops])
1122 elif fname == "opresult":
1123 row.append([op.result for op in job.ops])
1124 elif fname == "opstatus":
1125 row.append([op.status for op in job.ops])
1126 elif fname == "oplog":
1127 row.append([op.log for op in job.ops])
1128 elif fname == "opstart":
1129 row.append([op.start_timestamp for op in job.ops])
1130 elif fname == "opend":
1131 row.append([op.end_timestamp for op in job.ops])
1132 elif fname == "received_ts":
1133 row.append(job.received_timestamp)
1134 elif fname == "start_ts":
1135 row.append(job.start_timestamp)
1136 elif fname == "end_ts":
1137 row.append(job.end_timestamp)
1138 elif fname == "summary":
1139 row.append([op.input.Summary() for op in job.ops])
1141 raise errors.OpExecError("Invalid job query field '%s'" % fname)
1146 def QueryJobs(self, job_ids, fields):
1147 """Returns a list of jobs in queue.
1149 This is a wrapper of L{_GetJobsUnlocked}, which actually does the
1150 processing for each job.
1153 @param job_ids: sequence of job identifiers or None for all
1155 @param fields: names of fields to return
1157 @return: list one element per job, each element being list with
1158 the requested fields
1163 for job in self._GetJobsUnlocked(job_ids):
1167 jobs.append(self._GetJobInfoUnlocked(job, fields))
1174 """Stops the job queue.
1176 This shutdowns all the worker threads an closes the queue.
1179 self._wpool.TerminateWorkers()
1181 self._queue_lock.Close()
1182 self._queue_lock = None