Unbreak build after merge 2ea64524ce
[ganeti-local] / lib / mcpu.py
1 #
2 #
3
4 # Copyright (C) 2006, 2007, 2011 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 logic behind the cluster operations
23
24 This module implements the logic for doing operations in the cluster. There
25 are two kinds of classes defined:
26   - logical units, which know how to deal with their specific opcode only
27   - the processor, which dispatches the opcodes to their logical units
28
29 """
30
31 import logging
32 import random
33 import time
34
35 from ganeti import opcodes
36 from ganeti import constants
37 from ganeti import errors
38 from ganeti import cmdlib
39 from ganeti import locking
40 from ganeti import utils
41 from ganeti import compat
42
43
44 _OP_PREFIX = "Op"
45 _LU_PREFIX = "LU"
46
47
48 class LockAcquireTimeout(Exception):
49   """Exception to report timeouts on acquiring locks.
50
51   """
52
53
54 def _CalculateLockAttemptTimeouts():
55   """Calculate timeouts for lock attempts.
56
57   """
58   result = [constants.LOCK_ATTEMPTS_MINWAIT]
59   running_sum = result[0]
60
61   # Wait for a total of at least LOCK_ATTEMPTS_TIMEOUT before doing a
62   # blocking acquire
63   while running_sum < constants.LOCK_ATTEMPTS_TIMEOUT:
64     timeout = (result[-1] * 1.05) ** 1.25
65
66     # Cap max timeout. This gives other jobs a chance to run even if
67     # we're still trying to get our locks, before finally moving to a
68     # blocking acquire.
69     timeout = min(timeout, constants.LOCK_ATTEMPTS_MAXWAIT)
70     # And also cap the lower boundary for safety
71     timeout = max(timeout, constants.LOCK_ATTEMPTS_MINWAIT)
72
73     result.append(timeout)
74     running_sum += timeout
75
76   return result
77
78
79 class LockAttemptTimeoutStrategy(object):
80   """Class with lock acquire timeout strategy.
81
82   """
83   __slots__ = [
84     "_timeouts",
85     "_random_fn",
86     "_time_fn",
87     ]
88
89   _TIMEOUT_PER_ATTEMPT = _CalculateLockAttemptTimeouts()
90
91   def __init__(self, _time_fn=time.time, _random_fn=random.random):
92     """Initializes this class.
93
94     @param _time_fn: Time function for unittests
95     @param _random_fn: Random number generator for unittests
96
97     """
98     object.__init__(self)
99
100     self._timeouts = iter(self._TIMEOUT_PER_ATTEMPT)
101     self._time_fn = _time_fn
102     self._random_fn = _random_fn
103
104   def NextAttempt(self):
105     """Returns the timeout for the next attempt.
106
107     """
108     try:
109       timeout = self._timeouts.next()
110     except StopIteration:
111       # No more timeouts, do blocking acquire
112       timeout = None
113
114     if timeout is not None:
115       # Add a small variation (-/+ 5%) to timeout. This helps in situations
116       # where two or more jobs are fighting for the same lock(s).
117       variation_range = timeout * 0.1
118       timeout += ((self._random_fn() * variation_range) -
119                   (variation_range * 0.5))
120
121     return timeout
122
123
124 class OpExecCbBase: # pylint: disable=W0232
125   """Base class for OpCode execution callbacks.
126
127   """
128   def NotifyStart(self):
129     """Called when we are about to execute the LU.
130
131     This function is called when we're about to start the lu's Exec() method,
132     that is, after we have acquired all locks.
133
134     """
135
136   def Feedback(self, *args):
137     """Sends feedback from the LU code to the end-user.
138
139     """
140
141   def CheckCancel(self):
142     """Check whether job has been cancelled.
143
144     """
145
146   def SubmitManyJobs(self, jobs):
147     """Submits jobs for processing.
148
149     See L{jqueue.JobQueue.SubmitManyJobs}.
150
151     """
152     raise NotImplementedError
153
154
155 def _LUNameForOpName(opname):
156   """Computes the LU name for a given OpCode name.
157
158   """
159   assert opname.startswith(_OP_PREFIX), \
160       "Invalid OpCode name, doesn't start with %s: %s" % (_OP_PREFIX, opname)
161
162   return _LU_PREFIX + opname[len(_OP_PREFIX):]
163
164
165 def _ComputeDispatchTable():
166   """Computes the opcode-to-lu dispatch table.
167
168   """
169   return dict((op, getattr(cmdlib, _LUNameForOpName(op.__name__)))
170               for op in opcodes.OP_MAPPING.values()
171               if op.WITH_LU)
172
173
174 def _RpcResultsToHooksResults(rpc_results):
175   """Function to convert RPC results to the format expected by HooksMaster.
176
177   @type rpc_results: dict(node: L{rpc.RpcResult})
178   @param rpc_results: RPC results
179   @rtype: dict(node: (fail_msg, offline, hooks_results))
180   @return: RPC results unpacked according to the format expected by
181     L({mcpu.HooksMaster}
182
183   """
184   return dict((node, (rpc_res.fail_msg, rpc_res.offline, rpc_res.payload))
185               for (node, rpc_res) in rpc_results.items())
186
187
188 class Processor(object):
189   """Object which runs OpCodes"""
190   DISPATCH_TABLE = _ComputeDispatchTable()
191
192   def __init__(self, context, ec_id):
193     """Constructor for Processor
194
195     @type context: GanetiContext
196     @param context: global Ganeti context
197     @type ec_id: string
198     @param ec_id: execution context identifier
199
200     """
201     self.context = context
202     self._ec_id = ec_id
203     self._cbs = None
204     self.rpc = context.rpc
205     self.hmclass = HooksMaster
206
207   def _AcquireLocks(self, level, names, shared, timeout, priority):
208     """Acquires locks via the Ganeti lock manager.
209
210     @type level: int
211     @param level: Lock level
212     @type names: list or string
213     @param names: Lock names
214     @type shared: bool
215     @param shared: Whether the locks should be acquired in shared mode
216     @type timeout: None or float
217     @param timeout: Timeout for acquiring the locks
218     @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
219         amount of time
220
221     """
222     if self._cbs:
223       self._cbs.CheckCancel()
224
225     acquired = self.context.glm.acquire(level, names, shared=shared,
226                                         timeout=timeout, priority=priority)
227
228     if acquired is None:
229       raise LockAcquireTimeout()
230
231     return acquired
232
233   def _ProcessResult(self, result):
234     """Examines opcode result.
235
236     If necessary, additional processing on the result is done.
237
238     """
239     if isinstance(result, cmdlib.ResultWithJobs):
240       # Submit jobs
241       job_submission = self._cbs.SubmitManyJobs(result.jobs)
242
243       # Build dictionary
244       result = result.other
245
246       assert constants.JOB_IDS_KEY not in result, \
247         "Key '%s' found in additional return values" % constants.JOB_IDS_KEY
248
249       result[constants.JOB_IDS_KEY] = job_submission
250
251     return result
252
253   def _ExecLU(self, lu):
254     """Logical Unit execution sequence.
255
256     """
257     write_count = self.context.cfg.write_count
258     lu.CheckPrereq()
259
260     hm = self.BuildHooksManager(lu)
261     h_results = hm.RunPhase(constants.HOOKS_PHASE_PRE)
262     lu.HooksCallBack(constants.HOOKS_PHASE_PRE, h_results,
263                      self.Log, None)
264
265     if getattr(lu.op, "dry_run", False):
266       # in this mode, no post-hooks are run, and the config is not
267       # written (as it might have been modified by another LU, and we
268       # shouldn't do writeout on behalf of other threads
269       self.LogInfo("dry-run mode requested, not actually executing"
270                    " the operation")
271       return lu.dry_run_result
272
273     try:
274       result = self._ProcessResult(lu.Exec(self.Log))
275       h_results = hm.RunPhase(constants.HOOKS_PHASE_POST)
276       result = lu.HooksCallBack(constants.HOOKS_PHASE_POST, h_results,
277                                 self.Log, result)
278     finally:
279       # FIXME: This needs locks if not lu_class.REQ_BGL
280       if write_count != self.context.cfg.write_count:
281         hm.RunConfigUpdate()
282
283     return result
284
285   def BuildHooksManager(self, lu):
286     return self.hmclass.BuildFromLu(lu.rpc.call_hooks_runner, lu)
287
288   def _LockAndExecLU(self, lu, level, calc_timeout, priority):
289     """Execute a Logical Unit, with the needed locks.
290
291     This is a recursive function that starts locking the given level, and
292     proceeds up, till there are no more locks to acquire. Then it executes the
293     given LU and its opcodes.
294
295     """
296     adding_locks = level in lu.add_locks
297     acquiring_locks = level in lu.needed_locks
298     if level not in locking.LEVELS:
299       if self._cbs:
300         self._cbs.NotifyStart()
301
302       result = self._ExecLU(lu)
303
304     elif adding_locks and acquiring_locks:
305       # We could both acquire and add locks at the same level, but for now we
306       # don't need this, so we'll avoid the complicated code needed.
307       raise NotImplementedError("Can't declare locks to acquire when adding"
308                                 " others")
309
310     elif adding_locks or acquiring_locks:
311       lu.DeclareLocks(level)
312       share = lu.share_locks[level]
313
314       try:
315         assert adding_locks ^ acquiring_locks, \
316           "Locks must be either added or acquired"
317
318         if acquiring_locks:
319           # Acquiring locks
320           needed_locks = lu.needed_locks[level]
321
322           self._AcquireLocks(level, needed_locks, share,
323                              calc_timeout(), priority)
324         else:
325           # Adding locks
326           add_locks = lu.add_locks[level]
327           lu.remove_locks[level] = add_locks
328
329           try:
330             self.context.glm.add(level, add_locks, acquired=1, shared=share)
331           except errors.LockError:
332             raise errors.OpPrereqError(
333               "Couldn't add locks (%s), probably because of a race condition"
334               " with another job, who added them first" % add_locks,
335               errors.ECODE_FAULT)
336
337         try:
338           result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
339         finally:
340           if level in lu.remove_locks:
341             self.context.glm.remove(level, lu.remove_locks[level])
342       finally:
343         if self.context.glm.is_owned(level):
344           self.context.glm.release(level)
345
346     else:
347       result = self._LockAndExecLU(lu, level + 1, calc_timeout, priority)
348
349     return result
350
351   def ExecOpCode(self, op, cbs, timeout=None, priority=None):
352     """Execute an opcode.
353
354     @type op: an OpCode instance
355     @param op: the opcode to be executed
356     @type cbs: L{OpExecCbBase}
357     @param cbs: Runtime callbacks
358     @type timeout: float or None
359     @param timeout: Maximum time to acquire all locks, None for no timeout
360     @type priority: number or None
361     @param priority: Priority for acquiring lock(s)
362     @raise LockAcquireTimeout: In case locks couldn't be acquired in specified
363         amount of time
364
365     """
366     if not isinstance(op, opcodes.OpCode):
367       raise errors.ProgrammerError("Non-opcode instance passed"
368                                    " to ExecOpcode (%s)" % type(op))
369
370     lu_class = self.DISPATCH_TABLE.get(op.__class__, None)
371     if lu_class is None:
372       raise errors.OpCodeUnknown("Unknown opcode")
373
374     if timeout is None:
375       calc_timeout = lambda: None
376     else:
377       calc_timeout = utils.RunningTimeout(timeout, False).Remaining
378
379     self._cbs = cbs
380     try:
381       # Acquire the Big Ganeti Lock exclusively if this LU requires it,
382       # and in a shared fashion otherwise (to prevent concurrent run with
383       # an exclusive LU.
384       self._AcquireLocks(locking.LEVEL_CLUSTER, locking.BGL,
385                           not lu_class.REQ_BGL, calc_timeout(),
386                           priority)
387       try:
388         lu = lu_class(self, op, self.context, self.rpc)
389         lu.ExpandNames()
390         assert lu.needed_locks is not None, "needed_locks not set by LU"
391
392         try:
393           result = self._LockAndExecLU(lu, locking.LEVEL_INSTANCE, calc_timeout,
394                                        priority)
395         finally:
396           if self._ec_id:
397             self.context.cfg.DropECReservations(self._ec_id)
398       finally:
399         self.context.glm.release(locking.LEVEL_CLUSTER)
400     finally:
401       self._cbs = None
402
403     resultcheck_fn = op.OP_RESULT
404     if not (resultcheck_fn is None or resultcheck_fn(result)):
405       logging.error("Expected opcode result matching %s, got %s",
406                     resultcheck_fn, result)
407       raise errors.OpResultError("Opcode result does not match %s" %
408                                  resultcheck_fn)
409
410     return result
411
412   def Log(self, *args):
413     """Forward call to feedback callback function.
414
415     """
416     if self._cbs:
417       self._cbs.Feedback(*args)
418
419   def LogStep(self, current, total, message):
420     """Log a change in LU execution progress.
421
422     """
423     logging.debug("Step %d/%d %s", current, total, message)
424     self.Log("STEP %d/%d %s" % (current, total, message))
425
426   def LogWarning(self, message, *args, **kwargs):
427     """Log a warning to the logs and the user.
428
429     The optional keyword argument is 'hint' and can be used to show a
430     hint to the user (presumably related to the warning). If the
431     message is empty, it will not be printed at all, allowing one to
432     show only a hint.
433
434     """
435     assert not kwargs or (len(kwargs) == 1 and "hint" in kwargs), \
436            "Invalid keyword arguments for LogWarning (%s)" % str(kwargs)
437     if args:
438       message = message % tuple(args)
439     if message:
440       logging.warning(message)
441       self.Log(" - WARNING: %s" % message)
442     if "hint" in kwargs:
443       self.Log("      Hint: %s" % kwargs["hint"])
444
445   def LogInfo(self, message, *args):
446     """Log an informational message to the logs and the user.
447
448     """
449     if args:
450       message = message % tuple(args)
451     logging.info(message)
452     self.Log(" - INFO: %s" % message)
453
454   def GetECId(self):
455     """Returns the current execution context ID.
456
457     """
458     if not self._ec_id:
459       raise errors.ProgrammerError("Tried to use execution context id when"
460                                    " not set")
461     return self._ec_id
462
463
464 class HooksMaster(object):
465   def __init__(self, opcode, hooks_path, nodes, hooks_execution_fn,
466     hooks_results_adapt_fn, build_env_fn, log_fn, htype=None, cluster_name=None,
467     master_name=None):
468     """Base class for hooks masters.
469
470     This class invokes the execution of hooks according to the behaviour
471     specified by its parameters.
472
473     @type opcode: string
474     @param opcode: opcode of the operation to which the hooks are tied
475     @type hooks_path: string
476     @param hooks_path: prefix of the hooks directories
477     @type nodes: 2-tuple of lists
478     @param nodes: 2-tuple of lists containing nodes on which pre-hooks must be
479       run and nodes on which post-hooks must be run
480     @type hooks_execution_fn: function that accepts the following parameters:
481       (node_list, hooks_path, phase, environment)
482     @param hooks_execution_fn: function that will execute the hooks; can be
483       None, indicating that no conversion is necessary.
484     @type hooks_results_adapt_fn: function
485     @param hooks_results_adapt_fn: function that will adapt the return value of
486       hooks_execution_fn to the format expected by RunPhase
487     @type build_env_fn: function that returns a dictionary having strings as
488       keys
489     @param build_env_fn: function that builds the environment for the hooks
490     @type log_fn: function that accepts a string
491     @param log_fn: logging function
492     @type htype: string or None
493     @param htype: None or one of L{constants.HTYPE_CLUSTER},
494      L{constants.HTYPE_NODE}, L{constants.HTYPE_INSTANCE}
495     @type cluster_name: string
496     @param cluster_name: name of the cluster
497     @type master_name: string
498     @param master_name: name of the master
499
500     """
501     self.opcode = opcode
502     self.hooks_path = hooks_path
503     self.hooks_execution_fn = hooks_execution_fn
504     self.hooks_results_adapt_fn = hooks_results_adapt_fn
505     self.build_env_fn = build_env_fn
506     self.log_fn = log_fn
507     self.htype = htype
508     self.cluster_name = cluster_name
509     self.master_name = master_name
510
511     self.pre_env = self._BuildEnv(constants.HOOKS_PHASE_PRE)
512     (self.pre_nodes, self.post_nodes) = nodes
513
514   def _BuildEnv(self, phase):
515     """Compute the environment and the target nodes.
516
517     Based on the opcode and the current node list, this builds the
518     environment for the hooks and the target node list for the run.
519
520     """
521     if phase == constants.HOOKS_PHASE_PRE:
522       prefix = "GANETI_"
523     elif phase == constants.HOOKS_PHASE_POST:
524       prefix = "GANETI_POST_"
525     else:
526       raise AssertionError("Unknown phase '%s'" % phase)
527
528     env = {}
529
530     if self.hooks_path is not None:
531       phase_env = self.build_env_fn()
532       if phase_env:
533         assert not compat.any(key.upper().startswith(prefix)
534                               for key in phase_env)
535         env.update(("%s%s" % (prefix, key), value)
536                    for (key, value) in phase_env.items())
537
538     if phase == constants.HOOKS_PHASE_PRE:
539       assert compat.all((key.startswith("GANETI_") and
540                          not key.startswith("GANETI_POST_"))
541                         for key in env)
542
543     elif phase == constants.HOOKS_PHASE_POST:
544       assert compat.all(key.startswith("GANETI_POST_") for key in env)
545       assert isinstance(self.pre_env, dict)
546
547       # Merge with pre-phase environment
548       assert not compat.any(key.startswith("GANETI_POST_")
549                             for key in self.pre_env)
550       env.update(self.pre_env)
551     else:
552       raise AssertionError("Unknown phase '%s'" % phase)
553
554     return env
555
556   def _RunWrapper(self, node_list, hpath, phase, phase_env):
557     """Simple wrapper over self.callfn.
558
559     This method fixes the environment before executing the hooks.
560
561     """
562     env = {
563       "PATH": constants.HOOKS_PATH,
564       "GANETI_HOOKS_VERSION": constants.HOOKS_VERSION,
565       "GANETI_OP_CODE": self.opcode,
566       "GANETI_DATA_DIR": constants.DATA_DIR,
567       "GANETI_HOOKS_PHASE": phase,
568       "GANETI_HOOKS_PATH": hpath,
569       }
570
571     if self.htype:
572       env["GANETI_OBJECT_TYPE"] = self.htype
573
574     if self.cluster_name is not None:
575       env["GANETI_CLUSTER"] = self.cluster_name
576
577     if self.master_name is not None:
578       env["GANETI_MASTER"] = self.master_name
579
580     if phase_env:
581       env = utils.algo.JoinDisjointDicts(env, phase_env)
582
583     # Convert everything to strings
584     env = dict([(str(key), str(val)) for key, val in env.iteritems()])
585
586     assert compat.all(key == "PATH" or key.startswith("GANETI_")
587                       for key in env)
588
589     return self.hooks_execution_fn(node_list, hpath, phase, env)
590
591   def RunPhase(self, phase, nodes=None):
592     """Run all the scripts for a phase.
593
594     This is the main function of the HookMaster.
595     It executes self.hooks_execution_fn, and after running
596     self.hooks_results_adapt_fn on its results it expects them to be in the form
597     {node_name: (fail_msg, [(script, result, output), ...]}).
598
599     @param phase: one of L{constants.HOOKS_PHASE_POST} or
600         L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
601     @param nodes: overrides the predefined list of nodes for the given phase
602     @return: the processed results of the hooks multi-node rpc call
603     @raise errors.HooksFailure: on communication failure to the nodes
604     @raise errors.HooksAbort: on failure of one of the hooks
605
606     """
607     if phase == constants.HOOKS_PHASE_PRE:
608       if nodes is None:
609         nodes = self.pre_nodes
610       env = self.pre_env
611     elif phase == constants.HOOKS_PHASE_POST:
612       if nodes is None:
613         nodes = self.post_nodes
614       env = self._BuildEnv(phase)
615     else:
616       raise AssertionError("Unknown phase '%s'" % phase)
617
618     if not nodes:
619       # empty node list, we should not attempt to run this as either
620       # we're in the cluster init phase and the rpc client part can't
621       # even attempt to run, or this LU doesn't do hooks at all
622       return
623
624     results = self._RunWrapper(nodes, self.hooks_path, phase, env)
625     if not results:
626       msg = "Communication Failure"
627       if phase == constants.HOOKS_PHASE_PRE:
628         raise errors.HooksFailure(msg)
629       else:
630         self.log_fn(msg)
631         return results
632
633     converted_res = results
634     if self.hooks_results_adapt_fn:
635       converted_res = self.hooks_results_adapt_fn(results)
636
637     errs = []
638     for node_name, (fail_msg, offline, hooks_results) in converted_res.items():
639       if offline:
640         continue
641
642       if fail_msg:
643         self.log_fn("Communication failure to node %s: %s", node_name, fail_msg)
644         continue
645
646       for script, hkr, output in hooks_results:
647         if hkr == constants.HKR_FAIL:
648           if phase == constants.HOOKS_PHASE_PRE:
649             errs.append((node_name, script, output))
650           else:
651             if not output:
652               output = "(no output)"
653             self.log_fn("On %s script %s failed, output: %s" %
654                         (node_name, script, output))
655
656     if errs and phase == constants.HOOKS_PHASE_PRE:
657       raise errors.HooksAbort(errs)
658
659     return results
660
661   def RunConfigUpdate(self):
662     """Run the special configuration update hook
663
664     This is a special hook that runs only on the master after each
665     top-level LI if the configuration has been updated.
666
667     """
668     phase = constants.HOOKS_PHASE_POST
669     hpath = constants.HOOKS_NAME_CFGUPDATE
670     nodes = [self.master_name]
671     self._RunWrapper(nodes, hpath, phase, self.pre_env)
672
673   @staticmethod
674   def BuildFromLu(hooks_execution_fn, lu):
675     if lu.HPATH is None:
676       nodes = (None, None)
677     else:
678       nodes = map(frozenset, lu.BuildHooksNodes())
679
680     master_name = cluster_name = None
681     if lu.cfg:
682       master_name = lu.cfg.GetMasterNode()
683       cluster_name = lu.cfg.GetClusterName()
684
685     return HooksMaster(lu.op.OP_ID, lu.HPATH, nodes, hooks_execution_fn,
686                        _RpcResultsToHooksResults, lu.BuildHooksEnv,
687                        lu.LogWarning, lu.HTYPE, cluster_name, master_name)