instance_utils.py 18.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#
#

# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Utility function mainly, but not only used by instance LU's."""

import logging
import os

from ganeti import constants
from ganeti import errors
from ganeti import locking
from ganeti import network
from ganeti import objects
from ganeti import pathutils
from ganeti import utils
34
from ganeti.cmdlib.common import AnnotateDiskParams, \
35
  ComputeIPolicyInstanceViolation, CheckDiskTemplateEnabled
36
37


Thomas Thrainer's avatar
Thomas Thrainer committed
38
39
40
def BuildInstanceHookEnv(name, primary_node_name, secondary_node_names, os_type,
                         status, minmem, maxmem, vcpus, nics, disk_template,
                         disks, bep, hvp, hypervisor_name, tags):
41
42
43
44
45
46
  """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
Thomas Thrainer's avatar
Thomas Thrainer committed
47
48
49
50
  @type primary_node_name: string
  @param primary_node_name: the name of the instance's primary node
  @type secondary_node_names: list
  @param secondary_node_names: list of secondary nodes as strings
51
52
53
54
55
56
57
58
59
60
61
  @type os_type: string
  @param os_type: the name of the instance's OS
  @type status: string
  @param status: the desired status of the instance
  @type minmem: string
  @param minmem: the minimum memory size of the instance
  @type maxmem: string
  @param maxmem: the maximum memory size of the instance
  @type vcpus: string
  @param vcpus: the count of VCPUs the instance has
  @type nics: list
62
63
  @param nics: list of tuples (name, uuid, ip, mac, mode, link, vlan, net,
      netinfo) representing the NICs the instance has
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
  @type disk_template: string
  @param disk_template: the disk template of the instance
  @type disks: list
  @param disks: list of tuples (name, uuid, size, mode)
  @type bep: dict
  @param bep: the backend parameters for the instance
  @type hvp: dict
  @param hvp: the hypervisor parameters for the instance
  @type hypervisor_name: string
  @param hypervisor_name: the hypervisor for the instance
  @type tags: list
  @param tags: list of instance tags as strings
  @rtype: dict
  @return: the hook environment for this instance

  """
  env = {
    "OP_TARGET": name,
    "INSTANCE_NAME": name,
Thomas Thrainer's avatar
Thomas Thrainer committed
83
84
    "INSTANCE_PRIMARY": primary_node_name,
    "INSTANCE_SECONDARIES": " ".join(secondary_node_names),
85
86
87
88
89
90
91
92
93
94
95
96
    "INSTANCE_OS_TYPE": os_type,
    "INSTANCE_STATUS": status,
    "INSTANCE_MINMEM": minmem,
    "INSTANCE_MAXMEM": maxmem,
    # TODO(2.9) remove deprecated "memory" value
    "INSTANCE_MEMORY": maxmem,
    "INSTANCE_VCPUS": vcpus,
    "INSTANCE_DISK_TEMPLATE": disk_template,
    "INSTANCE_HYPERVISOR": hypervisor_name,
    }
  if nics:
    nic_count = len(nics)
97
98
    for idx, (name, uuid, ip, mac, mode, link, vlan, net, netinfo) \
        in enumerate(nics):
99
100
      if ip is None:
        ip = ""
101
102
103
      if name:
        env["INSTANCE_NIC%d_NAME" % idx] = name
      env["INSTANCE_NIC%d_UUID" % idx] = uuid
104
105
106
107
      env["INSTANCE_NIC%d_IP" % idx] = ip
      env["INSTANCE_NIC%d_MAC" % idx] = mac
      env["INSTANCE_NIC%d_MODE" % idx] = mode
      env["INSTANCE_NIC%d_LINK" % idx] = link
108
      env["INSTANCE_NIC%d_VLAN" % idx] = vlan
109
110
111
112
113
114
115
116
      if netinfo:
        nobj = objects.Network.FromDict(netinfo)
        env.update(nobj.HooksDict("INSTANCE_NIC%d_" % idx))
      elif network:
        # FIXME: broken network reference: the instance NIC specifies a
        # network, but the relevant network entry was not in the config. This
        # should be made impossible.
        env["INSTANCE_NIC%d_NETWORK_NAME" % idx] = net
117
118
      if mode == constants.NIC_MODE_BRIDGED or \
         mode == constants.NIC_MODE_OVS:
119
120
121
122
123
124
125
126
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
  else:
    nic_count = 0

  env["INSTANCE_NIC_COUNT"] = nic_count

  if disks:
    disk_count = len(disks)
127
128
129
130
    for idx, (name, uuid, size, mode) in enumerate(disks):
      if name:
        env["INSTANCE_DISK%d_NAME" % idx] = name
      env["INSTANCE_DISK%d_UUID" % idx] = uuid
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
      env["INSTANCE_DISK%d_SIZE" % idx] = size
      env["INSTANCE_DISK%d_MODE" % idx] = mode
  else:
    disk_count = 0

  env["INSTANCE_DISK_COUNT"] = disk_count

  if not tags:
    tags = []

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

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

  return env


150
def BuildInstanceHookEnvByObject(lu, instance, override=None):
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
  """Builds instance related env variables for hooks from an object.

  @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

  """
  cluster = lu.cfg.GetClusterInfo()
  bep = cluster.FillBE(instance)
  hvp = cluster.FillHV(instance)
  args = {
    "name": instance.name,
Thomas Thrainer's avatar
Thomas Thrainer committed
170
171
    "primary_node_name": lu.cfg.GetNodeName(instance.primary_node),
    "secondary_node_names": lu.cfg.GetNodeNames(instance.secondary_nodes),
172
173
174
175
176
    "os_type": instance.os,
    "status": instance.admin_state,
    "maxmem": bep[constants.BE_MAXMEM],
    "minmem": bep[constants.BE_MINMEM],
    "vcpus": bep[constants.BE_VCPUS],
177
    "nics": NICListToTuple(lu, instance.nics),
178
    "disk_template": instance.disk_template,
179
    "disks": [(disk.name, disk.uuid, disk.size, disk.mode)
180
181
182
183
184
185
186
187
              for disk in instance.disks],
    "bep": bep,
    "hvp": hvp,
    "hypervisor_name": instance.hypervisor,
    "tags": instance.tags,
  }
  if override:
    args.update(override)
188
  return BuildInstanceHookEnv(**args) # pylint: disable=W0142
189
190


191
def GetClusterDomainSecret():
192
193
194
195
196
197
198
  """Reads the cluster domain secret.

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


Thomas Thrainer's avatar
Thomas Thrainer committed
199
def CheckNodeNotDrained(lu, node_uuid):
200
201
202
  """Ensure that a given node is not drained.

  @param lu: the LU on behalf of which we make the check
Thomas Thrainer's avatar
Thomas Thrainer committed
203
  @param node_uuid: the node to check
204
205
206
  @raise errors.OpPrereqError: if the node is drained

  """
207
208
209
  node = lu.cfg.GetNodeInfo(node_uuid)
  if node.drained:
    raise errors.OpPrereqError("Can't use drained node %s" % node.name,
210
211
212
                               errors.ECODE_STATE)


Thomas Thrainer's avatar
Thomas Thrainer committed
213
def CheckNodeVmCapable(lu, node_uuid):
214
  """Ensure that a given node is vm capable.
215

216
  @param lu: the LU on behalf of which we make the check
Thomas Thrainer's avatar
Thomas Thrainer committed
217
  @param node_uuid: the node to check
218
  @raise errors.OpPrereqError: if the node is not vm capable
219
220

  """
Thomas Thrainer's avatar
Thomas Thrainer committed
221
222
  if not lu.cfg.GetNodeInfo(node_uuid).vm_capable:
    raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node_uuid,
223
                               errors.ECODE_STATE)
224
225


226
def RemoveInstance(lu, feedback_fn, instance, ignore_failures):
227
228
229
230
231
  """Utility function to remove an instance.

  """
  logging.info("Removing block devices for instance %s", instance.name)

232
  if not RemoveDisks(lu, instance, ignore_failures=ignore_failures):
233
234
235
236
237
238
    if not ignore_failures:
      raise errors.OpExecError("Can't remove instance's disks")
    feedback_fn("Warning: can't remove instance's disks")

  logging.info("Removing instance %s out of cluster config", instance.name)

239
  lu.cfg.RemoveInstance(instance.uuid)
240
241
242
243
244
245
246
247

  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
    "Instance lock removal conflict"

  # Remove lock for the instance
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name


Thomas Thrainer's avatar
Thomas Thrainer committed
248
def RemoveDisks(lu, instance, target_node_uuid=None, ignore_failures=False):
249
250
251
252
253
254
255
256
257
258
  """Remove all disks for an instance.

  This abstracts away some work from `AddInstance()` and
  `RemoveInstance()`. Note that in case some of the devices couldn't
  be removed, the removal will continue with the other ones.

  @type lu: L{LogicalUnit}
  @param lu: the logical unit on whose behalf we execute
  @type instance: L{objects.Instance}
  @param instance: the instance whose disks we should remove
Thomas Thrainer's avatar
Thomas Thrainer committed
259
260
261
  @type target_node_uuid: string
  @param target_node_uuid: used to override the node on which to remove the
          disks
262
263
264
265
266
267
268
269
  @rtype: boolean
  @return: the success of the removal

  """
  logging.info("Removing block devices for instance %s", instance.name)

  all_result = True
  ports_to_release = set()
270
  anno_disks = AnnotateDiskParams(instance, instance.disks, lu.cfg)
271
  for (idx, device) in enumerate(anno_disks):
Thomas Thrainer's avatar
Thomas Thrainer committed
272
273
    if target_node_uuid:
      edata = [(target_node_uuid, device)]
274
275
    else:
      edata = device.ComputeNodeTree(instance.primary_node)
Thomas Thrainer's avatar
Thomas Thrainer committed
276
    for node_uuid, disk in edata:
277
      result = lu.rpc.call_blockdev_remove(node_uuid, (disk, instance))
278
279
      if result.fail_msg:
        lu.LogWarning("Could not remove disk %s on node %s,"
Thomas Thrainer's avatar
Thomas Thrainer committed
280
281
282
                      " continuing anyway: %s", idx,
                      lu.cfg.GetNodeName(node_uuid), result.fail_msg)
        if not (result.offline and node_uuid != instance.primary_node):
283
284
285
          all_result = False

    # if this is a DRBD disk, return its port to the pool
Helga Velroyen's avatar
Helga Velroyen committed
286
    if device.dev_type in constants.DTS_DRBD:
287
288
289
290
291
292
      ports_to_release.add(device.logical_id[2])

  if all_result or ignore_failures:
    for port in ports_to_release:
      lu.cfg.AddTcpUdpPort(port)

293
294
  CheckDiskTemplateEnabled(lu.cfg.GetClusterInfo(), instance.disk_template)

Santi Raffa's avatar
Santi Raffa committed
295
  if instance.disk_template in [constants.DT_FILE, constants.DT_SHARED_FILE]:
296
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
Thomas Thrainer's avatar
Thomas Thrainer committed
297
298
    if target_node_uuid:
      tgt = target_node_uuid
299
300
301
302
303
    else:
      tgt = instance.primary_node
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
    if result.fail_msg:
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
Thomas Thrainer's avatar
Thomas Thrainer committed
304
                    file_storage_dir, lu.cfg.GetNodeName(tgt), result.fail_msg)
305
306
307
308
309
      all_result = False

  return all_result


310
def NICToTuple(lu, nic):
311
312
313
314
315
316
317
318
319
320
321
322
  """Build a tupple of nic information.

  @type lu:  L{LogicalUnit}
  @param lu: the logical unit on whose behalf we execute
  @type nic: L{objects.NIC}
  @param nic: nic to convert to hooks tuple

  """
  cluster = lu.cfg.GetClusterInfo()
  filled_params = cluster.SimpleFillNIC(nic.nicparams)
  mode = filled_params[constants.NIC_MODE]
  link = filled_params[constants.NIC_LINK]
323
  vlan = filled_params[constants.NIC_VLAN]
324
325
326
327
  netinfo = None
  if nic.network:
    nobj = lu.cfg.GetNetwork(nic.network)
    netinfo = objects.Network.ToDict(nobj)
328
329
  return (nic.name, nic.uuid, nic.ip, nic.mac, mode, link, vlan,
          nic.network, netinfo)
330
331


332
def NICListToTuple(lu, nics):
333
334
335
336
337
338
339
340
341
342
343
344
345
  """Build a list of nic information tuples.

  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
  value in LUInstanceQueryData.

  @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 = []
  for nic in nics:
346
    hooks_nics.append(NICToTuple(lu, nic))
347
  return hooks_nics
348
349


350
def CopyLockList(names):
351
352
353
354
355
356
357
358
359
360
361
  """Makes a copy of a list of lock names.

  Handles L{locking.ALL_SET} correctly.

  """
  if names == locking.ALL_SET:
    return locking.ALL_SET
  else:
    return names[:]


362
def ReleaseLocks(lu, level, names=None, keep=None):
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
  """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

  owned = lu.owned_locks(level)
  if not owned:
    # Not owning any lock at this level, do nothing
    pass

  elif should_release:
    retain = []
    release = []

    # Determine which locks to release
    for name in owned:
      if should_release(name):
        release.append(name)
      else:
        retain.append(name)

    assert len(lu.owned_locks(level)) == (len(retain) + len(release))

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

    assert frozenset(lu.owned_locks(level)) == frozenset(retain)
  else:
    # Release everything
    lu.glm.release(level)

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


def _ComputeIPolicyNodeViolation(ipolicy, instance, current_group,
                                 target_group, cfg,
414
                                 _compute_fn=ComputeIPolicyInstanceViolation):
415
416
417
418
419
420
421
422
423
  """Compute if instance meets the specs of the new target group.

  @param ipolicy: The ipolicy to verify
  @param instance: The instance object to verify
  @param current_group: The current group of the instance
  @param target_group: The new group of the instance
  @type cfg: L{config.ConfigWriter}
  @param cfg: Cluster configuration
  @param _compute_fn: The function to verify ipolicy (unittest only)
424
  @see: L{ganeti.cmdlib.common.ComputeIPolicySpecViolation}
425
426
427
428
429
430
431
432

  """
  if current_group == target_group:
    return []
  else:
    return _compute_fn(ipolicy, instance, cfg)


433
434
def CheckTargetNodeIPolicy(lu, ipolicy, instance, node, cfg, ignore=False,
                           _compute_fn=_ComputeIPolicyNodeViolation):
435
436
437
438
439
440
441
442
443
  """Checks that the target node is correct in terms of instance policy.

  @param ipolicy: The ipolicy to verify
  @param instance: The instance object to verify
  @param node: The new node to relocate
  @type cfg: L{config.ConfigWriter}
  @param cfg: Cluster configuration
  @param ignore: Ignore violations of the ipolicy
  @param _compute_fn: The function to verify ipolicy (unittest only)
444
  @see: L{ganeti.cmdlib.common.ComputeIPolicySpecViolation}
445
446
447
448
449
450
451
452
453
454
455
456
457
458

  """
  primary_node = lu.cfg.GetNodeInfo(instance.primary_node)
  res = _compute_fn(ipolicy, instance, primary_node.group, node.group, cfg)

  if res:
    msg = ("Instance does not meet target node group's (%s) instance"
           " policy: %s") % (node.group, utils.CommaJoin(res))
    if ignore:
      lu.LogWarning(msg)
    else:
      raise errors.OpPrereqError(msg, errors.ECODE_INVAL)


459
def GetInstanceInfoText(instance):
460
461
462
463
  """Compute that text that should be added to the disk's metadata.

  """
  return "originstname+%s" % instance.name
464
465


Thomas Thrainer's avatar
Thomas Thrainer committed
466
def CheckNodeFreeMemory(lu, node_uuid, reason, requested, hvname, hvparams):
467
468
469
470
471
472
473
474
475
  """Checks if a node has enough free memory.

  This function checks if a given node has the needed amount of free
  memory. In case the node has less memory or we cannot get the
  information from the node, this function raises an OpPrereqError
  exception.

  @type lu: C{LogicalUnit}
  @param lu: a logical unit from which we get configuration data
Thomas Thrainer's avatar
Thomas Thrainer committed
476
477
  @type node_uuid: C{str}
  @param node_uuid: the node to check
478
479
480
481
  @type reason: C{str}
  @param reason: string to use in the error message
  @type requested: C{int}
  @param requested: the amount of memory in MiB to check for
482
483
484
485
  @type hvname: string
  @param hvname: the hypervisor's name
  @type hvparams: dict of strings
  @param hvparams: the hypervisor's parameters
486
487
488
489
490
491
  @rtype: integer
  @return: node current free memory
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
      we cannot check the node

  """
Thomas Thrainer's avatar
Thomas Thrainer committed
492
  node_name = lu.cfg.GetNodeName(node_uuid)
493
  nodeinfo = lu.rpc.call_node_info([node_uuid], None, [(hvname, hvparams)])
Thomas Thrainer's avatar
Thomas Thrainer committed
494
495
496
  nodeinfo[node_uuid].Raise("Can't get data from node %s" % node_name,
                            prereq=True, ecode=errors.ECODE_ENVIRON)
  (_, _, (hv_info, )) = nodeinfo[node_uuid].payload
497
498
499
500

  free_mem = hv_info.get("memory_free", None)
  if not isinstance(free_mem, int):
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
Thomas Thrainer's avatar
Thomas Thrainer committed
501
                               " was '%s'" % (node_name, free_mem),
502
503
504
505
                               errors.ECODE_ENVIRON)
  if requested > free_mem:
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
                               " needed %s MiB, available %s MiB" %
Thomas Thrainer's avatar
Thomas Thrainer committed
506
                               (node_name, reason, requested, free_mem),
507
508
509
510
                               errors.ECODE_NORES)
  return free_mem


Thomas Thrainer's avatar
Thomas Thrainer committed
511
def CheckInstanceBridgesExist(lu, instance, node_uuid=None):
512
513
514
  """Check that the brigdes needed by an instance exist.

  """
Thomas Thrainer's avatar
Thomas Thrainer committed
515
516
517
  if node_uuid is None:
    node_uuid = instance.primary_node
  CheckNicsBridgesExist(lu, instance.nics, node_uuid)
518
519


Thomas Thrainer's avatar
Thomas Thrainer committed
520
def CheckNicsBridgesExist(lu, nics, node_uuid):
521
522
523
524
  """Check that the brigdes needed by a list of nics exist.

  """
  cluster = lu.cfg.GetClusterInfo()
Thomas Thrainer's avatar
Thomas Thrainer committed
525
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in nics]
526
527
528
  brlist = [params[constants.NIC_LINK] for params in paramslist
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
  if brlist:
Thomas Thrainer's avatar
Thomas Thrainer committed
529
    result = lu.rpc.call_bridges_exist(node_uuid, brlist)
530
    result.Raise("Error checking bridges on destination node '%s'" %
Thomas Thrainer's avatar
Thomas Thrainer committed
531
532
                 lu.cfg.GetNodeName(node_uuid), prereq=True,
                 ecode=errors.ECODE_ENVIRON)
533
534


Thomas Thrainer's avatar
Thomas Thrainer committed
535
def CheckNodeHasOS(lu, node_uuid, os_name, force_variant):
536
537
538
  """Ensure that a node supports a given OS.

  @param lu: the LU on behalf of which we make the check
Thomas Thrainer's avatar
Thomas Thrainer committed
539
  @param node_uuid: the node to check
540
541
542
543
544
  @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

  """
Thomas Thrainer's avatar
Thomas Thrainer committed
545
  result = lu.rpc.call_os_get(node_uuid, os_name)
546
  result.Raise("OS '%s' not in supported OS list for node %s" %
Thomas Thrainer's avatar
Thomas Thrainer committed
547
               (os_name, lu.cfg.GetNodeName(node_uuid)),
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
               prereq=True, ecode=errors.ECODE_INVAL)
  if not force_variant:
    _CheckOSVariant(result.payload, os_name)


def _CheckOSVariant(os_obj, name):
  """Check whether an OS name conforms to the os variants specification.

  @type os_obj: L{objects.OS}
  @param os_obj: OS object to check
  @type name: string
  @param name: OS name passed by the user, to check for validity

  """
  variant = objects.OS.GetVariant(name)
  if not os_obj.supported_variants:
    if variant:
      raise errors.OpPrereqError("OS '%s' doesn't support variants ('%s'"
                                 " passed)" % (os_obj.name, variant),
                                 errors.ECODE_INVAL)
    return
  if not variant:
    raise errors.OpPrereqError("OS name must include a variant",
                               errors.ECODE_INVAL)

  if variant not in os_obj.supported_variants:
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)