cmdlib.py 481 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
#
Iustin Pop's avatar
Iustin Pop committed
2 3
#

4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
Iustin Pop's avatar
Iustin Pop committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#
# 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.


22
"""Module implementing the master-side code."""
Iustin Pop's avatar
Iustin Pop committed
23

24
# pylint: disable=W0201,C0302
25 26 27

# W0201 since most LU attributes are defined in CheckPrereq or similar
# functions
Iustin Pop's avatar
Iustin Pop committed
28

29
# C0302: since we have waaaay too many lines in this module
Iustin Pop's avatar
Iustin Pop committed
30

Iustin Pop's avatar
Iustin Pop committed
31 32 33 34 35
import os
import os.path
import time
import re
import platform
36
import logging
37
import copy
38
import OpenSSL
39 40 41
import socket
import tempfile
import shutil
42
import itertools
43
import operator
Iustin Pop's avatar
Iustin Pop committed
44 45 46 47 48

from ganeti import ssh
from ganeti import utils
from ganeti import errors
from ganeti import hypervisor
Guido Trotter's avatar
Guido Trotter committed
49
from ganeti import locking
Iustin Pop's avatar
Iustin Pop committed
50 51
from ganeti import constants
from ganeti import objects
52
from ganeti import serializer
53
from ganeti import ssconf
54
from ganeti import uidpool
55
from ganeti import compat
56
from ganeti import masterd
57
from ganeti import netutils
58 59
from ganeti import query
from ganeti import qlang
60
from ganeti import opcodes
61
from ganeti import ht
62

63
import ganeti.masterd.instance # pylint: disable=W0611
64

Iustin Pop's avatar
Iustin Pop committed
65

66 67 68 69
#: Size of DRBD meta block device
DRBD_META_SIZE = 128


70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
class ResultWithJobs:
  """Data container for LU results with jobs.

  Instances of this class returned from L{LogicalUnit.Exec} will be recognized
  by L{mcpu.Processor._ProcessResult}. The latter will then submit the jobs
  contained in the C{jobs} attribute and include the job IDs in the opcode
  result.

  """
  def __init__(self, jobs, **kwargs):
    """Initializes this class.

    Additional return values can be specified as keyword arguments.

    @type jobs: list of lists of L{opcode.OpCode}
    @param jobs: A list of lists of opcode objects

    """
    self.jobs = jobs
    self.other = kwargs


Iustin Pop's avatar
Iustin Pop committed
92
class LogicalUnit(object):
93
  """Logical Unit base class.
Iustin Pop's avatar
Iustin Pop committed
94 95

  Subclasses must follow these rules:
96
    - implement ExpandNames
97 98
    - implement CheckPrereq (except when tasklets are used)
    - implement Exec (except when tasklets are used)
Iustin Pop's avatar
Iustin Pop committed
99
    - implement BuildHooksEnv
100
    - implement BuildHooksNodes
Iustin Pop's avatar
Iustin Pop committed
101
    - redefine HPATH and HTYPE
102
    - optionally redefine their run requirements:
103
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
104 105

  Note that all commands require root permissions.
Iustin Pop's avatar
Iustin Pop committed
106

107 108 109
  @ivar dry_run_result: the value (if any) that will be returned to the caller
      in dry-run mode (signalled by opcode dry_run parameter)

Iustin Pop's avatar
Iustin Pop committed
110 111 112
  """
  HPATH = None
  HTYPE = None
113
  REQ_BGL = True
Iustin Pop's avatar
Iustin Pop committed
114

Iustin Pop's avatar
Iustin Pop committed
115
  def __init__(self, processor, op, context, rpc):
Iustin Pop's avatar
Iustin Pop committed
116 117
    """Constructor for LogicalUnit.

Michael Hanselmann's avatar
Michael Hanselmann committed
118
    This needs to be overridden in derived classes in order to check op
Iustin Pop's avatar
Iustin Pop committed
119 120 121
    validity.

    """
Iustin Pop's avatar
Iustin Pop committed
122
    self.proc = processor
Iustin Pop's avatar
Iustin Pop committed
123
    self.op = op
Guido Trotter's avatar
Guido Trotter committed
124
    self.cfg = context.cfg
125
    self.glm = context.glm
Iustin Pop's avatar
Iustin Pop committed
126 127
    # readability alias
    self.owned_locks = context.glm.list_owned
Guido Trotter's avatar
Guido Trotter committed
128
    self.context = context
Iustin Pop's avatar
Iustin Pop committed
129
    self.rpc = rpc
130
    # Dicts used to declare locking needs to mcpu
131
    self.needed_locks = None
132
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
133 134
    self.add_locks = {}
    self.remove_locks = {}
135 136
    # Used to force good behavior when calling helper functions
    self.recalculate_locks = {}
137
    # logging
138 139 140 141
    self.Log = processor.Log # pylint: disable=C0103
    self.LogWarning = processor.LogWarning # pylint: disable=C0103
    self.LogInfo = processor.LogInfo # pylint: disable=C0103
    self.LogStep = processor.LogStep # pylint: disable=C0103
142 143
    # support for dry-run
    self.dry_run_result = None
144 145 146 147
    # support for generic debug attribute
    if (not hasattr(self.op, "debug_level") or
        not isinstance(self.op.debug_level, int)):
      self.op.debug_level = 0
148

149
    # Tasklets
150
    self.tasklets = None
151

152 153
    # Validate opcode parameters and set defaults
    self.op.Validate(True)
154

155
    self.CheckArguments()
Iustin Pop's avatar
Iustin Pop committed
156

157 158 159 160 161 162 163 164 165
  def CheckArguments(self):
    """Check syntactic validity for the opcode arguments.

    This method is for doing a simple syntactic check and ensure
    validity of opcode parameters, without any cluster-related
    checks. While the same can be accomplished in ExpandNames and/or
    CheckPrereq, doing these separate is better because:

      - ExpandNames is left as as purely a lock-related function
Michael Hanselmann's avatar
Michael Hanselmann committed
166
      - CheckPrereq is run after we have acquired locks (and possible
167 168 169 170 171 172 173 174
        waited for them)

    The function is allowed to change the self.op attribute so that
    later methods can no longer worry about missing parameters.

    """
    pass

175 176 177 178 179 180
  def ExpandNames(self):
    """Expand names for this LU.

    This method is called before starting to execute the opcode, and it should
    update all the parameters of the opcode to their canonical form (e.g. a
    short node name must be fully expanded after this method has successfully
Adeodato Simo's avatar
Adeodato Simo committed
181
    completed). This way locking, hooks, logging, etc. can work correctly.
182 183 184 185

    LUs which implement this method must also populate the self.needed_locks
    member, as a dict with lock levels as keys, and a list of needed lock names
    as values. Rules:
186 187 188 189 190

      - use an empty dict if you don't need any lock
      - if you don't need any lock at a particular level omit that level
      - don't put anything for the BGL level
      - if you want all locks at a level use locking.ALL_SET as a value
191

Guido Trotter's avatar
Guido Trotter committed
192 193 194 195
    If you need to share locks (rather than acquire them exclusively) at one
    level you can modify self.share_locks, setting a true value (usually 1) for
    that level. By default locks are not shared.

196 197 198 199
    This function can also define a list of tasklets, which then will be
    executed in order instead of the usual LU-level CheckPrereq and Exec
    functions, if those are not defined by the LU.

200 201 202 203 204
    Examples::

      # Acquire all nodes and one instance
      self.needed_locks = {
        locking.LEVEL_NODE: locking.ALL_SET,
205
        locking.LEVEL_INSTANCE: ['instance1.example.com'],
206 207 208
      }
      # Acquire just two nodes
      self.needed_locks = {
209
        locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
210 211 212
      }
      # Acquire no locks
      self.needed_locks = {} # No, you can't leave it to the default value None
213 214 215 216 217 218 219 220 221 222

    """
    # The implementation of this method is mandatory only if the new LU is
    # concurrent, so that old LUs don't need to be changed all at the same
    # time.
    if self.REQ_BGL:
      self.needed_locks = {} # Exclusive LUs don't need locks.
    else:
      raise NotImplementedError

Guido Trotter's avatar
Guido Trotter committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
  def DeclareLocks(self, level):
    """Declare LU locking needs for a level

    While most LUs can just declare their locking needs at ExpandNames time,
    sometimes there's the need to calculate some locks after having acquired
    the ones before. This function is called just before acquiring locks at a
    particular level, but after acquiring the ones at lower levels, and permits
    such calculations. It can be used to modify self.needed_locks, and by
    default it does nothing.

    This function is only called if you have something already set in
    self.needed_locks for the level.

    @param level: Locking level which is going to be locked
    @type level: member of ganeti.locking.LEVELS

    """

Iustin Pop's avatar
Iustin Pop committed
241 242 243 244 245 246 247 248 249 250 251 252
  def CheckPrereq(self):
    """Check prerequisites for this LU.

    This method should check that the prerequisites for the execution
    of this LU are fulfilled. It can do internode communication, but
    it should be idempotent - no cluster or system changes are
    allowed.

    The method should raise errors.OpPrereqError in case something is
    not fulfilled. Its return value is ignored.

    This method should also update all the parameters of the opcode to
253
    their canonical form if it hasn't been done by ExpandNames before.
Iustin Pop's avatar
Iustin Pop committed
254 255

    """
256
    if self.tasklets is not None:
257
      for (idx, tl) in enumerate(self.tasklets):
258 259
        logging.debug("Checking prerequisites for tasklet %s/%s",
                      idx + 1, len(self.tasklets))
260 261
        tl.CheckPrereq()
    else:
262
      pass
Iustin Pop's avatar
Iustin Pop committed
263 264 265 266 267 268 269 270 271

  def Exec(self, feedback_fn):
    """Execute the LU.

    This method should implement the actual work. It should raise
    errors.OpExecError for failures that are somewhat dealt with in
    code, or expected.

    """
272
    if self.tasklets is not None:
273
      for (idx, tl) in enumerate(self.tasklets):
274
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
275 276 277
        tl.Exec(feedback_fn)
    else:
      raise NotImplementedError
Iustin Pop's avatar
Iustin Pop committed
278 279 280 281

  def BuildHooksEnv(self):
    """Build hooks environment for this LU.

282 283 284 285 286 287 288 289
    @rtype: dict
    @return: Dictionary containing the environment that will be used for
      running the hooks for this LU. The keys of the dict must not be prefixed
      with "GANETI_"--that'll be added by the hooks runner. The hooks runner
      will extend the environment with additional variables. If no environment
      should be defined, an empty dictionary should be returned (not C{None}).
    @note: If the C{HPATH} attribute of the LU class is C{None}, this function
      will not be called.
Iustin Pop's avatar
Iustin Pop committed
290

291 292
    """
    raise NotImplementedError
Iustin Pop's avatar
Iustin Pop committed
293

294 295
  def BuildHooksNodes(self):
    """Build list of nodes to run LU's hooks.
Iustin Pop's avatar
Iustin Pop committed
296

297 298 299 300 301 302 303
    @rtype: tuple; (list, list)
    @return: Tuple containing a list of node names on which the hook
      should run before the execution and a list of node names on which the
      hook should run after the execution. No nodes should be returned as an
      empty list (and not None).
    @note: If the C{HPATH} attribute of the LU class is C{None}, this function
      will not be called.
Iustin Pop's avatar
Iustin Pop committed
304 305 306 307

    """
    raise NotImplementedError

308 309 310 311 312 313 314 315 316
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
    """Notify the LU about the results of its hooks.

    This method is called every time a hooks phase is executed, and notifies
    the Logical Unit about the hooks' result. The LU can then use it to alter
    its result based on the hooks.  By default the method does nothing and the
    previous result is passed back unchanged but any LU can define it if it
    wants to use the local cluster hook-scripts somehow.

317 318 319 320 321 322 323 324
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
    @param hook_results: the results of the multi-node hooks rpc call
    @param feedback_fn: function used send feedback back to the caller
    @param lu_result: the previous Exec result this LU had, or None
        in the PRE phase
    @return: the new Exec result, based on the previous result
        and hook results
325 326

    """
327 328
    # API must be kept, thus we ignore the unused argument and could
    # be a function warnings
329
    # pylint: disable=W0613,R0201
330 331
    return lu_result

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
  def _ExpandAndLockInstance(self):
    """Helper function to expand and lock an instance.

    Many LUs that work on an instance take its name in self.op.instance_name
    and need to expand it and then declare the expanded name for locking. This
    function does it, and then updates self.op.instance_name to the expanded
    name. It also initializes needed_locks as a dict, if this hasn't been done
    before.

    """
    if self.needed_locks is None:
      self.needed_locks = {}
    else:
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
        "_ExpandAndLockInstance called with instance-level locks set"
347 348 349
    self.op.instance_name = _ExpandInstanceName(self.cfg,
                                                self.op.instance_name)
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
350

351
  def _LockInstancesNodes(self, primary_only=False):
352 353 354 355 356 357 358 359 360 361 362 363 364
    """Helper function to declare instances' nodes for locking.

    This function should be called after locking one or more instances to lock
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
    with all primary or secondary nodes for instances already locked and
    present in self.needed_locks[locking.LEVEL_INSTANCE].

    It should be called from DeclareLocks, and for safety only works if
    self.recalculate_locks[locking.LEVEL_NODE] is set.

    In the future it may grow parameters to just lock some instance's nodes, or
    to just lock primaries or secondary nodes, if needed.

365
    If should be called in DeclareLocks in a way similar to::
366

367 368
      if level == locking.LEVEL_NODE:
        self._LockInstancesNodes()
369

370 371 372
    @type primary_only: boolean
    @param primary_only: only lock primary nodes of locked instances

373 374 375 376 377 378 379 380 381 382
    """
    assert locking.LEVEL_NODE in self.recalculate_locks, \
      "_LockInstancesNodes helper function called with no nodes to recalculate"

    # TODO: check if we're really been called with the instance locks held

    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
    # future we might want to have different behaviors depending on the value
    # of self.recalculate_locks[locking.LEVEL_NODE]
    wanted_nodes = []
Iustin Pop's avatar
Iustin Pop committed
383
    locked_i = self.owned_locks(locking.LEVEL_INSTANCE)
384
    for _, instance in self.cfg.GetMultiInstanceInfo(locked_i):
385
      wanted_nodes.append(instance.primary_node)
386 387
      if not primary_only:
        wanted_nodes.extend(instance.secondary_nodes)
388 389 390 391 392

    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
393 394 395

    del self.recalculate_locks[locking.LEVEL_NODE]

Iustin Pop's avatar
Iustin Pop committed
396

397
class NoHooksLU(LogicalUnit): # pylint: disable=W0223
Iustin Pop's avatar
Iustin Pop committed
398 399 400 401 402 403 404 405 406
  """Simple LU which runs no hooks.

  This LU is intended as a parent for other LogicalUnits which will
  run no hooks, in order to reduce duplicate code.

  """
  HPATH = None
  HTYPE = None

407 408 409 410 411 412
  def BuildHooksEnv(self):
    """Empty BuildHooksEnv for NoHooksLu.

    This just raises an error.

    """
413 414 415 416 417 418 419
    raise AssertionError("BuildHooksEnv called for NoHooksLUs")

  def BuildHooksNodes(self):
    """Empty BuildHooksNodes for NoHooksLU.

    """
    raise AssertionError("BuildHooksNodes called for NoHooksLU")
420

Iustin Pop's avatar
Iustin Pop committed
421

422 423 424 425 426 427 428 429 430 431 432 433
class Tasklet:
  """Tasklet base class.

  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
  tasklets know nothing about locks.

  Subclasses must follow these rules:
    - Implement CheckPrereq
    - Implement Exec

  """
434 435 436 437 438 439 440
  def __init__(self, lu):
    self.lu = lu

    # Shortcuts
    self.cfg = lu.cfg
    self.rpc = lu.rpc

441 442 443 444 445 446 447 448 449 450 451 452 453 454
  def CheckPrereq(self):
    """Check prerequisites for this tasklets.

    This method should check whether the prerequisites for the execution of
    this tasklet are fulfilled. It can do internode communication, but it
    should be idempotent - no cluster or system changes are allowed.

    The method should raise errors.OpPrereqError in case something is not
    fulfilled. Its return value is ignored.

    This method should also update all parameters to their canonical form if it
    hasn't been done before.

    """
455
    pass
456 457 458 459 460 461 462 463 464 465 466 467

  def Exec(self, feedback_fn):
    """Execute the tasklet.

    This method should implement the actual work. It should raise
    errors.OpExecError for failures that are somewhat dealt with in code, or
    expected.

    """
    raise NotImplementedError


468 469 470 471 472 473 474
class _QueryBase:
  """Base for query utility classes.

  """
  #: Attribute holding field definitions
  FIELDS = None

475
  def __init__(self, qfilter, fields, use_locking):
476 477 478 479 480
    """Initializes this class.

    """
    self.use_locking = use_locking

481
    self.query = query.Query(self.FIELDS, fields, qfilter=qfilter,
482
                             namefield="name")
483
    self.requested_data = self.query.RequestedData()
484
    self.names = self.query.RequestedNames()
485

486 487 488
    # Sort only if no names were requested
    self.sort_by_name = not self.names

489 490 491 492 493 494 495 496
    self.do_locking = None
    self.wanted = None

  def _GetNames(self, lu, all_names, lock_level):
    """Helper function to determine names asked for in the query.

    """
    if self.do_locking:
Iustin Pop's avatar
Iustin Pop committed
497
      names = lu.owned_locks(lock_level)
498 499 500 501 502 503 504 505 506 507
    else:
      names = all_names

    if self.wanted == locking.ALL_SET:
      assert not self.names
      # caller didn't specify names, so ordering is not important
      return utils.NiceSort(names)

    # caller specified names and we must keep the same order
    assert self.names
508
    assert not self.do_locking or lu.glm.is_owned(lock_level)
509 510 511 512 513 514 515 516 517

    missing = set(self.wanted).difference(names)
    if missing:
      raise errors.OpExecError("Some items were removed before retrieving"
                               " their data: %s" % missing)

    # Return expanded names
    return self.wanted

518 519 520 521 522 523 524 525
  def ExpandNames(self, lu):
    """Expand names for this query.

    See L{LogicalUnit.ExpandNames}.

    """
    raise NotImplementedError()

526
  def DeclareLocks(self, lu, level):
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    """Declare locks for this query.

    See L{LogicalUnit.DeclareLocks}.

    """
    raise NotImplementedError()

  def _GetQueryData(self, lu):
    """Collects all data for this query.

    @return: Query data object

    """
    raise NotImplementedError()

  def NewStyleQuery(self, lu):
    """Collect data and execute query.

    """
546 547
    return query.GetQueryResponse(self.query, self._GetQueryData(lu),
                                  sort_by_name=self.sort_by_name)
548 549 550 551 552

  def OldStyleQuery(self, lu):
    """Collect data and execute query.

    """
553 554
    return self.query.OldStyleQuery(self._GetQueryData(lu),
                                    sort_by_name=self.sort_by_name)
555 556


557 558 559 560 561 562 563
def _ShareAll():
  """Returns a dict declaring all lock levels shared.

  """
  return dict.fromkeys(locking.LEVELS, 1)


564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
def _CheckInstanceNodeGroups(cfg, instance_name, owned_groups):
  """Checks if the owned node groups are still correct for an instance.

  @type cfg: L{config.ConfigWriter}
  @param cfg: The cluster configuration
  @type instance_name: string
  @param instance_name: Instance name
  @type owned_groups: set or frozenset
  @param owned_groups: List of currently owned node groups

  """
  inst_groups = cfg.GetInstanceNodeGroups(instance_name)

  if not owned_groups.issuperset(inst_groups):
    raise errors.OpPrereqError("Instance %s's node groups changed since"
                               " locks were acquired, current groups are"
                               " are '%s', owning groups '%s'; retry the"
                               " operation" %
                               (instance_name,
                                utils.CommaJoin(inst_groups),
                                utils.CommaJoin(owned_groups)),
                               errors.ECODE_STATE)

  return inst_groups


590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
def _CheckNodeGroupInstances(cfg, group_uuid, owned_instances):
  """Checks if the instances in a node group are still correct.

  @type cfg: L{config.ConfigWriter}
  @param cfg: The cluster configuration
  @type group_uuid: string
  @param group_uuid: Node group UUID
  @type owned_instances: set or frozenset
  @param owned_instances: List of currently owned instances

  """
  wanted_instances = cfg.GetNodeGroupInstances(group_uuid)
  if owned_instances != wanted_instances:
    raise errors.OpPrereqError("Instances in node group '%s' changed since"
                               " locks were acquired, wanted '%s', have '%s';"
                               " retry the operation" %
                               (group_uuid,
                                utils.CommaJoin(wanted_instances),
                                utils.CommaJoin(owned_instances)),
                               errors.ECODE_STATE)

  return wanted_instances


614 615 616 617 618 619 620 621 622 623 624 625 626
def _SupportsOob(cfg, node):
  """Tells if node supports OOB.

  @type cfg: L{config.ConfigWriter}
  @param cfg: The cluster configuration
  @type node: L{objects.Node}
  @param node: The node
  @return: The OOB script if supported or an empty string otherwise

  """
  return cfg.GetNdParams(node)[constants.ND_OOB_PROGRAM]


627
def _GetWantedNodes(lu, nodes):
628
  """Returns list of checked and expanded node names.
629

630 631 632 633 634 635
  @type lu: L{LogicalUnit}
  @param lu: the logical unit on whose behalf we execute
  @type nodes: list
  @param nodes: list of node names or None for all nodes
  @rtype: list
  @return: the list of nodes, sorted
Iustin Pop's avatar
Iustin Pop committed
636
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
637 638

  """
639 640
  if nodes:
    return [_ExpandNodeName(lu.cfg, name) for name in nodes]
641

642
  return utils.NiceSort(lu.cfg.GetNodeList())
643 644 645


def _GetWantedInstances(lu, instances):
646
  """Returns list of checked and expanded instance names.
647

648 649 650 651 652 653 654 655
  @type lu: L{LogicalUnit}
  @param lu: the logical unit on whose behalf we execute
  @type instances: list
  @param instances: list of instance names or None for all instances
  @rtype: list
  @return: the list of instances, sorted
  @raise errors.OpPrereqError: if the instances parameter is wrong type
  @raise errors.OpPrereqError: if any of the passed instances is not found
656 657 658

  """
  if instances:
659
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
660
  else:
661 662
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
  return wanted
663 664


665 666
def _GetUpdatedParams(old_params, update_dict,
                      use_default=True, use_none=False):
667 668 669 670 671 672 673 674
  """Return the new version of a parameter dictionary.

  @type old_params: dict
  @param old_params: old parameters
  @type update_dict: dict
  @param update_dict: dict containing new parameter values, or
      constants.VALUE_DEFAULT to reset the parameter to its default
      value
675 676 677 678 679 680
  @param use_default: boolean
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
      values as 'to be deleted' values
  @param use_none: boolean
  @type use_none: whether to recognise C{None} values as 'to be
      deleted' values
681 682 683 684 685 686
  @rtype: dict
  @return: the new parameter dictionary

  """
  params_copy = copy.deepcopy(old_params)
  for key, val in update_dict.iteritems():
687 688
    if ((use_default and val == constants.VALUE_DEFAULT) or
        (use_none and val is None)):
689 690 691 692 693 694 695 696 697
      try:
        del params_copy[key]
      except KeyError:
        pass
    else:
      params_copy[key] = val
  return params_copy


698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
def _ReleaseLocks(lu, level, names=None, keep=None):
  """Releases locks owned by an LU.

  @type lu: L{LogicalUnit}
  @param level: Lock level
  @type names: list or None
  @param names: Names of locks to release
  @type keep: list or None
  @param keep: Names of locks to retain

  """
  assert not (keep is not None and names is not None), \
         "Only one of the 'names' and the 'keep' parameters can be given"

  if names is not None:
    should_release = names.__contains__
  elif keep:
    should_release = lambda name: name not in keep
  else:
    should_release = None

  if should_release:
    retain = []
    release = []

    # Determine which locks to release
Iustin Pop's avatar
Iustin Pop committed
724
    for name in lu.owned_locks(level):
725 726 727 728 729
      if should_release(name):
        release.append(name)
      else:
        retain.append(name)

Iustin Pop's avatar
Iustin Pop committed
730
    assert len(lu.owned_locks(level)) == (len(retain) + len(release))
731 732

    # Release just some locks
733
    lu.glm.release(level, names=release)
734

Iustin Pop's avatar
Iustin Pop committed
735
    assert frozenset(lu.owned_locks(level)) == frozenset(retain)
736 737
  else:
    # Release everything
738
    lu.glm.release(level)
739

740
    assert not lu.glm.is_owned(level), "No locks should be owned"
741 742


743 744 745 746 747 748 749 750 751 752 753 754 755
def _MapInstanceDisksToNodes(instances):
  """Creates a map from (node, volume) to instance name.

  @type instances: list of L{objects.Instance}
  @rtype: dict; tuple of (node name, volume name) as key, instance name as value

  """
  return dict(((node, vol), inst.name)
              for inst in instances
              for (node, vols) in inst.MapLVsByNode().items()
              for vol in vols)


756 757 758 759 760 761 762 763
def _RunPostHook(lu, node_name):
  """Runs the post-hook for an opcode on a single node.

  """
  hm = lu.proc.hmclass(lu.rpc.call_hooks_runner, lu)
  try:
    hm.RunPhase(constants.HOOKS_PHASE_POST, nodes=[node_name])
  except:
764
    # pylint: disable=W0702
765 766 767
    lu.LogWarning("Errors occurred running hooks on %s" % node_name)


768
def _CheckOutputFields(static, dynamic, selected):
769 770
  """Checks whether all selected fields are valid.

Iustin Pop's avatar
Iustin Pop committed
771
  @type static: L{utils.FieldSet}
Iustin Pop's avatar
Iustin Pop committed
772
  @param static: static fields set
Iustin Pop's avatar
Iustin Pop committed
773
  @type dynamic: L{utils.FieldSet}
Iustin Pop's avatar
Iustin Pop committed
774
  @param dynamic: dynamic fields set
775 776

  """
Iustin Pop's avatar
Iustin Pop committed
777
  f = utils.FieldSet()
Iustin Pop's avatar
Iustin Pop committed
778 779
  f.Extend(static)
  f.Extend(dynamic)
780

Iustin Pop's avatar
Iustin Pop committed
781 782
  delta = f.NonMatching(selected)
  if delta:
783
    raise errors.OpPrereqError("Unknown output fields selected: %s"
784
                               % ",".join(delta), errors.ECODE_INVAL)
785 786


787 788 789 790 791 792 793 794 795 796 797
def _CheckGlobalHvParams(params):
  """Validates that given hypervisor params are not global ones.

  This will ensure that instances don't get customised versions of
  global params.

  """
  used_globals = constants.HVC_GLOBALS.intersection(params)
  if used_globals:
    msg = ("The following hypervisor parameters are global and cannot"
           " be customized at instance level, please modify them at"
798
           " cluster level: %s" % utils.CommaJoin(used_globals))
799 800 801
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)


802
def _CheckNodeOnline(lu, node, msg=None):
803 804 805 806
  """Ensure that a given node is online.

  @param lu: the LU on behalf of which we make the check
  @param node: the node to check
807
  @param msg: if passed, should be a message to replace the default one
808
  @raise errors.OpPrereqError: if the node is offline
809 810

  """
811 812
  if msg is None:
    msg = "Can't use offline node"
813
  if lu.cfg.GetNodeInfo(node).offline:
814
    raise errors.OpPrereqError("%s: %s" % (msg, node), errors.ECODE_STATE)
815 816


817 818 819 820 821 822 823 824 825
def _CheckNodeNotDrained(lu, node):
  """Ensure that a given node is not drained.

  @param lu: the LU on behalf of which we make the check
  @param node: the node to check
  @raise errors.OpPrereqError: if the node is drained

  """
  if lu.cfg.GetNodeInfo(node).drained:
826
    raise errors.OpPrereqError("Can't use drained node %s" % node,
827 828 829 830 831 832 833 834 835 836 837 838 839 840
                               errors.ECODE_STATE)


def _CheckNodeVmCapable(lu, node):
  """Ensure that a given node is vm capable.

  @param lu: the LU on behalf of which we make the check
  @param node: the node to check
  @raise errors.OpPrereqError: if the node is not vm capable

  """
  if not lu.cfg.GetNodeInfo(node).vm_capable:
    raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node,
                               errors.ECODE_STATE)
841 842


Iustin Pop's avatar
Iustin Pop committed
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
def _CheckNodeHasOS(lu, node, os_name, force_variant):
  """Ensure that a node supports a given OS.

  @param lu: the LU on behalf of which we make the check
  @param node: the node to check
  @param os_name: the OS to query about
  @param force_variant: whether to ignore variant errors
  @raise errors.OpPrereqError: if the node is not supporting the OS

  """
  result = lu.rpc.call_os_get(node, os_name)
  result.Raise("OS '%s' not in supported OS list for node %s" %
               (os_name, node),
               prereq=True, ecode=errors.ECODE_INVAL)
  if not force_variant:
    _CheckOSVariant(result.payload, os_name)


861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
  """Ensure that a node has the given secondary ip.

  @type lu: L{LogicalUnit}
  @param lu: the LU on behalf of which we make the check
  @type node: string
  @param node: the node to check
  @type secondary_ip: string
  @param secondary_ip: the ip to check
  @type prereq: boolean
  @param prereq: whether to throw a prerequisite or an execute error
  @raise errors.OpPrereqError: if the node doesn't have the ip, and prereq=True
  @raise errors.OpExecError: if the node doesn't have the ip, and prereq=False

  """
  result = lu.rpc.call_node_has_ip_address(node, secondary_ip)
  result.Raise("Failure checking secondary ip on node %s" % node,
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
  if not result.payload:
    msg = ("Node claims it doesn't have the secondary ip you gave (%s),"
           " please fix and re-run this command" % secondary_ip)
    if prereq:
      raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
    else:
      raise errors.OpExecError(msg)


888 889 890 891 892 893 894
def _GetClusterDomainSecret():
  """Reads the cluster domain secret.

  """
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
                               strict=True)

895

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
def _CheckInstanceDown(lu, instance, reason):
  """Ensure that an instance is not running."""
  if instance.admin_up:
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
                               (instance.name, reason), errors.ECODE_STATE)

  pnode = instance.primary_node
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
              prereq=True, ecode=errors.ECODE_ENVIRON)

  if instance.name in ins_l.payload:
    raise errors.OpPrereqError("Instance %s is running, %s" %
                               (instance.name, reason), errors.ECODE_STATE)


912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
def _ExpandItemName(fn, name, kind):
  """Expand an item name.

  @param fn: the function to use for expansion
  @param name: requested item name
  @param kind: text description ('Node' or 'Instance')
  @return: the resolved (full) name
  @raise errors.OpPrereqError: if the item is not found

  """
  full_name = fn(name)
  if full_name is None:
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
                               errors.ECODE_NOENT)
  return full_name


def _ExpandNodeName(cfg, name):
  """Wrapper over L{_ExpandItemName} for nodes."""
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")


def _ExpandInstanceName(cfg, name):
  """Wrapper over L{_ExpandItemName} for instance."""
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")


939
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
940
                          memory, vcpus, nics, disk_template, disks,
941
                          bep, hvp, hypervisor_name, tags):
942 943 944 945 946 947 948 949 950 951 952 953
  """Builds instance related env variables for hooks

  This builds the hook environment from individual variables.

  @type name: string
  @param name: the name of the instance
  @type primary_node: string
  @param primary_node: the name of the instance's primary node
  @type secondary_nodes: list
  @param secondary_nodes: list of secondary nodes as strings
  @type os_type: string
  @param os_type: the name of the instance's OS
954 955
  @type status: boolean
  @param status: the should_run status of the instance
956 957 958 959 960
  @type memory: string
  @param memory: the memory size of the instance
  @type vcpus: string
  @param vcpus: the count of VCPUs the instance has
  @type nics: list
961 962
  @param nics: list of tuples (ip, mac, mode, link) representing
      the NICs the instance has
Iustin Pop's avatar
Iustin Pop committed
963
  @type disk_template: string
Michael Hanselmann's avatar
Michael Hanselmann committed
964
  @param disk_template: the disk template of the instance
Iustin Pop's avatar
Iustin Pop committed
965 966
  @type disks: list
  @param disks: the list of (size, mode) pairs
967 968 969 970
  @type bep: dict
  @param bep: the backend parameters for the instance
  @type hvp: dict
  @param hvp: the hypervisor parameters for the instance
Michael Hanselmann's avatar
Michael Hanselmann committed
971 972
  @type hypervisor_name: string
  @param hypervisor_name: the hypervisor for the instance
973 974
  @type tags: list
  @param tags: list of instance tags as strings
975 976
  @rtype: dict
  @return: the hook environment for this instance
977

978
  """
979 980 981 982
  if status:
    str_status = "up"
  else:
    str_status = "down"
983
  env = {
984
    "OP_TARGET": name,
985 986 987
    "INSTANCE_NAME": name,
    "INSTANCE_PRIMARY": primary_node,
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
988
    "INSTANCE_OS_TYPE": os_type,
989
    "INSTANCE_STATUS": str_status,
990 991
    "INSTANCE_MEMORY": memory,
    "INSTANCE_VCPUS": vcpus,
Iustin Pop's avatar
Iustin Pop committed
992
    "INSTANCE_DISK_TEMPLATE": disk_template,
Michael Hanselmann's avatar
Michael Hanselmann committed
993
    "INSTANCE_HYPERVISOR": hypervisor_name,
994 995 996 997
  }

  if nics:
    nic_count = len(nics)
998
    for idx, (ip, mac, mode, link) in enumerate(nics):
999 1000 1001
      if ip is None:
        ip = ""
      env["INSTANCE_NIC%d_IP" % idx] = ip
Iustin Pop's avatar
Iustin Pop committed
1002
      env["INSTANCE_NIC%d_MAC" % idx] = mac
1003 1004 1005 1006
      env["INSTANCE_NIC%d_MODE" % idx] = mode
      env["INSTANCE_NIC%d_LINK" % idx] = link
      if mode == constants.NIC_MODE_BRIDGED:
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
1007 1008 1009 1010 1011
  else:
    nic_count = 0

  env["INSTANCE_NIC_COUNT"] = nic_count

Iustin Pop's avatar
Iustin Pop committed
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
  if disks:
    disk_count = len(disks)
    for idx, (size, mode) in enumerate(disks):
      env["INSTANCE_DISK%d_SIZE" % idx] = size
      env["INSTANCE_DISK%d_MODE" % idx] = mode
  else:
    disk_count = 0

  env["INSTANCE_DISK_COUNT"] = disk_count

1022 1023 1024 1025 1026
  if not tags:
    tags = []

  env["INSTANCE_TAGS"] = " ".join(tags)

1027 1028 1029 1030
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
    for key, value in source.items():
      env["INSTANCE_%s_%s" % (kind, key)] = value

1031 1032
  return env

1033

1034
def _NICListToTuple(lu, nics):
1035 1036
  """Build a list of nic information tuples.

1037
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
1038
  value in LUInstanceQueryData.
1039 1040 1041 1042 1043 1044 1045 1046

  @type lu:  L{LogicalUnit}
  @param lu: the logical unit on whose behalf we execute
  @type nics: list of L{objects.NIC}
  @param nics: list of nics to convert to hooks tuples

  """
  hooks_nics = []
1047
  cluster = lu.cfg.GetClusterInfo()
1048 1049 1050
  for nic in nics:
    ip = nic.ip
    mac = nic.mac
1051
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
1052 1053 1054 1055
    mode = filled_params[constants.NIC_MODE]
    link = filled_params[constants.NIC_LINK]
    hooks_nics.append((ip, mac, mode, link))
  return hooks_nics
1056

1057

Iustin Pop's avatar
Iustin Pop committed
1058
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
1059 1060
  """Builds instance related env variables for hooks from an object.

1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
  @type lu: L{LogicalUnit}
  @param lu: the logical unit on whose behalf we execute
  @type instance: L{objects.Instance}
  @param instance: the instance for which we should build the
      environment
  @type override: dict
  @param override: dictionary with key/values that will override
      our values
  @rtype: dict
  @return: the hook environment dictionary

1072
  """
1073 1074 1075
  cluster = lu.cfg.GetClusterInfo()
  bep = cluster.FillBE(instance)
  hvp = cluster.FillHV(instance)
1076
  args = {
Iustin Pop's avatar
Iustin Pop committed
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    "name": instance.name,
    "primary_node": instance.primary_node,
    "secondary_nodes": instance.secondary_nodes,
    "os_type": instance.os,
    "status": instance.admin_up,
    "memory": bep[constants.BE_MEMORY],
    "vcpus": bep[constants.BE_VCPUS],
    "nics": _NICListToTuple(lu, instance.nics),
    "disk_template": instance.disk_template,
    "disks": [(disk.size, disk.mode) for disk in instance.disks],
    "bep": bep,
    "hvp": hvp,
    "hypervisor_name": instance.hypervisor,
    "tags": instance.tags,
1091 1092 1093
  }
  if override:
    args.update(override)
1094
  return _BuildInstanceHookEnv(**args) # pylint: disable=W0142
1095 1096


Guido Trotter's avatar
Guido Trotter committed
1097
def _AdjustCandidatePool(lu, exceptions):
1098 1099 1100
  """Adjust the candidate pool after node operations.

  """
Guido Trotter's avatar
Guido Trotter committed
1101
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
1102 1103
  if mod_list:
    lu.LogInfo("Promoted nodes to master candidate role: %s",
1104
               utils.CommaJoin(node.name for node in mod_list))
1105 1106
    for name in mod_list:
      lu.context.ReaddNode(name)
Guido Trotter's avatar
Guido Trotter committed
1107
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1108 1109 1110 1111 1112
  if mc_now > mc_max:
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
               (mc_now, mc_max))


1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
def _DecideSelfPromotion(lu, exceptions=None):
  """Decide whether I should promote myself as a master candidate.

  """
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
  # the new node will increase mc_max with one, so:
  mc_should = min(mc_should + 1, cp_size)
  return mc_now < mc_should


1124
def _CheckNicsBridgesExist(lu, target_nics, target_node):
1125 1126 1127
  """Check that the brigdes needed by a list of nics exist.

  """
1128 1129
  cluster = lu.cfg.GetClusterInfo()
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
1130 1131 1132 1133
  brlist = [params[constants.NIC_LINK] for params in paramslist
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
  if brlist:
    result = lu.rpc.call_bridges_exist(target_node, brlist)
1134
    result.Raise("Error checking bridges on destination node '%s'" %
1135
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
1136 1137 1138


def _CheckInstanceBridgesExist(lu, instance, node=None):
1139 1140 1141