Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib / instance.py @ 88acff3f

History | View | Annotate | Download (143.2 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 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
"""Logical units dealing with instances."""
23

    
24
import OpenSSL
25
import copy
26
import logging
27
import os
28

    
29
from ganeti import compat
30
from ganeti import constants
31
from ganeti import errors
32
from ganeti import ht
33
from ganeti import hypervisor
34
from ganeti import locking
35
from ganeti.masterd import iallocator
36
from ganeti import masterd
37
from ganeti import netutils
38
from ganeti import objects
39
from ganeti import pathutils
40
from ganeti import rpc
41
from ganeti import utils
42

    
43
from ganeti.cmdlib.base import NoHooksLU, LogicalUnit, ResultWithJobs
44

    
45
from ganeti.cmdlib.common import INSTANCE_DOWN, \
46
  INSTANCE_NOT_RUNNING, CAN_CHANGE_INSTANCE_OFFLINE, CheckNodeOnline, \
47
  ShareAll, GetDefaultIAllocator, CheckInstanceNodeGroups, \
48
  LoadNodeEvacResult, CheckIAllocatorOrNode, CheckParamsNotGlobal, \
49
  IsExclusiveStorageEnabledNode, CheckHVParams, CheckOSParams, \
50
  AnnotateDiskParams, GetUpdatedParams, ExpandInstanceUuidAndName, \
51
  ComputeIPolicySpecViolation, CheckInstanceState, ExpandNodeUuidAndName, \
52
  CheckDiskTemplateEnabled, IsValidDiskAccessModeCombination
53
from ganeti.cmdlib.instance_storage import CreateDisks, \
54
  CheckNodesFreeDiskPerVG, WipeDisks, WipeOrCleanupDisks, WaitForSync, \
55
  IsExclusiveStorageEnabledNodeUuid, CreateSingleBlockDev, ComputeDisks, \
56
  CheckRADOSFreeSpace, ComputeDiskSizePerVG, GenerateDiskTemplate, \
57
  StartInstanceDisks, ShutdownInstanceDisks, AssembleInstanceDisks, \
58
  CheckSpindlesExclusiveStorage
59
from ganeti.cmdlib.instance_utils import BuildInstanceHookEnvByObject, \
60
  GetClusterDomainSecret, BuildInstanceHookEnv, NICListToTuple, \
61
  NICToTuple, CheckNodeNotDrained, RemoveInstance, CopyLockList, \
62
  ReleaseLocks, CheckNodeVmCapable, CheckTargetNodeIPolicy, \
63
  GetInstanceInfoText, RemoveDisks, CheckNodeFreeMemory, \
64
  CheckInstanceBridgesExist, CheckNicsBridgesExist, CheckNodeHasOS
65

    
66
import ganeti.masterd.instance
67

    
68

    
69
#: Type description for changes as returned by L{_ApplyContainerMods}'s
70
#: callbacks
71
_TApplyContModsCbChanges = \
72
  ht.TMaybeListOf(ht.TAnd(ht.TIsLength(2), ht.TItems([
73
    ht.TNonEmptyString,
74
    ht.TAny,
75
    ])))
76

    
77

    
78
def _CheckHostnameSane(lu, name):
79
  """Ensures that a given hostname resolves to a 'sane' name.
80

81
  The given name is required to be a prefix of the resolved hostname,
82
  to prevent accidental mismatches.
83

84
  @param lu: the logical unit on behalf of which we're checking
85
  @param name: the name we should resolve and check
86
  @return: the resolved hostname object
87

88
  """
89
  hostname = netutils.GetHostname(name=name)
90
  if hostname.name != name:
91
    lu.LogInfo("Resolved given name '%s' to '%s'", name, hostname.name)
92
  if not utils.MatchNameComponent(name, [hostname.name]):
93
    raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
94
                                " same as given hostname '%s'") %
95
                               (hostname.name, name), errors.ECODE_INVAL)
96
  return hostname
97

    
98

    
99
def _CheckOpportunisticLocking(op):
100
  """Generate error if opportunistic locking is not possible.
101

102
  """
103
  if op.opportunistic_locking and not op.iallocator:
104
    raise errors.OpPrereqError("Opportunistic locking is only available in"
105
                               " combination with an instance allocator",
106
                               errors.ECODE_INVAL)
107

    
108

    
109
def _CreateInstanceAllocRequest(op, disks, nics, beparams, node_name_whitelist):
110
  """Wrapper around IAReqInstanceAlloc.
111

112
  @param op: The instance opcode
113
  @param disks: The computed disks
114
  @param nics: The computed nics
115
  @param beparams: The full filled beparams
116
  @param node_name_whitelist: List of nodes which should appear as online to the
117
    allocator (unless the node is already marked offline)
118

119
  @returns: A filled L{iallocator.IAReqInstanceAlloc}
120

121
  """
122
  spindle_use = beparams[constants.BE_SPINDLE_USE]
123
  return iallocator.IAReqInstanceAlloc(name=op.instance_name,
124
                                       disk_template=op.disk_template,
125
                                       tags=op.tags,
126
                                       os=op.os_type,
127
                                       vcpus=beparams[constants.BE_VCPUS],
128
                                       memory=beparams[constants.BE_MAXMEM],
129
                                       spindle_use=spindle_use,
130
                                       disks=disks,
131
                                       nics=[n.ToDict() for n in nics],
132
                                       hypervisor=op.hypervisor,
133
                                       node_whitelist=node_name_whitelist)
134

    
135

    
136
def _ComputeFullBeParams(op, cluster):
137
  """Computes the full beparams.
138

139
  @param op: The instance opcode
140
  @param cluster: The cluster config object
141

142
  @return: The fully filled beparams
143

144
  """
145
  default_beparams = cluster.beparams[constants.PP_DEFAULT]
146
  for param, value in op.beparams.iteritems():
147
    if value == constants.VALUE_AUTO:
148
      op.beparams[param] = default_beparams[param]
149
  objects.UpgradeBeParams(op.beparams)
150
  utils.ForceDictType(op.beparams, constants.BES_PARAMETER_TYPES)
151
  return cluster.SimpleFillBE(op.beparams)
152

    
153

    
154
def _ComputeNics(op, cluster, default_ip, cfg, ec_id):
155
  """Computes the nics.
156

157
  @param op: The instance opcode
158
  @param cluster: Cluster configuration object
159
  @param default_ip: The default ip to assign
160
  @param cfg: An instance of the configuration object
161
  @param ec_id: Execution context ID
162

163
  @returns: The build up nics
164

165
  """
166
  nics = []
167
  for nic in op.nics:
168
    nic_mode_req = nic.get(constants.INIC_MODE, None)
169
    nic_mode = nic_mode_req
170
    if nic_mode is None or nic_mode == constants.VALUE_AUTO:
171
      nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
172

    
173
    net = nic.get(constants.INIC_NETWORK, None)
174
    link = nic.get(constants.NIC_LINK, None)
175
    ip = nic.get(constants.INIC_IP, None)
176
    vlan = nic.get(constants.INIC_VLAN, None)
177

    
178
    if net is None or net.lower() == constants.VALUE_NONE:
179
      net = None
180
    else:
181
      if nic_mode_req is not None or link is not None:
182
        raise errors.OpPrereqError("If network is given, no mode or link"
183
                                   " is allowed to be passed",
184
                                   errors.ECODE_INVAL)
185

    
186
    if vlan is not None and nic_mode != constants.NIC_MODE_OVS:
187
      raise errors.OpPrereqError("VLAN is given, but network mode is not"
188
                                 " openvswitch", errors.ECODE_INVAL)
189

    
190
    # ip validity checks
191
    if ip is None or ip.lower() == constants.VALUE_NONE:
192
      nic_ip = None
193
    elif ip.lower() == constants.VALUE_AUTO:
194
      if not op.name_check:
195
        raise errors.OpPrereqError("IP address set to auto but name checks"
196
                                   " have been skipped",
197
                                   errors.ECODE_INVAL)
198
      nic_ip = default_ip
199
    else:
200
      # We defer pool operations until later, so that the iallocator has
201
      # filled in the instance's node(s) dimara
202
      if ip.lower() == constants.NIC_IP_POOL:
203
        if net is None:
204
          raise errors.OpPrereqError("if ip=pool, parameter network"
205
                                     " must be passed too",
206
                                     errors.ECODE_INVAL)
207

    
208
      elif not netutils.IPAddress.IsValid(ip):
209
        raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
210
                                   errors.ECODE_INVAL)
211

    
212
      nic_ip = ip
213

    
214
    # TODO: check the ip address for uniqueness
215
    if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
216
      raise errors.OpPrereqError("Routed nic mode requires an ip address",
217
                                 errors.ECODE_INVAL)
218

    
219
    # MAC address verification
220
    mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
221
    if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
222
      mac = utils.NormalizeAndValidateMac(mac)
223

    
224
      try:
225
        # TODO: We need to factor this out
226
        cfg.ReserveMAC(mac, ec_id)
227
      except errors.ReservationError:
228
        raise errors.OpPrereqError("MAC address %s already in use"
229
                                   " in cluster" % mac,
230
                                   errors.ECODE_NOTUNIQUE)
231

    
232
    #  Build nic parameters
233
    nicparams = {}
234
    if nic_mode_req:
235
      nicparams[constants.NIC_MODE] = nic_mode
236
    if link:
237
      nicparams[constants.NIC_LINK] = link
238
    if vlan:
239
      nicparams[constants.NIC_VLAN] = vlan
240

    
241
    check_params = cluster.SimpleFillNIC(nicparams)
242
    objects.NIC.CheckParameterSyntax(check_params)
243
    net_uuid = cfg.LookupNetwork(net)
244
    name = nic.get(constants.INIC_NAME, None)
245
    if name is not None and name.lower() == constants.VALUE_NONE:
246
      name = None
247
    nic_obj = objects.NIC(mac=mac, ip=nic_ip, name=name,
248
                          network=net_uuid, nicparams=nicparams)
249
    nic_obj.uuid = cfg.GenerateUniqueID(ec_id)
250
    nics.append(nic_obj)
251

    
252
  return nics
253

    
254

    
255
def _CheckForConflictingIp(lu, ip, node_uuid):
256
  """In case of conflicting IP address raise error.
257

258
  @type ip: string
259
  @param ip: IP address
260
  @type node_uuid: string
261
  @param node_uuid: node UUID
262

263
  """
264
  (conf_net, _) = lu.cfg.CheckIPInNodeGroup(ip, node_uuid)
265
  if conf_net is not None:
266
    raise errors.OpPrereqError(("The requested IP address (%s) belongs to"
267
                                " network %s, but the target NIC does not." %
268
                                (ip, conf_net)),
269
                               errors.ECODE_STATE)
270

    
271
  return (None, None)
272

    
273

    
274
def _ComputeIPolicyInstanceSpecViolation(
275
  ipolicy, instance_spec, disk_template,
276
  _compute_fn=ComputeIPolicySpecViolation):
277
  """Compute if instance specs meets the specs of ipolicy.
278

279
  @type ipolicy: dict
280
  @param ipolicy: The ipolicy to verify against
281
  @param instance_spec: dict
282
  @param instance_spec: The instance spec to verify
283
  @type disk_template: string
284
  @param disk_template: the disk template of the instance
285
  @param _compute_fn: The function to verify ipolicy (unittest only)
286
  @see: L{ComputeIPolicySpecViolation}
287

288
  """
289
  mem_size = instance_spec.get(constants.ISPEC_MEM_SIZE, None)
290
  cpu_count = instance_spec.get(constants.ISPEC_CPU_COUNT, None)
291
  disk_count = instance_spec.get(constants.ISPEC_DISK_COUNT, 0)
292
  disk_sizes = instance_spec.get(constants.ISPEC_DISK_SIZE, [])
293
  nic_count = instance_spec.get(constants.ISPEC_NIC_COUNT, 0)
294
  spindle_use = instance_spec.get(constants.ISPEC_SPINDLE_USE, None)
295

    
296
  return _compute_fn(ipolicy, mem_size, cpu_count, disk_count, nic_count,
297
                     disk_sizes, spindle_use, disk_template)
298

    
299

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

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

308
  """
309
  variant = objects.OS.GetVariant(name)
310
  if not os_obj.supported_variants:
311
    if variant:
312
      raise errors.OpPrereqError("OS '%s' doesn't support variants ('%s'"
313
                                 " passed)" % (os_obj.name, variant),
314
                                 errors.ECODE_INVAL)
315
    return
316
  if not variant:
317
    raise errors.OpPrereqError("OS name must include a variant",
318
                               errors.ECODE_INVAL)
319

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

    
323

    
324
class LUInstanceCreate(LogicalUnit):
325
  """Create an instance.
326

327
  """
328
  HPATH = "instance-add"
329
  HTYPE = constants.HTYPE_INSTANCE
330
  REQ_BGL = False
331

    
332
  def _CheckDiskTemplateValid(self):
333
    """Checks validity of disk template.
334

335
    """
336
    cluster = self.cfg.GetClusterInfo()
337
    if self.op.disk_template is None:
338
      # FIXME: It would be better to take the default disk template from the
339
      # ipolicy, but for the ipolicy we need the primary node, which we get from
340
      # the iallocator, which wants the disk template as input. To solve this
341
      # chicken-and-egg problem, it should be possible to specify just a node
342
      # group from the iallocator and take the ipolicy from that.
343
      self.op.disk_template = cluster.enabled_disk_templates[0]
344
    CheckDiskTemplateEnabled(cluster, self.op.disk_template)
345

    
346
  def _CheckDiskArguments(self):
347
    """Checks validity of disk-related arguments.
348

349
    """
350
    # check that disk's names are unique and valid
351
    utils.ValidateDeviceNames("disk", self.op.disks)
352

    
353
    self._CheckDiskTemplateValid()
354

    
355
    # check disks. parameter names and consistent adopt/no-adopt strategy
356
    has_adopt = has_no_adopt = False
357
    for disk in self.op.disks:
358
      if self.op.disk_template != constants.DT_EXT:
359
        utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
360
      if constants.IDISK_ADOPT in disk:
361
        has_adopt = True
362
      else:
363
        has_no_adopt = True
364
    if has_adopt and has_no_adopt:
365
      raise errors.OpPrereqError("Either all disks are adopted or none is",
366
                                 errors.ECODE_INVAL)
367
    if has_adopt:
368
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
369
        raise errors.OpPrereqError("Disk adoption is not supported for the"
370
                                   " '%s' disk template" %
371
                                   self.op.disk_template,
372
                                   errors.ECODE_INVAL)
373
      if self.op.iallocator is not None:
374
        raise errors.OpPrereqError("Disk adoption not allowed with an"
375
                                   " iallocator script", errors.ECODE_INVAL)
376
      if self.op.mode == constants.INSTANCE_IMPORT:
377
        raise errors.OpPrereqError("Disk adoption not allowed for"
378
                                   " instance import", errors.ECODE_INVAL)
379
    else:
380
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
381
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
382
                                   " but no 'adopt' parameter given" %
383
                                   self.op.disk_template,
384
                                   errors.ECODE_INVAL)
385

    
386
    self.adopt_disks = has_adopt
387

    
388
  def _CheckVLANArguments(self):
389
    """ Check validity of VLANs if given
390

391
    """
392
    for nic in self.op.nics:
393
      vlan = nic.get(constants.INIC_VLAN, None)
394
      if vlan:
395
        if vlan[0] == ".":
396
          # vlan starting with dot means single untagged vlan,
397
          # might be followed by trunk (:)
398
          if not vlan[1:].isdigit():
399
            vlanlist = vlan[1:].split(':')
400
            for vl in vlanlist:
401
              if not vl.isdigit():
402
                raise errors.OpPrereqError("Specified VLAN parameter is "
403
                                           "invalid : %s" % vlan,
404
                                             errors.ECODE_INVAL)
405
        elif vlan[0] == ":":
406
          # Trunk - tagged only
407
          vlanlist = vlan[1:].split(':')
408
          for vl in vlanlist:
409
            if not vl.isdigit():
410
              raise errors.OpPrereqError("Specified VLAN parameter is invalid"
411
                                           " : %s" % vlan, errors.ECODE_INVAL)
412
        elif vlan.isdigit():
413
          # This is the simplest case. No dots, only single digit
414
          # -> Create untagged access port, dot needs to be added
415
          nic[constants.INIC_VLAN] = "." + vlan
416
        else:
417
          raise errors.OpPrereqError("Specified VLAN parameter is invalid"
418
                                       " : %s" % vlan, errors.ECODE_INVAL)
419

    
420
  def CheckArguments(self):
421
    """Check arguments.
422

423
    """
424
    # do not require name_check to ease forward/backward compatibility
425
    # for tools
426
    if self.op.no_install and self.op.start:
427
      self.LogInfo("No-installation mode selected, disabling startup")
428
      self.op.start = False
429
    # validate/normalize the instance name
430
    self.op.instance_name = \
431
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
432

    
433
    if self.op.ip_check and not self.op.name_check:
434
      # TODO: make the ip check more flexible and not depend on the name check
435
      raise errors.OpPrereqError("Cannot do IP address check without a name"
436
                                 " check", errors.ECODE_INVAL)
437

    
438
    # check nics' parameter names
439
    for nic in self.op.nics:
440
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
441
    # check that NIC's parameters names are unique and valid
442
    utils.ValidateDeviceNames("NIC", self.op.nics)
443

    
444
    self._CheckVLANArguments()
445

    
446
    self._CheckDiskArguments()
447
    assert self.op.disk_template is not None
448

    
449
    # instance name verification
450
    if self.op.name_check:
451
      self.hostname = _CheckHostnameSane(self, self.op.instance_name)
452
      self.op.instance_name = self.hostname.name
453
      # used in CheckPrereq for ip ping check
454
      self.check_ip = self.hostname.ip
455
    else:
456
      self.check_ip = None
457

    
458
    # file storage checks
459
    if (self.op.file_driver and
460
        not self.op.file_driver in constants.FILE_DRIVER):
461
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
462
                                 self.op.file_driver, errors.ECODE_INVAL)
463

    
464
    # set default file_driver if unset and required
465
    if (not self.op.file_driver and
466
        self.op.disk_template in [constants.DT_FILE,
467
                                  constants.DT_SHARED_FILE]):
468
      self.op.file_driver = constants.FD_LOOP
469

    
470
    ### Node/iallocator related checks
471
    CheckIAllocatorOrNode(self, "iallocator", "pnode")
472

    
473
    if self.op.pnode is not None:
474
      if self.op.disk_template in constants.DTS_INT_MIRROR:
475
        if self.op.snode is None:
476
          raise errors.OpPrereqError("The networked disk templates need"
477
                                     " a mirror node", errors.ECODE_INVAL)
478
      elif self.op.snode:
479
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
480
                        " template")
481
        self.op.snode = None
482

    
483
    _CheckOpportunisticLocking(self.op)
484

    
485
    if self.op.mode == constants.INSTANCE_IMPORT:
486
      # On import force_variant must be True, because if we forced it at
487
      # initial install, our only chance when importing it back is that it
488
      # works again!
489
      self.op.force_variant = True
490

    
491
      if self.op.no_install:
492
        self.LogInfo("No-installation mode has no effect during import")
493

    
494
    elif self.op.mode == constants.INSTANCE_CREATE:
495
      if self.op.os_type is None:
496
        raise errors.OpPrereqError("No guest OS specified",
497
                                   errors.ECODE_INVAL)
498
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
499
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
500
                                   " installation" % self.op.os_type,
501
                                   errors.ECODE_STATE)
502
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
503
      self._cds = GetClusterDomainSecret()
504

    
505
      # Check handshake to ensure both clusters have the same domain secret
506
      src_handshake = self.op.source_handshake
507
      if not src_handshake:
508
        raise errors.OpPrereqError("Missing source handshake",
509
                                   errors.ECODE_INVAL)
510

    
511
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
512
                                                           src_handshake)
513
      if errmsg:
514
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
515
                                   errors.ECODE_INVAL)
516

    
517
      # Load and check source CA
518
      self.source_x509_ca_pem = self.op.source_x509_ca
519
      if not self.source_x509_ca_pem:
520
        raise errors.OpPrereqError("Missing source X509 CA",
521
                                   errors.ECODE_INVAL)
522

    
523
      try:
524
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
525
                                                    self._cds)
526
      except OpenSSL.crypto.Error, err:
527
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
528
                                   (err, ), errors.ECODE_INVAL)
529

    
530
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
531
      if errcode is not None:
532
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
533
                                   errors.ECODE_INVAL)
534

    
535
      self.source_x509_ca = cert
536

    
537
      src_instance_name = self.op.source_instance_name
538
      if not src_instance_name:
539
        raise errors.OpPrereqError("Missing source instance name",
540
                                   errors.ECODE_INVAL)
541

    
542
      self.source_instance_name = \
543
        netutils.GetHostname(name=src_instance_name).name
544

    
545
    else:
546
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
547
                                 self.op.mode, errors.ECODE_INVAL)
548

    
549
  def ExpandNames(self):
550
    """ExpandNames for CreateInstance.
551

552
    Figure out the right locks for instance creation.
553

554
    """
555
    self.needed_locks = {}
556

    
557
    # this is just a preventive check, but someone might still add this
558
    # instance in the meantime, and creation will fail at lock-add time
559
    if self.op.instance_name in\
560
      [inst.name for inst in self.cfg.GetAllInstancesInfo().values()]:
561
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
562
                                 self.op.instance_name, errors.ECODE_EXISTS)
563

    
564
    self.add_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
565

    
566
    if self.op.iallocator:
567
      # TODO: Find a solution to not lock all nodes in the cluster, e.g. by
568
      # specifying a group on instance creation and then selecting nodes from
569
      # that group
570
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
571
      self.needed_locks[locking.LEVEL_NODE_ALLOC] = locking.ALL_SET
572

    
573
      if self.op.opportunistic_locking:
574
        self.opportunistic_locks[locking.LEVEL_NODE] = True
575
        self.opportunistic_locks[locking.LEVEL_NODE_RES] = True
576
    else:
577
      (self.op.pnode_uuid, self.op.pnode) = \
578
        ExpandNodeUuidAndName(self.cfg, self.op.pnode_uuid, self.op.pnode)
579
      nodelist = [self.op.pnode_uuid]
580
      if self.op.snode is not None:
581
        (self.op.snode_uuid, self.op.snode) = \
582
          ExpandNodeUuidAndName(self.cfg, self.op.snode_uuid, self.op.snode)
583
        nodelist.append(self.op.snode_uuid)
584
      self.needed_locks[locking.LEVEL_NODE] = nodelist
585

    
586
    # in case of import lock the source node too
587
    if self.op.mode == constants.INSTANCE_IMPORT:
588
      src_node = self.op.src_node
589
      src_path = self.op.src_path
590

    
591
      if src_path is None:
592
        self.op.src_path = src_path = self.op.instance_name
593

    
594
      if src_node is None:
595
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
596
        self.needed_locks[locking.LEVEL_NODE_ALLOC] = locking.ALL_SET
597
        self.op.src_node = None
598
        if os.path.isabs(src_path):
599
          raise errors.OpPrereqError("Importing an instance from a path"
600
                                     " requires a source node option",
601
                                     errors.ECODE_INVAL)
602
      else:
603
        (self.op.src_node_uuid, self.op.src_node) = (_, src_node) = \
604
          ExpandNodeUuidAndName(self.cfg, self.op.src_node_uuid, src_node)
605
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
606
          self.needed_locks[locking.LEVEL_NODE].append(self.op.src_node_uuid)
607
        if not os.path.isabs(src_path):
608
          self.op.src_path = \
609
            utils.PathJoin(pathutils.EXPORT_DIR, src_path)
610

    
611
    self.needed_locks[locking.LEVEL_NODE_RES] = \
612
      CopyLockList(self.needed_locks[locking.LEVEL_NODE])
613

    
614
  def _RunAllocator(self):
615
    """Run the allocator based on input opcode.
616

617
    """
618
    if self.op.opportunistic_locking:
619
      # Only consider nodes for which a lock is held
620
      node_name_whitelist = self.cfg.GetNodeNames(
621
        self.owned_locks(locking.LEVEL_NODE))
622
    else:
623
      node_name_whitelist = None
624

    
625
    req = _CreateInstanceAllocRequest(self.op, self.disks,
626
                                      self.nics, self.be_full,
627
                                      node_name_whitelist)
628
    ial = iallocator.IAllocator(self.cfg, self.rpc, req)
629

    
630
    ial.Run(self.op.iallocator)
631

    
632
    if not ial.success:
633
      # When opportunistic locks are used only a temporary failure is generated
634
      if self.op.opportunistic_locking:
635
        ecode = errors.ECODE_TEMP_NORES
636
      else:
637
        ecode = errors.ECODE_NORES
638

    
639
      raise errors.OpPrereqError("Can't compute nodes using"
640
                                 " iallocator '%s': %s" %
641
                                 (self.op.iallocator, ial.info),
642
                                 ecode)
643

    
644
    (self.op.pnode_uuid, self.op.pnode) = \
645
      ExpandNodeUuidAndName(self.cfg, None, ial.result[0])
646
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
647
                 self.op.instance_name, self.op.iallocator,
648
                 utils.CommaJoin(ial.result))
649

    
650
    assert req.RequiredNodes() in (1, 2), "Wrong node count from iallocator"
651

    
652
    if req.RequiredNodes() == 2:
653
      (self.op.snode_uuid, self.op.snode) = \
654
        ExpandNodeUuidAndName(self.cfg, None, ial.result[1])
655

    
656
  def BuildHooksEnv(self):
657
    """Build hooks env.
658

659
    This runs on master, primary and secondary nodes of the instance.
660

661
    """
662
    env = {
663
      "ADD_MODE": self.op.mode,
664
      }
665
    if self.op.mode == constants.INSTANCE_IMPORT:
666
      env["SRC_NODE"] = self.op.src_node
667
      env["SRC_PATH"] = self.op.src_path
668
      env["SRC_IMAGES"] = self.src_images
669

    
670
    env.update(BuildInstanceHookEnv(
671
      name=self.op.instance_name,
672
      primary_node_name=self.op.pnode,
673
      secondary_node_names=self.cfg.GetNodeNames(self.secondaries),
674
      status=self.op.start,
675
      os_type=self.op.os_type,
676
      minmem=self.be_full[constants.BE_MINMEM],
677
      maxmem=self.be_full[constants.BE_MAXMEM],
678
      vcpus=self.be_full[constants.BE_VCPUS],
679
      nics=NICListToTuple(self, self.nics),
680
      disk_template=self.op.disk_template,
681
      disks=[(d[constants.IDISK_NAME], d.get("uuid", ""),
682
              d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
683
             for d in self.disks],
684
      bep=self.be_full,
685
      hvp=self.hv_full,
686
      hypervisor_name=self.op.hypervisor,
687
      tags=self.op.tags,
688
      ))
689

    
690
    return env
691

    
692
  def BuildHooksNodes(self):
693
    """Build hooks nodes.
694

695
    """
696
    nl = [self.cfg.GetMasterNode(), self.op.pnode_uuid] + self.secondaries
697
    return nl, nl
698

    
699
  def _ReadExportInfo(self):
700
    """Reads the export information from disk.
701

702
    It will override the opcode source node and path with the actual
703
    information, if these two were not specified before.
704

705
    @return: the export information
706

707
    """
708
    assert self.op.mode == constants.INSTANCE_IMPORT
709

    
710
    if self.op.src_node_uuid is None:
711
      locked_nodes = self.owned_locks(locking.LEVEL_NODE)
712
      exp_list = self.rpc.call_export_list(locked_nodes)
713
      found = False
714
      for node_uuid in exp_list:
715
        if exp_list[node_uuid].fail_msg:
716
          continue
717
        if self.op.src_path in exp_list[node_uuid].payload:
718
          found = True
719
          self.op.src_node = self.cfg.GetNodeInfo(node_uuid).name
720
          self.op.src_node_uuid = node_uuid
721
          self.op.src_path = utils.PathJoin(pathutils.EXPORT_DIR,
722
                                            self.op.src_path)
723
          break
724
      if not found:
725
        raise errors.OpPrereqError("No export found for relative path %s" %
726
                                   self.op.src_path, errors.ECODE_INVAL)
727

    
728
    CheckNodeOnline(self, self.op.src_node_uuid)
729
    result = self.rpc.call_export_info(self.op.src_node_uuid, self.op.src_path)
730
    result.Raise("No export or invalid export found in dir %s" %
731
                 self.op.src_path)
732

    
733
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
734
    if not export_info.has_section(constants.INISECT_EXP):
735
      raise errors.ProgrammerError("Corrupted export config",
736
                                   errors.ECODE_ENVIRON)
737

    
738
    ei_version = export_info.get(constants.INISECT_EXP, "version")
739
    if int(ei_version) != constants.EXPORT_VERSION:
740
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
741
                                 (ei_version, constants.EXPORT_VERSION),
742
                                 errors.ECODE_ENVIRON)
743
    return export_info
744

    
745
  def _ReadExportParams(self, einfo):
746
    """Use export parameters as defaults.
747

748
    In case the opcode doesn't specify (as in override) some instance
749
    parameters, then try to use them from the export information, if
750
    that declares them.
751

752
    """
753
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
754

    
755
    if not self.op.disks:
756
      disks = []
757
      # TODO: import the disk iv_name too
758
      for idx in range(constants.MAX_DISKS):
759
        if einfo.has_option(constants.INISECT_INS, "disk%d_size" % idx):
760
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
761
          disks.append({constants.IDISK_SIZE: disk_sz})
762
      self.op.disks = disks
763
      if not disks and self.op.disk_template != constants.DT_DISKLESS:
764
        raise errors.OpPrereqError("No disk info specified and the export"
765
                                   " is missing the disk information",
766
                                   errors.ECODE_INVAL)
767

    
768
    if not self.op.nics:
769
      nics = []
770
      for idx in range(constants.MAX_NICS):
771
        if einfo.has_option(constants.INISECT_INS, "nic%d_mac" % idx):
772
          ndict = {}
773
          for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
774
            nic_param_name = "nic%d_%s" % (idx, name)
775
            if einfo.has_option(constants.INISECT_INS, nic_param_name):
776
              v = einfo.get(constants.INISECT_INS, nic_param_name)
777
              ndict[name] = v
778
          nics.append(ndict)
779
        else:
780
          break
781
      self.op.nics = nics
782

    
783
    if not self.op.tags and einfo.has_option(constants.INISECT_INS, "tags"):
784
      self.op.tags = einfo.get(constants.INISECT_INS, "tags").split()
785

    
786
    if (self.op.hypervisor is None and
787
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
788
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
789

    
790
    if einfo.has_section(constants.INISECT_HYP):
791
      # use the export parameters but do not override the ones
792
      # specified by the user
793
      for name, value in einfo.items(constants.INISECT_HYP):
794
        if name not in self.op.hvparams:
795
          self.op.hvparams[name] = value
796

    
797
    if einfo.has_section(constants.INISECT_BEP):
798
      # use the parameters, without overriding
799
      for name, value in einfo.items(constants.INISECT_BEP):
800
        if name not in self.op.beparams:
801
          self.op.beparams[name] = value
802
        # Compatibility for the old "memory" be param
803
        if name == constants.BE_MEMORY:
804
          if constants.BE_MAXMEM not in self.op.beparams:
805
            self.op.beparams[constants.BE_MAXMEM] = value
806
          if constants.BE_MINMEM not in self.op.beparams:
807
            self.op.beparams[constants.BE_MINMEM] = value
808
    else:
809
      # try to read the parameters old style, from the main section
810
      for name in constants.BES_PARAMETERS:
811
        if (name not in self.op.beparams and
812
            einfo.has_option(constants.INISECT_INS, name)):
813
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
814

    
815
    if einfo.has_section(constants.INISECT_OSP):
816
      # use the parameters, without overriding
817
      for name, value in einfo.items(constants.INISECT_OSP):
818
        if name not in self.op.osparams:
819
          self.op.osparams[name] = value
820

    
821
  def _RevertToDefaults(self, cluster):
822
    """Revert the instance parameters to the default values.
823

824
    """
825
    # hvparams
826
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
827
    for name in self.op.hvparams.keys():
828
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
829
        del self.op.hvparams[name]
830
    # beparams
831
    be_defs = cluster.SimpleFillBE({})
832
    for name in self.op.beparams.keys():
833
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
834
        del self.op.beparams[name]
835
    # nic params
836
    nic_defs = cluster.SimpleFillNIC({})
837
    for nic in self.op.nics:
838
      for name in constants.NICS_PARAMETERS:
839
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
840
          del nic[name]
841
    # osparams
842
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
843
    for name in self.op.osparams.keys():
844
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
845
        del self.op.osparams[name]
846

    
847
  def _CalculateFileStorageDir(self):
848
    """Calculate final instance file storage dir.
849

850
    """
851
    # file storage dir calculation/check
852
    self.instance_file_storage_dir = None
853
    if self.op.disk_template in constants.DTS_FILEBASED:
854
      # build the full file storage dir path
855
      joinargs = []
856

    
857
      if self.op.disk_template == constants.DT_SHARED_FILE:
858
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
859
      else:
860
        get_fsd_fn = self.cfg.GetFileStorageDir
861

    
862
      cfg_storagedir = get_fsd_fn()
863
      if not cfg_storagedir:
864
        raise errors.OpPrereqError("Cluster file storage dir not defined",
865
                                   errors.ECODE_STATE)
866
      joinargs.append(cfg_storagedir)
867

    
868
      if self.op.file_storage_dir is not None:
869
        joinargs.append(self.op.file_storage_dir)
870

    
871
      joinargs.append(self.op.instance_name)
872

    
873
      # pylint: disable=W0142
874
      self.instance_file_storage_dir = utils.PathJoin(*joinargs)
875

    
876
  def CheckPrereq(self): # pylint: disable=R0914
877
    """Check prerequisites.
878

879
    """
880
    self._CalculateFileStorageDir()
881

    
882
    if self.op.mode == constants.INSTANCE_IMPORT:
883
      export_info = self._ReadExportInfo()
884
      self._ReadExportParams(export_info)
885
      self._old_instance_name = export_info.get(constants.INISECT_INS, "name")
886
    else:
887
      self._old_instance_name = None
888

    
889
    if (not self.cfg.GetVGName() and
890
        self.op.disk_template not in constants.DTS_NOT_LVM):
891
      raise errors.OpPrereqError("Cluster does not support lvm-based"
892
                                 " instances", errors.ECODE_STATE)
893

    
894
    if (self.op.hypervisor is None or
895
        self.op.hypervisor == constants.VALUE_AUTO):
896
      self.op.hypervisor = self.cfg.GetHypervisorType()
897

    
898
    cluster = self.cfg.GetClusterInfo()
899
    enabled_hvs = cluster.enabled_hypervisors
900
    if self.op.hypervisor not in enabled_hvs:
901
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
902
                                 " cluster (%s)" %
903
                                 (self.op.hypervisor, ",".join(enabled_hvs)),
904
                                 errors.ECODE_STATE)
905

    
906
    # Check tag validity
907
    for tag in self.op.tags:
908
      objects.TaggableObject.ValidateTag(tag)
909

    
910
    # check hypervisor parameter syntax (locally)
911
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
912
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
913
                                      self.op.hvparams)
914
    hv_type = hypervisor.GetHypervisorClass(self.op.hypervisor)
915
    hv_type.CheckParameterSyntax(filled_hvp)
916
    self.hv_full = filled_hvp
917
    # check that we don't specify global parameters on an instance
918
    CheckParamsNotGlobal(self.op.hvparams, constants.HVC_GLOBALS, "hypervisor",
919
                         "instance", "cluster")
920

    
921
    # fill and remember the beparams dict
922
    self.be_full = _ComputeFullBeParams(self.op, cluster)
923

    
924
    # build os parameters
925
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
926

    
927
    # now that hvp/bep are in final format, let's reset to defaults,
928
    # if told to do so
929
    if self.op.identify_defaults:
930
      self._RevertToDefaults(cluster)
931

    
932
    # NIC buildup
933
    self.nics = _ComputeNics(self.op, cluster, self.check_ip, self.cfg,
934
                             self.proc.GetECId())
935

    
936
    # disk checks/pre-build
937
    default_vg = self.cfg.GetVGName()
938
    self.disks = ComputeDisks(self.op, default_vg)
939

    
940
    if self.op.mode == constants.INSTANCE_IMPORT:
941
      disk_images = []
942
      for idx in range(len(self.disks)):
943
        option = "disk%d_dump" % idx
944
        if export_info.has_option(constants.INISECT_INS, option):
945
          # FIXME: are the old os-es, disk sizes, etc. useful?
946
          export_name = export_info.get(constants.INISECT_INS, option)
947
          image = utils.PathJoin(self.op.src_path, export_name)
948
          disk_images.append(image)
949
        else:
950
          disk_images.append(False)
951

    
952
      self.src_images = disk_images
953

    
954
      if self.op.instance_name == self._old_instance_name:
955
        for idx, nic in enumerate(self.nics):
956
          if nic.mac == constants.VALUE_AUTO:
957
            nic_mac_ini = "nic%d_mac" % idx
958
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
959

    
960
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
961

    
962
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
963
    if self.op.ip_check:
964
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
965
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
966
                                   (self.check_ip, self.op.instance_name),
967
                                   errors.ECODE_NOTUNIQUE)
968

    
969
    #### mac address generation
970
    # By generating here the mac address both the allocator and the hooks get
971
    # the real final mac address rather than the 'auto' or 'generate' value.
972
    # There is a race condition between the generation and the instance object
973
    # creation, which means that we know the mac is valid now, but we're not
974
    # sure it will be when we actually add the instance. If things go bad
975
    # adding the instance will abort because of a duplicate mac, and the
976
    # creation job will fail.
977
    for nic in self.nics:
978
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
979
        nic.mac = self.cfg.GenerateMAC(nic.network, self.proc.GetECId())
980

    
981
    #### allocator run
982

    
983
    if self.op.iallocator is not None:
984
      self._RunAllocator()
985

    
986
    # Release all unneeded node locks
987
    keep_locks = filter(None, [self.op.pnode_uuid, self.op.snode_uuid,
988
                               self.op.src_node_uuid])
989
    ReleaseLocks(self, locking.LEVEL_NODE, keep=keep_locks)
990
    ReleaseLocks(self, locking.LEVEL_NODE_RES, keep=keep_locks)
991
    ReleaseLocks(self, locking.LEVEL_NODE_ALLOC)
992

    
993
    assert (self.owned_locks(locking.LEVEL_NODE) ==
994
            self.owned_locks(locking.LEVEL_NODE_RES)), \
995
      "Node locks differ from node resource locks"
996

    
997
    #### node related checks
998

    
999
    # check primary node
1000
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode_uuid)
1001
    assert self.pnode is not None, \
1002
      "Cannot retrieve locked node %s" % self.op.pnode_uuid
1003
    if pnode.offline:
1004
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
1005
                                 pnode.name, errors.ECODE_STATE)
1006
    if pnode.drained:
1007
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
1008
                                 pnode.name, errors.ECODE_STATE)
1009
    if not pnode.vm_capable:
1010
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
1011
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
1012

    
1013
    self.secondaries = []
1014

    
1015
    # Fill in any IPs from IP pools. This must happen here, because we need to
1016
    # know the nic's primary node, as specified by the iallocator
1017
    for idx, nic in enumerate(self.nics):
1018
      net_uuid = nic.network
1019
      if net_uuid is not None:
1020
        nobj = self.cfg.GetNetwork(net_uuid)
1021
        netparams = self.cfg.GetGroupNetParams(net_uuid, self.pnode.uuid)
1022
        if netparams is None:
1023
          raise errors.OpPrereqError("No netparams found for network"
1024
                                     " %s. Probably not connected to"
1025
                                     " node's %s nodegroup" %
1026
                                     (nobj.name, self.pnode.name),
1027
                                     errors.ECODE_INVAL)
1028
        self.LogInfo("NIC/%d inherits netparams %s" %
1029
                     (idx, netparams.values()))
1030
        nic.nicparams = dict(netparams)
1031
        if nic.ip is not None:
1032
          if nic.ip.lower() == constants.NIC_IP_POOL:
1033
            try:
1034
              nic.ip = self.cfg.GenerateIp(net_uuid, self.proc.GetECId())
1035
            except errors.ReservationError:
1036
              raise errors.OpPrereqError("Unable to get a free IP for NIC %d"
1037
                                         " from the address pool" % idx,
1038
                                         errors.ECODE_STATE)
1039
            self.LogInfo("Chose IP %s from network %s", nic.ip, nobj.name)
1040
          else:
1041
            try:
1042
              self.cfg.ReserveIp(net_uuid, nic.ip, self.proc.GetECId())
1043
            except errors.ReservationError:
1044
              raise errors.OpPrereqError("IP address %s already in use"
1045
                                         " or does not belong to network %s" %
1046
                                         (nic.ip, nobj.name),
1047
                                         errors.ECODE_NOTUNIQUE)
1048

    
1049
      # net is None, ip None or given
1050
      elif self.op.conflicts_check:
1051
        _CheckForConflictingIp(self, nic.ip, self.pnode.uuid)
1052

    
1053
    # mirror node verification
1054
    if self.op.disk_template in constants.DTS_INT_MIRROR:
1055
      if self.op.snode_uuid == pnode.uuid:
1056
        raise errors.OpPrereqError("The secondary node cannot be the"
1057
                                   " primary node", errors.ECODE_INVAL)
1058
      CheckNodeOnline(self, self.op.snode_uuid)
1059
      CheckNodeNotDrained(self, self.op.snode_uuid)
1060
      CheckNodeVmCapable(self, self.op.snode_uuid)
1061
      self.secondaries.append(self.op.snode_uuid)
1062

    
1063
      snode = self.cfg.GetNodeInfo(self.op.snode_uuid)
1064
      if pnode.group != snode.group:
1065
        self.LogWarning("The primary and secondary nodes are in two"
1066
                        " different node groups; the disk parameters"
1067
                        " from the first disk's node group will be"
1068
                        " used")
1069

    
1070
    nodes = [pnode]
1071
    if self.op.disk_template in constants.DTS_INT_MIRROR:
1072
      nodes.append(snode)
1073
    has_es = lambda n: IsExclusiveStorageEnabledNode(self.cfg, n)
1074
    excl_stor = compat.any(map(has_es, nodes))
1075
    if excl_stor and not self.op.disk_template in constants.DTS_EXCL_STORAGE:
1076
      raise errors.OpPrereqError("Disk template %s not supported with"
1077
                                 " exclusive storage" % self.op.disk_template,
1078
                                 errors.ECODE_STATE)
1079
    for disk in self.disks:
1080
      CheckSpindlesExclusiveStorage(disk, excl_stor, True)
1081

    
1082
    node_uuids = [pnode.uuid] + self.secondaries
1083

    
1084
    if not self.adopt_disks:
1085
      if self.op.disk_template == constants.DT_RBD:
1086
        # _CheckRADOSFreeSpace() is just a placeholder.
1087
        # Any function that checks prerequisites can be placed here.
1088
        # Check if there is enough space on the RADOS cluster.
1089
        CheckRADOSFreeSpace()
1090
      elif self.op.disk_template == constants.DT_EXT:
1091
        # FIXME: Function that checks prereqs if needed
1092
        pass
1093
      elif self.op.disk_template in constants.DTS_LVM:
1094
        # Check lv size requirements, if not adopting
1095
        req_sizes = ComputeDiskSizePerVG(self.op.disk_template, self.disks)
1096
        CheckNodesFreeDiskPerVG(self, node_uuids, req_sizes)
1097
      else:
1098
        # FIXME: add checks for other, non-adopting, non-lvm disk templates
1099
        pass
1100

    
1101
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
1102
      all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
1103
                                disk[constants.IDISK_ADOPT])
1104
                     for disk in self.disks])
1105
      if len(all_lvs) != len(self.disks):
1106
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
1107
                                   errors.ECODE_INVAL)
1108
      for lv_name in all_lvs:
1109
        try:
1110
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
1111
          # to ReserveLV uses the same syntax
1112
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
1113
        except errors.ReservationError:
1114
          raise errors.OpPrereqError("LV named %s used by another instance" %
1115
                                     lv_name, errors.ECODE_NOTUNIQUE)
1116

    
1117
      vg_names = self.rpc.call_vg_list([pnode.uuid])[pnode.uuid]
1118
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
1119

    
1120
      node_lvs = self.rpc.call_lv_list([pnode.uuid],
1121
                                       vg_names.payload.keys())[pnode.uuid]
1122
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
1123
      node_lvs = node_lvs.payload
1124

    
1125
      delta = all_lvs.difference(node_lvs.keys())
1126
      if delta:
1127
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
1128
                                   utils.CommaJoin(delta),
1129
                                   errors.ECODE_INVAL)
1130
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
1131
      if online_lvs:
1132
        raise errors.OpPrereqError("Online logical volumes found, cannot"
1133
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
1134
                                   errors.ECODE_STATE)
1135
      # update the size of disk based on what is found
1136
      for dsk in self.disks:
1137
        dsk[constants.IDISK_SIZE] = \
1138
          int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
1139
                                        dsk[constants.IDISK_ADOPT])][0]))
1140

    
1141
    elif self.op.disk_template == constants.DT_BLOCK:
1142
      # Normalize and de-duplicate device paths
1143
      all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
1144
                       for disk in self.disks])
1145
      if len(all_disks) != len(self.disks):
1146
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
1147
                                   errors.ECODE_INVAL)
1148
      baddisks = [d for d in all_disks
1149
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
1150
      if baddisks:
1151
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
1152
                                   " cannot be adopted" %
1153
                                   (utils.CommaJoin(baddisks),
1154
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
1155
                                   errors.ECODE_INVAL)
1156

    
1157
      node_disks = self.rpc.call_bdev_sizes([pnode.uuid],
1158
                                            list(all_disks))[pnode.uuid]
1159
      node_disks.Raise("Cannot get block device information from node %s" %
1160
                       pnode.name)
1161
      node_disks = node_disks.payload
1162
      delta = all_disks.difference(node_disks.keys())
1163
      if delta:
1164
        raise errors.OpPrereqError("Missing block device(s): %s" %
1165
                                   utils.CommaJoin(delta),
1166
                                   errors.ECODE_INVAL)
1167
      for dsk in self.disks:
1168
        dsk[constants.IDISK_SIZE] = \
1169
          int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
1170

    
1171
    # Check disk access param to be compatible with specified hypervisor
1172
    node_info = self.cfg.GetNodeInfo(self.op.pnode_uuid)
1173
    node_group = self.cfg.GetNodeGroup(node_info.group)
1174
    disk_params = self.cfg.GetGroupDiskParams(node_group)
1175
    access_type = disk_params[self.op.disk_template].get(
1176
      constants.RBD_ACCESS, constants.DISK_KERNELSPACE
1177
    )
1178

    
1179
    if not IsValidDiskAccessModeCombination(self.op.hypervisor,
1180
                                            self.op.disk_template,
1181
                                            access_type):
1182
      raise errors.OpPrereqError("Selected hypervisor (%s) cannot be"
1183
                                 " used with %s disk access param" %
1184
                                 (self.op.hypervisor, access_type),
1185
                                  errors.ECODE_STATE)
1186

    
1187
    # Verify instance specs
1188
    spindle_use = self.be_full.get(constants.BE_SPINDLE_USE, None)
1189
    ispec = {
1190
      constants.ISPEC_MEM_SIZE: self.be_full.get(constants.BE_MAXMEM, None),
1191
      constants.ISPEC_CPU_COUNT: self.be_full.get(constants.BE_VCPUS, None),
1192
      constants.ISPEC_DISK_COUNT: len(self.disks),
1193
      constants.ISPEC_DISK_SIZE: [disk[constants.IDISK_SIZE]
1194
                                  for disk in self.disks],
1195
      constants.ISPEC_NIC_COUNT: len(self.nics),
1196
      constants.ISPEC_SPINDLE_USE: spindle_use,
1197
      }
1198

    
1199
    group_info = self.cfg.GetNodeGroup(pnode.group)
1200
    ipolicy = ganeti.masterd.instance.CalculateGroupIPolicy(cluster, group_info)
1201
    res = _ComputeIPolicyInstanceSpecViolation(ipolicy, ispec,
1202
                                               self.op.disk_template)
1203
    if not self.op.ignore_ipolicy and res:
1204
      msg = ("Instance allocation to group %s (%s) violates policy: %s" %
1205
             (pnode.group, group_info.name, utils.CommaJoin(res)))
1206
      raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
1207

    
1208
    CheckHVParams(self, node_uuids, self.op.hypervisor, self.op.hvparams)
1209

    
1210
    CheckNodeHasOS(self, pnode.uuid, self.op.os_type, self.op.force_variant)
1211
    # check OS parameters (remotely)
1212
    CheckOSParams(self, True, node_uuids, self.op.os_type, self.os_full)
1213

    
1214
    CheckNicsBridgesExist(self, self.nics, self.pnode.uuid)
1215

    
1216
    #TODO: _CheckExtParams (remotely)
1217
    # Check parameters for extstorage
1218

    
1219
    # memory check on primary node
1220
    #TODO(dynmem): use MINMEM for checking
1221
    if self.op.start:
1222
      hvfull = objects.FillDict(cluster.hvparams.get(self.op.hypervisor, {}),
1223
                                self.op.hvparams)
1224
      CheckNodeFreeMemory(self, self.pnode.uuid,
1225
                          "creating instance %s" % self.op.instance_name,
1226
                          self.be_full[constants.BE_MAXMEM],
1227
                          self.op.hypervisor, hvfull)
1228

    
1229
    self.dry_run_result = list(node_uuids)
1230

    
1231
  def Exec(self, feedback_fn):
1232
    """Create and add the instance to the cluster.
1233

1234
    """
1235
    assert not (self.owned_locks(locking.LEVEL_NODE_RES) -
1236
                self.owned_locks(locking.LEVEL_NODE)), \
1237
      "Node locks differ from node resource locks"
1238
    assert not self.glm.is_owned(locking.LEVEL_NODE_ALLOC)
1239

    
1240
    ht_kind = self.op.hypervisor
1241
    if ht_kind in constants.HTS_REQ_PORT:
1242
      network_port = self.cfg.AllocatePort()
1243
    else:
1244
      network_port = None
1245

    
1246
    instance_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
1247

    
1248
    # This is ugly but we got a chicken-egg problem here
1249
    # We can only take the group disk parameters, as the instance
1250
    # has no disks yet (we are generating them right here).
1251
    nodegroup = self.cfg.GetNodeGroup(self.pnode.group)
1252
    disks = GenerateDiskTemplate(self,
1253
                                 self.op.disk_template,
1254
                                 instance_uuid, self.pnode.uuid,
1255
                                 self.secondaries,
1256
                                 self.disks,
1257
                                 self.instance_file_storage_dir,
1258
                                 self.op.file_driver,
1259
                                 0,
1260
                                 feedback_fn,
1261
                                 self.cfg.GetGroupDiskParams(nodegroup))
1262

    
1263
    iobj = objects.Instance(name=self.op.instance_name,
1264
                            uuid=instance_uuid,
1265
                            os=self.op.os_type,
1266
                            primary_node=self.pnode.uuid,
1267
                            nics=self.nics, disks=disks,
1268
                            disk_template=self.op.disk_template,
1269
                            disks_active=False,
1270
                            admin_state=constants.ADMINST_DOWN,
1271
                            network_port=network_port,
1272
                            beparams=self.op.beparams,
1273
                            hvparams=self.op.hvparams,
1274
                            hypervisor=self.op.hypervisor,
1275
                            osparams=self.op.osparams,
1276
                            )
1277

    
1278
    if self.op.tags:
1279
      for tag in self.op.tags:
1280
        iobj.AddTag(tag)
1281

    
1282
    if self.adopt_disks:
1283
      if self.op.disk_template == constants.DT_PLAIN:
1284
        # rename LVs to the newly-generated names; we need to construct
1285
        # 'fake' LV disks with the old data, plus the new unique_id
1286
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
1287
        rename_to = []
1288
        for t_dsk, a_dsk in zip(tmp_disks, self.disks):
1289
          rename_to.append(t_dsk.logical_id)
1290
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
1291
        result = self.rpc.call_blockdev_rename(self.pnode.uuid,
1292
                                               zip(tmp_disks, rename_to))
1293
        result.Raise("Failed to rename adoped LVs")
1294
    else:
1295
      feedback_fn("* creating instance disks...")
1296
      try:
1297
        CreateDisks(self, iobj)
1298
      except errors.OpExecError:
1299
        self.LogWarning("Device creation failed")
1300
        self.cfg.ReleaseDRBDMinors(self.op.instance_name)
1301
        raise
1302

    
1303
    feedback_fn("adding instance %s to cluster config" % self.op.instance_name)
1304

    
1305
    self.cfg.AddInstance(iobj, self.proc.GetECId())
1306

    
1307
    # Declare that we don't want to remove the instance lock anymore, as we've
1308
    # added the instance to the config
1309
    del self.remove_locks[locking.LEVEL_INSTANCE]
1310

    
1311
    if self.op.mode == constants.INSTANCE_IMPORT:
1312
      # Release unused nodes
1313
      ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node_uuid])
1314
    else:
1315
      # Release all nodes
1316
      ReleaseLocks(self, locking.LEVEL_NODE)
1317

    
1318
    disk_abort = False
1319
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
1320
      feedback_fn("* wiping instance disks...")
1321
      try:
1322
        WipeDisks(self, iobj)
1323
      except errors.OpExecError, err:
1324
        logging.exception("Wiping disks failed")
1325
        self.LogWarning("Wiping instance disks failed (%s)", err)
1326
        disk_abort = True
1327

    
1328
    if disk_abort:
1329
      # Something is already wrong with the disks, don't do anything else
1330
      pass
1331
    elif self.op.wait_for_sync:
1332
      disk_abort = not WaitForSync(self, iobj)
1333
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
1334
      # make sure the disks are not degraded (still sync-ing is ok)
1335
      feedback_fn("* checking mirrors status")
1336
      disk_abort = not WaitForSync(self, iobj, oneshot=True)
1337
    else:
1338
      disk_abort = False
1339

    
1340
    if disk_abort:
1341
      RemoveDisks(self, iobj)
1342
      self.cfg.RemoveInstance(iobj.uuid)
1343
      # Make sure the instance lock gets removed
1344
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
1345
      raise errors.OpExecError("There are some degraded disks for"
1346
                               " this instance")
1347

    
1348
    # instance disks are now active
1349
    iobj.disks_active = True
1350

    
1351
    # Release all node resource locks
1352
    ReleaseLocks(self, locking.LEVEL_NODE_RES)
1353

    
1354
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
1355
      if self.op.mode == constants.INSTANCE_CREATE:
1356
        if not self.op.no_install:
1357
          pause_sync = (iobj.disk_template in constants.DTS_INT_MIRROR and
1358
                        not self.op.wait_for_sync)
1359
          if pause_sync:
1360
            feedback_fn("* pausing disk sync to install instance OS")
1361
            result = self.rpc.call_blockdev_pause_resume_sync(self.pnode.uuid,
1362
                                                              (iobj.disks,
1363
                                                               iobj), True)
1364
            for idx, success in enumerate(result.payload):
1365
              if not success:
1366
                logging.warn("pause-sync of instance %s for disk %d failed",
1367
                             self.op.instance_name, idx)
1368

    
1369
          feedback_fn("* running the instance OS create scripts...")
1370
          # FIXME: pass debug option from opcode to backend
1371
          os_add_result = \
1372
            self.rpc.call_instance_os_add(self.pnode.uuid, (iobj, None), False,
1373
                                          self.op.debug_level)
1374
          if pause_sync:
1375
            feedback_fn("* resuming disk sync")
1376
            result = self.rpc.call_blockdev_pause_resume_sync(self.pnode.uuid,
1377
                                                              (iobj.disks,
1378
                                                               iobj), False)
1379
            for idx, success in enumerate(result.payload):
1380
              if not success:
1381
                logging.warn("resume-sync of instance %s for disk %d failed",
1382
                             self.op.instance_name, idx)
1383

    
1384
          os_add_result.Raise("Could not add os for instance %s"
1385
                              " on node %s" % (self.op.instance_name,
1386
                                               self.pnode.name))
1387

    
1388
      else:
1389
        if self.op.mode == constants.INSTANCE_IMPORT:
1390
          feedback_fn("* running the instance OS import scripts...")
1391

    
1392
          transfers = []
1393

    
1394
          for idx, image in enumerate(self.src_images):
1395
            if not image:
1396
              continue
1397

    
1398
            # FIXME: pass debug option from opcode to backend
1399
            dt = masterd.instance.DiskTransfer("disk/%s" % idx,
1400
                                               constants.IEIO_FILE, (image, ),
1401
                                               constants.IEIO_SCRIPT,
1402
                                               ((iobj.disks[idx], iobj), idx),
1403
                                               None)
1404
            transfers.append(dt)
1405

    
1406
          import_result = \
1407
            masterd.instance.TransferInstanceData(self, feedback_fn,
1408
                                                  self.op.src_node_uuid,
1409
                                                  self.pnode.uuid,
1410
                                                  self.pnode.secondary_ip,
1411
                                                  self.op.compress,
1412
                                                  iobj, transfers)
1413
          if not compat.all(import_result):
1414
            self.LogWarning("Some disks for instance %s on node %s were not"
1415
                            " imported successfully" % (self.op.instance_name,
1416
                                                        self.pnode.name))
1417

    
1418
          rename_from = self._old_instance_name
1419

    
1420
        elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
1421
          feedback_fn("* preparing remote import...")
1422
          # The source cluster will stop the instance before attempting to make
1423
          # a connection. In some cases stopping an instance can take a long
1424
          # time, hence the shutdown timeout is added to the connection
1425
          # timeout.
1426
          connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
1427
                             self.op.source_shutdown_timeout)
1428
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
1429

    
1430
          assert iobj.primary_node == self.pnode.uuid
1431
          disk_results = \
1432
            masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
1433
                                          self.source_x509_ca,
1434
                                          self._cds, self.op.compress, timeouts)
1435
          if not compat.all(disk_results):
1436
            # TODO: Should the instance still be started, even if some disks
1437
            # failed to import (valid for local imports, too)?
1438
            self.LogWarning("Some disks for instance %s on node %s were not"
1439
                            " imported successfully" % (self.op.instance_name,
1440
                                                        self.pnode.name))
1441

    
1442
          rename_from = self.source_instance_name
1443

    
1444
        else:
1445
          # also checked in the prereq part
1446
          raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
1447
                                       % self.op.mode)
1448

    
1449
        # Run rename script on newly imported instance
1450
        assert iobj.name == self.op.instance_name
1451
        feedback_fn("Running rename script for %s" % self.op.instance_name)
1452
        result = self.rpc.call_instance_run_rename(self.pnode.uuid, iobj,
1453
                                                   rename_from,
1454
                                                   self.op.debug_level)
1455
        result.Warn("Failed to run rename script for %s on node %s" %
1456
                    (self.op.instance_name, self.pnode.name), self.LogWarning)
1457

    
1458
    assert not self.owned_locks(locking.LEVEL_NODE_RES)
1459

    
1460
    if self.op.start:
1461
      iobj.admin_state = constants.ADMINST_UP
1462
      self.cfg.Update(iobj, feedback_fn)
1463
      logging.info("Starting instance %s on node %s", self.op.instance_name,
1464
                   self.pnode.name)
1465
      feedback_fn("* starting instance...")
1466
      result = self.rpc.call_instance_start(self.pnode.uuid, (iobj, None, None),
1467
                                            False, self.op.reason)
1468
      result.Raise("Could not start instance")
1469

    
1470
    return list(iobj.all_nodes)
1471

    
1472

    
1473
class LUInstanceRename(LogicalUnit):
1474
  """Rename an instance.
1475

1476
  """
1477
  HPATH = "instance-rename"
1478
  HTYPE = constants.HTYPE_INSTANCE
1479

    
1480
  def CheckArguments(self):
1481
    """Check arguments.
1482

1483
    """
1484
    if self.op.ip_check and not self.op.name_check:
1485
      # TODO: make the ip check more flexible and not depend on the name check
1486
      raise errors.OpPrereqError("IP address check requires a name check",
1487
                                 errors.ECODE_INVAL)
1488

    
1489
  def BuildHooksEnv(self):
1490
    """Build hooks env.
1491

1492
    This runs on master, primary and secondary nodes of the instance.
1493

1494
    """
1495
    env = BuildInstanceHookEnvByObject(self, self.instance)
1496
    env["INSTANCE_NEW_NAME"] = self.op.new_name
1497
    return env
1498

    
1499
  def BuildHooksNodes(self):
1500
    """Build hooks nodes.
1501

1502
    """
1503
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
1504
    return (nl, nl)
1505

    
1506
  def CheckPrereq(self):
1507
    """Check prerequisites.
1508

1509
    This checks that the instance is in the cluster and is not running.
1510

1511
    """
1512
    (self.op.instance_uuid, self.op.instance_name) = \
1513
      ExpandInstanceUuidAndName(self.cfg, self.op.instance_uuid,
1514
                                self.op.instance_name)
1515
    instance = self.cfg.GetInstanceInfo(self.op.instance_uuid)
1516
    assert instance is not None
1517

    
1518
    # It should actually not happen that an instance is running with a disabled
1519
    # disk template, but in case it does, the renaming of file-based instances
1520
    # will fail horribly. Thus, we test it before.
1521
    if (instance.disk_template in constants.DTS_FILEBASED and
1522
        self.op.new_name != instance.name):
1523
      CheckDiskTemplateEnabled(self.cfg.GetClusterInfo(),
1524
                               instance.disk_template)
1525

    
1526
    CheckNodeOnline(self, instance.primary_node)
1527
    CheckInstanceState(self, instance, INSTANCE_NOT_RUNNING,
1528
                       msg="cannot rename")
1529
    self.instance = instance
1530

    
1531
    new_name = self.op.new_name
1532
    if self.op.name_check:
1533
      hostname = _CheckHostnameSane(self, new_name)
1534
      new_name = self.op.new_name = hostname.name
1535
      if (self.op.ip_check and
1536
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
1537
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
1538
                                   (hostname.ip, new_name),
1539
                                   errors.ECODE_NOTUNIQUE)
1540

    
1541
    instance_names = [inst.name for
1542
                      inst in self.cfg.GetAllInstancesInfo().values()]
1543
    if new_name in instance_names and new_name != instance.name:
1544
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
1545
                                 new_name, errors.ECODE_EXISTS)
1546

    
1547
  def Exec(self, feedback_fn):
1548
    """Rename the instance.
1549

1550
    """
1551
    old_name = self.instance.name
1552

    
1553
    rename_file_storage = False
1554
    if (self.instance.disk_template in constants.DTS_FILEBASED and
1555
        self.op.new_name != self.instance.name):
1556
      old_file_storage_dir = os.path.dirname(
1557
                               self.instance.disks[0].logical_id[1])
1558
      rename_file_storage = True
1559

    
1560
    self.cfg.RenameInstance(self.instance.uuid, self.op.new_name)
1561
    # Change the instance lock. This is definitely safe while we hold the BGL.
1562
    # Otherwise the new lock would have to be added in acquired mode.
1563
    assert self.REQ_BGL
1564
    assert locking.BGL in self.owned_locks(locking.LEVEL_CLUSTER)
1565
    self.glm.remove(locking.LEVEL_INSTANCE, old_name)
1566
    self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
1567

    
1568
    # re-read the instance from the configuration after rename
1569
    renamed_inst = self.cfg.GetInstanceInfo(self.instance.uuid)
1570

    
1571
    if rename_file_storage:
1572
      new_file_storage_dir = os.path.dirname(
1573
                               renamed_inst.disks[0].logical_id[1])
1574
      result = self.rpc.call_file_storage_dir_rename(renamed_inst.primary_node,
1575
                                                     old_file_storage_dir,
1576
                                                     new_file_storage_dir)
1577
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
1578
                   " (but the instance has been renamed in Ganeti)" %
1579
                   (self.cfg.GetNodeName(renamed_inst.primary_node),
1580
                    old_file_storage_dir, new_file_storage_dir))
1581

    
1582
    StartInstanceDisks(self, renamed_inst, None)
1583
    # update info on disks
1584
    info = GetInstanceInfoText(renamed_inst)
1585
    for (idx, disk) in enumerate(renamed_inst.disks):
1586
      for node_uuid in renamed_inst.all_nodes:
1587
        result = self.rpc.call_blockdev_setinfo(node_uuid,
1588
                                                (disk, renamed_inst), info)
1589
        result.Warn("Error setting info on node %s for disk %s" %
1590
                    (self.cfg.GetNodeName(node_uuid), idx), self.LogWarning)
1591
    try:
1592
      result = self.rpc.call_instance_run_rename(renamed_inst.primary_node,
1593
                                                 renamed_inst, old_name,
1594
                                                 self.op.debug_level)
1595
      result.Warn("Could not run OS rename script for instance %s on node %s"
1596
                  " (but the instance has been renamed in Ganeti)" %
1597
                  (renamed_inst.name,
1598
                   self.cfg.GetNodeName(renamed_inst.primary_node)),
1599
                  self.LogWarning)
1600
    finally:
1601
      ShutdownInstanceDisks(self, renamed_inst)
1602

    
1603
    return renamed_inst.name
1604

    
1605

    
1606
class LUInstanceRemove(LogicalUnit):
1607
  """Remove an instance.
1608

1609
  """
1610
  HPATH = "instance-remove"
1611
  HTYPE = constants.HTYPE_INSTANCE
1612
  REQ_BGL = False
1613

    
1614
  def ExpandNames(self):
1615
    self._ExpandAndLockInstance()
1616
    self.needed_locks[locking.LEVEL_NODE] = []
1617
    self.needed_locks[locking.LEVEL_NODE_RES] = []
1618
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
1619

    
1620
  def DeclareLocks(self, level):
1621
    if level == locking.LEVEL_NODE:
1622
      self._LockInstancesNodes()
1623
    elif level == locking.LEVEL_NODE_RES:
1624
      # Copy node locks
1625
      self.needed_locks[locking.LEVEL_NODE_RES] = \
1626
        CopyLockList(self.needed_locks[locking.LEVEL_NODE])
1627

    
1628
  def BuildHooksEnv(self):
1629
    """Build hooks env.
1630

1631
    This runs on master, primary and secondary nodes of the instance.
1632

1633
    """
1634
    env = BuildInstanceHookEnvByObject(self, self.instance)
1635
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
1636
    return env
1637

    
1638
  def BuildHooksNodes(self):
1639
    """Build hooks nodes.
1640

1641
    """
1642
    nl = [self.cfg.GetMasterNode()]
1643
    nl_post = list(self.instance.all_nodes) + nl
1644
    return (nl, nl_post)
1645

    
1646
  def CheckPrereq(self):
1647
    """Check prerequisites.
1648

1649
    This checks that the instance is in the cluster.
1650

1651
    """
1652
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_uuid)
1653
    assert self.instance is not None, \
1654
      "Cannot retrieve locked instance %s" % self.op.instance_name
1655

    
1656
  def Exec(self, feedback_fn):
1657
    """Remove the instance.
1658

1659
    """
1660
    logging.info("Shutting down instance %s on node %s", self.instance.name,
1661
                 self.cfg.GetNodeName(self.instance.primary_node))
1662

    
1663
    result = self.rpc.call_instance_shutdown(self.instance.primary_node,
1664
                                             self.instance,
1665
                                             self.op.shutdown_timeout,
1666
                                             self.op.reason)
1667
    if self.op.ignore_failures:
1668
      result.Warn("Warning: can't shutdown instance", feedback_fn)
1669
    else:
1670
      result.Raise("Could not shutdown instance %s on node %s" %
1671
                   (self.instance.name,
1672
                    self.cfg.GetNodeName(self.instance.primary_node)))
1673

    
1674
    assert (self.owned_locks(locking.LEVEL_NODE) ==
1675
            self.owned_locks(locking.LEVEL_NODE_RES))
1676
    assert not (set(self.instance.all_nodes) -
1677
                self.owned_locks(locking.LEVEL_NODE)), \
1678
      "Not owning correct locks"
1679

    
1680
    RemoveInstance(self, feedback_fn, self.instance, self.op.ignore_failures)
1681

    
1682

    
1683
class LUInstanceMove(LogicalUnit):
1684
  """Move an instance by data-copying.
1685

1686
  """
1687
  HPATH = "instance-move"
1688
  HTYPE = constants.HTYPE_INSTANCE
1689
  REQ_BGL = False
1690

    
1691
  def ExpandNames(self):
1692
    self._ExpandAndLockInstance()
1693
    (self.op.target_node_uuid, self.op.target_node) = \
1694
      ExpandNodeUuidAndName(self.cfg, self.op.target_node_uuid,
1695
                            self.op.target_node)
1696
    self.needed_locks[locking.LEVEL_NODE] = [self.op.target_node_uuid]
1697
    self.needed_locks[locking.LEVEL_NODE_RES] = []
1698
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
1699

    
1700
  def DeclareLocks(self, level):
1701
    if level == locking.LEVEL_NODE:
1702
      self._LockInstancesNodes(primary_only=True)
1703
    elif level == locking.LEVEL_NODE_RES:
1704
      # Copy node locks
1705
      self.needed_locks[locking.LEVEL_NODE_RES] = \
1706
        CopyLockList(self.needed_locks[locking.LEVEL_NODE])
1707

    
1708
  def BuildHooksEnv(self):
1709
    """Build hooks env.
1710

1711
    This runs on master, primary and target nodes of the instance.
1712

1713
    """
1714
    env = {
1715
      "TARGET_NODE": self.op.target_node,
1716
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
1717
      }
1718
    env.update(BuildInstanceHookEnvByObject(self, self.instance))
1719
    return env
1720

    
1721
  def BuildHooksNodes(self):
1722
    """Build hooks nodes.
1723

1724
    """
1725
    nl = [
1726
      self.cfg.GetMasterNode(),
1727
      self.instance.primary_node,
1728
      self.op.target_node_uuid,
1729
      ]
1730
    return (nl, nl)
1731

    
1732
  def CheckPrereq(self):
1733
    """Check prerequisites.
1734

1735
    This checks that the instance is in the cluster.
1736

1737
    """
1738
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_uuid)
1739
    assert self.instance is not None, \
1740
      "Cannot retrieve locked instance %s" % self.op.instance_name
1741

    
1742
    if self.instance.disk_template not in constants.DTS_COPYABLE:
1743
      raise errors.OpPrereqError("Disk template %s not suitable for copying" %
1744
                                 self.instance.disk_template,
1745
                                 errors.ECODE_STATE)
1746

    
1747
    target_node = self.cfg.GetNodeInfo(self.op.target_node_uuid)
1748
    assert target_node is not None, \
1749
      "Cannot retrieve locked node %s" % self.op.target_node
1750

    
1751
    self.target_node_uuid = target_node.uuid
1752
    if target_node.uuid == self.instance.primary_node:
1753
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
1754
                                 (self.instance.name, target_node.name),
1755
                                 errors.ECODE_STATE)
1756

    
1757
    cluster = self.cfg.GetClusterInfo()
1758
    bep = cluster.FillBE(self.instance)
1759

    
1760
    for idx, dsk in enumerate(self.instance.disks):
1761
      if dsk.dev_type not in (constants.DT_PLAIN, constants.DT_FILE,
1762
                              constants.DT_SHARED_FILE):
1763
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
1764
                                   " cannot copy" % idx, errors.ECODE_STATE)
1765

    
1766
    CheckNodeOnline(self, target_node.uuid)
1767
    CheckNodeNotDrained(self, target_node.uuid)
1768
    CheckNodeVmCapable(self, target_node.uuid)
1769
    group_info = self.cfg.GetNodeGroup(target_node.group)
1770
    ipolicy = ganeti.masterd.instance.CalculateGroupIPolicy(cluster, group_info)
1771
    CheckTargetNodeIPolicy(self, ipolicy, self.instance, target_node, self.cfg,
1772
                           ignore=self.op.ignore_ipolicy)
1773

    
1774
    if self.instance.admin_state == constants.ADMINST_UP:
1775
      # check memory requirements on the target node
1776
      CheckNodeFreeMemory(
1777
          self, target_node.uuid, "failing over instance %s" %
1778
          self.instance.name, bep[constants.BE_MAXMEM],
1779
          self.instance.hypervisor,
1780
          cluster.hvparams[self.instance.hypervisor])
1781
    else:
1782
      self.LogInfo("Not checking memory on the secondary node as"
1783
                   " instance will not be started")
1784

    
1785
    # check bridge existance
1786
    CheckInstanceBridgesExist(self, self.instance, node_uuid=target_node.uuid)
1787

    
1788
  def Exec(self, feedback_fn):
1789
    """Move an instance.
1790

1791
    The move is done by shutting it down on its present node, copying
1792
    the data over (slow) and starting it on the new node.
1793

1794
    """
1795
    source_node = self.cfg.GetNodeInfo(self.instance.primary_node)
1796
    target_node = self.cfg.GetNodeInfo(self.target_node_uuid)
1797

    
1798
    self.LogInfo("Shutting down instance %s on source node %s",
1799
                 self.instance.name, source_node.name)
1800

    
1801
    assert (self.owned_locks(locking.LEVEL_NODE) ==
1802
            self.owned_locks(locking.LEVEL_NODE_RES))
1803

    
1804
    result = self.rpc.call_instance_shutdown(source_node.uuid, self.instance,
1805
                                             self.op.shutdown_timeout,
1806
                                             self.op.reason)
1807
    if self.op.ignore_consistency:
1808
      result.Warn("Could not shutdown instance %s on node %s. Proceeding"
1809
                  " anyway. Please make sure node %s is down. Error details" %
1810
                  (self.instance.name, source_node.name, source_node.name),
1811
                  self.LogWarning)
1812
    else:
1813
      result.Raise("Could not shutdown instance %s on node %s" %
1814
                   (self.instance.name, source_node.name))
1815

    
1816
    # create the target disks
1817
    try:
1818
      CreateDisks(self, self.instance, target_node_uuid=target_node.uuid)
1819
    except errors.OpExecError:
1820
      self.LogWarning("Device creation failed")
1821
      self.cfg.ReleaseDRBDMinors(self.instance.uuid)
1822
      raise
1823

    
1824
    errs = []
1825
    transfers = []
1826
    # activate, get path, create transfer jobs
1827
    for idx, disk in enumerate(self.instance.disks):
1828
      # FIXME: pass debug option from opcode to backend
1829
      dt = masterd.instance.DiskTransfer("disk/%s" % idx,
1830
                                         constants.IEIO_RAW_DISK,
1831
                                         (disk, self.instance),
1832
                                         constants.IEIO_RAW_DISK,
1833
                                         (disk, self.instance),
1834
                                         None)
1835
      transfers.append(dt)
1836

    
1837
    import_result = \
1838
      masterd.instance.TransferInstanceData(self, feedback_fn,
1839
                                            source_node.uuid,
1840
                                            target_node.uuid,
1841
                                            target_node.secondary_ip,
1842
                                            self.op.compress,
1843
                                            self.instance, transfers)
1844
    if not compat.all(import_result):
1845
      errs.append("Failed to transfer instance data")
1846

    
1847
    if errs:
1848
      self.LogWarning("Some disks failed to copy, aborting")
1849
      try:
1850
        RemoveDisks(self, self.instance, target_node_uuid=target_node.uuid)
1851
      finally:
1852
        self.cfg.ReleaseDRBDMinors(self.instance.uuid)
1853
        raise errors.OpExecError("Errors during disk copy: %s" %
1854
                                 (",".join(errs),))
1855

    
1856
    self.instance.primary_node = target_node.uuid
1857
    self.cfg.Update(self.instance, feedback_fn)
1858

    
1859
    self.LogInfo("Removing the disks on the original node")
1860
    RemoveDisks(self, self.instance, target_node_uuid=source_node.uuid)
1861

    
1862
    # Only start the instance if it's marked as up
1863
    if self.instance.admin_state == constants.ADMINST_UP:
1864
      self.LogInfo("Starting instance %s on node %s",
1865
                   self.instance.name, target_node.name)
1866

    
1867
      disks_ok, _ = AssembleInstanceDisks(self, self.instance,
1868
                                          ignore_secondaries=True)
1869
      if not disks_ok:
1870
        ShutdownInstanceDisks(self, self.instance)
1871
        raise errors.OpExecError("Can't activate the instance's disks")
1872

    
1873
      result = self.rpc.call_instance_start(target_node.uuid,
1874
                                            (self.instance, None, None), False,
1875
                                            self.op.reason)
1876
      msg = result.fail_msg
1877
      if msg:
1878
        ShutdownInstanceDisks(self, self.instance)
1879
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
1880
                                 (self.instance.name, target_node.name, msg))
1881

    
1882

    
1883
class LUInstanceMultiAlloc(NoHooksLU):
1884
  """Allocates multiple instances at the same time.
1885

1886
  """
1887
  REQ_BGL = False
1888

    
1889
  def CheckArguments(self):
1890
    """Check arguments.
1891

1892
    """
1893
    nodes = []
1894
    for inst in self.op.instances:
1895
      if inst.iallocator is not None:
1896
        raise errors.OpPrereqError("iallocator are not allowed to be set on"
1897
                                   " instance objects", errors.ECODE_INVAL)
1898
      nodes.append(bool(inst.pnode))
1899
      if inst.disk_template in constants.DTS_INT_MIRROR:
1900
        nodes.append(bool(inst.snode))
1901

    
1902
    has_nodes = compat.any(nodes)
1903
    if compat.all(nodes) ^ has_nodes:
1904
      raise errors.OpPrereqError("There are instance objects providing"
1905
                                 " pnode/snode while others do not",
1906
                                 errors.ECODE_INVAL)
1907

    
1908
    if not has_nodes and self.op.iallocator is None:
1909
      default_iallocator = self.cfg.GetDefaultIAllocator()
1910
      if default_iallocator:
1911
        self.op.iallocator = default_iallocator
1912
      else:
1913
        raise errors.OpPrereqError("No iallocator or nodes on the instances"
1914
                                   " given and no cluster-wide default"
1915
                                   " iallocator found; please specify either"
1916
                                   " an iallocator or nodes on the instances"
1917
                                   " or set a cluster-wide default iallocator",
1918
                                   errors.ECODE_INVAL)
1919

    
1920
    _CheckOpportunisticLocking(self.op)
1921

    
1922
    dups = utils.FindDuplicates([op.instance_name for op in self.op.instances])
1923
    if dups:
1924
      raise errors.OpPrereqError("There are duplicate instance names: %s" %
1925
                                 utils.CommaJoin(dups), errors.ECODE_INVAL)
1926

    
1927
  def ExpandNames(self):
1928
    """Calculate the locks.
1929

1930
    """
1931
    self.share_locks = ShareAll()
1932
    self.needed_locks = {
1933
      # iallocator will select nodes and even if no iallocator is used,
1934
      # collisions with LUInstanceCreate should be avoided
1935
      locking.LEVEL_NODE_ALLOC: locking.ALL_SET,
1936
      }
1937

    
1938
    if self.op.iallocator:
1939
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
1940
      self.needed_locks[locking.LEVEL_NODE_RES] = locking.ALL_SET
1941

    
1942
      if self.op.opportunistic_locking:
1943
        self.opportunistic_locks[locking.LEVEL_NODE] = True
1944
        self.opportunistic_locks[locking.LEVEL_NODE_RES] = True
1945
    else:
1946
      nodeslist = []
1947
      for inst in self.op.instances:
1948
        (inst.pnode_uuid, inst.pnode) = \
1949
          ExpandNodeUuidAndName(self.cfg, inst.pnode_uuid, inst.pnode)
1950
        nodeslist.append(inst.pnode_uuid)
1951
        if inst.snode is not None:
1952
          (inst.snode_uuid, inst.snode) = \
1953
            ExpandNodeUuidAndName(self.cfg, inst.snode_uuid, inst.snode)
1954
          nodeslist.append(inst.snode_uuid)
1955

    
1956
      self.needed_locks[locking.LEVEL_NODE] = nodeslist
1957
      # Lock resources of instance's primary and secondary nodes (copy to
1958
      # prevent accidential modification)
1959
      self.needed_locks[locking.LEVEL_NODE_RES] = list(nodeslist)
1960

    
1961
  def CheckPrereq(self):
1962
    """Check prerequisite.
1963

1964
    """
1965
    if self.op.iallocator:
1966
      cluster = self.cfg.GetClusterInfo()
1967
      default_vg = self.cfg.GetVGName()
1968
      ec_id = self.proc.GetECId()
1969

    
1970
      if self.op.opportunistic_locking:
1971
        # Only consider nodes for which a lock is held
1972
        node_whitelist = self.cfg.GetNodeNames(
1973
                           list(self.owned_locks(locking.LEVEL_NODE)))
1974
      else:
1975
        node_whitelist = None
1976

    
1977
      insts = [_CreateInstanceAllocRequest(op, ComputeDisks(op, default_vg),
1978
                                           _ComputeNics(op, cluster, None,
1979
                                                        self.cfg, ec_id),
1980
                                           _ComputeFullBeParams(op, cluster),
1981
                                           node_whitelist)
1982
               for op in self.op.instances]
1983

    
1984
      req = iallocator.IAReqMultiInstanceAlloc(instances=insts)
1985
      ial = iallocator.IAllocator(self.cfg, self.rpc, req)
1986

    
1987
      ial.Run(self.op.iallocator)
1988

    
1989
      if not ial.success:
1990
        raise errors.OpPrereqError("Can't compute nodes using"
1991
                                   " iallocator '%s': %s" %
1992
                                   (self.op.iallocator, ial.info),
1993
                                   errors.ECODE_NORES)
1994

    
1995
      self.ia_result = ial.result
1996

    
1997
    if self.op.dry_run:
1998
      self.dry_run_result = objects.FillDict(self._ConstructPartialResult(), {
1999
        constants.JOB_IDS_KEY: [],
2000
        })
2001

    
2002
  def _ConstructPartialResult(self):
2003
    """Contructs the partial result.
2004

2005
    """
2006
    if self.op.iallocator:
2007
      (allocatable, failed_insts) = self.ia_result
2008
      allocatable_insts = map(compat.fst, allocatable)
2009
    else:
2010
      allocatable_insts = [op.instance_name for op in self.op.instances]
2011
      failed_insts = []
2012

    
2013
    return {
2014
      constants.ALLOCATABLE_KEY: allocatable_insts,
2015
      constants.FAILED_KEY: failed_insts,
2016
      }
2017

    
2018
  def Exec(self, feedback_fn):
2019
    """Executes the opcode.
2020

2021
    """
2022
    jobs = []
2023
    if self.op.iallocator:
2024
      op2inst = dict((op.instance_name, op) for op in self.op.instances)
2025
      (allocatable, failed) = self.ia_result
2026

    
2027
      for (name, node_names) in allocatable:
2028
        op = op2inst.pop(name)
2029

    
2030
        (op.pnode_uuid, op.pnode) = \
2031
          ExpandNodeUuidAndName(self.cfg, None, node_names[0])
2032
        if len(node_names) > 1:
2033
          (op.snode_uuid, op.snode) = \
2034
            ExpandNodeUuidAndName(self.cfg, None, node_names[1])
2035

    
2036
          jobs.append([op])
2037

    
2038
        missing = set(op2inst.keys()) - set(failed)
2039
        assert not missing, \
2040
          "Iallocator did return incomplete result: %s" % \
2041
          utils.CommaJoin(missing)
2042
    else:
2043
      jobs.extend([op] for op in self.op.instances)
2044

    
2045
    return ResultWithJobs(jobs, **self._ConstructPartialResult())
2046

    
2047

    
2048
class _InstNicModPrivate:
2049
  """Data structure for network interface modifications.
2050

2051
  Used by L{LUInstanceSetParams}.
2052

2053
  """
2054
  def __init__(self):
2055
    self.params = None
2056
    self.filled = None
2057

    
2058

    
2059
def _PrepareContainerMods(mods, private_fn):
2060
  """Prepares a list of container modifications by adding a private data field.
2061

2062
  @type mods: list of tuples; (operation, index, parameters)
2063
  @param mods: List of modifications
2064
  @type private_fn: callable or None
2065
  @param private_fn: Callable for constructing a private data field for a
2066
    modification
2067
  @rtype: list
2068

2069
  """
2070
  if private_fn is None:
2071
    fn = lambda: None
2072
  else:
2073
    fn = private_fn
2074

    
2075
  return [(op, idx, params, fn()) for (op, idx, params) in mods]
2076

    
2077

    
2078
def _CheckNodesPhysicalCPUs(lu, node_uuids, requested, hypervisor_specs):
2079
  """Checks if nodes have enough physical CPUs
2080

2081
  This function checks if all given nodes have the needed number of
2082
  physical CPUs. In case any node has less CPUs or we cannot get the
2083
  information from the node, this function raises an OpPrereqError
2084
  exception.
2085

2086
  @type lu: C{LogicalUnit}
2087
  @param lu: a logical unit from which we get configuration data
2088
  @type node_uuids: C{list}
2089
  @param node_uuids: the list of node UUIDs to check
2090
  @type requested: C{int}
2091
  @param requested: the minimum acceptable number of physical CPUs
2092
  @type hypervisor_specs: list of pairs (string, dict of strings)
2093
  @param hypervisor_specs: list of hypervisor specifications in
2094
      pairs (hypervisor_name, hvparams)
2095
  @raise errors.OpPrereqError: if the node doesn't have enough CPUs,
2096
      or we cannot check the node
2097

2098
  """
2099
  nodeinfo = lu.rpc.call_node_info(node_uuids, None, hypervisor_specs)
2100
  for node_uuid in node_uuids:
2101
    info = nodeinfo[node_uuid]
2102
    node_name = lu.cfg.GetNodeName(node_uuid)
2103
    info.Raise("Cannot get current information from node %s" % node_name,
2104
               prereq=True, ecode=errors.ECODE_ENVIRON)
2105
    (_, _, (hv_info, )) = info.payload
2106
    num_cpus = hv_info.get("cpu_total", None)
2107
    if not isinstance(num_cpus, int):
2108
      raise errors.OpPrereqError("Can't compute the number of physical CPUs"
2109
                                 " on node %s, result was '%s'" %
2110
                                 (node_name, num_cpus), errors.ECODE_ENVIRON)
2111
    if requested > num_cpus:
2112
      raise errors.OpPrereqError("Node %s has %s physical CPUs, but %s are "
2113
                                 "required" % (node_name, num_cpus, requested),
2114
                                 errors.ECODE_NORES)
2115

    
2116

    
2117
def GetItemFromContainer(identifier, kind, container):
2118
  """Return the item refered by the identifier.
2119

2120
  @type identifier: string
2121
  @param identifier: Item index or name or UUID
2122
  @type kind: string
2123
  @param kind: One-word item description
2124
  @type container: list
2125
  @param container: Container to get the item from
2126

2127
  """
2128
  # Index
2129
  try:
2130
    idx = int(identifier)
2131
    if idx == -1:
2132
      # Append
2133
      absidx = len(container) - 1
2134
    elif idx < 0:
2135
      raise IndexError("Not accepting negative indices other than -1")
2136
    elif idx > len(container):
2137
      raise IndexError("Got %s index %s, but there are only %s" %
2138
                       (kind, idx, len(container)))
2139
    else:
2140
      absidx = idx
2141
    return (absidx, container[idx])
2142
  except ValueError:
2143
    pass
2144

    
2145
  for idx, item in enumerate(container):
2146
    if item.uuid == identifier or item.name == identifier:
2147
      return (idx, item)
2148

    
2149
  raise errors.OpPrereqError("Cannot find %s with identifier %s" %
2150
                             (kind, identifier), errors.ECODE_NOENT)
2151

    
2152

    
2153
def _ApplyContainerMods(kind, container, chgdesc, mods,
2154
                        create_fn, modify_fn, remove_fn,
2155
                        post_add_fn=None):
2156
  """Applies descriptions in C{mods} to C{container}.
2157

2158
  @type kind: string
2159
  @param kind: One-word item description
2160
  @type container: list
2161
  @param container: Container to modify
2162
  @type chgdesc: None or list
2163
  @param chgdesc: List of applied changes
2164
  @type mods: list
2165
  @param mods: Modifications as returned by L{_PrepareContainerMods}
2166
  @type create_fn: callable
2167
  @param create_fn: Callback for creating a new item (L{constants.DDM_ADD});
2168
    receives absolute item index, parameters and private data object as added
2169
    by L{_PrepareContainerMods}, returns tuple containing new item and changes
2170
    as list
2171
  @type modify_fn: callable
2172
  @param modify_fn: Callback for modifying an existing item
2173
    (L{constants.DDM_MODIFY}); receives absolute item index, item, parameters
2174
    and private data object as added by L{_PrepareContainerMods}, returns
2175
    changes as list
2176
  @type remove_fn: callable
2177
  @param remove_fn: Callback on removing item; receives absolute item index,
2178
    item and private data object as added by L{_PrepareContainerMods}
2179
  @type post_add_fn: callable
2180
  @param post_add_fn: Callable for post-processing a newly created item after
2181
    it has been put into the container. It receives the index of the new item
2182
    and the new item as parameters.
2183

2184
  """
2185
  for (op, identifier, params, private) in mods:
2186
    changes = None
2187

    
2188
    if op == constants.DDM_ADD:
2189
      # Calculate where item will be added
2190
      # When adding an item, identifier can only be an index
2191
      try:
2192
        idx = int(identifier)
2193
      except ValueError:
2194
        raise errors.OpPrereqError("Only possitive integer or -1 is accepted as"
2195
                                   " identifier for %s" % constants.DDM_ADD,
2196
                                   errors.ECODE_INVAL)
2197
      if idx == -1:
2198
        addidx = len(container)
2199
      else:
2200
        if idx < 0:
2201
          raise IndexError("Not accepting negative indices other than -1")
2202
        elif idx > len(container):
2203
          raise IndexError("Got %s index %s, but there are only %s" %
2204
                           (kind, idx, len(container)))
2205
        addidx = idx
2206

    
2207
      if create_fn is None:
2208
        item = params
2209
      else:
2210
        (item, changes) = create_fn(addidx, params, private)
2211

    
2212
      if idx == -1:
2213
        container.append(item)
2214
      else:
2215
        assert idx >= 0
2216
        assert idx <= len(container)
2217
        # list.insert does so before the specified index
2218
        container.insert(idx, item)
2219

    
2220
      if post_add_fn is not None:
2221
        post_add_fn(addidx, item)
2222

    
2223
    else:
2224
      # Retrieve existing item
2225
      (absidx, item) = GetItemFromContainer(identifier, kind, container)
2226

    
2227
      if op == constants.DDM_REMOVE:
2228
        assert not params
2229

    
2230
        if remove_fn is not None:
2231
          remove_fn(absidx, item, private)
2232

    
2233
        changes = [("%s/%s" % (kind, absidx), "remove")]
2234

    
2235
        assert container[absidx] == item
2236
        del container[absidx]
2237
      elif op == constants.DDM_MODIFY:
2238
        if modify_fn is not None:
2239
          changes = modify_fn(absidx, item, params, private)
2240
      else:
2241
        raise errors.ProgrammerError("Unhandled operation '%s'" % op)
2242

    
2243
    assert _TApplyContModsCbChanges(changes)
2244

    
2245
    if not (chgdesc is None or changes is None):
2246
      chgdesc.extend(changes)
2247

    
2248

    
2249
def _UpdateIvNames(base_index, disks):
2250
  """Updates the C{iv_name} attribute of disks.
2251

2252
  @type disks: list of L{objects.Disk}
2253

2254
  """
2255
  for (idx, disk) in enumerate(disks):
2256
    disk.iv_name = "disk/%s" % (base_index + idx, )
2257

    
2258

    
2259
class LUInstanceSetParams(LogicalUnit):
2260
  """Modifies an instances's parameters.
2261

2262
  """
2263
  HPATH = "instance-modify"
2264
  HTYPE = constants.HTYPE_INSTANCE
2265
  REQ_BGL = False
2266

    
2267
  @staticmethod
2268
  def _UpgradeDiskNicMods(kind, mods, verify_fn):
2269
    assert ht.TList(mods)
2270
    assert not mods or len(mods[0]) in (2, 3)
2271

    
2272
    if mods and len(mods[0]) == 2:
2273
      result = []
2274

    
2275
      addremove = 0
2276
      for op, params in mods:
2277
        if op in (constants.DDM_ADD, constants.DDM_REMOVE):
2278
          result.append((op, -1, params))
2279
          addremove += 1
2280

    
2281
          if addremove > 1:
2282
            raise errors.OpPrereqError("Only one %s add or remove operation is"
2283
                                       " supported at a time" % kind,
2284
                                       errors.ECODE_INVAL)
2285
        else:
2286
          result.append((constants.DDM_MODIFY, op, params))
2287

    
2288
      assert verify_fn(result)
2289
    else:
2290
      result = mods
2291

    
2292
    return result
2293

    
2294
  @staticmethod
2295
  def _CheckMods(kind, mods, key_types, item_fn):
2296
    """Ensures requested disk/NIC modifications are valid.
2297

2298
    """
2299
    for (op, _, params) in mods:
2300
      assert ht.TDict(params)
2301

    
2302
      # If 'key_types' is an empty dict, we assume we have an
2303
      # 'ext' template and thus do not ForceDictType
2304
      if key_types:
2305
        utils.ForceDictType(params, key_types)
2306

    
2307
      if op == constants.DDM_REMOVE:
2308
        if params:
2309
          raise errors.OpPrereqError("No settings should be passed when"
2310
                                     " removing a %s" % kind,
2311
                                     errors.ECODE_INVAL)
2312
      elif op in (constants.DDM_ADD, constants.DDM_MODIFY):
2313
        item_fn(op, params)
2314
      else:
2315
        raise errors.ProgrammerError("Unhandled operation '%s'" % op)
2316

    
2317
  @staticmethod
2318
  def _VerifyDiskModification(op, params, excl_stor):
2319
    """Verifies a disk modification.
2320

2321
    """
2322
    if op == constants.DDM_ADD:
2323
      mode = params.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
2324
      if mode not in constants.DISK_ACCESS_SET:
2325
        raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
2326
                                   errors.ECODE_INVAL)
2327

    
2328
      size = params.get(constants.IDISK_SIZE, None)
2329
      if size is None:
2330
        raise errors.OpPrereqError("Required disk parameter '%s' missing" %
2331
                                   constants.IDISK_SIZE, errors.ECODE_INVAL)
2332
      size = int(size)
2333

    
2334
      params[constants.IDISK_SIZE] = size
2335
      name = params.get(constants.IDISK_NAME, None)
2336
      if name is not None and name.lower() == constants.VALUE_NONE:
2337
        params[constants.IDISK_NAME] = None
2338

    
2339
      CheckSpindlesExclusiveStorage(params, excl_stor, True)
2340

    
2341
    elif op == constants.DDM_MODIFY:
2342
      if constants.IDISK_SIZE in params:
2343
        raise errors.OpPrereqError("Disk size change not possible, use"
2344
                                   " grow-disk", errors.ECODE_INVAL)
2345
      if len(params) > 2:
2346
        raise errors.OpPrereqError("Disk modification doesn't support"
2347
                                   " additional arbitrary parameters",
2348
                                   errors.ECODE_INVAL)
2349
      name = params.get(constants.IDISK_NAME, None)
2350
      if name is not None and name.lower() == constants.VALUE_NONE:
2351
        params[constants.IDISK_NAME] = None
2352

    
2353
  @staticmethod
2354
  def _VerifyNicModification(op, params):
2355
    """Verifies a network interface modification.
2356

2357
    """
2358
    if op in (constants.DDM_ADD, constants.DDM_MODIFY):
2359
      ip = params.get(constants.INIC_IP, None)
2360
      name = params.get(constants.INIC_NAME, None)
2361
      req_net = params.get(constants.INIC_NETWORK, None)
2362
      link = params.get(constants.NIC_LINK, None)
2363
      mode = params.get(constants.NIC_MODE, None)
2364
      if name is not None and name.lower() == constants.VALUE_NONE:
2365
        params[constants.INIC_NAME] = None
2366
      if req_net is not None:
2367
        if req_net.lower() == constants.VALUE_NONE:
2368
          params[constants.INIC_NETWORK] = None
2369
          req_net = None
2370
        elif link is not None or mode is not None:
2371
          raise errors.OpPrereqError("If network is given"
2372
                                     " mode or link should not",
2373
                                     errors.ECODE_INVAL)
2374

    
2375
      if op == constants.DDM_ADD:
2376
        macaddr = params.get(constants.INIC_MAC, None)
2377
        if macaddr is None:
2378
          params[constants.INIC_MAC] = constants.VALUE_AUTO
2379

    
2380
      if ip is not None:
2381
        if ip.lower() == constants.VALUE_NONE:
2382
          params[constants.INIC_IP] = None
2383
        else:
2384
          if ip.lower() == constants.NIC_IP_POOL:
2385
            if op == constants.DDM_ADD and req_net is None:
2386
              raise errors.OpPrereqError("If ip=pool, parameter network"
2387
                                         " cannot be none",
2388
                                         errors.ECODE_INVAL)
2389
          else:
2390
            if not netutils.IPAddress.IsValid(ip):
2391
              raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
2392
                                         errors.ECODE_INVAL)
2393

    
2394
      if constants.INIC_MAC in params:
2395
        macaddr = params[constants.INIC_MAC]
2396
        if macaddr not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
2397
          macaddr = utils.NormalizeAndValidateMac(macaddr)
2398

    
2399
        if op == constants.DDM_MODIFY and macaddr == constants.VALUE_AUTO:
2400
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
2401
                                     " modifying an existing NIC",
2402
                                     errors.ECODE_INVAL)
2403

    
2404
  def CheckArguments(self):
2405
    if not (self.op.nics or self.op.disks or self.op.disk_template or
2406
            self.op.hvparams or self.op.beparams or self.op.os_name or
2407
            self.op.osparams or self.op.offline is not None or
2408
            self.op.runtime_mem or self.op.pnode):
2409
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
2410

    
2411
    if self.op.hvparams:
2412
      CheckParamsNotGlobal(self.op.hvparams, constants.HVC_GLOBALS,
2413
                           "hypervisor", "instance", "cluster")
2414

    
2415
    self.op.disks = self._UpgradeDiskNicMods(
2416
      "disk", self.op.disks, ht.TSetParamsMods(ht.TIDiskParams))
2417
    self.op.nics = self._UpgradeDiskNicMods(
2418
      "NIC", self.op.nics, ht.TSetParamsMods(ht.TINicParams))
2419

    
2420
    if self.op.disks and self.op.disk_template is not None:
2421
      raise errors.OpPrereqError("Disk template conversion and other disk"
2422
                                 " changes not supported at the same time",
2423
                                 errors.ECODE_INVAL)
2424

    
2425
    if (self.op.disk_template and
2426
        self.op.disk_template in constants.DTS_INT_MIRROR and
2427
        self.op.remote_node is None):
2428
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
2429
                                 " one requires specifying a secondary node",
2430
                                 errors.ECODE_INVAL)
2431

    
2432
    # Check NIC modifications
2433
    self._CheckMods("NIC", self.op.nics, constants.INIC_PARAMS_TYPES,
2434
                    self._VerifyNicModification)
2435

    
2436
    if self.op.pnode:
2437
      (self.op.pnode_uuid, self.op.pnode) = \
2438
        ExpandNodeUuidAndName(self.cfg, self.op.pnode_uuid, self.op.pnode)
2439

    
2440
  def ExpandNames(self):
2441
    self._ExpandAndLockInstance()
2442
    self.needed_locks[locking.LEVEL_NODEGROUP] = []
2443
    # Can't even acquire node locks in shared mode as upcoming changes in
2444
    # Ganeti 2.6 will start to modify the node object on disk conversion
2445
    self.needed_locks[locking.LEVEL_NODE] = []
2446
    self.needed_locks[locking.LEVEL_NODE_RES] = []
2447
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2448
    # Look node group to look up the ipolicy
2449
    self.share_locks[locking.LEVEL_NODEGROUP] = 1
2450

    
2451
  def DeclareLocks(self, level):
2452
    if level == locking.LEVEL_NODEGROUP:
2453
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
2454
      # Acquire locks for the instance's nodegroups optimistically. Needs
2455
      # to be verified in CheckPrereq
2456
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
2457
        self.cfg.GetInstanceNodeGroups(self.op.instance_uuid)
2458
    elif level == locking.LEVEL_NODE:
2459
      self._LockInstancesNodes()
2460
      if self.op.disk_template and self.op.remote_node:
2461
        (self.op.remote_node_uuid, self.op.remote_node) = \
2462
          ExpandNodeUuidAndName(self.cfg, self.op.remote_node_uuid,
2463
                                self.op.remote_node)
2464
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node_uuid)
2465
    elif level == locking.LEVEL_NODE_RES and self.op.disk_template:
2466
      # Copy node locks
2467
      self.needed_locks[locking.LEVEL_NODE_RES] = \
2468
        CopyLockList(self.needed_locks[locking.LEVEL_NODE])
2469

    
2470
  def BuildHooksEnv(self):
2471
    """Build hooks env.
2472

2473
    This runs on the master, primary and secondaries.
2474

2475
    """
2476
    args = {}
2477
    if constants.BE_MINMEM in self.be_new:
2478
      args["minmem"] = self.be_new[constants.BE_MINMEM]
2479
    if constants.BE_MAXMEM in self.be_new:
2480
      args["maxmem"] = self.be_new[constants.BE_MAXMEM]
2481
    if constants.BE_VCPUS in self.be_new:
2482
      args["vcpus"] = self.be_new[constants.BE_VCPUS]
2483
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
2484
    # information at all.
2485

    
2486
    if self._new_nics is not None:
2487
      nics = []
2488

    
2489
      for nic in self._new_nics:
2490
        n = copy.deepcopy(nic)
2491
        nicparams = self.cluster.SimpleFillNIC(n.nicparams)
2492
        n.nicparams = nicparams
2493
        nics.append(NICToTuple(self, n))
2494

    
2495
      args["nics"] = nics
2496

    
2497
    env = BuildInstanceHookEnvByObject(self, self.instance, override=args)
2498
    if self.op.disk_template:
2499
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
2500
    if self.op.runtime_mem:
2501
      env["RUNTIME_MEMORY"] = self.op.runtime_mem
2502

    
2503
    return env
2504

    
2505
  def BuildHooksNodes(self):
2506
    """Build hooks nodes.
2507

2508
    """
2509
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
2510
    return (nl, nl)
2511

    
2512
  def _PrepareNicModification(self, params, private, old_ip, old_net_uuid,
2513
                              old_params, cluster, pnode_uuid):
2514

    
2515
    update_params_dict = dict([(key, params[key])
2516
                               for key in constants.NICS_PARAMETERS
2517
                               if key in params])
2518

    
2519
    req_link = update_params_dict.get(constants.NIC_LINK, None)
2520
    req_mode = update_params_dict.get(constants.NIC_MODE, None)
2521

    
2522
    new_net_uuid = None
2523
    new_net_uuid_or_name = params.get(constants.INIC_NETWORK, old_net_uuid)
2524
    if new_net_uuid_or_name:
2525
      new_net_uuid = self.cfg.LookupNetwork(new_net_uuid_or_name)
2526
      new_net_obj = self.cfg.GetNetwork(new_net_uuid)
2527

    
2528
    if old_net_uuid:
2529
      old_net_obj = self.cfg.GetNetwork(old_net_uuid)
2530

    
2531
    if new_net_uuid:
2532
      netparams = self.cfg.GetGroupNetParams(new_net_uuid, pnode_uuid)
2533
      if not netparams:
2534
        raise errors.OpPrereqError("No netparams found for the network"
2535
                                   " %s, probably not connected" %
2536
                                   new_net_obj.name, errors.ECODE_INVAL)
2537
      new_params = dict(netparams)
2538
    else:
2539
      new_params = GetUpdatedParams(old_params, update_params_dict)
2540

    
2541
    utils.ForceDictType(new_params, constants.NICS_PARAMETER_TYPES)
2542

    
2543
    new_filled_params = cluster.SimpleFillNIC(new_params)
2544
    objects.NIC.CheckParameterSyntax(new_filled_params)
2545

    
2546
    new_mode = new_filled_params[constants.NIC_MODE]
2547
    if new_mode == constants.NIC_MODE_BRIDGED:
2548
      bridge = new_filled_params[constants.NIC_LINK]
2549
      msg = self.rpc.call_bridges_exist(pnode_uuid, [bridge]).fail_msg
2550
      if msg:
2551
        msg = "Error checking bridges on node '%s': %s" % \
2552
                (self.cfg.GetNodeName(pnode_uuid), msg)
2553
        if self.op.force:
2554
          self.warn.append(msg)
2555
        else:
2556
          raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
2557

    
2558
    elif new_mode == constants.NIC_MODE_ROUTED:
2559
      ip = params.get(constants.INIC_IP, old_ip)
2560
      if ip is None:
2561
        raise errors.OpPrereqError("Cannot set the NIC IP address to None"
2562
                                   " on a routed NIC", errors.ECODE_INVAL)
2563

    
2564
    elif new_mode == constants.NIC_MODE_OVS:
2565
      # TODO: check OVS link
2566
      self.LogInfo("OVS links are currently not checked for correctness")
2567

    
2568
    if constants.INIC_MAC in params:
2569
      mac = params[constants.INIC_MAC]
2570
      if mac is None:
2571
        raise errors.OpPrereqError("Cannot unset the NIC MAC address",
2572
                                   errors.ECODE_INVAL)
2573
      elif mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
2574
        # otherwise generate the MAC address
2575
        params[constants.INIC_MAC] = \
2576
          self.cfg.GenerateMAC(new_net_uuid, self.proc.GetECId())
2577
      else:
2578
        # or validate/reserve the current one
2579
        try:
2580
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
2581
        except errors.ReservationError:
2582
          raise errors.OpPrereqError("MAC address '%s' already in use"
2583
                                     " in cluster" % mac,
2584
                                     errors.ECODE_NOTUNIQUE)
2585
    elif new_net_uuid != old_net_uuid:
2586

    
2587
      def get_net_prefix(net_uuid):
2588
        mac_prefix = None
2589
        if net_uuid:
2590
          nobj = self.cfg.GetNetwork(net_uuid)
2591
          mac_prefix = nobj.mac_prefix
2592

    
2593
        return mac_prefix
2594

    
2595
      new_prefix = get_net_prefix(new_net_uuid)
2596
      old_prefix = get_net_prefix(old_net_uuid)
2597
      if old_prefix != new_prefix:
2598
        params[constants.INIC_MAC] = \
2599
          self.cfg.GenerateMAC(new_net_uuid, self.proc.GetECId())
2600

    
2601
    # if there is a change in (ip, network) tuple
2602
    new_ip = params.get(constants.INIC_IP, old_ip)
2603
    if (new_ip, new_net_uuid) != (old_ip, old_net_uuid):
2604
      if new_ip:
2605
        # if IP is pool then require a network and generate one IP
2606
        if new_ip.lower() == constants.NIC_IP_POOL:
2607
          if new_net_uuid:
2608
            try:
2609
              new_ip = self.cfg.GenerateIp(new_net_uuid, self.proc.GetECId())
2610
            except errors.ReservationError:
2611
              raise errors.OpPrereqError("Unable to get a free IP"
2612
                                         " from the address pool",
2613
                                         errors.ECODE_STATE)
2614
            self.LogInfo("Chose IP %s from network %s",
2615
                         new_ip,
2616
                         new_net_obj.name)
2617
            params[constants.INIC_IP] = new_ip
2618
          else:
2619
            raise errors.OpPrereqError("ip=pool, but no network found",
2620
                                       errors.ECODE_INVAL)
2621
        # Reserve new IP if in the new network if any
2622
        elif new_net_uuid:
2623
          try:
2624
            self.cfg.ReserveIp(new_net_uuid, new_ip, self.proc.GetECId())
2625
            self.LogInfo("Reserving IP %s in network %s",
2626
                         new_ip, new_net_obj.name)
2627
          except errors.ReservationError:
2628
            raise errors.OpPrereqError("IP %s not available in network %s" %
2629
                                       (new_ip, new_net_obj.name),
2630
                                       errors.ECODE_NOTUNIQUE)
2631
        # new network is None so check if new IP is a conflicting IP
2632
        elif self.op.conflicts_check:
2633
          _CheckForConflictingIp(self, new_ip, pnode_uuid)
2634

    
2635
      # release old IP if old network is not None
2636
      if old_ip and old_net_uuid:
2637
        try:
2638
          self.cfg.ReleaseIp(old_net_uuid, old_ip, self.proc.GetECId())
2639
        except errors.AddressPoolError:
2640
          logging.warning("Release IP %s not contained in network %s",
2641
                          old_ip, old_net_obj.name)
2642

    
2643
    # there are no changes in (ip, network) tuple and old network is not None
2644
    elif (old_net_uuid is not None and
2645
          (req_link is not None or req_mode is not None)):
2646
      raise errors.OpPrereqError("Not allowed to change link or mode of"
2647
                                 " a NIC that is connected to a network",
2648
                                 errors.ECODE_INVAL)
2649

    
2650
    private.params = new_params
2651
    private.filled = new_filled_params
2652

    
2653
  def _PreCheckDiskTemplate(self, pnode_info):
2654
    """CheckPrereq checks related to a new disk template."""
2655
    # Arguments are passed to avoid configuration lookups
2656
    pnode_uuid = self.instance.primary_node
2657
    if self.instance.disk_template == self.op.disk_template:
2658
      raise errors.OpPrereqError("Instance already has disk template %s" %
2659
                                 self.instance.disk_template,
2660
                                 errors.ECODE_INVAL)
2661

    
2662
    if not self.cluster.IsDiskTemplateEnabled(self.op.disk_template):
2663
      raise errors.OpPrereqError("Disk template '%s' is not enabled for this"
2664
                                 " cluster." % self.op.disk_template)
2665

    
2666
    if (self.instance.disk_template,
2667
        self.op.disk_template) not in self._DISK_CONVERSIONS:
2668
      raise errors.OpPrereqError("Unsupported disk template conversion from"
2669
                                 " %s to %s" % (self.instance.disk_template,
2670
                                                self.op.disk_template),
2671
                                 errors.ECODE_INVAL)
2672
    CheckInstanceState(self, self.instance, INSTANCE_DOWN,
2673
                       msg="cannot change disk template")
2674
    if self.op.disk_template in constants.DTS_INT_MIRROR:
2675
      if self.op.remote_node_uuid == pnode_uuid:
2676
        raise errors.OpPrereqError("Given new secondary node %s is the same"
2677
                                   " as the primary node of the instance" %
2678
                                   self.op.remote_node, errors.ECODE_STATE)
2679
      CheckNodeOnline(self, self.op.remote_node_uuid)
2680
      CheckNodeNotDrained(self, self.op.remote_node_uuid)
2681
      # FIXME: here we assume that the old instance type is DT_PLAIN
2682
      assert self.instance.disk_template == constants.DT_PLAIN
2683
      disks = [{constants.IDISK_SIZE: d.size,
2684
                constants.IDISK_VG: d.logical_id[0]}
2685
               for d in self.instance.disks]
2686
      required = ComputeDiskSizePerVG(self.op.disk_template, disks)
2687
      CheckNodesFreeDiskPerVG(self, [self.op.remote_node_uuid], required)
2688

    
2689
      snode_info = self.cfg.GetNodeInfo(self.op.remote_node_uuid)
2690
      snode_group = self.cfg.GetNodeGroup(snode_info.group)
2691
      ipolicy = ganeti.masterd.instance.CalculateGroupIPolicy(self.cluster,
2692
                                                              snode_group)
2693
      CheckTargetNodeIPolicy(self, ipolicy, self.instance, snode_info, self.cfg,
2694
                             ignore=self.op.ignore_ipolicy)
2695
      if pnode_info.group != snode_info.group:
2696
        self.LogWarning("The primary and secondary nodes are in two"
2697
                        " different node groups; the disk parameters"
2698
                        " from the first disk's node group will be"
2699
                        " used")
2700

    
2701
    if not self.op.disk_template in constants.DTS_EXCL_STORAGE:
2702
      # Make sure none of the nodes require exclusive storage
2703
      nodes = [pnode_info]
2704
      if self.op.disk_template in constants.DTS_INT_MIRROR:
2705
        assert snode_info
2706
        nodes.append(snode_info)
2707
      has_es = lambda n: IsExclusiveStorageEnabledNode(self.cfg, n)
2708
      if compat.any(map(has_es, nodes)):
2709
        errmsg = ("Cannot convert disk template from %s to %s when exclusive"
2710
                  " storage is enabled" % (self.instance.disk_template,
2711
                                           self.op.disk_template))
2712
        raise errors.OpPrereqError(errmsg, errors.ECODE_STATE)
2713

    
2714
  def _PreCheckDisks(self, ispec):
2715
    """CheckPrereq checks related to disk changes.
2716

2717
    @type ispec: dict
2718
    @param ispec: instance specs to be updated with the new disks
2719

2720
    """
2721
    self.diskparams = self.cfg.GetInstanceDiskParams(self.instance)
2722

    
2723
    excl_stor = compat.any(
2724
      rpc.GetExclusiveStorageForNodes(self.cfg,
2725
                                      self.instance.all_nodes).values()
2726
      )
2727

    
2728
    # Check disk modifications. This is done here and not in CheckArguments
2729
    # (as with NICs), because we need to know the instance's disk template
2730
    ver_fn = lambda op, par: self._VerifyDiskModification(op, par, excl_stor)
2731
    if self.instance.disk_template == constants.DT_EXT:
2732
      self._CheckMods("disk", self.op.disks, {}, ver_fn)
2733
    else:
2734
      self._CheckMods("disk", self.op.disks, constants.IDISK_PARAMS_TYPES,
2735
                      ver_fn)
2736

    
2737
    self.diskmod = _PrepareContainerMods(self.op.disks, None)
2738

    
2739
    # Check the validity of the `provider' parameter
2740
    if self.instance.disk_template in constants.DT_EXT:
2741
      for mod in self.diskmod:
2742
        ext_provider = mod[2].get(constants.IDISK_PROVIDER, None)
2743
        if mod[0] == constants.DDM_ADD:
2744
          if ext_provider is None:
2745
            raise errors.OpPrereqError("Instance template is '%s' and parameter"
2746
                                       " '%s' missing, during disk add" %
2747
                                       (constants.DT_EXT,
2748
                                        constants.IDISK_PROVIDER),
2749
                                       errors.ECODE_NOENT)
2750
        elif mod[0] == constants.DDM_MODIFY:
2751
          if ext_provider:
2752
            raise errors.OpPrereqError("Parameter '%s' is invalid during disk"
2753
                                       " modification" %
2754
                                       constants.IDISK_PROVIDER,
2755
                                       errors.ECODE_INVAL)
2756
    else:
2757
      for mod in self.diskmod:
2758
        ext_provider = mod[2].get(constants.IDISK_PROVIDER, None)
2759
        if ext_provider is not None:
2760
          raise errors.OpPrereqError("Parameter '%s' is only valid for"
2761
                                     " instances of type '%s'" %
2762
                                     (constants.IDISK_PROVIDER,
2763
                                      constants.DT_EXT),
2764
                                     errors.ECODE_INVAL)
2765

    
2766
    if not self.op.wait_for_sync and self.instance.disks_active:
2767
      for mod in self.diskmod:
2768
        if mod[0] == constants.DDM_ADD:
2769
          raise errors.OpPrereqError("Can't add a disk to an instance with"
2770
                                     " activated disks and"
2771
                                     " --no-wait-for-sync given.",
2772
                                     errors.ECODE_INVAL)
2773

    
2774
    if self.op.disks and self.instance.disk_template == constants.DT_DISKLESS:
2775
      raise errors.OpPrereqError("Disk operations not supported for"
2776
                                 " diskless instances", errors.ECODE_INVAL)
2777

    
2778
    def _PrepareDiskMod(_, disk, params, __):
2779
      disk.name = params.get(constants.IDISK_NAME, None)
2780

    
2781
    # Verify disk changes (operating on a copy)
2782
    disks = copy.deepcopy(self.instance.disks)
2783
    _ApplyContainerMods("disk", disks, None, self.diskmod, None,
2784
                        _PrepareDiskMod, None)
2785
    utils.ValidateDeviceNames("disk", disks)
2786
    if len(disks) > constants.MAX_DISKS:
2787
      raise errors.OpPrereqError("Instance has too many disks (%d), cannot add"
2788
                                 " more" % constants.MAX_DISKS,
2789
                                 errors.ECODE_STATE)
2790
    disk_sizes = [disk.size for disk in self.instance.disks]
2791
    disk_sizes.extend(params["size"] for (op, idx, params, private) in
2792
                      self.diskmod if op == constants.DDM_ADD)
2793
    ispec[constants.ISPEC_DISK_COUNT] = len(disk_sizes)
2794
    ispec[constants.ISPEC_DISK_SIZE] = disk_sizes
2795

    
2796
    if self.op.offline is not None and self.op.offline:
2797
      CheckInstanceState(self, self.instance, CAN_CHANGE_INSTANCE_OFFLINE,
2798
                         msg="can't change to offline")
2799

    
2800
  def CheckPrereq(self):
2801
    """Check prerequisites.
2802

2803
    This only checks the instance list against the existing names.
2804

2805
    """
2806
    assert self.op.instance_name in self.owned_locks(locking.LEVEL_INSTANCE)
2807
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_uuid)
2808
    self.cluster = self.cfg.GetClusterInfo()
2809

    
2810
    assert self.instance is not None, \
2811
      "Cannot retrieve locked instance %s" % self.op.instance_name
2812

    
2813
    pnode_uuid = self.instance.primary_node
2814

    
2815
    self.warn = []
2816

    
2817
    if (self.op.pnode_uuid is not None and self.op.pnode_uuid != pnode_uuid and
2818
        not self.op.force):
2819
      # verify that the instance is not up
2820
      instance_info = self.rpc.call_instance_info(
2821
          pnode_uuid, self.instance.name, self.instance.hypervisor,
2822
          self.instance.hvparams)
2823
      if instance_info.fail_msg:
2824
        self.warn.append("Can't get instance runtime information: %s" %
2825
                         instance_info.fail_msg)
2826
      elif instance_info.payload:
2827
        raise errors.OpPrereqError("Instance is still running on %s" %
2828
                                   self.cfg.GetNodeName(pnode_uuid),
2829
                                   errors.ECODE_STATE)
2830

    
2831
    assert pnode_uuid in self.owned_locks(locking.LEVEL_NODE)
2832
    node_uuids = list(self.instance.all_nodes)
2833
    pnode_info = self.cfg.GetNodeInfo(pnode_uuid)
2834

    
2835
    #_CheckInstanceNodeGroups(self.cfg, self.op.instance_name, owned_groups)
2836
    assert pnode_info.group in self.owned_locks(locking.LEVEL_NODEGROUP)
2837
    group_info = self.cfg.GetNodeGroup(pnode_info.group)
2838

    
2839
    # dictionary with instance information after the modification
2840
    ispec = {}
2841

    
2842
    # Prepare NIC modifications
2843
    self.nicmod = _PrepareContainerMods(self.op.nics, _InstNicModPrivate)
2844

    
2845
    # OS change
2846
    if self.op.os_name and not self.op.force:
2847
      CheckNodeHasOS(self, self.instance.primary_node, self.op.os_name,
2848
                     self.op.force_variant)
2849
      instance_os = self.op.os_name
2850
    else:
2851
      instance_os = self.instance.os
2852

    
2853
    assert not (self.op.disk_template and self.op.disks), \
2854
      "Can't modify disk template and apply disk changes at the same time"
2855

    
2856
    if self.op.disk_template:
2857
      self._PreCheckDiskTemplate(pnode_info)
2858

    
2859
    self._PreCheckDisks(ispec)
2860

    
2861
    # hvparams processing
2862
    if self.op.hvparams:
2863
      hv_type = self.instance.hypervisor
2864
      i_hvdict = GetUpdatedParams(self.instance.hvparams, self.op.hvparams)
2865
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
2866
      hv_new = self.cluster.SimpleFillHV(hv_type, self.instance.os, i_hvdict)
2867

    
2868
      # local check
2869
      hypervisor.GetHypervisorClass(hv_type).CheckParameterSyntax(hv_new)
2870
      CheckHVParams(self, node_uuids, self.instance.hypervisor, hv_new)
2871
      self.hv_proposed = self.hv_new = hv_new # the new actual values
2872
      self.hv_inst = i_hvdict # the new dict (without defaults)
2873
    else:
2874
      self.hv_proposed = self.cluster.SimpleFillHV(self.instance.hypervisor,
2875
                                                   self.instance.os,
2876
                                                   self.instance.hvparams)
2877
      self.hv_new = self.hv_inst = {}
2878

    
2879
    # beparams processing
2880
    if self.op.beparams:
2881
      i_bedict = GetUpdatedParams(self.instance.beparams, self.op.beparams,
2882
                                  use_none=True)
2883
      objects.UpgradeBeParams(i_bedict)
2884
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
2885
      be_new = self.cluster.SimpleFillBE(i_bedict)
2886
      self.be_proposed = self.be_new = be_new # the new actual values
2887
      self.be_inst = i_bedict # the new dict (without defaults)
2888
    else:
2889
      self.be_new = self.be_inst = {}
2890
      self.be_proposed = self.cluster.SimpleFillBE(self.instance.beparams)
2891
    be_old = self.cluster.FillBE(self.instance)
2892

    
2893
    # CPU param validation -- checking every time a parameter is
2894
    # changed to cover all cases where either CPU mask or vcpus have
2895
    # changed
2896
    if (constants.BE_VCPUS in self.be_proposed and
2897
        constants.HV_CPU_MASK in self.hv_proposed):
2898
      cpu_list = \
2899
        utils.ParseMultiCpuMask(self.hv_proposed[constants.HV_CPU_MASK])
2900
      # Verify mask is consistent with number of vCPUs. Can skip this
2901
      # test if only 1 entry in the CPU mask, which means same mask
2902
      # is applied to all vCPUs.
2903
      if (len(cpu_list) > 1 and
2904
          len(cpu_list) != self.be_proposed[constants.BE_VCPUS]):
2905
        raise errors.OpPrereqError("Number of vCPUs [%d] does not match the"
2906
                                   " CPU mask [%s]" %
2907
                                   (self.be_proposed[constants.BE_VCPUS],
2908
                                    self.hv_proposed[constants.HV_CPU_MASK]),
2909
                                   errors.ECODE_INVAL)
2910

    
2911
      # Only perform this test if a new CPU mask is given
2912
      if constants.HV_CPU_MASK in self.hv_new:
2913
        # Calculate the largest CPU number requested
2914
        max_requested_cpu = max(map(max, cpu_list))
2915
        # Check that all of the instance's nodes have enough physical CPUs to
2916
        # satisfy the requested CPU mask
2917
        hvspecs = [(self.instance.hypervisor,
2918
                    self.cfg.GetClusterInfo()
2919
                      .hvparams[self.instance.hypervisor])]
2920
        _CheckNodesPhysicalCPUs(self, self.instance.all_nodes,
2921
                                max_requested_cpu + 1,
2922
                                hvspecs)
2923

    
2924
    # osparams processing
2925
    if self.op.osparams:
2926
      i_osdict = GetUpdatedParams(self.instance.osparams, self.op.osparams)
2927
      CheckOSParams(self, True, node_uuids, instance_os, i_osdict)
2928
      self.os_inst = i_osdict # the new dict (without defaults)
2929
    else:
2930
      self.os_inst = {}
2931

    
2932
    #TODO(dynmem): do the appropriate check involving MINMEM
2933
    if (constants.BE_MAXMEM in self.op.beparams and not self.op.force and
2934
        be_new[constants.BE_MAXMEM] > be_old[constants.BE_MAXMEM]):
2935
      mem_check_list = [pnode_uuid]
2936
      if be_new[constants.BE_AUTO_BALANCE]:
2937
        # either we changed auto_balance to yes or it was from before
2938
        mem_check_list.extend(self.instance.secondary_nodes)
2939
      instance_info = self.rpc.call_instance_info(
2940
          pnode_uuid, self.instance.name, self.instance.hypervisor,
2941
          self.instance.hvparams)
2942
      hvspecs = [(self.instance.hypervisor,
2943
                  self.cluster.hvparams[self.instance.hypervisor])]
2944
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
2945
                                         hvspecs)
2946
      pninfo = nodeinfo[pnode_uuid]
2947
      msg = pninfo.fail_msg
2948
      if msg:
2949
        # Assume the primary node is unreachable and go ahead
2950
        self.warn.append("Can't get info from primary node %s: %s" %
2951
                         (self.cfg.GetNodeName(pnode_uuid), msg))
2952
      else:
2953
        (_, _, (pnhvinfo, )) = pninfo.payload
2954
        if not isinstance(pnhvinfo.get("memory_free", None), int):
2955
          self.warn.append("Node data from primary node %s doesn't contain"
2956
                           " free memory information" %
2957
                           self.cfg.GetNodeName(pnode_uuid))
2958
        elif instance_info.fail_msg:
2959
          self.warn.append("Can't get instance runtime information: %s" %
2960
                           instance_info.fail_msg)
2961
        else:
2962
          if instance_info.payload:
2963
            current_mem = int(instance_info.payload["memory"])
2964
          else:
2965
            # Assume instance not running
2966
            # (there is a slight race condition here, but it's not very
2967
            # probable, and we have no other way to check)
2968
            # TODO: Describe race condition
2969
            current_mem = 0
2970
          #TODO(dynmem): do the appropriate check involving MINMEM
2971
          miss_mem = (be_new[constants.BE_MAXMEM] - current_mem -
2972
                      pnhvinfo["memory_free"])
2973
          if miss_mem > 0:
2974
            raise errors.OpPrereqError("This change will prevent the instance"
2975
                                       " from starting, due to %d MB of memory"
2976
                                       " missing on its primary node" %
2977
                                       miss_mem, errors.ECODE_NORES)
2978

    
2979
      if be_new[constants.BE_AUTO_BALANCE]:
2980
        for node_uuid, nres in nodeinfo.items():
2981
          if node_uuid not in self.instance.secondary_nodes:
2982
            continue
2983
          nres.Raise("Can't get info from secondary node %s" %
2984
                     self.cfg.GetNodeName(node_uuid), prereq=True,
2985
                     ecode=errors.ECODE_STATE)
2986
          (_, _, (nhvinfo, )) = nres.payload
2987
          if not isinstance(nhvinfo.get("memory_free", None), int):
2988
            raise errors.OpPrereqError("Secondary node %s didn't return free"
2989
                                       " memory information" %
2990
                                       self.cfg.GetNodeName(node_uuid),
2991
                                       errors.ECODE_STATE)
2992
          #TODO(dynmem): do the appropriate check involving MINMEM
2993
          elif be_new[constants.BE_MAXMEM] > nhvinfo["memory_free"]:
2994
            raise errors.OpPrereqError("This change will prevent the instance"
2995
                                       " from failover to its secondary node"
2996
                                       " %s, due to not enough memory" %
2997
                                       self.cfg.GetNodeName(node_uuid),
2998
                                       errors.ECODE_STATE)
2999

    
3000
    if self.op.runtime_mem:
3001
      remote_info = self.rpc.call_instance_info(
3002
         self.instance.primary_node, self.instance.name,
3003
         self.instance.hypervisor,
3004
         self.cluster.hvparams[self.instance.hypervisor])
3005
      remote_info.Raise("Error checking node %s" %
3006
                        self.cfg.GetNodeName(self.instance.primary_node))
3007
      if not remote_info.payload: # not running already
3008
        raise errors.OpPrereqError("Instance %s is not running" %
3009
                                   self.instance.name, errors.ECODE_STATE)
3010

    
3011
      current_memory = remote_info.payload["memory"]
3012
      if (not self.op.force and
3013
           (self.op.runtime_mem > self.be_proposed[constants.BE_MAXMEM] or
3014
            self.op.runtime_mem < self.be_proposed[constants.BE_MINMEM])):
3015
        raise errors.OpPrereqError("Instance %s must have memory between %d"
3016
                                   " and %d MB of memory unless --force is"
3017
                                   " given" %
3018
                                   (self.instance.name,
3019
                                    self.be_proposed[constants.BE_MINMEM],
3020
                                    self.be_proposed[constants.BE_MAXMEM]),
3021
                                   errors.ECODE_INVAL)
3022

    
3023
      delta = self.op.runtime_mem - current_memory
3024
      if delta > 0:
3025
        CheckNodeFreeMemory(
3026
            self, self.instance.primary_node,
3027
            "ballooning memory for instance %s" % self.instance.name, delta,
3028
            self.instance.hypervisor,
3029
            self.cfg.GetClusterInfo().hvparams[self.instance.hypervisor])
3030

    
3031
    # make self.cluster visible in the functions below
3032
    cluster = self.cluster
3033

    
3034
    def _PrepareNicCreate(_, params, private):
3035
      self._PrepareNicModification(params, private, None, None,
3036
                                   {}, cluster, pnode_uuid)
3037
      return (None, None)
3038

    
3039
    def _PrepareNicMod(_, nic, params, private):
3040
      self._PrepareNicModification(params, private, nic.ip, nic.network,
3041
                                   nic.nicparams, cluster, pnode_uuid)
3042
      return None
3043

    
3044
    def _PrepareNicRemove(_, params, __):
3045
      ip = params.ip
3046
      net = params.network
3047
      if net is not None and ip is not None:
3048
        self.cfg.ReleaseIp(net, ip, self.proc.GetECId())
3049

    
3050
    # Verify NIC changes (operating on copy)
3051
    nics = self.instance.nics[:]
3052
    _ApplyContainerMods("NIC", nics, None, self.nicmod,
3053
                        _PrepareNicCreate, _PrepareNicMod, _PrepareNicRemove)
3054
    if len(nics) > constants.MAX_NICS:
3055
      raise errors.OpPrereqError("Instance has too many network interfaces"
3056
                                 " (%d), cannot add more" % constants.MAX_NICS,
3057
                                 errors.ECODE_STATE)
3058

    
3059
    # Pre-compute NIC changes (necessary to use result in hooks)
3060
    self._nic_chgdesc = []
3061
    if self.nicmod:
3062
      # Operate on copies as this is still in prereq
3063
      nics = [nic.Copy() for nic in self.instance.nics]
3064
      _ApplyContainerMods("NIC", nics, self._nic_chgdesc, self.nicmod,
3065
                          self._CreateNewNic, self._ApplyNicMods, None)
3066
      # Verify that NIC names are unique and valid
3067
      utils.ValidateDeviceNames("NIC", nics)
3068
      self._new_nics = nics
3069
      ispec[constants.ISPEC_NIC_COUNT] = len(self._new_nics)
3070
    else:
3071
      self._new_nics = None
3072
      ispec[constants.ISPEC_NIC_COUNT] = len(self.instance.nics)
3073

    
3074
    if not self.op.ignore_ipolicy:
3075
      ipolicy = ganeti.masterd.instance.CalculateGroupIPolicy(self.cluster,
3076
                                                              group_info)
3077

    
3078
      # Fill ispec with backend parameters
3079
      ispec[constants.ISPEC_SPINDLE_USE] = \
3080
        self.be_new.get(constants.BE_SPINDLE_USE, None)
3081
      ispec[constants.ISPEC_CPU_COUNT] = self.be_new.get(constants.BE_VCPUS,
3082
                                                         None)
3083

    
3084
      # Copy ispec to verify parameters with min/max values separately
3085
      if self.op.disk_template:
3086
        new_disk_template = self.op.disk_template
3087
      else:
3088
        new_disk_template = self.instance.disk_template
3089
      ispec_max = ispec.copy()
3090
      ispec_max[constants.ISPEC_MEM_SIZE] = \
3091
        self.be_new.get(constants.BE_MAXMEM, None)
3092
      res_max = _ComputeIPolicyInstanceSpecViolation(ipolicy, ispec_max,
3093
                                                     new_disk_template)
3094
      ispec_min = ispec.copy()
3095
      ispec_min[constants.ISPEC_MEM_SIZE] = \
3096
        self.be_new.get(constants.BE_MINMEM, None)
3097
      res_min = _ComputeIPolicyInstanceSpecViolation(ipolicy, ispec_min,
3098
                                                     new_disk_template)
3099

    
3100
      if (res_max or res_min):
3101
        # FIXME: Improve error message by including information about whether
3102
        # the upper or lower limit of the parameter fails the ipolicy.
3103
        msg = ("Instance allocation to group %s (%s) violates policy: %s" %
3104
               (group_info, group_info.name,
3105
                utils.CommaJoin(set(res_max + res_min))))
3106
        raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
3107

    
3108
  def _ConvertPlainToDrbd(self, feedback_fn):
3109
    """Converts an instance from plain to drbd.
3110

3111
    """
3112
    feedback_fn("Converting template to drbd")
3113
    pnode_uuid = self.instance.primary_node
3114
    snode_uuid = self.op.remote_node_uuid
3115

    
3116
    assert self.instance.disk_template == constants.DT_PLAIN
3117

    
3118
    # create a fake disk info for _GenerateDiskTemplate
3119
    disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
3120
                  constants.IDISK_VG: d.logical_id[0],
3121
                  constants.IDISK_NAME: d.name}
3122
                 for d in self.instance.disks]
3123
    new_disks = GenerateDiskTemplate(self, self.op.disk_template,
3124
                                     self.instance.uuid, pnode_uuid,
3125
                                     [snode_uuid], disk_info, None, None, 0,
3126
                                     feedback_fn, self.diskparams)
3127
    anno_disks = rpc.AnnotateDiskParams(new_disks, self.diskparams)
3128
    p_excl_stor = IsExclusiveStorageEnabledNodeUuid(self.cfg, pnode_uuid)
3129
    s_excl_stor = IsExclusiveStorageEnabledNodeUuid(self.cfg, snode_uuid)
3130
    info = GetInstanceInfoText(self.instance)
3131
    feedback_fn("Creating additional volumes...")
3132
    # first, create the missing data and meta devices
3133
    for disk in anno_disks:
3134
      # unfortunately this is... not too nice
3135
      CreateSingleBlockDev(self, pnode_uuid, self.instance, disk.children[1],
3136
                           info, True, p_excl_stor)
3137
      for child in disk.children:
3138
        CreateSingleBlockDev(self, snode_uuid, self.instance, child, info, True,
3139
                             s_excl_stor)
3140
    # at this stage, all new LVs have been created, we can rename the
3141
    # old ones
3142
    feedback_fn("Renaming original volumes...")
3143
    rename_list = [(o, n.children[0].logical_id)
3144
                   for (o, n) in zip(self.instance.disks, new_disks)]
3145
    result = self.rpc.call_blockdev_rename(pnode_uuid, rename_list)
3146
    result.Raise("Failed to rename original LVs")
3147

    
3148
    feedback_fn("Initializing DRBD devices...")
3149
    # all child devices are in place, we can now create the DRBD devices
3150
    try:
3151
      for disk in anno_disks:
3152
        for (node_uuid, excl_stor) in [(pnode_uuid, p_excl_stor),
3153
                                       (snode_uuid, s_excl_stor)]:
3154
          f_create = node_uuid == pnode_uuid
3155
          CreateSingleBlockDev(self, node_uuid, self.instance, disk, info,
3156
                               f_create, excl_stor)
3157
    except errors.GenericError, e:
3158
      feedback_fn("Initializing of DRBD devices failed;"
3159
                  " renaming back original volumes...")
3160
      rename_back_list = [(n.children[0], o.logical_id)
3161
                          for (n, o) in zip(new_disks, self.instance.disks)]
3162
      result = self.rpc.call_blockdev_rename(pnode_uuid, rename_back_list)
3163
      result.Raise("Failed to rename LVs back after error %s" % str(e))
3164
      raise
3165

    
3166
    # at this point, the instance has been modified
3167
    self.instance.disk_template = constants.DT_DRBD8
3168
    self.instance.disks = new_disks
3169
    self.cfg.Update(self.instance, feedback_fn)
3170

    
3171
    # Release node locks while waiting for sync
3172
    ReleaseLocks(self, locking.LEVEL_NODE)
3173

    
3174
    # disks are created, waiting for sync
3175
    disk_abort = not WaitForSync(self, self.instance,
3176
                                 oneshot=not self.op.wait_for_sync)
3177
    if disk_abort:
3178
      raise errors.OpExecError("There are some degraded disks for"
3179
                               " this instance, please cleanup manually")
3180

    
3181
    # Node resource locks will be released by caller
3182

    
3183
  def _ConvertDrbdToPlain(self, feedback_fn):
3184
    """Converts an instance from drbd to plain.
3185

3186
    """
3187
    assert len(self.instance.secondary_nodes) == 1
3188
    assert self.instance.disk_template == constants.DT_DRBD8
3189

    
3190
    pnode_uuid = self.instance.primary_node
3191
    snode_uuid = self.instance.secondary_nodes[0]
3192
    feedback_fn("Converting template to plain")
3193

    
3194
    old_disks = AnnotateDiskParams(self.instance, self.instance.disks, self.cfg)
3195
    new_disks = [d.children[0] for d in self.instance.disks]
3196

    
3197
    # copy over size, mode and name
3198
    for parent, child in zip(old_disks, new_disks):
3199
      child.size = parent.size
3200
      child.mode = parent.mode
3201
      child.name = parent.name
3202

    
3203
    # this is a DRBD disk, return its port to the pool
3204
    # NOTE: this must be done right before the call to cfg.Update!
3205
    for disk in old_disks:
3206
      tcp_port = disk.logical_id[2]
3207
      self.cfg.AddTcpUdpPort(tcp_port)
3208

    
3209
    # update instance structure
3210
    self.instance.disks = new_disks
3211
    self.instance.disk_template = constants.DT_PLAIN
3212
    _UpdateIvNames(0, self.instance.disks)
3213
    self.cfg.Update(self.instance, feedback_fn)
3214

    
3215
    # Release locks in case removing disks takes a while
3216
    ReleaseLocks(self, locking.LEVEL_NODE)
3217

    
3218
    feedback_fn("Removing volumes on the secondary node...")
3219
    for disk in old_disks:
3220
      result = self.rpc.call_blockdev_remove(snode_uuid, (disk, self.instance))
3221
      result.Warn("Could not remove block device %s on node %s,"
3222
                  " continuing anyway" %
3223
                  (disk.iv_name, self.cfg.GetNodeName(snode_uuid)),
3224
                  self.LogWarning)
3225

    
3226
    feedback_fn("Removing unneeded volumes on the primary node...")
3227
    for idx, disk in enumerate(old_disks):
3228
      meta = disk.children[1]
3229
      result = self.rpc.call_blockdev_remove(pnode_uuid, (meta, self.instance))
3230
      result.Warn("Could not remove metadata for disk %d on node %s,"
3231
                  " continuing anyway" %
3232
                  (idx, self.cfg.GetNodeName(pnode_uuid)),
3233
                  self.LogWarning)
3234

    
3235
  def _CreateNewDisk(self, idx, params, _):
3236
    """Creates a new disk.
3237

3238
    """
3239
    # add a new disk
3240
    if self.instance.disk_template in constants.DTS_FILEBASED:
3241
      (file_driver, file_path) = self.instance.disks[0].logical_id
3242
      file_path = os.path.dirname(file_path)
3243
    else:
3244
      file_driver = file_path = None
3245

    
3246
    disk = \
3247
      GenerateDiskTemplate(self, self.instance.disk_template,
3248
                           self.instance.uuid, self.instance.primary_node,
3249
                           self.instance.secondary_nodes, [params], file_path,
3250
                           file_driver, idx, self.Log, self.diskparams)[0]
3251

    
3252
    new_disks = CreateDisks(self, self.instance, disks=[disk])
3253

    
3254
    if self.cluster.prealloc_wipe_disks:
3255
      # Wipe new disk
3256
      WipeOrCleanupDisks(self, self.instance,
3257
                         disks=[(idx, disk, 0)],
3258
                         cleanup=new_disks)
3259

    
3260
    return (disk, [
3261
      ("disk/%d" % idx, "add:size=%s,mode=%s" % (disk.size, disk.mode)),
3262
      ])
3263

    
3264
  def _PostAddDisk(self, _, disk):
3265
    if not WaitForSync(self, self.instance, disks=[disk],
3266
                       oneshot=not self.op.wait_for_sync):
3267
      raise errors.OpExecError("Failed to sync disks of %s" %
3268
                               self.instance.name)
3269

    
3270
    # the disk is active at this point, so deactivate it if the instance disks
3271
    # are supposed to be inactive
3272
    if not self.instance.disks_active:
3273
      ShutdownInstanceDisks(self, self.instance, disks=[disk])
3274

    
3275
  @staticmethod
3276
  def _ModifyDisk(idx, disk, params, _):
3277
    """Modifies a disk.
3278

3279
    """
3280
    changes = []
3281
    mode = params.get(constants.IDISK_MODE, None)
3282
    if mode:
3283
      disk.mode = mode
3284
      changes.append(("disk.mode/%d" % idx, disk.mode))
3285

    
3286
    name = params.get(constants.IDISK_NAME, None)
3287
    disk.name = name
3288
    changes.append(("disk.name/%d" % idx, disk.name))
3289

    
3290
    return changes
3291

    
3292
  def _RemoveDisk(self, idx, root, _):
3293
    """Removes a disk.
3294

3295
    """
3296
    (anno_disk,) = AnnotateDiskParams(self.instance, [root], self.cfg)
3297
    for node_uuid, disk in anno_disk.ComputeNodeTree(
3298
                             self.instance.primary_node):
3299
      msg = self.rpc.call_blockdev_remove(node_uuid, (disk, self.instance)) \
3300
              .fail_msg
3301
      if msg:
3302
        self.LogWarning("Could not remove disk/%d on node '%s': %s,"
3303
                        " continuing anyway", idx,
3304
                        self.cfg.GetNodeName(node_uuid), msg)
3305

    
3306
    # if this is a DRBD disk, return its port to the pool
3307
    if root.dev_type in constants.DTS_DRBD:
3308
      self.cfg.AddTcpUdpPort(root.logical_id[2])
3309

    
3310
  def _CreateNewNic(self, idx, params, private):
3311
    """Creates data structure for a new network interface.
3312

3313
    """
3314
    mac = params[constants.INIC_MAC]
3315
    ip = params.get(constants.INIC_IP, None)
3316
    net = params.get(constants.INIC_NETWORK, None)
3317
    name = params.get(constants.INIC_NAME, None)
3318
    net_uuid = self.cfg.LookupNetwork(net)
3319
    #TODO: not private.filled?? can a nic have no nicparams??
3320
    nicparams = private.filled
3321
    nobj = objects.NIC(mac=mac, ip=ip, network=net_uuid, name=name,
3322
                       nicparams=nicparams)
3323
    nobj.uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
3324

    
3325
    return (nobj, [
3326
      ("nic.%d" % idx,
3327
       "add:mac=%s,ip=%s,mode=%s,link=%s,network=%s" %
3328
       (mac, ip, private.filled[constants.NIC_MODE],
3329
       private.filled[constants.NIC_LINK],
3330
       net)),
3331
      ])
3332

    
3333
  def _ApplyNicMods(self, idx, nic, params, private):
3334
    """Modifies a network interface.
3335

3336
    """
3337
    changes = []
3338

    
3339
    for key in [constants.INIC_MAC, constants.INIC_IP, constants.INIC_NAME]:
3340
      if key in params:
3341
        changes.append(("nic.%s/%d" % (key, idx), params[key]))
3342
        setattr(nic, key, params[key])
3343

    
3344
    new_net = params.get(constants.INIC_NETWORK, nic.network)
3345
    new_net_uuid = self.cfg.LookupNetwork(new_net)
3346
    if new_net_uuid != nic.network:
3347
      changes.append(("nic.network/%d" % idx, new_net))
3348
      nic.network = new_net_uuid
3349

    
3350
    if private.filled:
3351
      nic.nicparams = private.filled
3352

    
3353
      for (key, val) in nic.nicparams.items():
3354
        changes.append(("nic.%s/%d" % (key, idx), val))
3355

    
3356
    return changes
3357

    
3358
  def Exec(self, feedback_fn):
3359
    """Modifies an instance.
3360

3361
    All parameters take effect only at the next restart of the instance.
3362

3363
    """
3364
    # Process here the warnings from CheckPrereq, as we don't have a
3365
    # feedback_fn there.
3366
    # TODO: Replace with self.LogWarning
3367
    for warn in self.warn:
3368
      feedback_fn("WARNING: %s" % warn)
3369

    
3370
    assert ((self.op.disk_template is None) ^
3371
            bool(self.owned_locks(locking.LEVEL_NODE_RES))), \
3372
      "Not owning any node resource locks"
3373

    
3374
    result = []
3375

    
3376
    # New primary node
3377
    if self.op.pnode_uuid:
3378
      self.instance.primary_node = self.op.pnode_uuid
3379

    
3380
    # runtime memory
3381
    if self.op.runtime_mem:
3382
      rpcres = self.rpc.call_instance_balloon_memory(self.instance.primary_node,
3383
                                                     self.instance,
3384
                                                     self.op.runtime_mem)
3385
      rpcres.Raise("Cannot modify instance runtime memory")
3386
      result.append(("runtime_memory", self.op.runtime_mem))
3387

    
3388
    # Apply disk changes
3389
    _ApplyContainerMods("disk", self.instance.disks, result, self.diskmod,
3390
                        self._CreateNewDisk, self._ModifyDisk,
3391
                        self._RemoveDisk, post_add_fn=self._PostAddDisk)
3392
    _UpdateIvNames(0, self.instance.disks)
3393

    
3394
    if self.op.disk_template:
3395
      if __debug__:
3396
        check_nodes = set(self.instance.all_nodes)
3397
        if self.op.remote_node_uuid:
3398
          check_nodes.add(self.op.remote_node_uuid)
3399
        for level in [locking.LEVEL_NODE, locking.LEVEL_NODE_RES]:
3400
          owned = self.owned_locks(level)
3401
          assert not (check_nodes - owned), \
3402
            ("Not owning the correct locks, owning %r, expected at least %r" %
3403
             (owned, check_nodes))
3404

    
3405
      r_shut = ShutdownInstanceDisks(self, self.instance)
3406
      if not r_shut:
3407
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
3408
                                 " proceed with disk template conversion")
3409
      mode = (self.instance.disk_template, self.op.disk_template)
3410
      try:
3411
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
3412
      except:
3413
        self.cfg.ReleaseDRBDMinors(self.instance.uuid)
3414
        raise
3415
      result.append(("disk_template", self.op.disk_template))
3416

    
3417
      assert self.instance.disk_template == self.op.disk_template, \
3418
        ("Expected disk template '%s', found '%s'" %
3419
         (self.op.disk_template, self.instance.disk_template))
3420

    
3421
    # Release node and resource locks if there are any (they might already have
3422
    # been released during disk conversion)
3423
    ReleaseLocks(self, locking.LEVEL_NODE)
3424
    ReleaseLocks(self, locking.LEVEL_NODE_RES)
3425

    
3426
    # Apply NIC changes
3427
    if self._new_nics is not None:
3428
      self.instance.nics = self._new_nics
3429
      result.extend(self._nic_chgdesc)
3430

    
3431
    # hvparams changes
3432
    if self.op.hvparams:
3433
      self.instance.hvparams = self.hv_inst
3434
      for key, val in self.op.hvparams.iteritems():
3435
        result.append(("hv/%s" % key, val))
3436

    
3437
    # beparams changes
3438
    if self.op.beparams:
3439
      self.instance.beparams = self.be_inst
3440
      for key, val in self.op.beparams.iteritems():
3441
        result.append(("be/%s" % key, val))
3442

    
3443
    # OS change
3444
    if self.op.os_name:
3445
      self.instance.os = self.op.os_name
3446

    
3447
    # osparams changes
3448
    if self.op.osparams:
3449
      self.instance.osparams = self.os_inst
3450
      for key, val in self.op.osparams.iteritems():
3451
        result.append(("os/%s" % key, val))
3452

    
3453
    if self.op.offline is None:
3454
      # Ignore
3455
      pass
3456
    elif self.op.offline:
3457
      # Mark instance as offline
3458
      self.cfg.MarkInstanceOffline(self.instance.uuid)
3459
      result.append(("admin_state", constants.ADMINST_OFFLINE))
3460
    else:
3461
      # Mark instance as online, but stopped
3462
      self.cfg.MarkInstanceDown(self.instance.uuid)
3463
      result.append(("admin_state", constants.ADMINST_DOWN))
3464

    
3465
    self.cfg.Update(self.instance, feedback_fn, self.proc.GetECId())
3466

    
3467
    assert not (self.owned_locks(locking.LEVEL_NODE_RES) or
3468
                self.owned_locks(locking.LEVEL_NODE)), \
3469
      "All node locks should have been released by now"
3470

    
3471
    return result
3472

    
3473
  _DISK_CONVERSIONS = {
3474
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
3475
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
3476
    }
3477

    
3478

    
3479
class LUInstanceChangeGroup(LogicalUnit):
3480
  HPATH = "instance-change-group"
3481
  HTYPE = constants.HTYPE_INSTANCE
3482
  REQ_BGL = False
3483

    
3484
  def ExpandNames(self):
3485
    self.share_locks = ShareAll()
3486

    
3487
    self.needed_locks = {
3488
      locking.LEVEL_NODEGROUP: [],
3489
      locking.LEVEL_NODE: [],
3490
      locking.LEVEL_NODE_ALLOC: locking.ALL_SET,
3491
      }
3492

    
3493
    self._ExpandAndLockInstance()
3494

    
3495
    if self.op.target_groups:
3496
      self.req_target_uuids = map(self.cfg.LookupNodeGroup,
3497
                                  self.op.target_groups)
3498
    else:
3499
      self.req_target_uuids = None
3500

    
3501
    self.op.iallocator = GetDefaultIAllocator(self.cfg, self.op.iallocator)
3502

    
3503
  def DeclareLocks(self, level):
3504
    if level == locking.LEVEL_NODEGROUP:
3505
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
3506

    
3507
      if self.req_target_uuids:
3508
        lock_groups = set(self.req_target_uuids)
3509

    
3510
        # Lock all groups used by instance optimistically; this requires going
3511
        # via the node before it's locked, requiring verification later on
3512
        instance_groups = self.cfg.GetInstanceNodeGroups(self.op.instance_uuid)
3513
        lock_groups.update(instance_groups)
3514
      else:
3515
        # No target groups, need to lock all of them
3516
        lock_groups = locking.ALL_SET
3517

    
3518
      self.needed_locks[locking.LEVEL_NODEGROUP] = lock_groups
3519

    
3520
    elif level == locking.LEVEL_NODE:
3521
      if self.req_target_uuids:
3522
        # Lock all nodes used by instances
3523
        self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
3524
        self._LockInstancesNodes()
3525

    
3526
        # Lock all nodes in all potential target groups
3527
        lock_groups = (frozenset(self.owned_locks(locking.LEVEL_NODEGROUP)) -
3528
                       self.cfg.GetInstanceNodeGroups(self.op.instance_uuid))
3529
        member_nodes = [node_uuid
3530
                        for group in lock_groups
3531
                        for node_uuid in self.cfg.GetNodeGroup(group).members]
3532
        self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
3533
      else:
3534
        # Lock all nodes as all groups are potential targets
3535
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3536

    
3537
  def CheckPrereq(self):
3538
    owned_instance_names = frozenset(self.owned_locks(locking.LEVEL_INSTANCE))
3539
    owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
3540
    owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE))
3541

    
3542
    assert (self.req_target_uuids is None or
3543
            owned_groups.issuperset(self.req_target_uuids))
3544
    assert owned_instance_names == set([self.op.instance_name])
3545

    
3546
    # Get instance information
3547
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_uuid)
3548

    
3549
    # Check if node groups for locked instance are still correct
3550
    assert owned_nodes.issuperset(self.instance.all_nodes), \
3551
      ("Instance %s's nodes changed while we kept the lock" %
3552
       self.op.instance_name)
3553

    
3554
    inst_groups = CheckInstanceNodeGroups(self.cfg, self.op.instance_uuid,
3555
                                          owned_groups)
3556

    
3557
    if self.req_target_uuids:
3558
      # User requested specific target groups
3559
      self.target_uuids = frozenset(self.req_target_uuids)
3560
    else:
3561
      # All groups except those used by the instance are potential targets
3562
      self.target_uuids = owned_groups - inst_groups
3563

    
3564
    conflicting_groups = self.target_uuids & inst_groups
3565
    if conflicting_groups:
3566
      raise errors.OpPrereqError("Can't use group(s) '%s' as targets, they are"
3567
                                 " used by the instance '%s'" %
3568
                                 (utils.CommaJoin(conflicting_groups),
3569
                                  self.op.instance_name),
3570
                                 errors.ECODE_INVAL)
3571

    
3572
    if not self.target_uuids:
3573
      raise errors.OpPrereqError("There are no possible target groups",
3574
                                 errors.ECODE_INVAL)
3575

    
3576
  def BuildHooksEnv(self):
3577
    """Build hooks env.
3578

3579
    """
3580
    assert self.target_uuids
3581

    
3582
    env = {
3583
      "TARGET_GROUPS": " ".join(self.target_uuids),
3584
      }
3585

    
3586
    env.update(BuildInstanceHookEnvByObject(self, self.instance))
3587

    
3588
    return env
3589

    
3590
  def BuildHooksNodes(self):
3591
    """Build hooks nodes.
3592

3593
    """
3594
    mn = self.cfg.GetMasterNode()
3595
    return ([mn], [mn])
3596

    
3597
  def Exec(self, feedback_fn):
3598
    instances = list(self.owned_locks(locking.LEVEL_INSTANCE))
3599

    
3600
    assert instances == [self.op.instance_name], "Instance not locked"
3601

    
3602
    req = iallocator.IAReqGroupChange(instances=instances,
3603
                                      target_groups=list(self.target_uuids))
3604
    ial = iallocator.IAllocator(self.cfg, self.rpc, req)
3605

    
3606
    ial.Run(self.op.iallocator)
3607

    
3608
    if not ial.success:
3609
      raise errors.OpPrereqError("Can't compute solution for changing group of"
3610
                                 " instance '%s' using iallocator '%s': %s" %
3611
                                 (self.op.instance_name, self.op.iallocator,
3612
                                  ial.info), errors.ECODE_NORES)
3613

    
3614
    jobs = LoadNodeEvacResult(self, ial.result, self.op.early_release, False)
3615

    
3616
    self.LogInfo("Iallocator returned %s job(s) for changing group of"
3617
                 " instance '%s'", len(jobs), self.op.instance_name)
3618

    
3619
    return ResultWithJobs(jobs)