root / lib / cmdlib / instance.py @ bb3011ad
History | View | Annotate | Download (156.1 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 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 serializer |
41 |
import ganeti.rpc.node as rpc |
42 |
from ganeti import utils |
43 |
|
44 |
from ganeti.cmdlib.base import NoHooksLU, LogicalUnit, ResultWithJobs |
45 |
|
46 |
from ganeti.cmdlib.common import INSTANCE_DOWN, \ |
47 |
INSTANCE_NOT_RUNNING, CAN_CHANGE_INSTANCE_OFFLINE, CheckNodeOnline, \ |
48 |
ShareAll, GetDefaultIAllocator, CheckInstanceNodeGroups, \ |
49 |
LoadNodeEvacResult, CheckIAllocatorOrNode, CheckParamsNotGlobal, \ |
50 |
IsExclusiveStorageEnabledNode, CheckHVParams, CheckOSParams, \ |
51 |
AnnotateDiskParams, GetUpdatedParams, ExpandInstanceUuidAndName, \ |
52 |
ComputeIPolicySpecViolation, CheckInstanceState, ExpandNodeUuidAndName, \ |
53 |
CheckDiskTemplateEnabled, IsValidDiskAccessModeCombination |
54 |
from ganeti.cmdlib.instance_storage import CreateDisks, \ |
55 |
CheckNodesFreeDiskPerVG, WipeDisks, WipeOrCleanupDisks, WaitForSync, \ |
56 |
IsExclusiveStorageEnabledNodeUuid, CreateSingleBlockDev, ComputeDisks, \ |
57 |
CheckRADOSFreeSpace, ComputeDiskSizePerVG, GenerateDiskTemplate, \ |
58 |
StartInstanceDisks, ShutdownInstanceDisks, AssembleInstanceDisks, \ |
59 |
CheckSpindlesExclusiveStorage
|
60 |
from ganeti.cmdlib.instance_utils import BuildInstanceHookEnvByObject, \ |
61 |
GetClusterDomainSecret, BuildInstanceHookEnv, NICListToTuple, \ |
62 |
NICToTuple, CheckNodeNotDrained, RemoveInstance, CopyLockList, \ |
63 |
ReleaseLocks, CheckNodeVmCapable, CheckTargetNodeIPolicy, \ |
64 |
GetInstanceInfoText, RemoveDisks, CheckNodeFreeMemory, \ |
65 |
CheckInstanceBridgesExist, CheckNicsBridgesExist, CheckNodeHasOS |
66 |
|
67 |
import ganeti.masterd.instance |
68 |
|
69 |
|
70 |
#: Type description for changes as returned by L{_ApplyContainerMods}'s
|
71 |
#: callbacks
|
72 |
_TApplyContModsCbChanges = \ |
73 |
ht.TMaybeListOf(ht.TAnd(ht.TIsLength(2), ht.TItems([
|
74 |
ht.TNonEmptyString, |
75 |
ht.TAny, |
76 |
]))) |
77 |
|
78 |
|
79 |
def _CheckHostnameSane(lu, name): |
80 |
"""Ensures that a given hostname resolves to a 'sane' name.
|
81 |
|
82 |
The given name is required to be a prefix of the resolved hostname,
|
83 |
to prevent accidental mismatches.
|
84 |
|
85 |
@param lu: the logical unit on behalf of which we're checking
|
86 |
@param name: the name we should resolve and check
|
87 |
@return: the resolved hostname object
|
88 |
|
89 |
"""
|
90 |
hostname = netutils.GetHostname(name=name) |
91 |
if hostname.name != name:
|
92 |
lu.LogInfo("Resolved given name '%s' to '%s'", name, hostname.name)
|
93 |
if not utils.MatchNameComponent(name, [hostname.name]): |
94 |
raise errors.OpPrereqError(("Resolved hostname '%s' does not look the" |
95 |
" same as given hostname '%s'") %
|
96 |
(hostname.name, name), errors.ECODE_INVAL) |
97 |
return hostname
|
98 |
|
99 |
|
100 |
def _CheckOpportunisticLocking(op): |
101 |
"""Generate error if opportunistic locking is not possible.
|
102 |
|
103 |
"""
|
104 |
if op.opportunistic_locking and not op.iallocator: |
105 |
raise errors.OpPrereqError("Opportunistic locking is only available in" |
106 |
" combination with an instance allocator",
|
107 |
errors.ECODE_INVAL) |
108 |
|
109 |
|
110 |
def _CreateInstanceAllocRequest(op, disks, nics, beparams, node_name_whitelist): |
111 |
"""Wrapper around IAReqInstanceAlloc.
|
112 |
|
113 |
@param op: The instance opcode
|
114 |
@param disks: The computed disks
|
115 |
@param nics: The computed nics
|
116 |
@param beparams: The full filled beparams
|
117 |
@param node_name_whitelist: List of nodes which should appear as online to the
|
118 |
allocator (unless the node is already marked offline)
|
119 |
|
120 |
@returns: A filled L{iallocator.IAReqInstanceAlloc}
|
121 |
|
122 |
"""
|
123 |
spindle_use = beparams[constants.BE_SPINDLE_USE] |
124 |
return iallocator.IAReqInstanceAlloc(name=op.instance_name,
|
125 |
disk_template=op.disk_template, |
126 |
tags=op.tags, |
127 |
os=op.os_type, |
128 |
vcpus=beparams[constants.BE_VCPUS], |
129 |
memory=beparams[constants.BE_MAXMEM], |
130 |
spindle_use=spindle_use, |
131 |
disks=disks, |
132 |
nics=[n.ToDict() for n in nics], |
133 |
hypervisor=op.hypervisor, |
134 |
node_whitelist=node_name_whitelist) |
135 |
|
136 |
|
137 |
def _ComputeFullBeParams(op, cluster): |
138 |
"""Computes the full beparams.
|
139 |
|
140 |
@param op: The instance opcode
|
141 |
@param cluster: The cluster config object
|
142 |
|
143 |
@return: The fully filled beparams
|
144 |
|
145 |
"""
|
146 |
default_beparams = cluster.beparams[constants.PP_DEFAULT] |
147 |
for param, value in op.beparams.iteritems(): |
148 |
if value == constants.VALUE_AUTO:
|
149 |
op.beparams[param] = default_beparams[param] |
150 |
objects.UpgradeBeParams(op.beparams) |
151 |
utils.ForceDictType(op.beparams, constants.BES_PARAMETER_TYPES) |
152 |
return cluster.SimpleFillBE(op.beparams)
|
153 |
|
154 |
|
155 |
def _ComputeNics(op, cluster, default_ip, cfg, ec_id): |
156 |
"""Computes the nics.
|
157 |
|
158 |
@param op: The instance opcode
|
159 |
@param cluster: Cluster configuration object
|
160 |
@param default_ip: The default ip to assign
|
161 |
@param cfg: An instance of the configuration object
|
162 |
@param ec_id: Execution context ID
|
163 |
|
164 |
@returns: The build up nics
|
165 |
|
166 |
"""
|
167 |
nics = [] |
168 |
for nic in op.nics: |
169 |
nic_mode_req = nic.get(constants.INIC_MODE, None)
|
170 |
nic_mode = nic_mode_req |
171 |
if nic_mode is None or nic_mode == constants.VALUE_AUTO: |
172 |
nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE] |
173 |
|
174 |
net = nic.get(constants.INIC_NETWORK, None)
|
175 |
link = nic.get(constants.NIC_LINK, None)
|
176 |
ip = nic.get(constants.INIC_IP, None)
|
177 |
vlan = nic.get(constants.INIC_VLAN, None)
|
178 |
|
179 |
if net is None or net.lower() == constants.VALUE_NONE: |
180 |
net = None
|
181 |
else:
|
182 |
if nic_mode_req is not None or link is not None: |
183 |
raise errors.OpPrereqError("If network is given, no mode or link" |
184 |
" is allowed to be passed",
|
185 |
errors.ECODE_INVAL) |
186 |
|
187 |
# ip validity checks
|
188 |
if ip is None or ip.lower() == constants.VALUE_NONE: |
189 |
nic_ip = None
|
190 |
elif ip.lower() == constants.VALUE_AUTO:
|
191 |
if not op.name_check: |
192 |
raise errors.OpPrereqError("IP address set to auto but name checks" |
193 |
" have been skipped",
|
194 |
errors.ECODE_INVAL) |
195 |
nic_ip = default_ip |
196 |
else:
|
197 |
# We defer pool operations until later, so that the iallocator has
|
198 |
# filled in the instance's node(s) dimara
|
199 |
if ip.lower() == constants.NIC_IP_POOL:
|
200 |
if net is None: |
201 |
raise errors.OpPrereqError("if ip=pool, parameter network" |
202 |
" must be passed too",
|
203 |
errors.ECODE_INVAL) |
204 |
|
205 |
elif not netutils.IPAddress.IsValid(ip): |
206 |
raise errors.OpPrereqError("Invalid IP address '%s'" % ip, |
207 |
errors.ECODE_INVAL) |
208 |
|
209 |
nic_ip = ip |
210 |
|
211 |
# TODO: check the ip address for uniqueness
|
212 |
if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip: |
213 |
raise errors.OpPrereqError("Routed nic mode requires an ip address", |
214 |
errors.ECODE_INVAL) |
215 |
|
216 |
# MAC address verification
|
217 |
mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO) |
218 |
if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE): |
219 |
mac = utils.NormalizeAndValidateMac(mac) |
220 |
|
221 |
try:
|
222 |
# TODO: We need to factor this out
|
223 |
cfg.ReserveMAC(mac, ec_id) |
224 |
except errors.ReservationError:
|
225 |
raise errors.OpPrereqError("MAC address %s already in use" |
226 |
" in cluster" % mac,
|
227 |
errors.ECODE_NOTUNIQUE) |
228 |
|
229 |
# Build nic parameters
|
230 |
nicparams = {} |
231 |
if nic_mode_req:
|
232 |
nicparams[constants.NIC_MODE] = nic_mode |
233 |
if link:
|
234 |
nicparams[constants.NIC_LINK] = link |
235 |
if vlan:
|
236 |
nicparams[constants.NIC_VLAN] = vlan |
237 |
|
238 |
check_params = cluster.SimpleFillNIC(nicparams) |
239 |
objects.NIC.CheckParameterSyntax(check_params) |
240 |
net_uuid = cfg.LookupNetwork(net) |
241 |
name = nic.get(constants.INIC_NAME, None)
|
242 |
if name is not None and name.lower() == constants.VALUE_NONE: |
243 |
name = None
|
244 |
nic_obj = objects.NIC(mac=mac, ip=nic_ip, name=name, |
245 |
network=net_uuid, nicparams=nicparams) |
246 |
nic_obj.uuid = cfg.GenerateUniqueID(ec_id) |
247 |
nics.append(nic_obj) |
248 |
|
249 |
return nics
|
250 |
|
251 |
|
252 |
def _CheckForConflictingIp(lu, ip, node_uuid): |
253 |
"""In case of conflicting IP address raise error.
|
254 |
|
255 |
@type ip: string
|
256 |
@param ip: IP address
|
257 |
@type node_uuid: string
|
258 |
@param node_uuid: node UUID
|
259 |
|
260 |
"""
|
261 |
(conf_net, _) = lu.cfg.CheckIPInNodeGroup(ip, node_uuid) |
262 |
if conf_net is not None: |
263 |
raise errors.OpPrereqError(("The requested IP address (%s) belongs to" |
264 |
" network %s, but the target NIC does not." %
|
265 |
(ip, conf_net)), |
266 |
errors.ECODE_STATE) |
267 |
|
268 |
return (None, None) |
269 |
|
270 |
|
271 |
def _ComputeIPolicyInstanceSpecViolation( |
272 |
ipolicy, instance_spec, disk_template, |
273 |
_compute_fn=ComputeIPolicySpecViolation): |
274 |
"""Compute if instance specs meets the specs of ipolicy.
|
275 |
|
276 |
@type ipolicy: dict
|
277 |
@param ipolicy: The ipolicy to verify against
|
278 |
@param instance_spec: dict
|
279 |
@param instance_spec: The instance spec to verify
|
280 |
@type disk_template: string
|
281 |
@param disk_template: the disk template of the instance
|
282 |
@param _compute_fn: The function to verify ipolicy (unittest only)
|
283 |
@see: L{ComputeIPolicySpecViolation}
|
284 |
|
285 |
"""
|
286 |
mem_size = instance_spec.get(constants.ISPEC_MEM_SIZE, None)
|
287 |
cpu_count = instance_spec.get(constants.ISPEC_CPU_COUNT, None)
|
288 |
disk_count = instance_spec.get(constants.ISPEC_DISK_COUNT, 0)
|
289 |
disk_sizes = instance_spec.get(constants.ISPEC_DISK_SIZE, []) |
290 |
nic_count = instance_spec.get(constants.ISPEC_NIC_COUNT, 0)
|
291 |
spindle_use = instance_spec.get(constants.ISPEC_SPINDLE_USE, None)
|
292 |
|
293 |
return _compute_fn(ipolicy, mem_size, cpu_count, disk_count, nic_count,
|
294 |
disk_sizes, spindle_use, disk_template) |
295 |
|
296 |
|
297 |
def _CheckOSVariant(os_obj, name): |
298 |
"""Check whether an OS name conforms to the os variants specification.
|
299 |
|
300 |
@type os_obj: L{objects.OS}
|
301 |
@param os_obj: OS object to check
|
302 |
@type name: string
|
303 |
@param name: OS name passed by the user, to check for validity
|
304 |
|
305 |
"""
|
306 |
variant = objects.OS.GetVariant(name) |
307 |
if not os_obj.supported_variants: |
308 |
if variant:
|
309 |
raise errors.OpPrereqError("OS '%s' doesn't support variants ('%s'" |
310 |
" passed)" % (os_obj.name, variant),
|
311 |
errors.ECODE_INVAL) |
312 |
return
|
313 |
if not variant: |
314 |
raise errors.OpPrereqError("OS name must include a variant", |
315 |
errors.ECODE_INVAL) |
316 |
|
317 |
if variant not in os_obj.supported_variants: |
318 |
raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL) |
319 |
|
320 |
|
321 |
def _ComputeInstanceCommunicationNIC(instance_name): |
322 |
"""Compute the name of the instance NIC used by instance
|
323 |
communication.
|
324 |
|
325 |
With instance communication, a new NIC is added to the instance.
|
326 |
This NIC has a special name that identities it as being part of
|
327 |
instance communication, and not just a normal NIC. This function
|
328 |
generates the name of the NIC based on a prefix and the instance
|
329 |
name
|
330 |
|
331 |
@type instance_name: string
|
332 |
@param instance_name: name of the instance the NIC belongs to
|
333 |
|
334 |
@rtype: string
|
335 |
@return: name of the NIC
|
336 |
|
337 |
"""
|
338 |
return constants.INSTANCE_COMMUNICATION_NIC_PREFIX + instance_name
|
339 |
|
340 |
|
341 |
class LUInstanceCreate(LogicalUnit): |
342 |
"""Create an instance.
|
343 |
|
344 |
"""
|
345 |
HPATH = "instance-add"
|
346 |
HTYPE = constants.HTYPE_INSTANCE |
347 |
REQ_BGL = False
|
348 |
|
349 |
def _CheckDiskTemplateValid(self): |
350 |
"""Checks validity of disk template.
|
351 |
|
352 |
"""
|
353 |
cluster = self.cfg.GetClusterInfo()
|
354 |
if self.op.disk_template is None: |
355 |
# FIXME: It would be better to take the default disk template from the
|
356 |
# ipolicy, but for the ipolicy we need the primary node, which we get from
|
357 |
# the iallocator, which wants the disk template as input. To solve this
|
358 |
# chicken-and-egg problem, it should be possible to specify just a node
|
359 |
# group from the iallocator and take the ipolicy from that.
|
360 |
self.op.disk_template = cluster.enabled_disk_templates[0] |
361 |
CheckDiskTemplateEnabled(cluster, self.op.disk_template)
|
362 |
|
363 |
def _CheckDiskArguments(self): |
364 |
"""Checks validity of disk-related arguments.
|
365 |
|
366 |
"""
|
367 |
# check that disk's names are unique and valid
|
368 |
utils.ValidateDeviceNames("disk", self.op.disks) |
369 |
|
370 |
self._CheckDiskTemplateValid()
|
371 |
|
372 |
# check disks. parameter names and consistent adopt/no-adopt strategy
|
373 |
has_adopt = has_no_adopt = False
|
374 |
for disk in self.op.disks: |
375 |
if self.op.disk_template != constants.DT_EXT: |
376 |
utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES) |
377 |
if constants.IDISK_ADOPT in disk: |
378 |
has_adopt = True
|
379 |
else:
|
380 |
has_no_adopt = True
|
381 |
if has_adopt and has_no_adopt: |
382 |
raise errors.OpPrereqError("Either all disks are adopted or none is", |
383 |
errors.ECODE_INVAL) |
384 |
if has_adopt:
|
385 |
if self.op.disk_template not in constants.DTS_MAY_ADOPT: |
386 |
raise errors.OpPrereqError("Disk adoption is not supported for the" |
387 |
" '%s' disk template" %
|
388 |
self.op.disk_template,
|
389 |
errors.ECODE_INVAL) |
390 |
if self.op.iallocator is not None: |
391 |
raise errors.OpPrereqError("Disk adoption not allowed with an" |
392 |
" iallocator script", errors.ECODE_INVAL)
|
393 |
if self.op.mode == constants.INSTANCE_IMPORT: |
394 |
raise errors.OpPrereqError("Disk adoption not allowed for" |
395 |
" instance import", errors.ECODE_INVAL)
|
396 |
else:
|
397 |
if self.op.disk_template in constants.DTS_MUST_ADOPT: |
398 |
raise errors.OpPrereqError("Disk template %s requires disk adoption," |
399 |
" but no 'adopt' parameter given" %
|
400 |
self.op.disk_template,
|
401 |
errors.ECODE_INVAL) |
402 |
|
403 |
self.adopt_disks = has_adopt
|
404 |
|
405 |
def _CheckVLANArguments(self): |
406 |
""" Check validity of VLANs if given
|
407 |
|
408 |
"""
|
409 |
for nic in self.op.nics: |
410 |
vlan = nic.get(constants.INIC_VLAN, None)
|
411 |
if vlan:
|
412 |
if vlan[0] == ".": |
413 |
# vlan starting with dot means single untagged vlan,
|
414 |
# might be followed by trunk (:)
|
415 |
if not vlan[1:].isdigit(): |
416 |
vlanlist = vlan[1:].split(':') |
417 |
for vl in vlanlist: |
418 |
if not vl.isdigit(): |
419 |
raise errors.OpPrereqError("Specified VLAN parameter is " |
420 |
"invalid : %s" % vlan,
|
421 |
errors.ECODE_INVAL) |
422 |
elif vlan[0] == ":": |
423 |
# Trunk - tagged only
|
424 |
vlanlist = vlan[1:].split(':') |
425 |
for vl in vlanlist: |
426 |
if not vl.isdigit(): |
427 |
raise errors.OpPrereqError("Specified VLAN parameter is invalid" |
428 |
" : %s" % vlan, errors.ECODE_INVAL)
|
429 |
elif vlan.isdigit():
|
430 |
# This is the simplest case. No dots, only single digit
|
431 |
# -> Create untagged access port, dot needs to be added
|
432 |
nic[constants.INIC_VLAN] = "." + vlan
|
433 |
else:
|
434 |
raise errors.OpPrereqError("Specified VLAN parameter is invalid" |
435 |
" : %s" % vlan, errors.ECODE_INVAL)
|
436 |
|
437 |
def CheckArguments(self): |
438 |
"""Check arguments.
|
439 |
|
440 |
"""
|
441 |
# do not require name_check to ease forward/backward compatibility
|
442 |
# for tools
|
443 |
if self.op.no_install and self.op.start: |
444 |
self.LogInfo("No-installation mode selected, disabling startup") |
445 |
self.op.start = False |
446 |
# validate/normalize the instance name
|
447 |
self.op.instance_name = \
|
448 |
netutils.Hostname.GetNormalizedName(self.op.instance_name)
|
449 |
|
450 |
if self.op.ip_check and not self.op.name_check: |
451 |
# TODO: make the ip check more flexible and not depend on the name check
|
452 |
raise errors.OpPrereqError("Cannot do IP address check without a name" |
453 |
" check", errors.ECODE_INVAL)
|
454 |
|
455 |
# add NIC for instance communication
|
456 |
if self.op.instance_communication: |
457 |
nic_name = _ComputeInstanceCommunicationNIC(self.op.instance_name)
|
458 |
|
459 |
self.op.nics.append({constants.INIC_NAME: nic_name,
|
460 |
constants.INIC_MAC: constants.VALUE_GENERATE, |
461 |
constants.INIC_IP: constants.NIC_IP_POOL, |
462 |
constants.INIC_NETWORK: |
463 |
self.cfg.GetInstanceCommunicationNetwork()})
|
464 |
|
465 |
# check nics' parameter names
|
466 |
for nic in self.op.nics: |
467 |
utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES) |
468 |
# check that NIC's parameters names are unique and valid
|
469 |
utils.ValidateDeviceNames("NIC", self.op.nics) |
470 |
|
471 |
self._CheckVLANArguments()
|
472 |
|
473 |
self._CheckDiskArguments()
|
474 |
assert self.op.disk_template is not None |
475 |
|
476 |
# instance name verification
|
477 |
if self.op.name_check: |
478 |
self.hostname = _CheckHostnameSane(self, self.op.instance_name) |
479 |
self.op.instance_name = self.hostname.name |
480 |
# used in CheckPrereq for ip ping check
|
481 |
self.check_ip = self.hostname.ip |
482 |
else:
|
483 |
self.check_ip = None |
484 |
|
485 |
# file storage checks
|
486 |
if (self.op.file_driver and |
487 |
not self.op.file_driver in constants.FILE_DRIVER): |
488 |
raise errors.OpPrereqError("Invalid file driver name '%s'" % |
489 |
self.op.file_driver, errors.ECODE_INVAL)
|
490 |
|
491 |
# set default file_driver if unset and required
|
492 |
if (not self.op.file_driver and |
493 |
self.op.disk_template in constants.DTS_FILEBASED): |
494 |
self.op.file_driver = constants.FD_LOOP
|
495 |
|
496 |
### Node/iallocator related checks
|
497 |
CheckIAllocatorOrNode(self, "iallocator", "pnode") |
498 |
|
499 |
if self.op.pnode is not None: |
500 |
if self.op.disk_template in constants.DTS_INT_MIRROR: |
501 |
if self.op.snode is None: |
502 |
raise errors.OpPrereqError("The networked disk templates need" |
503 |
" a mirror node", errors.ECODE_INVAL)
|
504 |
elif self.op.snode: |
505 |
self.LogWarning("Secondary node will be ignored on non-mirrored disk" |
506 |
" template")
|
507 |
self.op.snode = None |
508 |
|
509 |
_CheckOpportunisticLocking(self.op)
|
510 |
|
511 |
if self.op.mode == constants.INSTANCE_IMPORT: |
512 |
# On import force_variant must be True, because if we forced it at
|
513 |
# initial install, our only chance when importing it back is that it
|
514 |
# works again!
|
515 |
self.op.force_variant = True |
516 |
|
517 |
if self.op.no_install: |
518 |
self.LogInfo("No-installation mode has no effect during import") |
519 |
|
520 |
elif self.op.mode == constants.INSTANCE_CREATE: |
521 |
if self.op.os_type is None: |
522 |
raise errors.OpPrereqError("No guest OS specified", |
523 |
errors.ECODE_INVAL) |
524 |
if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os: |
525 |
raise errors.OpPrereqError("Guest OS '%s' is not allowed for" |
526 |
" installation" % self.op.os_type, |
527 |
errors.ECODE_STATE) |
528 |
elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT: |
529 |
self._cds = GetClusterDomainSecret()
|
530 |
|
531 |
# Check handshake to ensure both clusters have the same domain secret
|
532 |
src_handshake = self.op.source_handshake
|
533 |
if not src_handshake: |
534 |
raise errors.OpPrereqError("Missing source handshake", |
535 |
errors.ECODE_INVAL) |
536 |
|
537 |
errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
|
538 |
src_handshake) |
539 |
if errmsg:
|
540 |
raise errors.OpPrereqError("Invalid handshake: %s" % errmsg, |
541 |
errors.ECODE_INVAL) |
542 |
|
543 |
# Load and check source CA
|
544 |
self.source_x509_ca_pem = self.op.source_x509_ca |
545 |
if not self.source_x509_ca_pem: |
546 |
raise errors.OpPrereqError("Missing source X509 CA", |
547 |
errors.ECODE_INVAL) |
548 |
|
549 |
try:
|
550 |
(cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
|
551 |
self._cds)
|
552 |
except OpenSSL.crypto.Error, err:
|
553 |
raise errors.OpPrereqError("Unable to load source X509 CA (%s)" % |
554 |
(err, ), errors.ECODE_INVAL) |
555 |
|
556 |
(errcode, msg) = utils.VerifyX509Certificate(cert, None, None) |
557 |
if errcode is not None: |
558 |
raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ), |
559 |
errors.ECODE_INVAL) |
560 |
|
561 |
self.source_x509_ca = cert
|
562 |
|
563 |
src_instance_name = self.op.source_instance_name
|
564 |
if not src_instance_name: |
565 |
raise errors.OpPrereqError("Missing source instance name", |
566 |
errors.ECODE_INVAL) |
567 |
|
568 |
self.source_instance_name = \
|
569 |
netutils.GetHostname(name=src_instance_name).name |
570 |
|
571 |
else:
|
572 |
raise errors.OpPrereqError("Invalid instance creation mode %r" % |
573 |
self.op.mode, errors.ECODE_INVAL)
|
574 |
|
575 |
def ExpandNames(self): |
576 |
"""ExpandNames for CreateInstance.
|
577 |
|
578 |
Figure out the right locks for instance creation.
|
579 |
|
580 |
"""
|
581 |
self.needed_locks = {}
|
582 |
|
583 |
# this is just a preventive check, but someone might still add this
|
584 |
# instance in the meantime, and creation will fail at lock-add time
|
585 |
if self.op.instance_name in\ |
586 |
[inst.name for inst in self.cfg.GetAllInstancesInfo().values()]: |
587 |
raise errors.OpPrereqError("Instance '%s' is already in the cluster" % |
588 |
self.op.instance_name, errors.ECODE_EXISTS)
|
589 |
|
590 |
self.add_locks[locking.LEVEL_INSTANCE] = self.op.instance_name |
591 |
|
592 |
if self.op.iallocator: |
593 |
# TODO: Find a solution to not lock all nodes in the cluster, e.g. by
|
594 |
# specifying a group on instance creation and then selecting nodes from
|
595 |
# that group
|
596 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
597 |
self.needed_locks[locking.LEVEL_NODE_ALLOC] = locking.ALL_SET
|
598 |
|
599 |
if self.op.opportunistic_locking: |
600 |
self.opportunistic_locks[locking.LEVEL_NODE] = True |
601 |
else:
|
602 |
(self.op.pnode_uuid, self.op.pnode) = \ |
603 |
ExpandNodeUuidAndName(self.cfg, self.op.pnode_uuid, self.op.pnode) |
604 |
nodelist = [self.op.pnode_uuid]
|
605 |
if self.op.snode is not None: |
606 |
(self.op.snode_uuid, self.op.snode) = \ |
607 |
ExpandNodeUuidAndName(self.cfg, self.op.snode_uuid, self.op.snode) |
608 |
nodelist.append(self.op.snode_uuid)
|
609 |
self.needed_locks[locking.LEVEL_NODE] = nodelist
|
610 |
|
611 |
# in case of import lock the source node too
|
612 |
if self.op.mode == constants.INSTANCE_IMPORT: |
613 |
src_node = self.op.src_node
|
614 |
src_path = self.op.src_path
|
615 |
|
616 |
if src_path is None: |
617 |
self.op.src_path = src_path = self.op.instance_name |
618 |
|
619 |
if src_node is None: |
620 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
621 |
self.needed_locks[locking.LEVEL_NODE_ALLOC] = locking.ALL_SET
|
622 |
self.op.src_node = None |
623 |
if os.path.isabs(src_path):
|
624 |
raise errors.OpPrereqError("Importing an instance from a path" |
625 |
" requires a source node option",
|
626 |
errors.ECODE_INVAL) |
627 |
else:
|
628 |
(self.op.src_node_uuid, self.op.src_node) = (_, src_node) = \ |
629 |
ExpandNodeUuidAndName(self.cfg, self.op.src_node_uuid, src_node) |
630 |
if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET: |
631 |
self.needed_locks[locking.LEVEL_NODE].append(self.op.src_node_uuid) |
632 |
if not os.path.isabs(src_path): |
633 |
self.op.src_path = \
|
634 |
utils.PathJoin(pathutils.EXPORT_DIR, src_path) |
635 |
|
636 |
self.needed_locks[locking.LEVEL_NODE_RES] = \
|
637 |
CopyLockList(self.needed_locks[locking.LEVEL_NODE])
|
638 |
|
639 |
# Optimistically acquire shared group locks (we're reading the
|
640 |
# configuration). We can't just call GetInstanceNodeGroups, because the
|
641 |
# instance doesn't exist yet. Therefore we lock all node groups of all
|
642 |
# nodes we have.
|
643 |
if self.needed_locks[locking.LEVEL_NODE] == locking.ALL_SET: |
644 |
# In the case we lock all nodes for opportunistic allocation, we have no
|
645 |
# choice than to lock all groups, because they're allocated before nodes.
|
646 |
# This is sad, but true. At least we release all those we don't need in
|
647 |
# CheckPrereq later.
|
648 |
self.needed_locks[locking.LEVEL_NODEGROUP] = locking.ALL_SET
|
649 |
else:
|
650 |
self.needed_locks[locking.LEVEL_NODEGROUP] = \
|
651 |
list(self.cfg.GetNodeGroupsFromNodes( |
652 |
self.needed_locks[locking.LEVEL_NODE]))
|
653 |
self.share_locks[locking.LEVEL_NODEGROUP] = 1 |
654 |
|
655 |
def DeclareLocks(self, level): |
656 |
if level == locking.LEVEL_NODE_RES and \ |
657 |
self.opportunistic_locks[locking.LEVEL_NODE]:
|
658 |
# Even when using opportunistic locking, we require the same set of
|
659 |
# NODE_RES locks as we got NODE locks
|
660 |
self.needed_locks[locking.LEVEL_NODE_RES] = \
|
661 |
self.owned_locks(locking.LEVEL_NODE)
|
662 |
|
663 |
def _RunAllocator(self): |
664 |
"""Run the allocator based on input opcode.
|
665 |
|
666 |
"""
|
667 |
if self.op.opportunistic_locking: |
668 |
# Only consider nodes for which a lock is held
|
669 |
node_name_whitelist = self.cfg.GetNodeNames(
|
670 |
self.owned_locks(locking.LEVEL_NODE))
|
671 |
else:
|
672 |
node_name_whitelist = None
|
673 |
|
674 |
req = _CreateInstanceAllocRequest(self.op, self.disks, |
675 |
self.nics, self.be_full, |
676 |
node_name_whitelist) |
677 |
ial = iallocator.IAllocator(self.cfg, self.rpc, req) |
678 |
|
679 |
ial.Run(self.op.iallocator)
|
680 |
|
681 |
if not ial.success: |
682 |
# When opportunistic locks are used only a temporary failure is generated
|
683 |
if self.op.opportunistic_locking: |
684 |
ecode = errors.ECODE_TEMP_NORES |
685 |
else:
|
686 |
ecode = errors.ECODE_NORES |
687 |
|
688 |
raise errors.OpPrereqError("Can't compute nodes using" |
689 |
" iallocator '%s': %s" %
|
690 |
(self.op.iallocator, ial.info),
|
691 |
ecode) |
692 |
|
693 |
(self.op.pnode_uuid, self.op.pnode) = \ |
694 |
ExpandNodeUuidAndName(self.cfg, None, ial.result[0]) |
695 |
self.LogInfo("Selected nodes for instance %s via iallocator %s: %s", |
696 |
self.op.instance_name, self.op.iallocator, |
697 |
utils.CommaJoin(ial.result)) |
698 |
|
699 |
assert req.RequiredNodes() in (1, 2), "Wrong node count from iallocator" |
700 |
|
701 |
if req.RequiredNodes() == 2: |
702 |
(self.op.snode_uuid, self.op.snode) = \ |
703 |
ExpandNodeUuidAndName(self.cfg, None, ial.result[1]) |
704 |
|
705 |
def BuildHooksEnv(self): |
706 |
"""Build hooks env.
|
707 |
|
708 |
This runs on master, primary and secondary nodes of the instance.
|
709 |
|
710 |
"""
|
711 |
env = { |
712 |
"ADD_MODE": self.op.mode, |
713 |
} |
714 |
if self.op.mode == constants.INSTANCE_IMPORT: |
715 |
env["SRC_NODE"] = self.op.src_node |
716 |
env["SRC_PATH"] = self.op.src_path |
717 |
env["SRC_IMAGES"] = self.src_images |
718 |
|
719 |
env.update(BuildInstanceHookEnv( |
720 |
name=self.op.instance_name,
|
721 |
primary_node_name=self.op.pnode,
|
722 |
secondary_node_names=self.cfg.GetNodeNames(self.secondaries), |
723 |
status=self.op.start,
|
724 |
os_type=self.op.os_type,
|
725 |
minmem=self.be_full[constants.BE_MINMEM],
|
726 |
maxmem=self.be_full[constants.BE_MAXMEM],
|
727 |
vcpus=self.be_full[constants.BE_VCPUS],
|
728 |
nics=NICListToTuple(self, self.nics), |
729 |
disk_template=self.op.disk_template,
|
730 |
disks=[(d[constants.IDISK_NAME], d.get("uuid", ""), |
731 |
d[constants.IDISK_SIZE], d[constants.IDISK_MODE]) |
732 |
for d in self.disks], |
733 |
bep=self.be_full,
|
734 |
hvp=self.hv_full,
|
735 |
hypervisor_name=self.op.hypervisor,
|
736 |
tags=self.op.tags,
|
737 |
)) |
738 |
|
739 |
return env
|
740 |
|
741 |
def BuildHooksNodes(self): |
742 |
"""Build hooks nodes.
|
743 |
|
744 |
"""
|
745 |
nl = [self.cfg.GetMasterNode(), self.op.pnode_uuid] + self.secondaries |
746 |
return nl, nl
|
747 |
|
748 |
def _ReadExportInfo(self): |
749 |
"""Reads the export information from disk.
|
750 |
|
751 |
It will override the opcode source node and path with the actual
|
752 |
information, if these two were not specified before.
|
753 |
|
754 |
@return: the export information
|
755 |
|
756 |
"""
|
757 |
assert self.op.mode == constants.INSTANCE_IMPORT |
758 |
|
759 |
if self.op.src_node_uuid is None: |
760 |
locked_nodes = self.owned_locks(locking.LEVEL_NODE)
|
761 |
exp_list = self.rpc.call_export_list(locked_nodes)
|
762 |
found = False
|
763 |
for node_uuid in exp_list: |
764 |
if exp_list[node_uuid].fail_msg:
|
765 |
continue
|
766 |
if self.op.src_path in exp_list[node_uuid].payload: |
767 |
found = True
|
768 |
self.op.src_node = self.cfg.GetNodeInfo(node_uuid).name |
769 |
self.op.src_node_uuid = node_uuid
|
770 |
self.op.src_path = utils.PathJoin(pathutils.EXPORT_DIR,
|
771 |
self.op.src_path)
|
772 |
break
|
773 |
if not found: |
774 |
raise errors.OpPrereqError("No export found for relative path %s" % |
775 |
self.op.src_path, errors.ECODE_INVAL)
|
776 |
|
777 |
CheckNodeOnline(self, self.op.src_node_uuid) |
778 |
result = self.rpc.call_export_info(self.op.src_node_uuid, self.op.src_path) |
779 |
result.Raise("No export or invalid export found in dir %s" %
|
780 |
self.op.src_path)
|
781 |
|
782 |
export_info = objects.SerializableConfigParser.Loads(str(result.payload))
|
783 |
if not export_info.has_section(constants.INISECT_EXP): |
784 |
raise errors.ProgrammerError("Corrupted export config", |
785 |
errors.ECODE_ENVIRON) |
786 |
|
787 |
ei_version = export_info.get(constants.INISECT_EXP, "version")
|
788 |
if int(ei_version) != constants.EXPORT_VERSION: |
789 |
raise errors.OpPrereqError("Wrong export version %s (wanted %d)" % |
790 |
(ei_version, constants.EXPORT_VERSION), |
791 |
errors.ECODE_ENVIRON) |
792 |
return export_info
|
793 |
|
794 |
def _ReadExportParams(self, einfo): |
795 |
"""Use export parameters as defaults.
|
796 |
|
797 |
In case the opcode doesn't specify (as in override) some instance
|
798 |
parameters, then try to use them from the export information, if
|
799 |
that declares them.
|
800 |
|
801 |
"""
|
802 |
self.op.os_type = einfo.get(constants.INISECT_EXP, "os") |
803 |
|
804 |
if not self.op.disks: |
805 |
disks = [] |
806 |
# TODO: import the disk iv_name too
|
807 |
for idx in range(constants.MAX_DISKS): |
808 |
if einfo.has_option(constants.INISECT_INS, "disk%d_size" % idx): |
809 |
disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
|
810 |
disks.append({constants.IDISK_SIZE: disk_sz}) |
811 |
self.op.disks = disks
|
812 |
if not disks and self.op.disk_template != constants.DT_DISKLESS: |
813 |
raise errors.OpPrereqError("No disk info specified and the export" |
814 |
" is missing the disk information",
|
815 |
errors.ECODE_INVAL) |
816 |
|
817 |
if not self.op.nics: |
818 |
nics = [] |
819 |
for idx in range(constants.MAX_NICS): |
820 |
if einfo.has_option(constants.INISECT_INS, "nic%d_mac" % idx): |
821 |
ndict = {} |
822 |
for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]: |
823 |
nic_param_name = "nic%d_%s" % (idx, name)
|
824 |
if einfo.has_option(constants.INISECT_INS, nic_param_name):
|
825 |
v = einfo.get(constants.INISECT_INS, nic_param_name) |
826 |
ndict[name] = v |
827 |
nics.append(ndict) |
828 |
else:
|
829 |
break
|
830 |
self.op.nics = nics
|
831 |
|
832 |
if not self.op.tags and einfo.has_option(constants.INISECT_INS, "tags"): |
833 |
self.op.tags = einfo.get(constants.INISECT_INS, "tags").split() |
834 |
|
835 |
if (self.op.hypervisor is None and |
836 |
einfo.has_option(constants.INISECT_INS, "hypervisor")):
|
837 |
self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor") |
838 |
|
839 |
if einfo.has_section(constants.INISECT_HYP):
|
840 |
# use the export parameters but do not override the ones
|
841 |
# specified by the user
|
842 |
for name, value in einfo.items(constants.INISECT_HYP): |
843 |
if name not in self.op.hvparams: |
844 |
self.op.hvparams[name] = value
|
845 |
|
846 |
if einfo.has_section(constants.INISECT_BEP):
|
847 |
# use the parameters, without overriding
|
848 |
for name, value in einfo.items(constants.INISECT_BEP): |
849 |
if name not in self.op.beparams: |
850 |
self.op.beparams[name] = value
|
851 |
# Compatibility for the old "memory" be param
|
852 |
if name == constants.BE_MEMORY:
|
853 |
if constants.BE_MAXMEM not in self.op.beparams: |
854 |
self.op.beparams[constants.BE_MAXMEM] = value
|
855 |
if constants.BE_MINMEM not in self.op.beparams: |
856 |
self.op.beparams[constants.BE_MINMEM] = value
|
857 |
else:
|
858 |
# try to read the parameters old style, from the main section
|
859 |
for name in constants.BES_PARAMETERS: |
860 |
if (name not in self.op.beparams and |
861 |
einfo.has_option(constants.INISECT_INS, name)): |
862 |
self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
|
863 |
|
864 |
if einfo.has_section(constants.INISECT_OSP):
|
865 |
# use the parameters, without overriding
|
866 |
for name, value in einfo.items(constants.INISECT_OSP): |
867 |
if name not in self.op.osparams: |
868 |
self.op.osparams[name] = value
|
869 |
|
870 |
if einfo.has_section(constants.INISECT_OSP_PRIVATE):
|
871 |
# use the parameters, without overriding
|
872 |
for name, value in einfo.items(constants.INISECT_OSP_PRIVATE): |
873 |
if name not in self.op.osparams_private: |
874 |
self.op.osparams_private[name] = serializer.Private(value, descr=name)
|
875 |
|
876 |
def _RevertToDefaults(self, cluster): |
877 |
"""Revert the instance parameters to the default values.
|
878 |
|
879 |
"""
|
880 |
# hvparams
|
881 |
hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {}) |
882 |
for name in self.op.hvparams.keys(): |
883 |
if name in hv_defs and hv_defs[name] == self.op.hvparams[name]: |
884 |
del self.op.hvparams[name] |
885 |
# beparams
|
886 |
be_defs = cluster.SimpleFillBE({}) |
887 |
for name in self.op.beparams.keys(): |
888 |
if name in be_defs and be_defs[name] == self.op.beparams[name]: |
889 |
del self.op.beparams[name] |
890 |
# nic params
|
891 |
nic_defs = cluster.SimpleFillNIC({}) |
892 |
for nic in self.op.nics: |
893 |
for name in constants.NICS_PARAMETERS: |
894 |
if name in nic and name in nic_defs and nic[name] == nic_defs[name]: |
895 |
del nic[name]
|
896 |
# osparams
|
897 |
os_defs = cluster.SimpleFillOS(self.op.os_type, {})
|
898 |
for name in self.op.osparams.keys(): |
899 |
if name in os_defs and os_defs[name] == self.op.osparams[name]: |
900 |
del self.op.osparams[name] |
901 |
|
902 |
os_defs_ = cluster.SimpleFillOS(self.op.os_type, {},
|
903 |
os_params_private={}) |
904 |
for name in self.op.osparams_private.keys(): |
905 |
if name in os_defs_ and os_defs_[name] == self.op.osparams_private[name]: |
906 |
del self.op.osparams_private[name] |
907 |
|
908 |
def _CalculateFileStorageDir(self): |
909 |
"""Calculate final instance file storage dir.
|
910 |
|
911 |
"""
|
912 |
# file storage dir calculation/check
|
913 |
self.instance_file_storage_dir = None |
914 |
if self.op.disk_template in constants.DTS_FILEBASED: |
915 |
# build the full file storage dir path
|
916 |
joinargs = [] |
917 |
|
918 |
cfg_storage = None
|
919 |
if self.op.disk_template == constants.DT_FILE: |
920 |
cfg_storage = self.cfg.GetFileStorageDir()
|
921 |
elif self.op.disk_template == constants.DT_SHARED_FILE: |
922 |
cfg_storage = self.cfg.GetSharedFileStorageDir()
|
923 |
elif self.op.disk_template == constants.DT_GLUSTER: |
924 |
cfg_storage = self.cfg.GetGlusterStorageDir()
|
925 |
|
926 |
if not cfg_storage: |
927 |
raise errors.OpPrereqError(
|
928 |
"Cluster file storage dir for {tpl} storage type not defined".format(
|
929 |
tpl=repr(self.op.disk_template) |
930 |
), |
931 |
errors.ECODE_STATE |
932 |
) |
933 |
|
934 |
joinargs.append(cfg_storage) |
935 |
|
936 |
if self.op.file_storage_dir is not None: |
937 |
joinargs.append(self.op.file_storage_dir)
|
938 |
|
939 |
if self.op.disk_template != constants.DT_GLUSTER: |
940 |
joinargs.append(self.op.instance_name)
|
941 |
|
942 |
if len(joinargs) > 1: |
943 |
# pylint: disable=W0142
|
944 |
self.instance_file_storage_dir = utils.PathJoin(*joinargs)
|
945 |
else:
|
946 |
self.instance_file_storage_dir = joinargs[0] |
947 |
|
948 |
def CheckPrereq(self): # pylint: disable=R0914 |
949 |
"""Check prerequisites.
|
950 |
|
951 |
"""
|
952 |
# Check that the optimistically acquired groups are correct wrt the
|
953 |
# acquired nodes
|
954 |
owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP)) |
955 |
owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE)) |
956 |
cur_groups = list(self.cfg.GetNodeGroupsFromNodes(owned_nodes)) |
957 |
if not owned_groups.issuperset(cur_groups): |
958 |
raise errors.OpPrereqError("New instance %s's node groups changed since" |
959 |
" locks were acquired, current groups are"
|
960 |
" are '%s', owning groups '%s'; retry the"
|
961 |
" operation" %
|
962 |
(self.op.instance_name,
|
963 |
utils.CommaJoin(cur_groups), |
964 |
utils.CommaJoin(owned_groups)), |
965 |
errors.ECODE_STATE) |
966 |
|
967 |
self._CalculateFileStorageDir()
|
968 |
|
969 |
if self.op.mode == constants.INSTANCE_IMPORT: |
970 |
export_info = self._ReadExportInfo()
|
971 |
self._ReadExportParams(export_info)
|
972 |
self._old_instance_name = export_info.get(constants.INISECT_INS, "name") |
973 |
else:
|
974 |
self._old_instance_name = None |
975 |
|
976 |
if (not self.cfg.GetVGName() and |
977 |
self.op.disk_template not in constants.DTS_NOT_LVM): |
978 |
raise errors.OpPrereqError("Cluster does not support lvm-based" |
979 |
" instances", errors.ECODE_STATE)
|
980 |
|
981 |
if (self.op.hypervisor is None or |
982 |
self.op.hypervisor == constants.VALUE_AUTO):
|
983 |
self.op.hypervisor = self.cfg.GetHypervisorType() |
984 |
|
985 |
cluster = self.cfg.GetClusterInfo()
|
986 |
enabled_hvs = cluster.enabled_hypervisors |
987 |
if self.op.hypervisor not in enabled_hvs: |
988 |
raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the" |
989 |
" cluster (%s)" %
|
990 |
(self.op.hypervisor, ",".join(enabled_hvs)), |
991 |
errors.ECODE_STATE) |
992 |
|
993 |
# Check tag validity
|
994 |
for tag in self.op.tags: |
995 |
objects.TaggableObject.ValidateTag(tag) |
996 |
|
997 |
# check hypervisor parameter syntax (locally)
|
998 |
utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
|
999 |
filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, |
1000 |
self.op.hvparams)
|
1001 |
hv_type = hypervisor.GetHypervisorClass(self.op.hypervisor)
|
1002 |
hv_type.CheckParameterSyntax(filled_hvp) |
1003 |
self.hv_full = filled_hvp
|
1004 |
# check that we don't specify global parameters on an instance
|
1005 |
CheckParamsNotGlobal(self.op.hvparams, constants.HVC_GLOBALS, "hypervisor", |
1006 |
"instance", "cluster") |
1007 |
|
1008 |
# fill and remember the beparams dict
|
1009 |
self.be_full = _ComputeFullBeParams(self.op, cluster) |
1010 |
|
1011 |
# build os parameters
|
1012 |
if self.op.osparams_private is None: |
1013 |
self.op.osparams_private = serializer.PrivateDict()
|
1014 |
if self.op.osparams_secret is None: |
1015 |
self.op.osparams_secret = serializer.PrivateDict()
|
1016 |
|
1017 |
self.os_full = cluster.SimpleFillOS(
|
1018 |
self.op.os_type,
|
1019 |
self.op.osparams,
|
1020 |
os_params_private=self.op.osparams_private,
|
1021 |
os_params_secret=self.op.osparams_secret
|
1022 |
) |
1023 |
|
1024 |
# now that hvp/bep are in final format, let's reset to defaults,
|
1025 |
# if told to do so
|
1026 |
if self.op.identify_defaults: |
1027 |
self._RevertToDefaults(cluster)
|
1028 |
|
1029 |
# NIC buildup
|
1030 |
self.nics = _ComputeNics(self.op, cluster, self.check_ip, self.cfg, |
1031 |
self.proc.GetECId())
|
1032 |
|
1033 |
# disk checks/pre-build
|
1034 |
default_vg = self.cfg.GetVGName()
|
1035 |
self.disks = ComputeDisks(self.op, default_vg) |
1036 |
|
1037 |
if self.op.mode == constants.INSTANCE_IMPORT: |
1038 |
disk_images = [] |
1039 |
for idx in range(len(self.disks)): |
1040 |
option = "disk%d_dump" % idx
|
1041 |
if export_info.has_option(constants.INISECT_INS, option):
|
1042 |
# FIXME: are the old os-es, disk sizes, etc. useful?
|
1043 |
export_name = export_info.get(constants.INISECT_INS, option) |
1044 |
image = utils.PathJoin(self.op.src_path, export_name)
|
1045 |
disk_images.append(image) |
1046 |
else:
|
1047 |
disk_images.append(False)
|
1048 |
|
1049 |
self.src_images = disk_images
|
1050 |
|
1051 |
if self.op.instance_name == self._old_instance_name: |
1052 |
for idx, nic in enumerate(self.nics): |
1053 |
if nic.mac == constants.VALUE_AUTO:
|
1054 |
nic_mac_ini = "nic%d_mac" % idx
|
1055 |
nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini) |
1056 |
|
1057 |
# ENDIF: self.op.mode == constants.INSTANCE_IMPORT
|
1058 |
|
1059 |
# ip ping checks (we use the same ip that was resolved in ExpandNames)
|
1060 |
if self.op.ip_check: |
1061 |
if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT): |
1062 |
raise errors.OpPrereqError("IP %s of instance %s already in use" % |
1063 |
(self.check_ip, self.op.instance_name), |
1064 |
errors.ECODE_NOTUNIQUE) |
1065 |
|
1066 |
#### mac address generation
|
1067 |
# By generating here the mac address both the allocator and the hooks get
|
1068 |
# the real final mac address rather than the 'auto' or 'generate' value.
|
1069 |
# There is a race condition between the generation and the instance object
|
1070 |
# creation, which means that we know the mac is valid now, but we're not
|
1071 |
# sure it will be when we actually add the instance. If things go bad
|
1072 |
# adding the instance will abort because of a duplicate mac, and the
|
1073 |
# creation job will fail.
|
1074 |
for nic in self.nics: |
1075 |
if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE): |
1076 |
nic.mac = self.cfg.GenerateMAC(nic.network, self.proc.GetECId()) |
1077 |
|
1078 |
#### allocator run
|
1079 |
|
1080 |
if self.op.iallocator is not None: |
1081 |
self._RunAllocator()
|
1082 |
|
1083 |
# Release all unneeded node locks
|
1084 |
keep_locks = filter(None, [self.op.pnode_uuid, self.op.snode_uuid, |
1085 |
self.op.src_node_uuid])
|
1086 |
ReleaseLocks(self, locking.LEVEL_NODE, keep=keep_locks)
|
1087 |
ReleaseLocks(self, locking.LEVEL_NODE_RES, keep=keep_locks)
|
1088 |
ReleaseLocks(self, locking.LEVEL_NODE_ALLOC)
|
1089 |
# Release all unneeded group locks
|
1090 |
ReleaseLocks(self, locking.LEVEL_NODEGROUP,
|
1091 |
keep=self.cfg.GetNodeGroupsFromNodes(keep_locks))
|
1092 |
|
1093 |
assert (self.owned_locks(locking.LEVEL_NODE) == |
1094 |
self.owned_locks(locking.LEVEL_NODE_RES)), \
|
1095 |
"Node locks differ from node resource locks"
|
1096 |
|
1097 |
#### node related checks
|
1098 |
|
1099 |
# check primary node
|
1100 |
self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode_uuid) |
1101 |
assert self.pnode is not None, \ |
1102 |
"Cannot retrieve locked node %s" % self.op.pnode_uuid |
1103 |
if pnode.offline:
|
1104 |
raise errors.OpPrereqError("Cannot use offline primary node '%s'" % |
1105 |
pnode.name, errors.ECODE_STATE) |
1106 |
if pnode.drained:
|
1107 |
raise errors.OpPrereqError("Cannot use drained primary node '%s'" % |
1108 |
pnode.name, errors.ECODE_STATE) |
1109 |
if not pnode.vm_capable: |
1110 |
raise errors.OpPrereqError("Cannot use non-vm_capable primary node" |
1111 |
" '%s'" % pnode.name, errors.ECODE_STATE)
|
1112 |
|
1113 |
self.secondaries = []
|
1114 |
|
1115 |
# Fill in any IPs from IP pools. This must happen here, because we need to
|
1116 |
# know the nic's primary node, as specified by the iallocator
|
1117 |
for idx, nic in enumerate(self.nics): |
1118 |
net_uuid = nic.network |
1119 |
if net_uuid is not None: |
1120 |
nobj = self.cfg.GetNetwork(net_uuid)
|
1121 |
netparams = self.cfg.GetGroupNetParams(net_uuid, self.pnode.uuid) |
1122 |
if netparams is None: |
1123 |
raise errors.OpPrereqError("No netparams found for network" |
1124 |
" %s. Probably not connected to"
|
1125 |
" node's %s nodegroup" %
|
1126 |
(nobj.name, self.pnode.name),
|
1127 |
errors.ECODE_INVAL) |
1128 |
self.LogInfo("NIC/%d inherits netparams %s" % |
1129 |
(idx, netparams.values())) |
1130 |
nic.nicparams = dict(netparams)
|
1131 |
if nic.ip is not None: |
1132 |
if nic.ip.lower() == constants.NIC_IP_POOL:
|
1133 |
try:
|
1134 |
nic.ip = self.cfg.GenerateIp(net_uuid, self.proc.GetECId()) |
1135 |
except errors.ReservationError:
|
1136 |
raise errors.OpPrereqError("Unable to get a free IP for NIC %d" |
1137 |
" from the address pool" % idx,
|
1138 |
errors.ECODE_STATE) |
1139 |
self.LogInfo("Chose IP %s from network %s", nic.ip, nobj.name) |
1140 |
else:
|
1141 |
try:
|
1142 |
self.cfg.ReserveIp(net_uuid, nic.ip, self.proc.GetECId(), |
1143 |
check=self.op.conflicts_check)
|
1144 |
except errors.ReservationError:
|
1145 |
raise errors.OpPrereqError("IP address %s already in use" |
1146 |
" or does not belong to network %s" %
|
1147 |
(nic.ip, nobj.name), |
1148 |
errors.ECODE_NOTUNIQUE) |
1149 |
|
1150 |
# net is None, ip None or given
|
1151 |
elif self.op.conflicts_check: |
1152 |
_CheckForConflictingIp(self, nic.ip, self.pnode.uuid) |
1153 |
|
1154 |
# mirror node verification
|
1155 |
if self.op.disk_template in constants.DTS_INT_MIRROR: |
1156 |
if self.op.snode_uuid == pnode.uuid: |
1157 |
raise errors.OpPrereqError("The secondary node cannot be the" |
1158 |
" primary node", errors.ECODE_INVAL)
|
1159 |
CheckNodeOnline(self, self.op.snode_uuid) |
1160 |
CheckNodeNotDrained(self, self.op.snode_uuid) |
1161 |
CheckNodeVmCapable(self, self.op.snode_uuid) |
1162 |
self.secondaries.append(self.op.snode_uuid) |
1163 |
|
1164 |
snode = self.cfg.GetNodeInfo(self.op.snode_uuid) |
1165 |
if pnode.group != snode.group:
|
1166 |
self.LogWarning("The primary and secondary nodes are in two" |
1167 |
" different node groups; the disk parameters"
|
1168 |
" from the first disk's node group will be"
|
1169 |
" used")
|
1170 |
|
1171 |
nodes = [pnode] |
1172 |
if self.op.disk_template in constants.DTS_INT_MIRROR: |
1173 |
nodes.append(snode) |
1174 |
has_es = lambda n: IsExclusiveStorageEnabledNode(self.cfg, n) |
1175 |
excl_stor = compat.any(map(has_es, nodes))
|
1176 |
if excl_stor and not self.op.disk_template in constants.DTS_EXCL_STORAGE: |
1177 |
raise errors.OpPrereqError("Disk template %s not supported with" |
1178 |
" exclusive storage" % self.op.disk_template, |
1179 |
errors.ECODE_STATE) |
1180 |
for disk in self.disks: |
1181 |
CheckSpindlesExclusiveStorage(disk, excl_stor, True)
|
1182 |
|
1183 |
node_uuids = [pnode.uuid] + self.secondaries
|
1184 |
|
1185 |
if not self.adopt_disks: |
1186 |
if self.op.disk_template == constants.DT_RBD: |
1187 |
# _CheckRADOSFreeSpace() is just a placeholder.
|
1188 |
# Any function that checks prerequisites can be placed here.
|
1189 |
# Check if there is enough space on the RADOS cluster.
|
1190 |
CheckRADOSFreeSpace() |
1191 |
elif self.op.disk_template == constants.DT_EXT: |
1192 |
# FIXME: Function that checks prereqs if needed
|
1193 |
pass
|
1194 |
elif self.op.disk_template in constants.DTS_LVM: |
1195 |
# Check lv size requirements, if not adopting
|
1196 |
req_sizes = ComputeDiskSizePerVG(self.op.disk_template, self.disks) |
1197 |
CheckNodesFreeDiskPerVG(self, node_uuids, req_sizes)
|
1198 |
else:
|
1199 |
# FIXME: add checks for other, non-adopting, non-lvm disk templates
|
1200 |
pass
|
1201 |
|
1202 |
elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data |
1203 |
all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG], |
1204 |
disk[constants.IDISK_ADOPT]) |
1205 |
for disk in self.disks]) |
1206 |
if len(all_lvs) != len(self.disks): |
1207 |
raise errors.OpPrereqError("Duplicate volume names given for adoption", |
1208 |
errors.ECODE_INVAL) |
1209 |
for lv_name in all_lvs: |
1210 |
try:
|
1211 |
# FIXME: lv_name here is "vg/lv" need to ensure that other calls
|
1212 |
# to ReserveLV uses the same syntax
|
1213 |
self.cfg.ReserveLV(lv_name, self.proc.GetECId()) |
1214 |
except errors.ReservationError:
|
1215 |
raise errors.OpPrereqError("LV named %s used by another instance" % |
1216 |
lv_name, errors.ECODE_NOTUNIQUE) |
1217 |
|
1218 |
vg_names = self.rpc.call_vg_list([pnode.uuid])[pnode.uuid]
|
1219 |
vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
|
1220 |
|
1221 |
node_lvs = self.rpc.call_lv_list([pnode.uuid],
|
1222 |
vg_names.payload.keys())[pnode.uuid] |
1223 |
node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
|
1224 |
node_lvs = node_lvs.payload |
1225 |
|
1226 |
delta = all_lvs.difference(node_lvs.keys()) |
1227 |
if delta:
|
1228 |
raise errors.OpPrereqError("Missing logical volume(s): %s" % |
1229 |
utils.CommaJoin(delta), |
1230 |
errors.ECODE_INVAL) |
1231 |
online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]] |
1232 |
if online_lvs:
|
1233 |
raise errors.OpPrereqError("Online logical volumes found, cannot" |
1234 |
" adopt: %s" % utils.CommaJoin(online_lvs),
|
1235 |
errors.ECODE_STATE) |
1236 |
# update the size of disk based on what is found
|
1237 |
for dsk in self.disks: |
1238 |
dsk[constants.IDISK_SIZE] = \ |
1239 |
int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG], |
1240 |
dsk[constants.IDISK_ADOPT])][0]))
|
1241 |
|
1242 |
elif self.op.disk_template == constants.DT_BLOCK: |
1243 |
# Normalize and de-duplicate device paths
|
1244 |
all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
|
1245 |
for disk in self.disks]) |
1246 |
if len(all_disks) != len(self.disks): |
1247 |
raise errors.OpPrereqError("Duplicate disk names given for adoption", |
1248 |
errors.ECODE_INVAL) |
1249 |
baddisks = [d for d in all_disks |
1250 |
if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)] |
1251 |
if baddisks:
|
1252 |
raise errors.OpPrereqError("Device node(s) %s lie outside %s and" |
1253 |
" cannot be adopted" %
|
1254 |
(utils.CommaJoin(baddisks), |
1255 |
constants.ADOPTABLE_BLOCKDEV_ROOT), |
1256 |
errors.ECODE_INVAL) |
1257 |
|
1258 |
node_disks = self.rpc.call_bdev_sizes([pnode.uuid],
|
1259 |
list(all_disks))[pnode.uuid]
|
1260 |
node_disks.Raise("Cannot get block device information from node %s" %
|
1261 |
pnode.name) |
1262 |
node_disks = node_disks.payload |
1263 |
delta = all_disks.difference(node_disks.keys()) |
1264 |
if delta:
|
1265 |
raise errors.OpPrereqError("Missing block device(s): %s" % |
1266 |
utils.CommaJoin(delta), |
1267 |
errors.ECODE_INVAL) |
1268 |
for dsk in self.disks: |
1269 |
dsk[constants.IDISK_SIZE] = \ |
1270 |
int(float(node_disks[dsk[constants.IDISK_ADOPT]])) |
1271 |
|
1272 |
# Check disk access param to be compatible with specified hypervisor
|
1273 |
node_info = self.cfg.GetNodeInfo(self.op.pnode_uuid) |
1274 |
node_group = self.cfg.GetNodeGroup(node_info.group)
|
1275 |
disk_params = self.cfg.GetGroupDiskParams(node_group)
|
1276 |
access_type = disk_params[self.op.disk_template].get(
|
1277 |
constants.RBD_ACCESS, constants.DISK_KERNELSPACE |
1278 |
) |
1279 |
|
1280 |
if not IsValidDiskAccessModeCombination(self.op.hypervisor, |
1281 |
self.op.disk_template,
|
1282 |
access_type): |
1283 |
raise errors.OpPrereqError("Selected hypervisor (%s) cannot be" |
1284 |
" used with %s disk access param" %
|
1285 |
(self.op.hypervisor, access_type),
|
1286 |
errors.ECODE_STATE) |
1287 |
|
1288 |
# Verify instance specs
|
1289 |
spindle_use = self.be_full.get(constants.BE_SPINDLE_USE, None) |
1290 |
ispec = { |
1291 |
constants.ISPEC_MEM_SIZE: self.be_full.get(constants.BE_MAXMEM, None), |
1292 |
constants.ISPEC_CPU_COUNT: self.be_full.get(constants.BE_VCPUS, None), |
1293 |
constants.ISPEC_DISK_COUNT: len(self.disks), |
1294 |
constants.ISPEC_DISK_SIZE: [disk[constants.IDISK_SIZE] |
1295 |
for disk in self.disks], |
1296 |
constants.ISPEC_NIC_COUNT: len(self.nics), |
1297 |
constants.ISPEC_SPINDLE_USE: spindle_use, |
1298 |
} |
1299 |
|
1300 |
group_info = self.cfg.GetNodeGroup(pnode.group)
|
1301 |
ipolicy = ganeti.masterd.instance.CalculateGroupIPolicy(cluster, group_info) |
1302 |
res = _ComputeIPolicyInstanceSpecViolation(ipolicy, ispec, |
1303 |
self.op.disk_template)
|
1304 |
if not self.op.ignore_ipolicy and res: |
1305 |
msg = ("Instance allocation to group %s (%s) violates policy: %s" %
|
1306 |
(pnode.group, group_info.name, utils.CommaJoin(res))) |
1307 |
raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
|
1308 |
|
1309 |
CheckHVParams(self, node_uuids, self.op.hypervisor, self.op.hvparams) |
1310 |
|
1311 |
CheckNodeHasOS(self, pnode.uuid, self.op.os_type, self.op.force_variant) |
1312 |
# check OS parameters (remotely)
|
1313 |
CheckOSParams(self, True, node_uuids, self.op.os_type, self.os_full) |
1314 |
|
1315 |
CheckNicsBridgesExist(self, self.nics, self.pnode.uuid) |
1316 |
|
1317 |
#TODO: _CheckExtParams (remotely)
|
1318 |
# Check parameters for extstorage
|
1319 |
|
1320 |
# memory check on primary node
|
1321 |
#TODO(dynmem): use MINMEM for checking
|
1322 |
if self.op.start: |
1323 |
hvfull = objects.FillDict(cluster.hvparams.get(self.op.hypervisor, {}),
|
1324 |
self.op.hvparams)
|
1325 |
CheckNodeFreeMemory(self, self.pnode.uuid, |
1326 |
"creating instance %s" % self.op.instance_name, |
1327 |
self.be_full[constants.BE_MAXMEM],
|
1328 |
self.op.hypervisor, hvfull)
|
1329 |
|
1330 |
self.dry_run_result = list(node_uuids) |
1331 |
|
1332 |
def Exec(self, feedback_fn): |
1333 |
"""Create and add the instance to the cluster.
|
1334 |
|
1335 |
"""
|
1336 |
assert not (self.owned_locks(locking.LEVEL_NODE_RES) - |
1337 |
self.owned_locks(locking.LEVEL_NODE)), \
|
1338 |
"Node locks differ from node resource locks"
|
1339 |
assert not self.glm.is_owned(locking.LEVEL_NODE_ALLOC) |
1340 |
|
1341 |
ht_kind = self.op.hypervisor
|
1342 |
if ht_kind in constants.HTS_REQ_PORT: |
1343 |
network_port = self.cfg.AllocatePort()
|
1344 |
else:
|
1345 |
network_port = None
|
1346 |
|
1347 |
instance_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId()) |
1348 |
|
1349 |
# This is ugly but we got a chicken-egg problem here
|
1350 |
# We can only take the group disk parameters, as the instance
|
1351 |
# has no disks yet (we are generating them right here).
|
1352 |
nodegroup = self.cfg.GetNodeGroup(self.pnode.group) |
1353 |
disks = GenerateDiskTemplate(self,
|
1354 |
self.op.disk_template,
|
1355 |
instance_uuid, self.pnode.uuid,
|
1356 |
self.secondaries,
|
1357 |
self.disks,
|
1358 |
self.instance_file_storage_dir,
|
1359 |
self.op.file_driver,
|
1360 |
0,
|
1361 |
feedback_fn, |
1362 |
self.cfg.GetGroupDiskParams(nodegroup))
|
1363 |
|
1364 |
iobj = objects.Instance(name=self.op.instance_name,
|
1365 |
uuid=instance_uuid, |
1366 |
os=self.op.os_type,
|
1367 |
primary_node=self.pnode.uuid,
|
1368 |
nics=self.nics, disks=[],
|
1369 |
disk_template=self.op.disk_template,
|
1370 |
disks_active=False,
|
1371 |
admin_state=constants.ADMINST_DOWN, |
1372 |
network_port=network_port, |
1373 |
beparams=self.op.beparams,
|
1374 |
hvparams=self.op.hvparams,
|
1375 |
hypervisor=self.op.hypervisor,
|
1376 |
osparams=self.op.osparams,
|
1377 |
osparams_private=self.op.osparams_private,
|
1378 |
) |
1379 |
|
1380 |
if self.op.tags: |
1381 |
for tag in self.op.tags: |
1382 |
iobj.AddTag(tag) |
1383 |
|
1384 |
if self.adopt_disks: |
1385 |
if self.op.disk_template == constants.DT_PLAIN: |
1386 |
# rename LVs to the newly-generated names; we need to construct
|
1387 |
# 'fake' LV disks with the old data, plus the new unique_id
|
1388 |
tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks] |
1389 |
rename_to = [] |
1390 |
for t_dsk, a_dsk in zip(tmp_disks, self.disks): |
1391 |
rename_to.append(t_dsk.logical_id) |
1392 |
t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
|
1393 |
result = self.rpc.call_blockdev_rename(self.pnode.uuid, |
1394 |
zip(tmp_disks, rename_to))
|
1395 |
result.Raise("Failed to rename adoped LVs")
|
1396 |
else:
|
1397 |
feedback_fn("* creating instance disks...")
|
1398 |
try:
|
1399 |
CreateDisks(self, iobj, disks=disks)
|
1400 |
except errors.OpExecError:
|
1401 |
self.LogWarning("Device creation failed") |
1402 |
self.cfg.ReleaseDRBDMinors(self.op.instance_name) |
1403 |
raise
|
1404 |
|
1405 |
feedback_fn("adding instance %s to cluster config" % self.op.instance_name) |
1406 |
self.cfg.AddInstance(iobj, self.proc.GetECId()) |
1407 |
feedback_fn("adding disks to cluster config")
|
1408 |
for disk in disks: |
1409 |
self.cfg.AddInstDisk(iobj, disk)
|
1410 |
|
1411 |
# Declare that we don't want to remove the instance lock anymore, as we've
|
1412 |
# added the instance to the config
|
1413 |
del self.remove_locks[locking.LEVEL_INSTANCE] |
1414 |
|
1415 |
if self.op.mode == constants.INSTANCE_IMPORT: |
1416 |
# Release unused nodes
|
1417 |
ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node_uuid]) |
1418 |
else:
|
1419 |
# Release all nodes
|
1420 |
ReleaseLocks(self, locking.LEVEL_NODE)
|
1421 |
|
1422 |
disk_abort = False
|
1423 |
if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks: |
1424 |
feedback_fn("* wiping instance disks...")
|
1425 |
try:
|
1426 |
WipeDisks(self, iobj)
|
1427 |
except errors.OpExecError, err:
|
1428 |
logging.exception("Wiping disks failed")
|
1429 |
self.LogWarning("Wiping instance disks failed (%s)", err) |
1430 |
disk_abort = True
|
1431 |
|
1432 |
if disk_abort:
|
1433 |
# Something is already wrong with the disks, don't do anything else
|
1434 |
pass
|
1435 |
elif self.op.wait_for_sync: |
1436 |
disk_abort = not WaitForSync(self, iobj) |
1437 |
elif iobj.disk_template in constants.DTS_INT_MIRROR: |
1438 |
# make sure the disks are not degraded (still sync-ing is ok)
|
1439 |
feedback_fn("* checking mirrors status")
|
1440 |
disk_abort = not WaitForSync(self, iobj, oneshot=True) |
1441 |
else:
|
1442 |
disk_abort = False
|
1443 |
|
1444 |
if disk_abort:
|
1445 |
RemoveDisks(self, iobj)
|
1446 |
# Copy the 'iboj.disks' list, because it changes inside 'RemoveInstDisk'
|
1447 |
for disk_uuid in list(iobj.disks): |
1448 |
self.cfg.RemoveInstDisk(disk_uuid)
|
1449 |
self.cfg.RemoveInstance(iobj.uuid)
|
1450 |
# Make sure the instance lock gets removed
|
1451 |
self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
|
1452 |
raise errors.OpExecError("There are some degraded disks for" |
1453 |
" this instance")
|
1454 |
|
1455 |
# instance disks are now active
|
1456 |
iobj.disks_active = True
|
1457 |
|
1458 |
# Release all node resource locks
|
1459 |
ReleaseLocks(self, locking.LEVEL_NODE_RES)
|
1460 |
|
1461 |
if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks: |
1462 |
disks = self.cfg.GetInstanceDisks(iobj)
|
1463 |
if self.op.mode == constants.INSTANCE_CREATE: |
1464 |
if not self.op.no_install: |
1465 |
pause_sync = (iobj.disk_template in constants.DTS_INT_MIRROR and |
1466 |
not self.op.wait_for_sync) |
1467 |
if pause_sync:
|
1468 |
feedback_fn("* pausing disk sync to install instance OS")
|
1469 |
result = self.rpc.call_blockdev_pause_resume_sync(self.pnode.uuid, |
1470 |
(disks, iobj), |
1471 |
True)
|
1472 |
for idx, success in enumerate(result.payload): |
1473 |
if not success: |
1474 |
logging.warn("pause-sync of instance %s for disk %d failed",
|
1475 |
self.op.instance_name, idx)
|
1476 |
|
1477 |
feedback_fn("* running the instance OS create scripts...")
|
1478 |
# FIXME: pass debug option from opcode to backend
|
1479 |
os_add_result = \ |
1480 |
self.rpc.call_instance_os_add(self.pnode.uuid, |
1481 |
(iobj, self.op.osparams_secret),
|
1482 |
False,
|
1483 |
self.op.debug_level)
|
1484 |
if pause_sync:
|
1485 |
feedback_fn("* resuming disk sync")
|
1486 |
result = self.rpc.call_blockdev_pause_resume_sync(self.pnode.uuid, |
1487 |
(disks, iobj), |
1488 |
False)
|
1489 |
for idx, success in enumerate(result.payload): |
1490 |
if not success: |
1491 |
logging.warn("resume-sync of instance %s for disk %d failed",
|
1492 |
self.op.instance_name, idx)
|
1493 |
|
1494 |
os_add_result.Raise("Could not add os for instance %s"
|
1495 |
" on node %s" % (self.op.instance_name, |
1496 |
self.pnode.name))
|
1497 |
|
1498 |
else:
|
1499 |
if self.op.mode == constants.INSTANCE_IMPORT: |
1500 |
feedback_fn("* running the instance OS import scripts...")
|
1501 |
|
1502 |
transfers = [] |
1503 |
|
1504 |
for idx, image in enumerate(self.src_images): |
1505 |
if not image: |
1506 |
continue
|
1507 |
|
1508 |
# FIXME: pass debug option from opcode to backend
|
1509 |
dt = masterd.instance.DiskTransfer("disk/%s" % idx,
|
1510 |
constants.IEIO_FILE, (image, ), |
1511 |
constants.IEIO_SCRIPT, |
1512 |
((disks[idx], iobj), idx), |
1513 |
None)
|
1514 |
transfers.append(dt) |
1515 |
|
1516 |
import_result = \ |
1517 |
masterd.instance.TransferInstanceData(self, feedback_fn,
|
1518 |
self.op.src_node_uuid,
|
1519 |
self.pnode.uuid,
|
1520 |
self.pnode.secondary_ip,
|
1521 |
self.op.compress,
|
1522 |
iobj, transfers) |
1523 |
if not compat.all(import_result): |
1524 |
self.LogWarning("Some disks for instance %s on node %s were not" |
1525 |
" imported successfully" % (self.op.instance_name, |
1526 |
self.pnode.name))
|
1527 |
|
1528 |
rename_from = self._old_instance_name
|
1529 |
|
1530 |
elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT: |
1531 |
feedback_fn("* preparing remote import...")
|
1532 |
# The source cluster will stop the instance before attempting to make
|
1533 |
# a connection. In some cases stopping an instance can take a long
|
1534 |
# time, hence the shutdown timeout is added to the connection
|
1535 |
# timeout.
|
1536 |
connect_timeout = (constants.RIE_CONNECT_TIMEOUT + |
1537 |
self.op.source_shutdown_timeout)
|
1538 |
timeouts = masterd.instance.ImportExportTimeouts(connect_timeout) |
1539 |
|
1540 |
assert iobj.primary_node == self.pnode.uuid |
1541 |
disk_results = \ |
1542 |
masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode, |
1543 |
self.source_x509_ca,
|
1544 |
self._cds, self.op.compress, timeouts) |
1545 |
if not compat.all(disk_results): |
1546 |
# TODO: Should the instance still be started, even if some disks
|
1547 |
# failed to import (valid for local imports, too)?
|
1548 |
self.LogWarning("Some disks for instance %s on node %s were not" |
1549 |
" imported successfully" % (self.op.instance_name, |
1550 |
self.pnode.name))
|
1551 |
|
1552 |
rename_from = self.source_instance_name
|
1553 |
|
1554 |
else:
|
1555 |
# also checked in the prereq part
|
1556 |
raise errors.ProgrammerError("Unknown OS initialization mode '%s'" |
1557 |
% self.op.mode)
|
1558 |
|
1559 |
# Run rename script on newly imported instance
|
1560 |
assert iobj.name == self.op.instance_name |
1561 |
feedback_fn("Running rename script for %s" % self.op.instance_name) |
1562 |
result = self.rpc.call_instance_run_rename(self.pnode.uuid, iobj, |
1563 |
rename_from, |
1564 |
self.op.debug_level)
|
1565 |
result.Warn("Failed to run rename script for %s on node %s" %
|
1566 |
(self.op.instance_name, self.pnode.name), self.LogWarning) |
1567 |
|
1568 |
assert not self.owned_locks(locking.LEVEL_NODE_RES) |
1569 |
|
1570 |
if self.op.start: |
1571 |
iobj.admin_state = constants.ADMINST_UP |
1572 |
self.cfg.Update(iobj, feedback_fn)
|
1573 |
logging.info("Starting instance %s on node %s", self.op.instance_name, |
1574 |
self.pnode.name)
|
1575 |
feedback_fn("* starting instance...")
|
1576 |
result = self.rpc.call_instance_start(self.pnode.uuid, (iobj, None, None), |
1577 |
False, self.op.reason) |
1578 |
result.Raise("Could not start instance")
|
1579 |
|
1580 |
return self.cfg.GetNodeNames(list(self.cfg.GetInstanceNodes(iobj))) |
1581 |
|
1582 |
|
1583 |
class LUInstanceRename(LogicalUnit): |
1584 |
"""Rename an instance.
|
1585 |
|
1586 |
"""
|
1587 |
HPATH = "instance-rename"
|
1588 |
HTYPE = constants.HTYPE_INSTANCE |
1589 |
|
1590 |
def CheckArguments(self): |
1591 |
"""Check arguments.
|
1592 |
|
1593 |
"""
|
1594 |
if self.op.ip_check and not self.op.name_check: |
1595 |
# TODO: make the ip check more flexible and not depend on the name check
|
1596 |
raise errors.OpPrereqError("IP address check requires a name check", |
1597 |
errors.ECODE_INVAL) |
1598 |
|
1599 |
def BuildHooksEnv(self): |
1600 |
"""Build hooks env.
|
1601 |
|
1602 |
This runs on master, primary and secondary nodes of the instance.
|
1603 |
|
1604 |
"""
|
1605 |
env = BuildInstanceHookEnvByObject(self, self.instance) |
1606 |
env["INSTANCE_NEW_NAME"] = self.op.new_name |
1607 |
return env
|
1608 |
|
1609 |
def BuildHooksNodes(self): |
1610 |
"""Build hooks nodes.
|
1611 |
|
1612 |
"""
|
1613 |
nl = [self.cfg.GetMasterNode()] + \
|
1614 |
list(self.cfg.GetInstanceNodes(self.instance)) |
1615 |
return (nl, nl)
|
1616 |
|
1617 |
def CheckPrereq(self): |
1618 |
"""Check prerequisites.
|
1619 |
|
1620 |
This checks that the instance is in the cluster and is not running.
|
1621 |
|
1622 |
"""
|
1623 |
(self.op.instance_uuid, self.op.instance_name) = \ |
1624 |
ExpandInstanceUuidAndName(self.cfg, self.op.instance_uuid, |
1625 |
self.op.instance_name)
|
1626 |
instance = self.cfg.GetInstanceInfo(self.op.instance_uuid) |
1627 |
assert instance is not None |
1628 |
|
1629 |
# It should actually not happen that an instance is running with a disabled
|
1630 |
# disk template, but in case it does, the renaming of file-based instances
|
1631 |
# will fail horribly. Thus, we test it before.
|
1632 |
if (instance.disk_template in constants.DTS_FILEBASED and |
1633 |
self.op.new_name != instance.name):
|
1634 |
CheckDiskTemplateEnabled(self.cfg.GetClusterInfo(),
|
1635 |
instance.disk_template) |
1636 |
|
1637 |
CheckNodeOnline(self, instance.primary_node)
|
1638 |
CheckInstanceState(self, instance, INSTANCE_NOT_RUNNING,
|
1639 |
msg="cannot rename")
|
1640 |
self.instance = instance
|
1641 |
|
1642 |
new_name = self.op.new_name
|
1643 |
if self.op.name_check: |
1644 |
hostname = _CheckHostnameSane(self, new_name)
|
1645 |
new_name = self.op.new_name = hostname.name
|
1646 |
if (self.op.ip_check and |
1647 |
netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)): |
1648 |
raise errors.OpPrereqError("IP %s of instance %s already in use" % |
1649 |
(hostname.ip, new_name), |
1650 |
errors.ECODE_NOTUNIQUE) |
1651 |
|
1652 |
instance_names = [inst.name for
|
1653 |
inst in self.cfg.GetAllInstancesInfo().values()] |
1654 |
if new_name in instance_names and new_name != instance.name: |
1655 |
raise errors.OpPrereqError("Instance '%s' is already in the cluster" % |
1656 |
new_name, errors.ECODE_EXISTS) |
1657 |
|
1658 |
def Exec(self, feedback_fn): |
1659 |
"""Rename the instance.
|
1660 |
|
1661 |
"""
|
1662 |
old_name = self.instance.name
|
1663 |
|
1664 |
rename_file_storage = False
|
1665 |
if (self.instance.disk_template in (constants.DT_FILE, |
1666 |
constants.DT_SHARED_FILE) and
|
1667 |
self.op.new_name != self.instance.name): |
1668 |
disks = self.cfg.GetInstanceDisks(self.instance) |
1669 |
old_file_storage_dir = os.path.dirname(disks[0].logical_id[1]) |
1670 |
rename_file_storage = True
|
1671 |
|
1672 |
self.cfg.RenameInstance(self.instance.uuid, self.op.new_name) |
1673 |
# Change the instance lock. This is definitely safe while we hold the BGL.
|
1674 |
# Otherwise the new lock would have to be added in acquired mode.
|
1675 |
assert self.REQ_BGL |
1676 |
assert locking.BGL in self.owned_locks(locking.LEVEL_CLUSTER) |
1677 |
self.glm.remove(locking.LEVEL_INSTANCE, old_name)
|
1678 |
self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name) |
1679 |
|
1680 |
# re-read the instance from the configuration after rename
|
1681 |
renamed_inst = self.cfg.GetInstanceInfo(self.instance.uuid) |
1682 |
disks = self.cfg.GetInstanceDisks(renamed_inst)
|
1683 |
|
1684 |
if rename_file_storage:
|
1685 |
new_file_storage_dir = os.path.dirname(disks[0].logical_id[1]) |
1686 |
result = self.rpc.call_file_storage_dir_rename(renamed_inst.primary_node,
|
1687 |
old_file_storage_dir, |
1688 |
new_file_storage_dir) |
1689 |
result.Raise("Could not rename on node %s directory '%s' to '%s'"
|
1690 |
" (but the instance has been renamed in Ganeti)" %
|
1691 |
(self.cfg.GetNodeName(renamed_inst.primary_node),
|
1692 |
old_file_storage_dir, new_file_storage_dir)) |
1693 |
|
1694 |
StartInstanceDisks(self, renamed_inst, None) |
1695 |
# update info on disks
|
1696 |
info = GetInstanceInfoText(renamed_inst) |
1697 |
for (idx, disk) in enumerate(disks): |
1698 |
for node_uuid in self.cfg.GetInstanceNodes(renamed_inst): |
1699 |
result = self.rpc.call_blockdev_setinfo(node_uuid,
|
1700 |
(disk, renamed_inst), info) |
1701 |
result.Warn("Error setting info on node %s for disk %s" %
|
1702 |
(self.cfg.GetNodeName(node_uuid), idx), self.LogWarning) |
1703 |
try:
|
1704 |
result = self.rpc.call_instance_run_rename(renamed_inst.primary_node,
|
1705 |
renamed_inst, old_name, |
1706 |
self.op.debug_level)
|
1707 |
result.Warn("Could not run OS rename script for instance %s on node %s"
|
1708 |
" (but the instance has been renamed in Ganeti)" %
|
1709 |
(renamed_inst.name, |
1710 |
self.cfg.GetNodeName(renamed_inst.primary_node)),
|
1711 |
self.LogWarning)
|
1712 |
finally:
|
1713 |
ShutdownInstanceDisks(self, renamed_inst)
|
1714 |
|
1715 |
return renamed_inst.name
|
1716 |
|
1717 |
|
1718 |
class LUInstanceRemove(LogicalUnit): |
1719 |
"""Remove an instance.
|
1720 |
|
1721 |
"""
|
1722 |
HPATH = "instance-remove"
|
1723 |
HTYPE = constants.HTYPE_INSTANCE |
1724 |
REQ_BGL = False
|
1725 |
|
1726 |
def ExpandNames(self): |
1727 |
self._ExpandAndLockInstance()
|
1728 |
self.needed_locks[locking.LEVEL_NODE] = []
|
1729 |
self.needed_locks[locking.LEVEL_NODE_RES] = []
|
1730 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
|
1731 |
|
1732 |
def DeclareLocks(self, level): |
1733 |
if level == locking.LEVEL_NODE:
|
1734 |
self._LockInstancesNodes()
|
1735 |
elif level == locking.LEVEL_NODE_RES:
|
1736 |
# Copy node locks
|
1737 |
self.needed_locks[locking.LEVEL_NODE_RES] = \
|
1738 |
CopyLockList(self.needed_locks[locking.LEVEL_NODE])
|
1739 |
|
1740 |
def BuildHooksEnv(self): |
1741 |
"""Build hooks env.
|
1742 |
|
1743 |
This runs on master, primary and secondary nodes of the instance.
|
1744 |
|
1745 |
"""
|
1746 |
env = BuildInstanceHookEnvByObject(self, self.instance) |
1747 |
env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout |
1748 |
return env
|
1749 |
|
1750 |
def BuildHooksNodes(self): |
1751 |
"""Build hooks nodes.
|
1752 |
|
1753 |
"""
|
1754 |
nl = [self.cfg.GetMasterNode()]
|
1755 |
nl_post = list(self.cfg.GetInstanceNodes(self.instance)) + nl |
1756 |
return (nl, nl_post)
|
1757 |
|
1758 |
def CheckPrereq(self): |
1759 |
"""Check prerequisites.
|
1760 |
|
1761 |
This checks that the instance is in the cluster.
|
1762 |
|
1763 |
"""
|
1764 |
self.instance = self.cfg.GetInstanceInfo(self.op.instance_uuid) |
1765 |
assert self.instance is not None, \ |
1766 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
1767 |
|
1768 |
def Exec(self, feedback_fn): |
1769 |
"""Remove the instance.
|
1770 |
|
1771 |
"""
|
1772 |
logging.info("Shutting down instance %s on node %s", self.instance.name, |
1773 |
self.cfg.GetNodeName(self.instance.primary_node)) |
1774 |
|
1775 |
result = self.rpc.call_instance_shutdown(self.instance.primary_node, |
1776 |
self.instance,
|
1777 |
self.op.shutdown_timeout,
|
1778 |
self.op.reason)
|
1779 |
if self.op.ignore_failures: |
1780 |
result.Warn("Warning: can't shutdown instance", feedback_fn)
|
1781 |
else:
|
1782 |
result.Raise("Could not shutdown instance %s on node %s" %
|
1783 |
(self.instance.name,
|
1784 |
self.cfg.GetNodeName(self.instance.primary_node))) |
1785 |
|
1786 |
assert (self.owned_locks(locking.LEVEL_NODE) == |
1787 |
self.owned_locks(locking.LEVEL_NODE_RES))
|
1788 |
assert not (set(self.cfg.GetInstanceNodes(self.instance)) - |
1789 |
self.owned_locks(locking.LEVEL_NODE)), \
|
1790 |
"Not owning correct locks"
|
1791 |
|
1792 |
RemoveInstance(self, feedback_fn, self.instance, self.op.ignore_failures) |
1793 |
|
1794 |
|
1795 |
class LUInstanceMove(LogicalUnit): |
1796 |
"""Move an instance by data-copying.
|
1797 |
|
1798 |
"""
|
1799 |
HPATH = "instance-move"
|
1800 |
HTYPE = constants.HTYPE_INSTANCE |
1801 |
REQ_BGL = False
|
1802 |
|
1803 |
def ExpandNames(self): |
1804 |
self._ExpandAndLockInstance()
|
1805 |
(self.op.target_node_uuid, self.op.target_node) = \ |
1806 |
ExpandNodeUuidAndName(self.cfg, self.op.target_node_uuid, |
1807 |
self.op.target_node)
|
1808 |
self.needed_locks[locking.LEVEL_NODE] = [self.op.target_node_uuid] |
1809 |
self.needed_locks[locking.LEVEL_NODE_RES] = []
|
1810 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
|
1811 |
|
1812 |
def DeclareLocks(self, level): |
1813 |
if level == locking.LEVEL_NODE:
|
1814 |
self._LockInstancesNodes(primary_only=True) |
1815 |
elif level == locking.LEVEL_NODE_RES:
|
1816 |
# Copy node locks
|
1817 |
self.needed_locks[locking.LEVEL_NODE_RES] = \
|
1818 |
CopyLockList(self.needed_locks[locking.LEVEL_NODE])
|
1819 |
|
1820 |
def BuildHooksEnv(self): |
1821 |
"""Build hooks env.
|
1822 |
|
1823 |
This runs on master, primary and target nodes of the instance.
|
1824 |
|
1825 |
"""
|
1826 |
env = { |
1827 |
"TARGET_NODE": self.op.target_node, |
1828 |
"SHUTDOWN_TIMEOUT": self.op.shutdown_timeout, |
1829 |
} |
1830 |
env.update(BuildInstanceHookEnvByObject(self, self.instance)) |
1831 |
return env
|
1832 |
|
1833 |
def BuildHooksNodes(self): |
1834 |
"""Build hooks nodes.
|
1835 |
|
1836 |
"""
|
1837 |
nl = [ |
1838 |
self.cfg.GetMasterNode(),
|
1839 |
self.instance.primary_node,
|
1840 |
self.op.target_node_uuid,
|
1841 |
] |
1842 |
return (nl, nl)
|
1843 |
|
1844 |
def CheckPrereq(self): |
1845 |
"""Check prerequisites.
|
1846 |
|
1847 |
This checks that the instance is in the cluster.
|
1848 |
|
1849 |
"""
|
1850 |
self.instance = self.cfg.GetInstanceInfo(self.op.instance_uuid) |
1851 |
assert self.instance is not None, \ |
1852 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
1853 |
|
1854 |
if self.instance.disk_template not in constants.DTS_COPYABLE: |
1855 |
raise errors.OpPrereqError("Disk template %s not suitable for copying" % |
1856 |
self.instance.disk_template,
|
1857 |
errors.ECODE_STATE) |
1858 |
|
1859 |
target_node = self.cfg.GetNodeInfo(self.op.target_node_uuid) |
1860 |
assert target_node is not None, \ |
1861 |
"Cannot retrieve locked node %s" % self.op.target_node |
1862 |
|
1863 |
self.target_node_uuid = target_node.uuid
|
1864 |
if target_node.uuid == self.instance.primary_node: |
1865 |
raise errors.OpPrereqError("Instance %s is already on the node %s" % |
1866 |
(self.instance.name, target_node.name),
|
1867 |
errors.ECODE_STATE) |
1868 |
|
1869 |
cluster = self.cfg.GetClusterInfo()
|
1870 |
bep = cluster.FillBE(self.instance)
|
1871 |
|
1872 |
disks = self.cfg.GetInstanceDisks(self.instance) |
1873 |
for idx, dsk in enumerate(disks): |
1874 |
if dsk.dev_type not in (constants.DT_PLAIN, constants.DT_FILE, |
1875 |
constants.DT_SHARED_FILE, constants.DT_GLUSTER): |
1876 |
raise errors.OpPrereqError("Instance disk %d has a complex layout," |
1877 |
" cannot copy" % idx, errors.ECODE_STATE)
|
1878 |
|
1879 |
CheckNodeOnline(self, target_node.uuid)
|
1880 |
CheckNodeNotDrained(self, target_node.uuid)
|
1881 |
CheckNodeVmCapable(self, target_node.uuid)
|
1882 |
group_info = self.cfg.GetNodeGroup(target_node.group)
|
1883 |
ipolicy = ganeti.masterd.instance.CalculateGroupIPolicy(cluster, group_info) |
1884 |
CheckTargetNodeIPolicy(self, ipolicy, self.instance, target_node, self.cfg, |
1885 |
ignore=self.op.ignore_ipolicy)
|
1886 |
|
1887 |
if self.instance.admin_state == constants.ADMINST_UP: |
1888 |
# check memory requirements on the target node
|
1889 |
CheckNodeFreeMemory( |
1890 |
self, target_node.uuid, "failing over instance %s" % |
1891 |
self.instance.name, bep[constants.BE_MAXMEM],
|
1892 |
self.instance.hypervisor,
|
1893 |
cluster.hvparams[self.instance.hypervisor])
|
1894 |
else:
|
1895 |
self.LogInfo("Not checking memory on the secondary node as" |
1896 |
" instance will not be started")
|
1897 |
|
1898 |
# check bridge existance
|
1899 |
CheckInstanceBridgesExist(self, self.instance, node_uuid=target_node.uuid) |
1900 |
|
1901 |
def Exec(self, feedback_fn): |
1902 |
"""Move an instance.
|
1903 |
|
1904 |
The move is done by shutting it down on its present node, copying
|
1905 |
the data over (slow) and starting it on the new node.
|
1906 |
|
1907 |
"""
|
1908 |
source_node = self.cfg.GetNodeInfo(self.instance.primary_node) |
1909 |
target_node = self.cfg.GetNodeInfo(self.target_node_uuid) |
1910 |
|
1911 |
self.LogInfo("Shutting down instance %s on source node %s", |
1912 |
self.instance.name, source_node.name)
|
1913 |
|
1914 |
assert (self.owned_locks(locking.LEVEL_NODE) == |
1915 |
self.owned_locks(locking.LEVEL_NODE_RES))
|
1916 |
|
1917 |
result = self.rpc.call_instance_shutdown(source_node.uuid, self.instance, |
1918 |
self.op.shutdown_timeout,
|
1919 |
self.op.reason)
|
1920 |
if self.op.ignore_consistency: |
1921 |
result.Warn("Could not shutdown instance %s on node %s. Proceeding"
|
1922 |
" anyway. Please make sure node %s is down. Error details" %
|
1923 |
(self.instance.name, source_node.name, source_node.name),
|
1924 |
self.LogWarning)
|
1925 |
else:
|
1926 |
result.Raise("Could not shutdown instance %s on node %s" %
|
1927 |
(self.instance.name, source_node.name))
|
1928 |
|
1929 |
# create the target disks
|
1930 |
try:
|
1931 |
CreateDisks(self, self.instance, target_node_uuid=target_node.uuid) |
1932 |
except errors.OpExecError:
|
1933 |
self.LogWarning("Device creation failed") |
1934 |
self.cfg.ReleaseDRBDMinors(self.instance.uuid) |
1935 |
raise
|
1936 |
|
1937 |
errs = [] |
1938 |
transfers = [] |
1939 |
# activate, get path, create transfer jobs
|
1940 |
disks = self.cfg.GetInstanceDisks(self.instance) |
1941 |
for idx, disk in enumerate(disks): |
1942 |
# FIXME: pass debug option from opcode to backend
|
1943 |
dt = masterd.instance.DiskTransfer("disk/%s" % idx,
|
1944 |
constants.IEIO_RAW_DISK, |
1945 |
(disk, self.instance),
|
1946 |
constants.IEIO_RAW_DISK, |
1947 |
(disk, self.instance),
|
1948 |
None)
|
1949 |
transfers.append(dt) |
1950 |
self.cfg.Update(disk, feedback_fn)
|
1951 |
|
1952 |
import_result = \ |
1953 |
masterd.instance.TransferInstanceData(self, feedback_fn,
|
1954 |
source_node.uuid, |
1955 |
target_node.uuid, |
1956 |
target_node.secondary_ip, |
1957 |
self.op.compress,
|
1958 |
self.instance, transfers)
|
1959 |
if not compat.all(import_result): |
1960 |
errs.append("Failed to transfer instance data")
|
1961 |
|
1962 |
if errs:
|
1963 |
self.LogWarning("Some disks failed to copy, aborting") |
1964 |
try:
|
1965 |
RemoveDisks(self, self.instance, target_node_uuid=target_node.uuid) |
1966 |
finally:
|
1967 |
self.cfg.ReleaseDRBDMinors(self.instance.uuid) |
1968 |
raise errors.OpExecError("Errors during disk copy: %s" % |
1969 |
(",".join(errs),))
|
1970 |
|
1971 |
self.instance.primary_node = target_node.uuid
|
1972 |
self.cfg.Update(self.instance, feedback_fn) |
1973 |
|
1974 |
self.LogInfo("Removing the disks on the original node") |
1975 |
RemoveDisks(self, self.instance, target_node_uuid=source_node.uuid) |
1976 |
|
1977 |
# Only start the instance if it's marked as up
|
1978 |
if self.instance.admin_state == constants.ADMINST_UP: |
1979 |
self.LogInfo("Starting instance %s on node %s", |
1980 |
self.instance.name, target_node.name)
|
1981 |
|
1982 |
disks_ok, _ = AssembleInstanceDisks(self, self.instance, |
1983 |
ignore_secondaries=True)
|
1984 |
if not disks_ok: |
1985 |
ShutdownInstanceDisks(self, self.instance) |
1986 |
raise errors.OpExecError("Can't activate the instance's disks") |
1987 |
|
1988 |
result = self.rpc.call_instance_start(target_node.uuid,
|
1989 |
(self.instance, None, None), False, |
1990 |
self.op.reason)
|
1991 |
msg = result.fail_msg |
1992 |
if msg:
|
1993 |
ShutdownInstanceDisks(self, self.instance) |
1994 |
raise errors.OpExecError("Could not start instance %s on node %s: %s" % |
1995 |
(self.instance.name, target_node.name, msg))
|
1996 |
|
1997 |
|
1998 |
class LUInstanceMultiAlloc(NoHooksLU): |
1999 |
"""Allocates multiple instances at the same time.
|
2000 |
|
2001 |
"""
|
2002 |
REQ_BGL = False
|
2003 |
|
2004 |
def CheckArguments(self): |
2005 |
"""Check arguments.
|
2006 |
|
2007 |
"""
|
2008 |
nodes = [] |
2009 |
for inst in self.op.instances: |
2010 |
if inst.iallocator is not None: |
2011 |
raise errors.OpPrereqError("iallocator are not allowed to be set on" |
2012 |
" instance objects", errors.ECODE_INVAL)
|
2013 |
nodes.append(bool(inst.pnode))
|
2014 |
if inst.disk_template in constants.DTS_INT_MIRROR: |
2015 |
nodes.append(bool(inst.snode))
|
2016 |
|
2017 |
has_nodes = compat.any(nodes) |
2018 |
if compat.all(nodes) ^ has_nodes:
|
2019 |
raise errors.OpPrereqError("There are instance objects providing" |
2020 |
" pnode/snode while others do not",
|
2021 |
errors.ECODE_INVAL) |
2022 |
|
2023 |
if not has_nodes and self.op.iallocator is None: |
2024 |
default_iallocator = self.cfg.GetDefaultIAllocator()
|
2025 |
if default_iallocator:
|
2026 |
self.op.iallocator = default_iallocator
|
2027 |
else:
|
2028 |
raise errors.OpPrereqError("No iallocator or nodes on the instances" |
2029 |
" given and no cluster-wide default"
|
2030 |
" iallocator found; please specify either"
|
2031 |
" an iallocator or nodes on the instances"
|
2032 |
" or set a cluster-wide default iallocator",
|
2033 |
errors.ECODE_INVAL) |
2034 |
|
2035 |
_CheckOpportunisticLocking(self.op)
|
2036 |
|
2037 |
dups = utils.FindDuplicates([op.instance_name for op in self.op.instances]) |
2038 |
if dups:
|
2039 |
raise errors.OpPrereqError("There are duplicate instance names: %s" % |
2040 |
utils.CommaJoin(dups), errors.ECODE_INVAL) |
2041 |
|
2042 |
def ExpandNames(self): |
2043 |
"""Calculate the locks.
|
2044 |
|
2045 |
"""
|
2046 |
self.share_locks = ShareAll()
|
2047 |
self.needed_locks = {
|
2048 |
# iallocator will select nodes and even if no iallocator is used,
|
2049 |
# collisions with LUInstanceCreate should be avoided
|
2050 |
locking.LEVEL_NODE_ALLOC: locking.ALL_SET, |
2051 |
} |
2052 |
|
2053 |
if self.op.iallocator: |
2054 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
2055 |
self.needed_locks[locking.LEVEL_NODE_RES] = locking.ALL_SET
|
2056 |
|
2057 |
if self.op.opportunistic_locking: |
2058 |
self.opportunistic_locks[locking.LEVEL_NODE] = True |
2059 |
else:
|
2060 |
nodeslist = [] |
2061 |
for inst in self.op.instances: |
2062 |
(inst.pnode_uuid, inst.pnode) = \ |
2063 |
ExpandNodeUuidAndName(self.cfg, inst.pnode_uuid, inst.pnode)
|
2064 |
nodeslist.append(inst.pnode_uuid) |
2065 |
if inst.snode is not None: |
2066 |
(inst.snode_uuid, inst.snode) = \ |
2067 |
ExpandNodeUuidAndName(self.cfg, inst.snode_uuid, inst.snode)
|
2068 |
nodeslist.append(inst.snode_uuid) |
2069 |
|
2070 |
self.needed_locks[locking.LEVEL_NODE] = nodeslist
|
2071 |
# Lock resources of instance's primary and secondary nodes (copy to
|
2072 |
# prevent accidential modification)
|
2073 |
self.needed_locks[locking.LEVEL_NODE_RES] = list(nodeslist) |
2074 |
|
2075 |
def DeclareLocks(self, level): |
2076 |
if level == locking.LEVEL_NODE_RES and \ |
2077 |
self.opportunistic_locks[locking.LEVEL_NODE]:
|
2078 |
# Even when using opportunistic locking, we require the same set of
|
2079 |
# NODE_RES locks as we got NODE locks
|
2080 |
self.needed_locks[locking.LEVEL_NODE_RES] = \
|
2081 |
self.owned_locks(locking.LEVEL_NODE)
|
2082 |
|
2083 |
def CheckPrereq(self): |
2084 |
"""Check prerequisite.
|
2085 |
|
2086 |
"""
|
2087 |
if self.op.iallocator: |
2088 |
cluster = self.cfg.GetClusterInfo()
|
2089 |
default_vg = self.cfg.GetVGName()
|
2090 |
ec_id = self.proc.GetECId()
|
2091 |
|
2092 |
if self.op.opportunistic_locking: |
2093 |
# Only consider nodes for which a lock is held
|
2094 |
node_whitelist = self.cfg.GetNodeNames(
|
2095 |
list(self.owned_locks(locking.LEVEL_NODE))) |
2096 |
else:
|
2097 |
node_whitelist = None
|
2098 |
|
2099 |
insts = [_CreateInstanceAllocRequest(op, ComputeDisks(op, default_vg), |
2100 |
_ComputeNics(op, cluster, None,
|
2101 |
self.cfg, ec_id),
|
2102 |
_ComputeFullBeParams(op, cluster), |
2103 |
node_whitelist) |
2104 |
for op in self.op.instances] |
2105 |
|
2106 |
req = iallocator.IAReqMultiInstanceAlloc(instances=insts) |
2107 |
ial = iallocator.IAllocator(self.cfg, self.rpc, req) |
2108 |
|
2109 |
ial.Run(self.op.iallocator)
|
2110 |
|
2111 |
if not ial.success: |
2112 |
raise errors.OpPrereqError("Can't compute nodes using" |
2113 |
" iallocator '%s': %s" %
|
2114 |
(self.op.iallocator, ial.info),
|
2115 |
errors.ECODE_NORES) |
2116 |
|
2117 |
self.ia_result = ial.result
|
2118 |
|
2119 |
if self.op.dry_run: |
2120 |
self.dry_run_result = objects.FillDict(self._ConstructPartialResult(), { |
2121 |
constants.JOB_IDS_KEY: [], |
2122 |
}) |
2123 |
|
2124 |
def _ConstructPartialResult(self): |
2125 |
"""Contructs the partial result.
|
2126 |
|
2127 |
"""
|
2128 |
if self.op.iallocator: |
2129 |
(allocatable, failed_insts) = self.ia_result
|
2130 |
allocatable_insts = map(compat.fst, allocatable)
|
2131 |
else:
|
2132 |
allocatable_insts = [op.instance_name for op in self.op.instances] |
2133 |
failed_insts = [] |
2134 |
|
2135 |
return {
|
2136 |
constants.ALLOCATABLE_KEY: allocatable_insts, |
2137 |
constants.FAILED_KEY: failed_insts, |
2138 |
} |
2139 |
|
2140 |
def Exec(self, feedback_fn): |
2141 |
"""Executes the opcode.
|
2142 |
|
2143 |
"""
|
2144 |
jobs = [] |
2145 |
if self.op.iallocator: |
2146 |
op2inst = dict((op.instance_name, op) for op in self.op.instances) |
2147 |
(allocatable, failed) = self.ia_result
|
2148 |
|
2149 |
for (name, node_names) in allocatable: |
2150 |
op = op2inst.pop(name) |
2151 |
|
2152 |
(op.pnode_uuid, op.pnode) = \ |
2153 |
ExpandNodeUuidAndName(self.cfg, None, node_names[0]) |
2154 |
if len(node_names) > 1: |
2155 |
(op.snode_uuid, op.snode) = \ |
2156 |
ExpandNodeUuidAndName(self.cfg, None, node_names[1]) |
2157 |
|
2158 |
jobs.append([op]) |
2159 |
|
2160 |
missing = set(op2inst.keys()) - set(failed) |
2161 |
assert not missing, \ |
2162 |
"Iallocator did return incomplete result: %s" % \
|
2163 |
utils.CommaJoin(missing) |
2164 |
else:
|
2165 |
jobs.extend([op] for op in self.op.instances) |
2166 |
|
2167 |
return ResultWithJobs(jobs, **self._ConstructPartialResult()) |
2168 |
|
2169 |
|
2170 |
class _InstNicModPrivate: |
2171 |
"""Data structure for network interface modifications.
|
2172 |
|
2173 |
Used by L{LUInstanceSetParams}.
|
2174 |
|
2175 |
"""
|
2176 |
def __init__(self): |
2177 |
self.params = None |
2178 |
self.filled = None |
2179 |
|
2180 |
|
2181 |
def _PrepareContainerMods(mods, private_fn): |
2182 |
"""Prepares a list of container modifications by adding a private data field.
|
2183 |
|
2184 |
@type mods: list of tuples; (operation, index, parameters)
|
2185 |
@param mods: List of modifications
|
2186 |
@type private_fn: callable or None
|
2187 |
@param private_fn: Callable for constructing a private data field for a
|
2188 |
modification
|
2189 |
@rtype: list
|
2190 |
|
2191 |
"""
|
2192 |
if private_fn is None: |
2193 |
fn = lambda: None |
2194 |
else:
|
2195 |
fn = private_fn |
2196 |
|
2197 |
return [(op, idx, params, fn()) for (op, idx, params) in mods] |
2198 |
|
2199 |
|
2200 |
def _CheckNodesPhysicalCPUs(lu, node_uuids, requested, hypervisor_specs): |
2201 |
"""Checks if nodes have enough physical CPUs
|
2202 |
|
2203 |
This function checks if all given nodes have the needed number of
|
2204 |
physical CPUs. In case any node has less CPUs or we cannot get the
|
2205 |
information from the node, this function raises an OpPrereqError
|
2206 |
exception.
|
2207 |
|
2208 |
@type lu: C{LogicalUnit}
|
2209 |
@param lu: a logical unit from which we get configuration data
|
2210 |
@type node_uuids: C{list}
|
2211 |
@param node_uuids: the list of node UUIDs to check
|
2212 |
@type requested: C{int}
|
2213 |
@param requested: the minimum acceptable number of physical CPUs
|
2214 |
@type hypervisor_specs: list of pairs (string, dict of strings)
|
2215 |
@param hypervisor_specs: list of hypervisor specifications in
|
2216 |
pairs (hypervisor_name, hvparams)
|
2217 |
@raise errors.OpPrereqError: if the node doesn't have enough CPUs,
|
2218 |
or we cannot check the node
|
2219 |
|
2220 |
"""
|
2221 |
nodeinfo = lu.rpc.call_node_info(node_uuids, None, hypervisor_specs)
|
2222 |
for node_uuid in node_uuids: |
2223 |
info = nodeinfo[node_uuid] |
2224 |
node_name = lu.cfg.GetNodeName(node_uuid) |
2225 |
info.Raise("Cannot get current information from node %s" % node_name,
|
2226 |
prereq=True, ecode=errors.ECODE_ENVIRON)
|
2227 |
(_, _, (hv_info, )) = info.payload |
2228 |
num_cpus = hv_info.get("cpu_total", None) |
2229 |
if not isinstance(num_cpus, int): |
2230 |
raise errors.OpPrereqError("Can't compute the number of physical CPUs" |
2231 |
" on node %s, result was '%s'" %
|
2232 |
(node_name, num_cpus), errors.ECODE_ENVIRON) |
2233 |
if requested > num_cpus:
|
2234 |
raise errors.OpPrereqError("Node %s has %s physical CPUs, but %s are " |
2235 |
"required" % (node_name, num_cpus, requested),
|
2236 |
errors.ECODE_NORES) |
2237 |
|
2238 |
|
2239 |
def GetItemFromContainer(identifier, kind, container): |
2240 |
"""Return the item refered by the identifier.
|
2241 |
|
2242 |
@type identifier: string
|
2243 |
@param identifier: Item index or name or UUID
|
2244 |
@type kind: string
|
2245 |
@param kind: One-word item description
|
2246 |
@type container: list
|
2247 |
@param container: Container to get the item from
|
2248 |
|
2249 |
"""
|
2250 |
# Index
|
2251 |
try:
|
2252 |
idx = int(identifier)
|
2253 |
if idx == -1: |
2254 |
# Append
|
2255 |
absidx = len(container) - 1 |
2256 |
elif idx < 0: |
2257 |
raise IndexError("Not accepting negative indices other than -1") |
2258 |
elif idx > len(container): |
2259 |
raise IndexError("Got %s index %s, but there are only %s" % |
2260 |
(kind, idx, len(container)))
|
2261 |
else:
|
2262 |
absidx = idx |
2263 |
return (absidx, container[idx])
|
2264 |
except ValueError: |
2265 |
pass
|
2266 |
|
2267 |
for idx, item in enumerate(container): |
2268 |
if item.uuid == identifier or item.name == identifier: |
2269 |
return (idx, item)
|
2270 |
|
2271 |
raise errors.OpPrereqError("Cannot find %s with identifier %s" % |
2272 |
(kind, identifier), errors.ECODE_NOENT) |
2273 |
|
2274 |
|
2275 |
def _ApplyContainerMods(kind, container, chgdesc, mods, |
2276 |
create_fn, modify_fn, remove_fn, |
2277 |
post_add_fn=None):
|
2278 |
"""Applies descriptions in C{mods} to C{container}.
|
2279 |
|
2280 |
@type kind: string
|
2281 |
@param kind: One-word item description
|
2282 |
@type container: list
|
2283 |
@param container: Container to modify
|
2284 |
@type chgdesc: None or list
|
2285 |
@param chgdesc: List of applied changes
|
2286 |
@type mods: list
|
2287 |
@param mods: Modifications as returned by L{_PrepareContainerMods}
|
2288 |
@type create_fn: callable
|
2289 |
@param create_fn: Callback for creating a new item (L{constants.DDM_ADD});
|
2290 |
receives absolute item index, parameters and private data object as added
|
2291 |
by L{_PrepareContainerMods}, returns tuple containing new item and changes
|
2292 |
as list
|
2293 |
@type modify_fn: callable
|
2294 |
@param modify_fn: Callback for modifying an existing item
|
2295 |
(L{constants.DDM_MODIFY}); receives absolute item index, item, parameters
|
2296 |
and private data object as added by L{_PrepareContainerMods}, returns
|
2297 |
changes as list
|
2298 |
@type remove_fn: callable
|
2299 |
@param remove_fn: Callback on removing item; receives absolute item index,
|
2300 |
item and private data object as added by L{_PrepareContainerMods}
|
2301 |
@type post_add_fn: callable
|
2302 |
@param post_add_fn: Callable for post-processing a newly created item after
|
2303 |
it has been put into the container. It receives the index of the new item
|
2304 |
and the new item as parameters.
|
2305 |
|
2306 |
"""
|
2307 |
for (op, identifier, params, private) in mods: |
2308 |
changes = None
|
2309 |
|
2310 |
if op == constants.DDM_ADD:
|
2311 |
# Calculate where item will be added
|
2312 |
# When adding an item, identifier can only be an index
|
2313 |
try:
|
2314 |
idx = int(identifier)
|
2315 |
except ValueError: |
2316 |
raise errors.OpPrereqError("Only possitive integer or -1 is accepted as" |
2317 |
" identifier for %s" % constants.DDM_ADD,
|
2318 |
errors.ECODE_INVAL) |
2319 |
if idx == -1: |
2320 |
addidx = len(container)
|
2321 |
else:
|
2322 |
if idx < 0: |
2323 |
raise IndexError("Not accepting negative indices other than -1") |
2324 |
elif idx > len(container): |
2325 |
raise IndexError("Got %s index %s, but there are only %s" % |
2326 |
(kind, idx, len(container)))
|
2327 |
addidx = idx |
2328 |
|
2329 |
if create_fn is None: |
2330 |
item = params |
2331 |
else:
|
2332 |
(item, changes) = create_fn(addidx, params, private) |
2333 |
|
2334 |
if idx == -1: |
2335 |
container.append(item) |
2336 |
else:
|
2337 |
assert idx >= 0 |
2338 |
assert idx <= len(container) |
2339 |
# list.insert does so before the specified index
|
2340 |
container.insert(idx, item) |
2341 |
|
2342 |
if post_add_fn is not None: |
2343 |
post_add_fn(addidx, item) |
2344 |
|
2345 |
else:
|
2346 |
# Retrieve existing item
|
2347 |
(absidx, item) = GetItemFromContainer(identifier, kind, container) |
2348 |
|
2349 |
if op == constants.DDM_REMOVE:
|
2350 |
assert not params |
2351 |
|
2352 |
changes = [("%s/%s" % (kind, absidx), "remove")] |
2353 |
|
2354 |
if remove_fn is not None: |
2355 |
msg = remove_fn(absidx, item, private) |
2356 |
if msg:
|
2357 |
changes.append(("%s/%s" % (kind, absidx), msg))
|
2358 |
|
2359 |
assert container[absidx] == item
|
2360 |
del container[absidx]
|
2361 |
elif op == constants.DDM_MODIFY:
|
2362 |
if modify_fn is not None: |
2363 |
changes = modify_fn(absidx, item, params, private) |
2364 |
else:
|
2365 |
raise errors.ProgrammerError("Unhandled operation '%s'" % op) |
2366 |
|
2367 |
assert _TApplyContModsCbChanges(changes)
|
2368 |
|
2369 |
if not (chgdesc is None or changes is None): |
2370 |
chgdesc.extend(changes) |
2371 |
|
2372 |
|
2373 |
class LUInstanceSetParams(LogicalUnit): |
2374 |
"""Modifies an instances's parameters.
|
2375 |
|
2376 |
"""
|
2377 |
HPATH = "instance-modify"
|
2378 |
HTYPE = constants.HTYPE_INSTANCE |
2379 |
REQ_BGL = False
|
2380 |
|
2381 |
@staticmethod
|
2382 |
def _UpgradeDiskNicMods(kind, mods, verify_fn): |
2383 |
assert ht.TList(mods)
|
2384 |
assert not mods or len(mods[0]) in (2, 3) |
2385 |
|
2386 |
if mods and len(mods[0]) == 2: |
2387 |
result = [] |
2388 |
|
2389 |
addremove = 0
|
2390 |
for op, params in mods: |
2391 |
if op in (constants.DDM_ADD, constants.DDM_REMOVE): |
2392 |
result.append((op, -1, params))
|
2393 |
addremove += 1
|
2394 |
|
2395 |
if addremove > 1: |
2396 |
raise errors.OpPrereqError("Only one %s add or remove operation is" |
2397 |
" supported at a time" % kind,
|
2398 |
errors.ECODE_INVAL) |
2399 |
else:
|
2400 |
result.append((constants.DDM_MODIFY, op, params)) |
2401 |
|
2402 |
assert verify_fn(result)
|
2403 |
else:
|
2404 |
result = mods |
2405 |
|
2406 |
return result
|
2407 |
|
2408 |
@staticmethod
|
2409 |
def _CheckMods(kind, mods, key_types, item_fn): |
2410 |
"""Ensures requested disk/NIC modifications are valid.
|
2411 |
|
2412 |
"""
|
2413 |
for (op, _, params) in mods: |
2414 |
assert ht.TDict(params)
|
2415 |
|
2416 |
# If 'key_types' is an empty dict, we assume we have an
|
2417 |
# 'ext' template and thus do not ForceDictType
|
2418 |
if key_types:
|
2419 |
utils.ForceDictType(params, key_types) |
2420 |
|
2421 |
if op == constants.DDM_REMOVE:
|
2422 |
if params:
|
2423 |
raise errors.OpPrereqError("No settings should be passed when" |
2424 |
" removing a %s" % kind,
|
2425 |
errors.ECODE_INVAL) |
2426 |
elif op in (constants.DDM_ADD, constants.DDM_MODIFY): |
2427 |
item_fn(op, params) |
2428 |
else:
|
2429 |
raise errors.ProgrammerError("Unhandled operation '%s'" % op) |
2430 |
|
2431 |
def _VerifyDiskModification(self, op, params, excl_stor): |
2432 |
"""Verifies a disk modification.
|
2433 |
|
2434 |
"""
|
2435 |
if op == constants.DDM_ADD:
|
2436 |
mode = params.setdefault(constants.IDISK_MODE, constants.DISK_RDWR) |
2437 |
if mode not in constants.DISK_ACCESS_SET: |
2438 |
raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode, |
2439 |
errors.ECODE_INVAL) |
2440 |
|
2441 |
size = params.get(constants.IDISK_SIZE, None)
|
2442 |
if size is None: |
2443 |
raise errors.OpPrereqError("Required disk parameter '%s' missing" % |
2444 |
constants.IDISK_SIZE, errors.ECODE_INVAL) |
2445 |
size = int(size)
|
2446 |
|
2447 |
params[constants.IDISK_SIZE] = size |
2448 |
name = params.get(constants.IDISK_NAME, None)
|
2449 |
if name is not None and name.lower() == constants.VALUE_NONE: |
2450 |
params[constants.IDISK_NAME] = None
|
2451 |
|
2452 |
CheckSpindlesExclusiveStorage(params, excl_stor, True)
|
2453 |
|
2454 |
elif op == constants.DDM_MODIFY:
|
2455 |
if constants.IDISK_SIZE in params: |
2456 |
raise errors.OpPrereqError("Disk size change not possible, use" |
2457 |
" grow-disk", errors.ECODE_INVAL)
|
2458 |
|
2459 |
# Disk modification supports changing only the disk name and mode.
|
2460 |
# Changing arbitrary parameters is allowed only for ext disk template",
|
2461 |
if self.instance.disk_template != constants.DT_EXT: |
2462 |
utils.ForceDictType(params, constants.MODIFIABLE_IDISK_PARAMS_TYPES) |
2463 |
|
2464 |
name = params.get(constants.IDISK_NAME, None)
|
2465 |
if name is not None and name.lower() == constants.VALUE_NONE: |
2466 |
params[constants.IDISK_NAME] = None
|
2467 |
|
2468 |
@staticmethod
|
2469 |
def _VerifyNicModification(op, params): |
2470 |
"""Verifies a network interface modification.
|
2471 |
|
2472 |
"""
|
2473 |
if op in (constants.DDM_ADD, constants.DDM_MODIFY): |
2474 |
ip = params.get(constants.INIC_IP, None)
|
2475 |
name = params.get(constants.INIC_NAME, None)
|
2476 |
req_net = params.get(constants.INIC_NETWORK, None)
|
2477 |
link = params.get(constants.NIC_LINK, None)
|
2478 |
mode = params.get(constants.NIC_MODE, None)
|
2479 |
if name is not None and name.lower() == constants.VALUE_NONE: |
2480 |
params[constants.INIC_NAME] = None
|
2481 |
if req_net is not None: |
2482 |
if req_net.lower() == constants.VALUE_NONE:
|
2483 |
params[constants.INIC_NETWORK] = None
|
2484 |
req_net = None
|
2485 |
elif link is not None or mode is not None: |
2486 |
raise errors.OpPrereqError("If network is given" |
2487 |
" mode or link should not",
|
2488 |
errors.ECODE_INVAL) |
2489 |
|
2490 |
if op == constants.DDM_ADD:
|
2491 |
macaddr = params.get(constants.INIC_MAC, None)
|
2492 |
if macaddr is None: |
2493 |
params[constants.INIC_MAC] = constants.VALUE_AUTO |
2494 |
|
2495 |
if ip is not None: |
2496 |
if ip.lower() == constants.VALUE_NONE:
|
2497 |
params[constants.INIC_IP] = None
|
2498 |
else:
|
2499 |
if ip.lower() == constants.NIC_IP_POOL:
|
2500 |
if op == constants.DDM_ADD and req_net is None: |
2501 |
raise errors.OpPrereqError("If ip=pool, parameter network" |
2502 |
" cannot be none",
|
2503 |
errors.ECODE_INVAL) |
2504 |
else:
|
2505 |
if not netutils.IPAddress.IsValid(ip): |
2506 |
raise errors.OpPrereqError("Invalid IP address '%s'" % ip, |
2507 |
errors.ECODE_INVAL) |
2508 |
|
2509 |
if constants.INIC_MAC in params: |
2510 |
macaddr = params[constants.INIC_MAC] |
2511 |
if macaddr not in (constants.VALUE_AUTO, constants.VALUE_GENERATE): |
2512 |
macaddr = utils.NormalizeAndValidateMac(macaddr) |
2513 |
|
2514 |
if op == constants.DDM_MODIFY and macaddr == constants.VALUE_AUTO: |
2515 |
raise errors.OpPrereqError("'auto' is not a valid MAC address when" |
2516 |
" modifying an existing NIC",
|
2517 |
errors.ECODE_INVAL) |
2518 |
|
2519 |
def CheckArguments(self): |
2520 |
if not (self.op.nics or self.op.disks or self.op.disk_template or |
2521 |
self.op.hvparams or self.op.beparams or self.op.os_name or |
2522 |
self.op.osparams or self.op.offline is not None or |
2523 |
self.op.runtime_mem or self.op.pnode or self.op.osparams_private or |
2524 |
self.op.instance_communication is not None): |
2525 |
raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL) |
2526 |
|
2527 |
if self.op.hvparams: |
2528 |
CheckParamsNotGlobal(self.op.hvparams, constants.HVC_GLOBALS,
|
2529 |
"hypervisor", "instance", "cluster") |
2530 |
|
2531 |
self.op.disks = self._UpgradeDiskNicMods( |
2532 |
"disk", self.op.disks, ht.TSetParamsMods(ht.TIDiskParams)) |
2533 |
self.op.nics = self._UpgradeDiskNicMods( |
2534 |
"NIC", self.op.nics, ht.TSetParamsMods(ht.TINicParams)) |
2535 |
|
2536 |
if self.op.disks and self.op.disk_template is not None: |
2537 |
raise errors.OpPrereqError("Disk template conversion and other disk" |
2538 |
" changes not supported at the same time",
|
2539 |
errors.ECODE_INVAL) |
2540 |
|
2541 |
if (self.op.disk_template and |
2542 |
self.op.disk_template in constants.DTS_INT_MIRROR and |
2543 |
self.op.remote_node is None): |
2544 |
raise errors.OpPrereqError("Changing the disk template to a mirrored" |
2545 |
" one requires specifying a secondary node",
|
2546 |
errors.ECODE_INVAL) |
2547 |
|
2548 |
# Check NIC modifications
|
2549 |
self._CheckMods("NIC", self.op.nics, constants.INIC_PARAMS_TYPES, |
2550 |
self._VerifyNicModification)
|
2551 |
|
2552 |
if self.op.pnode: |
2553 |
(self.op.pnode_uuid, self.op.pnode) = \ |
2554 |
ExpandNodeUuidAndName(self.cfg, self.op.pnode_uuid, self.op.pnode) |
2555 |
|
2556 |
def ExpandNames(self): |
2557 |
self._ExpandAndLockInstance()
|
2558 |
self.needed_locks[locking.LEVEL_NODEGROUP] = []
|
2559 |
# Can't even acquire node locks in shared mode as upcoming changes in
|
2560 |
# Ganeti 2.6 will start to modify the node object on disk conversion
|
2561 |
self.needed_locks[locking.LEVEL_NODE] = []
|
2562 |
self.needed_locks[locking.LEVEL_NODE_RES] = []
|
2563 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
|
2564 |
# Look node group to look up the ipolicy
|
2565 |
self.share_locks[locking.LEVEL_NODEGROUP] = 1 |
2566 |
|
2567 |
def DeclareLocks(self, level): |
2568 |
if level == locking.LEVEL_NODEGROUP:
|
2569 |
assert not self.needed_locks[locking.LEVEL_NODEGROUP] |
2570 |
# Acquire locks for the instance's nodegroups optimistically. Needs
|
2571 |
# to be verified in CheckPrereq
|
2572 |
self.needed_locks[locking.LEVEL_NODEGROUP] = \
|
2573 |
self.cfg.GetInstanceNodeGroups(self.op.instance_uuid) |
2574 |
elif level == locking.LEVEL_NODE:
|
2575 |
self._LockInstancesNodes()
|
2576 |
if self.op.disk_template and self.op.remote_node: |
2577 |
(self.op.remote_node_uuid, self.op.remote_node) = \ |
2578 |
ExpandNodeUuidAndName(self.cfg, self.op.remote_node_uuid, |
2579 |
self.op.remote_node)
|
2580 |
self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node_uuid) |
2581 |
elif level == locking.LEVEL_NODE_RES and self.op.disk_template: |
2582 |
# Copy node locks
|
2583 |
self.needed_locks[locking.LEVEL_NODE_RES] = \
|
2584 |
CopyLockList(self.needed_locks[locking.LEVEL_NODE])
|
2585 |
|
2586 |
def BuildHooksEnv(self): |
2587 |
"""Build hooks env.
|
2588 |
|
2589 |
This runs on the master, primary and secondaries.
|
2590 |
|
2591 |
"""
|
2592 |
args = {} |
2593 |
if constants.BE_MINMEM in self.be_new: |
2594 |
args["minmem"] = self.be_new[constants.BE_MINMEM] |
2595 |
if constants.BE_MAXMEM in self.be_new: |
2596 |
args["maxmem"] = self.be_new[constants.BE_MAXMEM] |
2597 |
if constants.BE_VCPUS in self.be_new: |
2598 |
args["vcpus"] = self.be_new[constants.BE_VCPUS] |
2599 |
# TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
|
2600 |
# information at all.
|
2601 |
|
2602 |
if self._new_nics is not None: |
2603 |
nics = [] |
2604 |
|
2605 |
for nic in self._new_nics: |
2606 |
n = copy.deepcopy(nic) |
2607 |
nicparams = self.cluster.SimpleFillNIC(n.nicparams)
|
2608 |
n.nicparams = nicparams |
2609 |
nics.append(NICToTuple(self, n))
|
2610 |
|
2611 |
args["nics"] = nics
|
2612 |
|
2613 |
env = BuildInstanceHookEnvByObject(self, self.instance, override=args) |
2614 |
if self.op.disk_template: |
2615 |
env["NEW_DISK_TEMPLATE"] = self.op.disk_template |
2616 |
if self.op.runtime_mem: |
2617 |
env["RUNTIME_MEMORY"] = self.op.runtime_mem |
2618 |
|
2619 |
return env
|
2620 |
|
2621 |
def BuildHooksNodes(self): |
2622 |
"""Build hooks nodes.
|
2623 |
|
2624 |
"""
|
2625 |
nl = [self.cfg.GetMasterNode()] + \
|
2626 |
list(self.cfg.GetInstanceNodes(self.instance)) |
2627 |
return (nl, nl)
|
2628 |
|
2629 |
def _PrepareNicModification(self, params, private, old_ip, old_net_uuid, |
2630 |
old_params, cluster, pnode_uuid): |
2631 |
|
2632 |
update_params_dict = dict([(key, params[key])
|
2633 |
for key in constants.NICS_PARAMETERS |
2634 |
if key in params]) |
2635 |
|
2636 |
req_link = update_params_dict.get(constants.NIC_LINK, None)
|
2637 |
req_mode = update_params_dict.get(constants.NIC_MODE, None)
|
2638 |
|
2639 |
new_net_uuid = None
|
2640 |
new_net_uuid_or_name = params.get(constants.INIC_NETWORK, old_net_uuid) |
2641 |
if new_net_uuid_or_name:
|
2642 |
new_net_uuid = self.cfg.LookupNetwork(new_net_uuid_or_name)
|
2643 |
new_net_obj = self.cfg.GetNetwork(new_net_uuid)
|
2644 |
|
2645 |
if old_net_uuid:
|
2646 |
old_net_obj = self.cfg.GetNetwork(old_net_uuid)
|
2647 |
|
2648 |
if new_net_uuid:
|
2649 |
netparams = self.cfg.GetGroupNetParams(new_net_uuid, pnode_uuid)
|
2650 |
if not netparams: |
2651 |
raise errors.OpPrereqError("No netparams found for the network" |
2652 |
" %s, probably not connected" %
|
2653 |
new_net_obj.name, errors.ECODE_INVAL) |
2654 |
new_params = dict(netparams)
|
2655 |
else:
|
2656 |
new_params = GetUpdatedParams(old_params, update_params_dict) |
2657 |
|
2658 |
utils.ForceDictType(new_params, constants.NICS_PARAMETER_TYPES) |
2659 |
|
2660 |
new_filled_params = cluster.SimpleFillNIC(new_params) |
2661 |
objects.NIC.CheckParameterSyntax(new_filled_params) |
2662 |
|
2663 |
new_mode = new_filled_params[constants.NIC_MODE] |
2664 |
if new_mode == constants.NIC_MODE_BRIDGED:
|
2665 |
bridge = new_filled_params[constants.NIC_LINK] |
2666 |
msg = self.rpc.call_bridges_exist(pnode_uuid, [bridge]).fail_msg
|
2667 |
if msg:
|
2668 |
msg = "Error checking bridges on node '%s': %s" % \
|
2669 |
(self.cfg.GetNodeName(pnode_uuid), msg)
|
2670 |
if self.op.force: |
2671 |
self.warn.append(msg)
|
2672 |
else:
|
2673 |
raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
|
2674 |
|
2675 |
elif new_mode == constants.NIC_MODE_ROUTED:
|
2676 |
ip = params.get(constants.INIC_IP, old_ip) |
2677 |
if ip is None: |
2678 |
raise errors.OpPrereqError("Cannot set the NIC IP address to None" |
2679 |
" on a routed NIC", errors.ECODE_INVAL)
|
2680 |
|
2681 |
elif new_mode == constants.NIC_MODE_OVS:
|
2682 |
# TODO: check OVS link
|
2683 |
self.LogInfo("OVS links are currently not checked for correctness") |
2684 |
|
2685 |
if constants.INIC_MAC in params: |
2686 |
mac = params[constants.INIC_MAC] |
2687 |
if mac is None: |
2688 |
raise errors.OpPrereqError("Cannot unset the NIC MAC address", |
2689 |
errors.ECODE_INVAL) |
2690 |
elif mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE): |
2691 |
# otherwise generate the MAC address
|
2692 |
params[constants.INIC_MAC] = \ |
2693 |
self.cfg.GenerateMAC(new_net_uuid, self.proc.GetECId()) |
2694 |
else:
|
2695 |
# or validate/reserve the current one
|
2696 |
try:
|
2697 |
self.cfg.ReserveMAC(mac, self.proc.GetECId()) |
2698 |
except errors.ReservationError:
|
2699 |
raise errors.OpPrereqError("MAC address '%s' already in use" |
2700 |
" in cluster" % mac,
|
2701 |
errors.ECODE_NOTUNIQUE) |
2702 |
elif new_net_uuid != old_net_uuid:
|
2703 |
|
2704 |
def get_net_prefix(net_uuid): |
2705 |
mac_prefix = None
|
2706 |
if net_uuid:
|
2707 |
nobj = self.cfg.GetNetwork(net_uuid)
|
2708 |
mac_prefix = nobj.mac_prefix |
2709 |
|
2710 |
return mac_prefix
|
2711 |
|
2712 |
new_prefix = get_net_prefix(new_net_uuid) |
2713 |
old_prefix = get_net_prefix(old_net_uuid) |
2714 |
if old_prefix != new_prefix:
|
2715 |
params[constants.INIC_MAC] = \ |
2716 |
self.cfg.GenerateMAC(new_net_uuid, self.proc.GetECId()) |
2717 |
|
2718 |
# if there is a change in (ip, network) tuple
|
2719 |
new_ip = params.get(constants.INIC_IP, old_ip) |
2720 |
if (new_ip, new_net_uuid) != (old_ip, old_net_uuid):
|
2721 |
if new_ip:
|
2722 |
# if IP is pool then require a network and generate one IP
|
2723 |
if new_ip.lower() == constants.NIC_IP_POOL:
|
2724 |
if new_net_uuid:
|
2725 |
try:
|
2726 |
new_ip = self.cfg.GenerateIp(new_net_uuid, self.proc.GetECId()) |
2727 |
except errors.ReservationError:
|
2728 |
raise errors.OpPrereqError("Unable to get a free IP" |
2729 |
" from the address pool",
|
2730 |
errors.ECODE_STATE) |
2731 |
self.LogInfo("Chose IP %s from network %s", |
2732 |
new_ip, |
2733 |
new_net_obj.name) |
2734 |
params[constants.INIC_IP] = new_ip |
2735 |
else:
|
2736 |
raise errors.OpPrereqError("ip=pool, but no network found", |
2737 |
errors.ECODE_INVAL) |
2738 |
# Reserve new IP if in the new network if any
|
2739 |
elif new_net_uuid:
|
2740 |
try:
|
2741 |
self.cfg.ReserveIp(new_net_uuid, new_ip, self.proc.GetECId(), |
2742 |
check=self.op.conflicts_check)
|
2743 |
self.LogInfo("Reserving IP %s in network %s", |
2744 |
new_ip, new_net_obj.name) |
2745 |
except errors.ReservationError:
|
2746 |
raise errors.OpPrereqError("IP %s not available in network %s" % |
2747 |
(new_ip, new_net_obj.name), |
2748 |
errors.ECODE_NOTUNIQUE) |
2749 |
# new network is None so check if new IP is a conflicting IP
|
2750 |
elif self.op.conflicts_check: |
2751 |
_CheckForConflictingIp(self, new_ip, pnode_uuid)
|
2752 |
|
2753 |
# release old IP if old network is not None
|
2754 |
if old_ip and old_net_uuid: |
2755 |
try:
|
2756 |
self.cfg.ReleaseIp(old_net_uuid, old_ip, self.proc.GetECId()) |
2757 |
except errors.AddressPoolError:
|
2758 |
logging.warning("Release IP %s not contained in network %s",
|
2759 |
old_ip, old_net_obj.name) |
2760 |
|
2761 |
# there are no changes in (ip, network) tuple and old network is not None
|
2762 |
elif (old_net_uuid is not None and |
2763 |
(req_link is not None or req_mode is not None)): |
2764 |
raise errors.OpPrereqError("Not allowed to change link or mode of" |
2765 |
" a NIC that is connected to a network",
|
2766 |
errors.ECODE_INVAL) |
2767 |
|
2768 |
private.params = new_params |
2769 |
private.filled = new_filled_params |
2770 |
|
2771 |
def _PreCheckDiskTemplate(self, pnode_info): |
2772 |
"""CheckPrereq checks related to a new disk template."""
|
2773 |
# Arguments are passed to avoid configuration lookups
|
2774 |
pnode_uuid = self.instance.primary_node
|
2775 |
if self.instance.disk_template == self.op.disk_template: |
2776 |
raise errors.OpPrereqError("Instance already has disk template %s" % |
2777 |
self.instance.disk_template,
|
2778 |
errors.ECODE_INVAL) |
2779 |
|
2780 |
if not self.cluster.IsDiskTemplateEnabled(self.op.disk_template): |
2781 |
raise errors.OpPrereqError("Disk template '%s' is not enabled for this" |
2782 |
" cluster." % self.op.disk_template) |
2783 |
|
2784 |
if (self.instance.disk_template, |
2785 |
self.op.disk_template) not in self._DISK_CONVERSIONS: |
2786 |
raise errors.OpPrereqError("Unsupported disk template conversion from" |
2787 |
" %s to %s" % (self.instance.disk_template, |
2788 |
self.op.disk_template),
|
2789 |
errors.ECODE_INVAL) |
2790 |
CheckInstanceState(self, self.instance, INSTANCE_DOWN, |
2791 |
msg="cannot change disk template")
|
2792 |
if self.op.disk_template in constants.DTS_INT_MIRROR: |
2793 |
if self.op.remote_node_uuid == pnode_uuid: |
2794 |
raise errors.OpPrereqError("Given new secondary node %s is the same" |
2795 |
" as the primary node of the instance" %
|
2796 |
self.op.remote_node, errors.ECODE_STATE)
|
2797 |
CheckNodeOnline(self, self.op.remote_node_uuid) |
2798 |
CheckNodeNotDrained(self, self.op.remote_node_uuid) |
2799 |
# FIXME: here we assume that the old instance type is DT_PLAIN
|
2800 |
assert self.instance.disk_template == constants.DT_PLAIN |
2801 |
disks = [{constants.IDISK_SIZE: d.size, |
2802 |
constants.IDISK_VG: d.logical_id[0]}
|
2803 |
for d in self.cfg.GetInstanceDisks(self.instance)] |
2804 |
required = ComputeDiskSizePerVG(self.op.disk_template, disks)
|
2805 |
CheckNodesFreeDiskPerVG(self, [self.op.remote_node_uuid], required) |
2806 |
|
2807 |
snode_info = self.cfg.GetNodeInfo(self.op.remote_node_uuid) |
2808 |
snode_group = self.cfg.GetNodeGroup(snode_info.group)
|
2809 |
ipolicy = ganeti.masterd.instance.CalculateGroupIPolicy(self.cluster,
|
2810 |
snode_group) |
2811 |
CheckTargetNodeIPolicy(self, ipolicy, self.instance, snode_info, self.cfg, |
2812 |
ignore=self.op.ignore_ipolicy)
|
2813 |
if pnode_info.group != snode_info.group:
|
2814 |
self.LogWarning("The primary and secondary nodes are in two" |
2815 |
" different node groups; the disk parameters"
|
2816 |
" from the first disk's node group will be"
|
2817 |
" used")
|
2818 |
|
2819 |
if not self.op.disk_template in constants.DTS_EXCL_STORAGE: |
2820 |
# Make sure none of the nodes require exclusive storage
|
2821 |
nodes = [pnode_info] |
2822 |
if self.op.disk_template in constants.DTS_INT_MIRROR: |
2823 |
assert snode_info
|
2824 |
nodes.append(snode_info) |
2825 |
has_es = lambda n: IsExclusiveStorageEnabledNode(self.cfg, n) |
2826 |
if compat.any(map(has_es, nodes)): |
2827 |
errmsg = ("Cannot convert disk template from %s to %s when exclusive"
|
2828 |
" storage is enabled" % (self.instance.disk_template, |
2829 |
self.op.disk_template))
|
2830 |
raise errors.OpPrereqError(errmsg, errors.ECODE_STATE)
|
2831 |
|
2832 |
def _PreCheckDisks(self, ispec): |
2833 |
"""CheckPrereq checks related to disk changes.
|
2834 |
|
2835 |
@type ispec: dict
|
2836 |
@param ispec: instance specs to be updated with the new disks
|
2837 |
|
2838 |
"""
|
2839 |
self.diskparams = self.cfg.GetInstanceDiskParams(self.instance) |
2840 |
|
2841 |
inst_nodes = self.cfg.GetInstanceNodes(self.instance) |
2842 |
excl_stor = compat.any( |
2843 |
rpc.GetExclusiveStorageForNodes(self.cfg, inst_nodes).values()
|
2844 |
) |
2845 |
|
2846 |
# Check disk modifications. This is done here and not in CheckArguments
|
2847 |
# (as with NICs), because we need to know the instance's disk template
|
2848 |
ver_fn = lambda op, par: self._VerifyDiskModification(op, par, excl_stor) |
2849 |
if self.instance.disk_template == constants.DT_EXT: |
2850 |
self._CheckMods("disk", self.op.disks, {}, ver_fn) |
2851 |
else:
|
2852 |
self._CheckMods("disk", self.op.disks, constants.IDISK_PARAMS_TYPES, |
2853 |
ver_fn) |
2854 |
|
2855 |
self.diskmod = _PrepareContainerMods(self.op.disks, None) |
2856 |
|
2857 |
# Check the validity of the `provider' parameter
|
2858 |
if self.instance.disk_template in constants.DT_EXT: |
2859 |
for mod in self.diskmod: |
2860 |
ext_provider = mod[2].get(constants.IDISK_PROVIDER, None) |
2861 |
if mod[0] == constants.DDM_ADD: |
2862 |
if ext_provider is None: |
2863 |
raise errors.OpPrereqError("Instance template is '%s' and parameter" |
2864 |
" '%s' missing, during disk add" %
|
2865 |
(constants.DT_EXT, |
2866 |
constants.IDISK_PROVIDER), |
2867 |
errors.ECODE_NOENT) |
2868 |
elif mod[0] == constants.DDM_MODIFY: |
2869 |
if ext_provider:
|
2870 |
raise errors.OpPrereqError("Parameter '%s' is invalid during disk" |
2871 |
" modification" %
|
2872 |
constants.IDISK_PROVIDER, |
2873 |
errors.ECODE_INVAL) |
2874 |
else:
|
2875 |
for mod in self.diskmod: |
2876 |
ext_provider = mod[2].get(constants.IDISK_PROVIDER, None) |
2877 |
if ext_provider is not None: |
2878 |
raise errors.OpPrereqError("Parameter '%s' is only valid for" |
2879 |
" instances of type '%s'" %
|
2880 |
(constants.IDISK_PROVIDER, |
2881 |
constants.DT_EXT), |
2882 |
errors.ECODE_INVAL) |
2883 |
|
2884 |
if not self.op.wait_for_sync and self.instance.disks_active: |
2885 |
for mod in self.diskmod: |
2886 |
if mod[0] == constants.DDM_ADD: |
2887 |
raise errors.OpPrereqError("Can't add a disk to an instance with" |
2888 |
" activated disks and"
|
2889 |
" --no-wait-for-sync given.",
|
2890 |
errors.ECODE_INVAL) |
2891 |
|
2892 |
if self.op.disks and self.instance.disk_template == constants.DT_DISKLESS: |
2893 |
raise errors.OpPrereqError("Disk operations not supported for" |
2894 |
" diskless instances", errors.ECODE_INVAL)
|
2895 |
|
2896 |
def _PrepareDiskMod(_, disk, params, __): |
2897 |
disk.name = params.get(constants.IDISK_NAME, None)
|
2898 |
|
2899 |
# Verify disk changes (operating on a copy)
|
2900 |
inst_disks = self.cfg.GetInstanceDisks(self.instance) |
2901 |
disks = copy.deepcopy(inst_disks) |
2902 |
_ApplyContainerMods("disk", disks, None, self.diskmod, None, |
2903 |
_PrepareDiskMod, None)
|
2904 |
utils.ValidateDeviceNames("disk", disks)
|
2905 |
if len(disks) > constants.MAX_DISKS: |
2906 |
raise errors.OpPrereqError("Instance has too many disks (%d), cannot add" |
2907 |
" more" % constants.MAX_DISKS,
|
2908 |
errors.ECODE_STATE) |
2909 |
disk_sizes = [disk.size for disk in inst_disks] |
2910 |
disk_sizes.extend(params["size"] for (op, idx, params, private) in |
2911 |
self.diskmod if op == constants.DDM_ADD) |
2912 |
ispec[constants.ISPEC_DISK_COUNT] = len(disk_sizes)
|
2913 |
ispec[constants.ISPEC_DISK_SIZE] = disk_sizes |
2914 |
|
2915 |
if self.op.offline is not None and self.op.offline: |
2916 |
CheckInstanceState(self, self.instance, CAN_CHANGE_INSTANCE_OFFLINE, |
2917 |
msg="can't change to offline")
|
2918 |
|
2919 |
@staticmethod
|
2920 |
def _InstanceCommunicationDDM(cfg, instance_communication, instance): |
2921 |
"""Create a NIC mod that adds or removes the instance
|
2922 |
communication NIC to a running instance.
|
2923 |
|
2924 |
The NICS are dynamically created using the Dynamic Device
|
2925 |
Modification (DDM). This function produces a NIC modification
|
2926 |
(mod) that inserts an additional NIC meant for instance
|
2927 |
communication in or removes an existing instance communication NIC
|
2928 |
from a running instance, using DDM.
|
2929 |
|
2930 |
@type cfg: L{config.ConfigWriter}
|
2931 |
@param cfg: cluster configuration
|
2932 |
|
2933 |
@type instance_communication: boolean
|
2934 |
@param instance_communication: whether instance communication is
|
2935 |
enabled or disabled
|
2936 |
|
2937 |
@type instance: L{objects.Instance}
|
2938 |
@param instance: instance to which the NIC mod will be applied to
|
2939 |
|
2940 |
@rtype: (L{constants.DDM_ADD}, -1, parameters) or
|
2941 |
(L{constants.DDM_REMOVE}, -1, parameters) or
|
2942 |
L{None}
|
2943 |
@return: DDM mod containing an action to add or remove the NIC, or
|
2944 |
None if nothing needs to be done
|
2945 |
|
2946 |
"""
|
2947 |
nic_name = _ComputeInstanceCommunicationNIC(instance.name) |
2948 |
|
2949 |
instance_communication_nic = None
|
2950 |
|
2951 |
for nic in instance.nics: |
2952 |
if nic.name == nic_name:
|
2953 |
instance_communication_nic = nic |
2954 |
break
|
2955 |
|
2956 |
if instance_communication and not instance_communication_nic: |
2957 |
action = constants.DDM_ADD |
2958 |
params = {constants.INIC_NAME: nic_name, |
2959 |
constants.INIC_MAC: constants.VALUE_GENERATE, |
2960 |
constants.INIC_IP: constants.NIC_IP_POOL, |
2961 |
constants.INIC_NETWORK: |
2962 |
cfg.GetInstanceCommunicationNetwork()} |
2963 |
elif not instance_communication and instance_communication_nic: |
2964 |
action = constants.DDM_REMOVE |
2965 |
params = None
|
2966 |
else:
|
2967 |
action = None
|
2968 |
params = None
|
2969 |
|
2970 |
if action is not None: |
2971 |
return (action, -1, params) |
2972 |
else:
|
2973 |
return None |
2974 |
|
2975 |
def CheckPrereq(self): |
2976 |
"""Check prerequisites.
|
2977 |
|
2978 |
This only checks the instance list against the existing names.
|
2979 |
|
2980 |
"""
|
2981 |
assert self.op.instance_name in self.owned_locks(locking.LEVEL_INSTANCE) |
2982 |
self.instance = self.cfg.GetInstanceInfo(self.op.instance_uuid) |
2983 |
self.cluster = self.cfg.GetClusterInfo() |
2984 |
cluster_hvparams = self.cluster.hvparams[self.instance.hypervisor] |
2985 |
|
2986 |
assert self.instance is not None, \ |
2987 |
"Cannot retrieve locked instance %s" % self.op.instance_name |
2988 |
|
2989 |
pnode_uuid = self.instance.primary_node
|
2990 |
|
2991 |
self.warn = []
|
2992 |
|
2993 |
if (self.op.pnode_uuid is not None and self.op.pnode_uuid != pnode_uuid and |
2994 |
not self.op.force): |
2995 |
# verify that the instance is not up
|
2996 |
instance_info = self.rpc.call_instance_info(
|
2997 |
pnode_uuid, self.instance.name, self.instance.hypervisor, |
2998 |
cluster_hvparams) |
2999 |
if instance_info.fail_msg:
|
3000 |
self.warn.append("Can't get instance runtime information: %s" % |
3001 |
instance_info.fail_msg) |
3002 |
elif instance_info.payload:
|
3003 |
raise errors.OpPrereqError("Instance is still running on %s" % |
3004 |
self.cfg.GetNodeName(pnode_uuid),
|
3005 |
errors.ECODE_STATE) |
3006 |
|
3007 |
assert pnode_uuid in self.owned_locks(locking.LEVEL_NODE) |
3008 |
node_uuids = list(self.cfg.GetInstanceNodes(self.instance)) |
3009 |
pnode_info = self.cfg.GetNodeInfo(pnode_uuid)
|
3010 |
|
3011 |
#_CheckInstanceNodeGroups(self.cfg, self.op.instance_name, owned_groups)
|
3012 |
assert pnode_info.group in self.owned_locks(locking.LEVEL_NODEGROUP) |
3013 |
group_info = self.cfg.GetNodeGroup(pnode_info.group)
|
3014 |
|
3015 |
# dictionary with instance information after the modification
|
3016 |
ispec = {} |
3017 |
|
3018 |
if self.op.hotplug or self.op.hotplug_if_possible: |
3019 |
result = self.rpc.call_hotplug_supported(self.instance.primary_node, |
3020 |
self.instance)
|
3021 |
if result.fail_msg:
|
3022 |
if self.op.hotplug: |
3023 |
result.Raise("Hotplug is not possible: %s" % result.fail_msg,
|
3024 |
prereq=True)
|
3025 |
else:
|
3026 |
self.LogWarning(result.fail_msg)
|
3027 |
self.op.hotplug = False |
3028 |
self.LogInfo("Modification will take place without hotplugging.") |
3029 |
else:
|
3030 |
self.op.hotplug = True |
3031 |
|
3032 |
# Prepare NIC modifications
|
3033 |
# add or remove NIC for instance communication
|
3034 |
if self.op.instance_communication is not None: |
3035 |
mod = self._InstanceCommunicationDDM(self.cfg, |
3036 |
self.op.instance_communication,
|
3037 |
self.instance)
|
3038 |
if mod is not None: |
3039 |
self.op.nics.append(mod)
|
3040 |
|
3041 |
self.nicmod = _PrepareContainerMods(self.op.nics, _InstNicModPrivate) |
3042 |
|
3043 |
# OS change
|
3044 |
if self.op.os_name and not self.op.force: |
3045 |
CheckNodeHasOS(self, self.instance.primary_node, self.op.os_name, |
3046 |
self.op.force_variant)
|
3047 |
instance_os = self.op.os_name
|
3048 |
else:
|
3049 |
instance_os = self.instance.os
|
3050 |
|
3051 |
assert not (self.op.disk_template and self.op.disks), \ |
3052 |
"Can't modify disk template and apply disk changes at the same time"
|
3053 |
|
3054 |
if self.op.disk_template: |
3055 |
self._PreCheckDiskTemplate(pnode_info)
|
3056 |
|
3057 |
self._PreCheckDisks(ispec)
|
3058 |
|
3059 |
# hvparams processing
|
3060 |
if self.op.hvparams: |
3061 |
hv_type = self.instance.hypervisor
|
3062 |
i_hvdict = GetUpdatedParams(self.instance.hvparams, self.op.hvparams) |
3063 |
utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES) |
3064 |
hv_new = self.cluster.SimpleFillHV(hv_type, self.instance.os, i_hvdict) |
3065 |
|
3066 |
# local check
|
3067 |
hypervisor.GetHypervisorClass(hv_type).CheckParameterSyntax(hv_new) |
3068 |
CheckHVParams(self, node_uuids, self.instance.hypervisor, hv_new) |
3069 |
self.hv_proposed = self.hv_new = hv_new # the new actual values |
3070 |
self.hv_inst = i_hvdict # the new dict (without defaults) |
3071 |
else:
|
3072 |
self.hv_proposed = self.cluster.SimpleFillHV(self.instance.hypervisor, |
3073 |
self.instance.os,
|
3074 |
self.instance.hvparams)
|
3075 |
self.hv_new = self.hv_inst = {} |
3076 |
|
3077 |
# beparams processing
|
3078 |
if self.op.beparams: |
3079 |
i_bedict = GetUpdatedParams(self.instance.beparams, self.op.beparams, |
3080 |
use_none=True)
|
3081 |
objects.UpgradeBeParams(i_bedict) |
3082 |
utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES) |
3083 |
be_new = self.cluster.SimpleFillBE(i_bedict)
|
3084 |
self.be_proposed = self.be_new = be_new # the new actual values |
3085 |
self.be_inst = i_bedict # the new dict (without defaults) |
3086 |
else:
|
3087 |
self.be_new = self.be_inst = {} |
3088 |
self.be_proposed = self.cluster.SimpleFillBE(self.instance.beparams) |
3089 |
be_old = self.cluster.FillBE(self.instance) |
3090 |
|
3091 |
# CPU param validation -- checking every time a parameter is
|
3092 |
# changed to cover all cases where either CPU mask or vcpus have
|
3093 |
# changed
|
3094 |
if (constants.BE_VCPUS in self.be_proposed and |
3095 |
constants.HV_CPU_MASK in self.hv_proposed): |
3096 |
cpu_list = \ |
3097 |
utils.ParseMultiCpuMask(self.hv_proposed[constants.HV_CPU_MASK])
|
3098 |
# Verify mask is consistent with number of vCPUs. Can skip this
|
3099 |
# test if only 1 entry in the CPU mask, which means same mask
|
3100 |
# is applied to all vCPUs.
|
3101 |
if (len(cpu_list) > 1 and |
3102 |
len(cpu_list) != self.be_proposed[constants.BE_VCPUS]): |
3103 |
raise errors.OpPrereqError("Number of vCPUs [%d] does not match the" |
3104 |
" CPU mask [%s]" %
|
3105 |
(self.be_proposed[constants.BE_VCPUS],
|
3106 |
self.hv_proposed[constants.HV_CPU_MASK]),
|
3107 |
errors.ECODE_INVAL) |
3108 |
|
3109 |
# Only perform this test if a new CPU mask is given
|
3110 |
if constants.HV_CPU_MASK in self.hv_new: |
3111 |
# Calculate the largest CPU number requested
|
3112 |
max_requested_cpu = max(map(max, cpu_list)) |
3113 |
# Check that all of the instance's nodes have enough physical CPUs to
|
3114 |
# satisfy the requested CPU mask
|
3115 |
hvspecs = [(self.instance.hypervisor,
|
3116 |
self.cfg.GetClusterInfo()
|
3117 |
.hvparams[self.instance.hypervisor])]
|
3118 |
_CheckNodesPhysicalCPUs(self, self.cfg.GetInstanceNodes(self.instance), |
3119 |
max_requested_cpu + 1,
|
3120 |
hvspecs) |
3121 |
|
3122 |
# osparams processing
|
3123 |
if self.op.osparams or self.op.osparams_private: |
3124 |
public_parms = self.op.osparams or {} |
3125 |
private_parms = self.op.osparams_private or {} |
3126 |
dupe_keys = utils.GetRepeatedKeys(public_parms, private_parms) |
3127 |
|
3128 |
if dupe_keys:
|
3129 |
raise errors.OpPrereqError("OS parameters repeated multiple times: %s" % |
3130 |
utils.CommaJoin(dupe_keys)) |
3131 |
|
3132 |
self.os_inst = GetUpdatedParams(self.instance.osparams, |
3133 |
public_parms) |
3134 |
self.os_inst_private = GetUpdatedParams(self.instance.osparams_private, |
3135 |
private_parms) |
3136 |
|
3137 |
CheckOSParams(self, True, node_uuids, instance_os, |
3138 |
objects.FillDict(self.os_inst,
|
3139 |
self.os_inst_private))
|
3140 |
|
3141 |
else:
|
3142 |
self.os_inst = {}
|
3143 |
self.os_inst_private = {}
|
3144 |
|
3145 |
#TODO(dynmem): do the appropriate check involving MINMEM
|
3146 |
if (constants.BE_MAXMEM in self.op.beparams and not self.op.force and |
3147 |
be_new[constants.BE_MAXMEM] > be_old[constants.BE_MAXMEM]): |
3148 |
mem_check_list = [pnode_uuid] |
3149 |
if be_new[constants.BE_AUTO_BALANCE]:
|
3150 |
# either we changed auto_balance to yes or it was from before
|
3151 |
mem_check_list.extend( |
3152 |
self.cfg.GetInstanceSecondaryNodes(self.instance)) |
3153 |
instance_info = self.rpc.call_instance_info(
|
3154 |
pnode_uuid, self.instance.name, self.instance.hypervisor, |
3155 |
cluster_hvparams) |
3156 |
hvspecs = [(self.instance.hypervisor,
|
3157 |
cluster_hvparams)] |
3158 |
nodeinfo = self.rpc.call_node_info(mem_check_list, None, |
3159 |
hvspecs) |
3160 |
pninfo = nodeinfo[pnode_uuid] |
3161 |
msg = pninfo.fail_msg |
3162 |
if msg:
|
3163 |
# Assume the primary node is unreachable and go ahead
|
3164 |
self.warn.append("Can't get info from primary node %s: %s" % |
3165 |
(self.cfg.GetNodeName(pnode_uuid), msg))
|
3166 |
else:
|
3167 |
(_, _, (pnhvinfo, )) = pninfo.payload |
3168 |
if not isinstance(pnhvinfo.get("memory_free", None), int): |
3169 |
self.warn.append("Node data from primary node %s doesn't contain" |
3170 |
" free memory information" %
|
3171 |
self.cfg.GetNodeName(pnode_uuid))
|
3172 |
elif instance_info.fail_msg:
|
3173 |
self.warn.append("Can't get instance runtime information: %s" % |
3174 |
instance_info.fail_msg) |
3175 |
else:
|
3176 |
if instance_info.payload:
|
3177 |
current_mem = int(instance_info.payload["memory"]) |
3178 |
else:
|
3179 |
# Assume instance not running
|
3180 |
# (there is a slight race condition here, but it's not very
|
3181 |
# probable, and we have no other way to check)
|
3182 |
# TODO: Describe race condition
|
3183 |
current_mem = 0
|
3184 |
#TODO(dynmem): do the appropriate check involving MINMEM
|
3185 |
miss_mem = (be_new[constants.BE_MAXMEM] - current_mem - |
3186 |
pnhvinfo["memory_free"])
|
3187 |
if miss_mem > 0: |
3188 |
raise errors.OpPrereqError("This change will prevent the instance" |
3189 |
" from starting, due to %d MB of memory"
|
3190 |
" missing on its primary node" %
|
3191 |
miss_mem, errors.ECODE_NORES) |
3192 |
|
3193 |
if be_new[constants.BE_AUTO_BALANCE]:
|
3194 |
secondary_nodes = self.cfg.GetInstanceSecondaryNodes(self.instance) |
3195 |
for node_uuid, nres in nodeinfo.items(): |
3196 |
if node_uuid not in secondary_nodes: |
3197 |
continue
|
3198 |
nres.Raise("Can't get info from secondary node %s" %
|
3199 |
self.cfg.GetNodeName(node_uuid), prereq=True, |
3200 |
ecode=errors.ECODE_STATE) |
3201 |
(_, _, (nhvinfo, )) = nres.payload |
3202 |
if not isinstance(nhvinfo.get("memory_free", None), int): |
3203 |
raise errors.OpPrereqError("Secondary node %s didn't return free" |
3204 |
" memory information" %
|
3205 |
self.cfg.GetNodeName(node_uuid),
|
3206 |
errors.ECODE_STATE) |
3207 |
#TODO(dynmem): do the appropriate check involving MINMEM
|
3208 |
elif be_new[constants.BE_MAXMEM] > nhvinfo["memory_free"]: |
3209 |
raise errors.OpPrereqError("This change will prevent the instance" |
3210 |
" from failover to its secondary node"
|
3211 |
" %s, due to not enough memory" %
|
3212 |
self.cfg.GetNodeName(node_uuid),
|
3213 |
errors.ECODE_STATE) |
3214 |
|
3215 |
if self.op.runtime_mem: |
3216 |
remote_info = self.rpc.call_instance_info(
|
3217 |
self.instance.primary_node, self.instance.name, |
3218 |
self.instance.hypervisor,
|
3219 |
cluster_hvparams) |
3220 |
remote_info.Raise("Error checking node %s" %
|
3221 |
self.cfg.GetNodeName(self.instance.primary_node)) |
3222 |
if not remote_info.payload: # not running already |
3223 |
raise errors.OpPrereqError("Instance %s is not running" % |
3224 |
self.instance.name, errors.ECODE_STATE)
|
3225 |
|
3226 |
current_memory = remote_info.payload["memory"]
|
3227 |
if (not self.op.force and |
3228 |
(self.op.runtime_mem > self.be_proposed[constants.BE_MAXMEM] or |
3229 |
self.op.runtime_mem < self.be_proposed[constants.BE_MINMEM])): |
3230 |
raise errors.OpPrereqError("Instance %s must have memory between %d" |
3231 |
" and %d MB of memory unless --force is"
|
3232 |
" given" %
|
3233 |
(self.instance.name,
|
3234 |
self.be_proposed[constants.BE_MINMEM],
|
3235 |
self.be_proposed[constants.BE_MAXMEM]),
|
3236 |
errors.ECODE_INVAL) |
3237 |
|
3238 |
delta = self.op.runtime_mem - current_memory
|
3239 |
if delta > 0: |
3240 |
CheckNodeFreeMemory( |
3241 |
self, self.instance.primary_node, |
3242 |
"ballooning memory for instance %s" % self.instance.name, delta, |
3243 |
self.instance.hypervisor,
|
3244 |
self.cfg.GetClusterInfo().hvparams[self.instance.hypervisor]) |
3245 |
|
3246 |
# make self.cluster visible in the functions below
|
3247 |
cluster = self.cluster
|
3248 |
|
3249 |
def _PrepareNicCreate(_, params, private): |
3250 |
self._PrepareNicModification(params, private, None, None, |
3251 |
{}, cluster, pnode_uuid) |
3252 |
return (None, None) |
3253 |
|
3254 |
def _PrepareNicMod(_, nic, params, private): |
3255 |
self._PrepareNicModification(params, private, nic.ip, nic.network,
|
3256 |
nic.nicparams, cluster, pnode_uuid) |
3257 |
return None |
3258 |
|
3259 |
def _PrepareNicRemove(_, params, __): |
3260 |
ip = params.ip |
3261 |
net = params.network |
3262 |
if net is not None and ip is not None: |
3263 |
self.cfg.ReleaseIp(net, ip, self.proc.GetECId()) |
3264 |
|
3265 |
# Verify NIC changes (operating on copy)
|
3266 |
nics = [nic.Copy() for nic in self.instance.nics] |
3267 |
_ApplyContainerMods("NIC", nics, None, self.nicmod, |
3268 |
_PrepareNicCreate, _PrepareNicMod, _PrepareNicRemove) |
3269 |
if len(nics) > constants.MAX_NICS: |
3270 |
raise errors.OpPrereqError("Instance has too many network interfaces" |
3271 |
" (%d), cannot add more" % constants.MAX_NICS,
|
3272 |
errors.ECODE_STATE) |
3273 |
|
3274 |
# Pre-compute NIC changes (necessary to use result in hooks)
|
3275 |
self._nic_chgdesc = []
|
3276 |
if self.nicmod: |
3277 |
# Operate on copies as this is still in prereq
|
3278 |
nics = [nic.Copy() for nic in self.instance.nics] |
3279 |
_ApplyContainerMods("NIC", nics, self._nic_chgdesc, self.nicmod, |
3280 |
self._CreateNewNic, self._ApplyNicMods, |
3281 |
self._RemoveNic)
|
3282 |
# Verify that NIC names are unique and valid
|
3283 |
utils.ValidateDeviceNames("NIC", nics)
|
3284 |
self._new_nics = nics
|
3285 |
ispec[constants.ISPEC_NIC_COUNT] = len(self._new_nics) |
3286 |
else:
|
3287 |
self._new_nics = None |
3288 |
ispec[constants.ISPEC_NIC_COUNT] = len(self.instance.nics) |
3289 |
|
3290 |
if not self.op.ignore_ipolicy: |
3291 |
ipolicy = ganeti.masterd.instance.CalculateGroupIPolicy(self.cluster,
|
3292 |
group_info) |
3293 |
|
3294 |
# Fill ispec with backend parameters
|
3295 |
ispec[constants.ISPEC_SPINDLE_USE] = \ |
3296 |
self.be_new.get(constants.BE_SPINDLE_USE, None) |
3297 |
ispec[constants.ISPEC_CPU_COUNT] = self.be_new.get(constants.BE_VCPUS,
|
3298 |
None)
|
3299 |
|
3300 |
# Copy ispec to verify parameters with min/max values separately
|
3301 |
if self.op.disk_template: |
3302 |
new_disk_template = self.op.disk_template
|
3303 |
else:
|
3304 |
new_disk_template = self.instance.disk_template
|
3305 |
ispec_max = ispec.copy() |
3306 |
ispec_max[constants.ISPEC_MEM_SIZE] = \ |
3307 |
self.be_new.get(constants.BE_MAXMEM, None) |
3308 |
res_max = _ComputeIPolicyInstanceSpecViolation(ipolicy, ispec_max, |
3309 |
new_disk_template) |
3310 |
ispec_min = ispec.copy() |
3311 |
ispec_min[constants.ISPEC_MEM_SIZE] = \ |
3312 |
self.be_new.get(constants.BE_MINMEM, None) |
3313 |
res_min = _ComputeIPolicyInstanceSpecViolation(ipolicy, ispec_min, |
3314 |
new_disk_template) |
3315 |
|
3316 |
if (res_max or res_min): |
3317 |
# FIXME: Improve error message by including information about whether
|
3318 |
# the upper or lower limit of the parameter fails the ipolicy.
|
3319 |
msg = ("Instance allocation to group %s (%s) violates policy: %s" %
|
3320 |
(group_info, group_info.name, |
3321 |
utils.CommaJoin(set(res_max + res_min))))
|
3322 |
raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
|
3323 |
|
3324 |
def _ConvertPlainToDrbd(self, feedback_fn): |
3325 |
"""Converts an instance from plain to drbd.
|
3326 |
|
3327 |
"""
|
3328 |
feedback_fn("Converting template to drbd")
|
3329 |
pnode_uuid = self.instance.primary_node
|
3330 |
snode_uuid = self.op.remote_node_uuid
|
3331 |
|
3332 |
assert self.instance.disk_template == constants.DT_PLAIN |
3333 |
|
3334 |
old_disks = self.cfg.GetInstanceDisks(self.instance) |
3335 |
# create a fake disk info for _GenerateDiskTemplate
|
3336 |
disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode, |
3337 |
constants.IDISK_VG: d.logical_id[0],
|
3338 |
constants.IDISK_NAME: d.name} |
3339 |
for d in old_disks] |
3340 |
new_disks = GenerateDiskTemplate(self, self.op.disk_template, |
3341 |
self.instance.uuid, pnode_uuid,
|
3342 |
[snode_uuid], disk_info, None, None, 0, |
3343 |
feedback_fn, self.diskparams)
|
3344 |
anno_disks = rpc.AnnotateDiskParams(new_disks, self.diskparams)
|
3345 |
p_excl_stor = IsExclusiveStorageEnabledNodeUuid(self.cfg, pnode_uuid)
|
3346 |
s_excl_stor = IsExclusiveStorageEnabledNodeUuid(self.cfg, snode_uuid)
|
3347 |
info = GetInstanceInfoText(self.instance)
|
3348 |
feedback_fn("Creating additional volumes...")
|
3349 |
# first, create the missing data and meta devices
|
3350 |
for disk in anno_disks: |
3351 |
# unfortunately this is... not too nice
|
3352 |
CreateSingleBlockDev(self, pnode_uuid, self.instance, disk.children[1], |
3353 |
info, True, p_excl_stor)
|
3354 |
for child in disk.children: |
3355 |
CreateSingleBlockDev(self, snode_uuid, self.instance, child, info, True, |
3356 |
s_excl_stor) |
3357 |
# at this stage, all new LVs have been created, we can rename the
|
3358 |
# old ones
|
3359 |
feedback_fn("Renaming original volumes...")
|
3360 |
rename_list = [(o, n.children[0].logical_id)
|
3361 |
for (o, n) in zip(old_disks, new_disks)] |
3362 |
result = self.rpc.call_blockdev_rename(pnode_uuid, rename_list)
|
3363 |
result.Raise("Failed to rename original LVs")
|
3364 |
|
3365 |
feedback_fn("Initializing DRBD devices...")
|
3366 |
# all child devices are in place, we can now create the DRBD devices
|
3367 |
try:
|
3368 |
for disk in anno_disks: |
3369 |
for (node_uuid, excl_stor) in [(pnode_uuid, p_excl_stor), |
3370 |
(snode_uuid, s_excl_stor)]: |
3371 |
f_create = node_uuid == pnode_uuid |
3372 |
CreateSingleBlockDev(self, node_uuid, self.instance, disk, info, |
3373 |
f_create, excl_stor) |
3374 |
except errors.GenericError, e:
|
3375 |
feedback_fn("Initializing of DRBD devices failed;"
|
3376 |
" renaming back original volumes...")
|
3377 |
rename_back_list = [(n.children[0], o.logical_id)
|
3378 |
for (n, o) in zip(new_disks, old_disks)] |
3379 |
result = self.rpc.call_blockdev_rename(pnode_uuid, rename_back_list)
|
3380 |
result.Raise("Failed to rename LVs back after error %s" % str(e)) |
3381 |
raise
|
3382 |
|
3383 |
# at this point, the instance has been modified
|
3384 |
self.instance.disk_template = constants.DT_DRBD8
|
3385 |
for old_disk in old_disks: |
3386 |
self.cfg.RemoveInstDisk(old_disk.uuid)
|
3387 |
for (idx, new_disk) in enumerate(new_disks): |
3388 |
self.cfg.AddInstDisk(self.instance, new_disk, idx=idx) |
3389 |
self.cfg.Update(self.instance, feedback_fn) |
3390 |
|
3391 |
# Release node locks while waiting for sync
|
3392 |
ReleaseLocks(self, locking.LEVEL_NODE)
|
3393 |
|
3394 |
# disks are created, waiting for sync
|
3395 |
disk_abort = not WaitForSync(self, self.instance, |
3396 |
oneshot=not self.op.wait_for_sync) |
3397 |
if disk_abort:
|
3398 |
raise errors.OpExecError("There are some degraded disks for" |
3399 |
" this instance, please cleanup manually")
|
3400 |
|
3401 |
# Node resource locks will be released by caller
|
3402 |
|
3403 |
def _ConvertDrbdToPlain(self, feedback_fn): |
3404 |
"""Converts an instance from drbd to plain.
|
3405 |
|
3406 |
"""
|
3407 |
secondary_nodes = self.cfg.GetInstanceSecondaryNodes(self.instance) |
3408 |
assert len(secondary_nodes) == 1 |
3409 |
assert self.instance.disk_template == constants.DT_DRBD8 |
3410 |
|
3411 |
pnode_uuid = self.instance.primary_node
|
3412 |
snode_uuid = secondary_nodes[0]
|
3413 |
feedback_fn("Converting template to plain")
|
3414 |
|
3415 |
disks = self.cfg.GetInstanceDisks(self.instance) |
3416 |
old_disks = AnnotateDiskParams(self.instance, disks, self.cfg) |
3417 |
new_disks = [d.children[0] for d in disks] |
3418 |
|
3419 |
# copy over size, mode and name
|
3420 |
for parent, child in zip(old_disks, new_disks): |
3421 |
child.size = parent.size |
3422 |
child.mode = parent.mode |
3423 |
child.name = parent.name |
3424 |
|
3425 |
# this is a DRBD disk, return its port to the pool
|
3426 |
# NOTE: this must be done right before the call to cfg.Update!
|
3427 |
for disk in old_disks: |
3428 |
tcp_port = disk.logical_id[2]
|
3429 |
self.cfg.AddTcpUdpPort(tcp_port)
|
3430 |
|
3431 |
# update instance structure
|
3432 |
for old_disk in old_disks: |
3433 |
self.cfg.RemoveInstDisk(old_disk.uuid)
|
3434 |
self.instance.disk_template = constants.DT_PLAIN
|
3435 |
for (idx, new_disk) in enumerate(new_disks): |
3436 |
self.cfg.AddInstDisk(self.instance, new_disk, idx=idx) |
3437 |
self.cfg.Update(self.instance, feedback_fn) |
3438 |
|
3439 |
# Release locks in case removing disks takes a while
|
3440 |
ReleaseLocks(self, locking.LEVEL_NODE)
|
3441 |
|
3442 |
feedback_fn("Removing volumes on the secondary node...")
|
3443 |
for disk in old_disks: |
3444 |
result = self.rpc.call_blockdev_remove(snode_uuid, (disk, self.instance)) |
3445 |
result.Warn("Could not remove block device %s on node %s,"
|
3446 |
" continuing anyway" %
|
3447 |
(disk.iv_name, self.cfg.GetNodeName(snode_uuid)),
|
3448 |
self.LogWarning)
|
3449 |
|
3450 |
feedback_fn("Removing unneeded volumes on the primary node...")
|
3451 |
for idx, disk in enumerate(old_disks): |
3452 |
meta = disk.children[1]
|
3453 |
result = self.rpc.call_blockdev_remove(pnode_uuid, (meta, self.instance)) |
3454 |
result.Warn("Could not remove metadata for disk %d on node %s,"
|
3455 |
" continuing anyway" %
|
3456 |
(idx, self.cfg.GetNodeName(pnode_uuid)),
|
3457 |
self.LogWarning)
|
3458 |
|
3459 |
def _HotplugDevice(self, action, dev_type, device, extra, seq): |
3460 |
self.LogInfo("Trying to hotplug device...") |
3461 |
msg = "hotplug:"
|
3462 |
result = self.rpc.call_hotplug_device(self.instance.primary_node, |
3463 |
self.instance, action, dev_type,
|
3464 |
(device, self.instance),
|
3465 |
extra, seq) |
3466 |
if result.fail_msg:
|
3467 |
self.LogWarning("Could not hotplug device: %s" % result.fail_msg) |
3468 |
self.LogInfo("Continuing execution..") |
3469 |
msg += "failed"
|
3470 |
else:
|
3471 |
self.LogInfo("Hotplug done.") |
3472 |
msg += "done"
|
3473 |
return msg
|
3474 |
|
3475 |
def _CreateNewDisk(self, idx, params, _): |
3476 |
"""Creates a new disk.
|
3477 |
|
3478 |
"""
|
3479 |
# add a new disk
|
3480 |
if self.instance.disk_template in constants.DTS_FILEBASED: |
3481 |
disks = self.cfg.GetInstanceDisks(self.instance) |
3482 |
(file_driver, file_path) = disks[0].logical_id
|
3483 |
file_path = os.path.dirname(file_path) |
3484 |
else:
|
3485 |
file_driver = file_path = None
|
3486 |
|
3487 |
secondary_nodes = self.cfg.GetInstanceSecondaryNodes(self.instance) |
3488 |
disk = \ |
3489 |
GenerateDiskTemplate(self, self.instance.disk_template, |
3490 |
self.instance.uuid, self.instance.primary_node, |
3491 |
secondary_nodes, [params], file_path, |
3492 |
file_driver, idx, self.Log, self.diskparams)[0] |
3493 |
|
3494 |
new_disks = CreateDisks(self, self.instance, disks=[disk]) |
3495 |
self.cfg.AddInstDisk(self.instance, disk, idx) |
3496 |
|
3497 |
if self.cluster.prealloc_wipe_disks: |
3498 |
# Wipe new disk
|
3499 |
WipeOrCleanupDisks(self, self.instance, |
3500 |
disks=[(idx, disk, 0)],
|
3501 |
cleanup=new_disks) |
3502 |
|
3503 |
changes = [ |
3504 |
("disk/%d" % idx,
|
3505 |
"add:size=%s,mode=%s" % (disk.size, disk.mode)),
|
3506 |
] |
3507 |
if self.op.hotplug: |
3508 |
result = self.rpc.call_blockdev_assemble(self.instance.primary_node, |
3509 |
(disk, self.instance),
|
3510 |
self.instance.name, True, idx) |
3511 |
if result.fail_msg:
|
3512 |
changes.append(("disk/%d" % idx, "assemble:failed")) |
3513 |
self.LogWarning("Can't assemble newly created disk %d: %s", |
3514 |
idx, result.fail_msg) |
3515 |
else:
|
3516 |
_, link_name = result.payload |
3517 |
msg = self._HotplugDevice(constants.HOTPLUG_ACTION_ADD,
|
3518 |
constants.HOTPLUG_TARGET_DISK, |
3519 |
disk, link_name, idx) |
3520 |
changes.append(("disk/%d" % idx, msg))
|
3521 |
|
3522 |
return (disk, changes)
|
3523 |
|
3524 |
def _PostAddDisk(self, _, disk): |
3525 |
if not WaitForSync(self, self.instance, disks=[disk], |
3526 |
oneshot=not self.op.wait_for_sync): |
3527 |
raise errors.OpExecError("Failed to sync disks of %s" % |
3528 |
self.instance.name)
|
3529 |
|
3530 |
# the disk is active at this point, so deactivate it if the instance disks
|
3531 |
# are supposed to be inactive
|
3532 |
if not self.instance.disks_active: |
3533 |
ShutdownInstanceDisks(self, self.instance, disks=[disk]) |
3534 |
|
3535 |
def _ModifyDisk(self, idx, disk, params, _): |
3536 |
"""Modifies a disk.
|
3537 |
|
3538 |
"""
|
3539 |
changes = [] |
3540 |
if constants.IDISK_MODE in params: |
3541 |
disk.mode = params.get(constants.IDISK_MODE) |
3542 |
changes.append(("disk.mode/%d" % idx, disk.mode))
|
3543 |
|
3544 |
if constants.IDISK_NAME in params: |
3545 |
disk.name = params.get(constants.IDISK_NAME) |
3546 |
changes.append(("disk.name/%d" % idx, disk.name))
|
3547 |
|
3548 |
# Modify arbitrary params in case instance template is ext
|
3549 |
for key, value in params.iteritems(): |
3550 |
if (key not in constants.MODIFIABLE_IDISK_PARAMS and |
3551 |
self.instance.disk_template == constants.DT_EXT):
|
3552 |
# stolen from GetUpdatedParams: default means reset/delete
|
3553 |
if value.lower() == constants.VALUE_DEFAULT:
|
3554 |
try:
|
3555 |
del disk.params[key]
|
3556 |
except KeyError: |
3557 |
pass
|
3558 |
else:
|
3559 |
disk.params[key] = value |
3560 |
changes.append(("disk.params:%s/%d" % (key, idx), value))
|
3561 |
|
3562 |
return changes
|
3563 |
|
3564 |
def _RemoveDisk(self, idx, root, _): |
3565 |
"""Removes a disk.
|
3566 |
|
3567 |
"""
|
3568 |
hotmsg = ""
|
3569 |
if self.op.hotplug: |
3570 |
hotmsg = self._HotplugDevice(constants.HOTPLUG_ACTION_REMOVE,
|
3571 |
constants.HOTPLUG_TARGET_DISK, |
3572 |
root, None, idx)
|
3573 |
ShutdownInstanceDisks(self, self.instance, [root]) |
3574 |
|
3575 |
(anno_disk,) = AnnotateDiskParams(self.instance, [root], self.cfg) |
3576 |
for node_uuid, disk in anno_disk.ComputeNodeTree( |
3577 |
self.instance.primary_node):
|
3578 |
msg = self.rpc.call_blockdev_remove(node_uuid, (disk, self.instance)) \ |
3579 |
.fail_msg |
3580 |
if msg:
|
3581 |
self.LogWarning("Could not remove disk/%d on node '%s': %s," |
3582 |
" continuing anyway", idx,
|
3583 |
self.cfg.GetNodeName(node_uuid), msg)
|
3584 |
|
3585 |
# if this is a DRBD disk, return its port to the pool
|
3586 |
if root.dev_type in constants.DTS_DRBD: |
3587 |
self.cfg.AddTcpUdpPort(root.logical_id[2]) |
3588 |
|
3589 |
# Remove disk from config
|
3590 |
self.cfg.RemoveInstDisk(root.uuid)
|
3591 |
|
3592 |
return hotmsg
|
3593 |
|
3594 |
def _CreateNewNic(self, idx, params, private): |
3595 |
"""Creates data structure for a new network interface.
|
3596 |
|
3597 |
"""
|
3598 |
mac = params[constants.INIC_MAC] |
3599 |
ip = params.get(constants.INIC_IP, None)
|
3600 |
net = params.get(constants.INIC_NETWORK, None)
|
3601 |
name = params.get(constants.INIC_NAME, None)
|
3602 |
net_uuid = self.cfg.LookupNetwork(net)
|
3603 |
#TODO: not private.filled?? can a nic have no nicparams??
|
3604 |
nicparams = private.filled |
3605 |
nobj = objects.NIC(mac=mac, ip=ip, network=net_uuid, name=name, |
3606 |
nicparams=nicparams) |
3607 |
nobj.uuid = self.cfg.GenerateUniqueID(self.proc.GetECId()) |
3608 |
|
3609 |
changes = [ |
3610 |
("nic.%d" % idx,
|
3611 |
"add:mac=%s,ip=%s,mode=%s,link=%s,network=%s" %
|
3612 |
(mac, ip, private.filled[constants.NIC_MODE], |
3613 |
private.filled[constants.NIC_LINK], net)), |
3614 |
] |
3615 |
|
3616 |
if self.op.hotplug: |
3617 |
msg = self._HotplugDevice(constants.HOTPLUG_ACTION_ADD,
|
3618 |
constants.HOTPLUG_TARGET_NIC, |
3619 |
nobj, None, idx)
|
3620 |
changes.append(("nic.%d" % idx, msg))
|
3621 |
|
3622 |
return (nobj, changes)
|
3623 |
|
3624 |
def _ApplyNicMods(self, idx, nic, params, private): |
3625 |
"""Modifies a network interface.
|
3626 |
|
3627 |
"""
|
3628 |
changes = [] |
3629 |
|
3630 |
for key in [constants.INIC_MAC, constants.INIC_IP, constants.INIC_NAME]: |
3631 |
if key in params: |
3632 |
changes.append(("nic.%s/%d" % (key, idx), params[key]))
|
3633 |
setattr(nic, key, params[key])
|
3634 |
|
3635 |
new_net = params.get(constants.INIC_NETWORK, nic.network) |
3636 |
new_net_uuid = self.cfg.LookupNetwork(new_net)
|
3637 |
if new_net_uuid != nic.network:
|
3638 |
changes.append(("nic.network/%d" % idx, new_net))
|
3639 |
nic.network = new_net_uuid |
3640 |
|
3641 |
if private.filled:
|
3642 |
nic.nicparams = private.filled |
3643 |
|
3644 |
for (key, val) in nic.nicparams.items(): |
3645 |
changes.append(("nic.%s/%d" % (key, idx), val))
|
3646 |
|
3647 |
if self.op.hotplug: |
3648 |
msg = self._HotplugDevice(constants.HOTPLUG_ACTION_MODIFY,
|
3649 |
constants.HOTPLUG_TARGET_NIC, |
3650 |
nic, None, idx)
|
3651 |
changes.append(("nic/%d" % idx, msg))
|
3652 |
|
3653 |
return changes
|
3654 |
|
3655 |
def _RemoveNic(self, idx, nic, _): |
3656 |
if self.op.hotplug: |
3657 |
return self._HotplugDevice(constants.HOTPLUG_ACTION_REMOVE, |
3658 |
constants.HOTPLUG_TARGET_NIC, |
3659 |
nic, None, idx)
|
3660 |
|
3661 |
def Exec(self, feedback_fn): |
3662 |
"""Modifies an instance.
|
3663 |
|
3664 |
All parameters take effect only at the next restart of the instance.
|
3665 |
|
3666 |
"""
|
3667 |
# Process here the warnings from CheckPrereq, as we don't have a
|
3668 |
# feedback_fn there.
|
3669 |
# TODO: Replace with self.LogWarning
|
3670 |
for warn in self.warn: |
3671 |
feedback_fn("WARNING: %s" % warn)
|
3672 |
|
3673 |
assert ((self.op.disk_template is None) ^ |
3674 |
bool(self.owned_locks(locking.LEVEL_NODE_RES))), \ |
3675 |
"Not owning any node resource locks"
|
3676 |
|
3677 |
result = [] |
3678 |
|
3679 |
# New primary node
|
3680 |
if self.op.pnode_uuid: |
3681 |
self.instance.primary_node = self.op.pnode_uuid |
3682 |
|
3683 |
# runtime memory
|
3684 |
if self.op.runtime_mem: |
3685 |
rpcres = self.rpc.call_instance_balloon_memory(self.instance.primary_node, |
3686 |
self.instance,
|
3687 |
self.op.runtime_mem)
|
3688 |
rpcres.Raise("Cannot modify instance runtime memory")
|
3689 |
result.append(("runtime_memory", self.op.runtime_mem)) |
3690 |
|
3691 |
# Apply disk changes
|
3692 |
inst_disks = self.cfg.GetInstanceDisks(self.instance) |
3693 |
_ApplyContainerMods("disk", inst_disks, result, self.diskmod, |
3694 |
self._CreateNewDisk, self._ModifyDisk, |
3695 |
self._RemoveDisk, post_add_fn=self._PostAddDisk) |
3696 |
|
3697 |
if self.op.disk_template: |
3698 |
if __debug__:
|
3699 |
check_nodes = set(self.cfg.GetInstanceNodes(self.instance)) |
3700 |
if self.op.remote_node_uuid: |
3701 |
check_nodes.add(self.op.remote_node_uuid)
|
3702 |
for level in [locking.LEVEL_NODE, locking.LEVEL_NODE_RES]: |
3703 |
owned = self.owned_locks(level)
|
3704 |
assert not (check_nodes - owned), \ |
3705 |
("Not owning the correct locks, owning %r, expected at least %r" %
|
3706 |
(owned, check_nodes)) |
3707 |
|
3708 |
r_shut = ShutdownInstanceDisks(self, self.instance) |
3709 |
if not r_shut: |
3710 |
raise errors.OpExecError("Cannot shutdown instance disks, unable to" |
3711 |
" proceed with disk template conversion")
|
3712 |
mode = (self.instance.disk_template, self.op.disk_template) |
3713 |
try:
|
3714 |
self._DISK_CONVERSIONS[mode](self, feedback_fn) |
3715 |
except:
|
3716 |
self.cfg.ReleaseDRBDMinors(self.instance.uuid) |
3717 |
raise
|
3718 |
result.append(("disk_template", self.op.disk_template)) |
3719 |
|
3720 |
assert self.instance.disk_template == self.op.disk_template, \ |
3721 |
("Expected disk template '%s', found '%s'" %
|
3722 |
(self.op.disk_template, self.instance.disk_template)) |
3723 |
|
3724 |
# Release node and resource locks if there are any (they might already have
|
3725 |
# been released during disk conversion)
|
3726 |
ReleaseLocks(self, locking.LEVEL_NODE)
|
3727 |
ReleaseLocks(self, locking.LEVEL_NODE_RES)
|
3728 |
|
3729 |
# Apply NIC changes
|
3730 |
if self._new_nics is not None: |
3731 |
self.instance.nics = self._new_nics |
3732 |
result.extend(self._nic_chgdesc)
|
3733 |
|
3734 |
# hvparams changes
|
3735 |
if self.op.hvparams: |
3736 |
self.instance.hvparams = self.hv_inst |
3737 |
for key, val in self.op.hvparams.iteritems(): |
3738 |
result.append(("hv/%s" % key, val))
|
3739 |
|
3740 |
# beparams changes
|
3741 |
if self.op.beparams: |
3742 |
self.instance.beparams = self.be_inst |
3743 |
for key, val in self.op.beparams.iteritems(): |
3744 |
result.append(("be/%s" % key, val))
|
3745 |
|
3746 |
# OS change
|
3747 |
if self.op.os_name: |
3748 |
self.instance.os = self.op.os_name |
3749 |
|
3750 |
# osparams changes
|
3751 |
if self.op.osparams: |
3752 |
self.instance.osparams = self.os_inst |
3753 |
for key, val in self.op.osparams.iteritems(): |
3754 |
result.append(("os/%s" % key, val))
|
3755 |
|
3756 |
if self.op.osparams_private: |
3757 |
self.instance.osparams_private = self.os_inst_private |
3758 |
for key, val in self.op.osparams_private.iteritems(): |
3759 |
# Show the Private(...) blurb.
|
3760 |
result.append(("os_private/%s" % key, repr(val))) |
3761 |
|
3762 |
if self.op.offline is None: |
3763 |
# Ignore
|
3764 |
pass
|
3765 |
elif self.op.offline: |
3766 |
# Mark instance as offline
|
3767 |
self.cfg.MarkInstanceOffline(self.instance.uuid) |
3768 |
result.append(("admin_state", constants.ADMINST_OFFLINE))
|
3769 |
else:
|
3770 |
# Mark instance as online, but stopped
|
3771 |
self.cfg.MarkInstanceDown(self.instance.uuid) |
3772 |
result.append(("admin_state", constants.ADMINST_DOWN))
|
3773 |
|
3774 |
self.cfg.Update(self.instance, feedback_fn, self.proc.GetECId()) |
3775 |
|
3776 |
assert not (self.owned_locks(locking.LEVEL_NODE_RES) or |
3777 |
self.owned_locks(locking.LEVEL_NODE)), \
|
3778 |
"All node locks should have been released by now"
|
3779 |
|
3780 |
return result
|
3781 |
|
3782 |
_DISK_CONVERSIONS = { |
3783 |
(constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd, |
3784 |
(constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain, |
3785 |
} |
3786 |
|
3787 |
|
3788 |
class LUInstanceChangeGroup(LogicalUnit): |
3789 |
HPATH = "instance-change-group"
|
3790 |
HTYPE = constants.HTYPE_INSTANCE |
3791 |
REQ_BGL = False
|
3792 |
|
3793 |
def ExpandNames(self): |
3794 |
self.share_locks = ShareAll()
|
3795 |
|
3796 |
self.needed_locks = {
|
3797 |
locking.LEVEL_NODEGROUP: [], |
3798 |
locking.LEVEL_NODE: [], |
3799 |
locking.LEVEL_NODE_ALLOC: locking.ALL_SET, |
3800 |
} |
3801 |
|
3802 |
self._ExpandAndLockInstance()
|
3803 |
|
3804 |
if self.op.target_groups: |
3805 |
self.req_target_uuids = map(self.cfg.LookupNodeGroup, |
3806 |
self.op.target_groups)
|
3807 |
else:
|
3808 |
self.req_target_uuids = None |
3809 |
|
3810 |
self.op.iallocator = GetDefaultIAllocator(self.cfg, self.op.iallocator) |
3811 |
|
3812 |
def DeclareLocks(self, level): |
3813 |
if level == locking.LEVEL_NODEGROUP:
|
3814 |
assert not self.needed_locks[locking.LEVEL_NODEGROUP] |
3815 |
|
3816 |
if self.req_target_uuids: |
3817 |
lock_groups = set(self.req_target_uuids) |
3818 |
|
3819 |
# Lock all groups used by instance optimistically; this requires going
|
3820 |
# via the node before it's locked, requiring verification later on
|
3821 |
instance_groups = self.cfg.GetInstanceNodeGroups(self.op.instance_uuid) |
3822 |
lock_groups.update(instance_groups) |
3823 |
else:
|
3824 |
# No target groups, need to lock all of them
|
3825 |
lock_groups = locking.ALL_SET |
3826 |
|
3827 |
self.needed_locks[locking.LEVEL_NODEGROUP] = lock_groups
|
3828 |
|
3829 |
elif level == locking.LEVEL_NODE:
|
3830 |
if self.req_target_uuids: |
3831 |
# Lock all nodes used by instances
|
3832 |
self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
|
3833 |
self._LockInstancesNodes()
|
3834 |
|
3835 |
# Lock all nodes in all potential target groups
|
3836 |
lock_groups = (frozenset(self.owned_locks(locking.LEVEL_NODEGROUP)) - |
3837 |
self.cfg.GetInstanceNodeGroups(self.op.instance_uuid)) |
3838 |
member_nodes = [node_uuid |
3839 |
for group in lock_groups |
3840 |
for node_uuid in self.cfg.GetNodeGroup(group).members] |
3841 |
self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
|
3842 |
else:
|
3843 |
# Lock all nodes as all groups are potential targets
|
3844 |
self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
|
3845 |
|
3846 |
def CheckPrereq(self): |
3847 |
owned_instance_names = frozenset(self.owned_locks(locking.LEVEL_INSTANCE)) |
3848 |
owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP)) |
3849 |
owned_nodes = frozenset(self.owned_locks(locking.LEVEL_NODE)) |
3850 |
|
3851 |
assert (self.req_target_uuids is None or |
3852 |
owned_groups.issuperset(self.req_target_uuids))
|
3853 |
assert owned_instance_names == set([self.op.instance_name]) |
3854 |
|
3855 |
# Get instance information
|
3856 |
self.instance = self.cfg.GetInstanceInfo(self.op.instance_uuid) |
3857 |
|
3858 |
# Check if node groups for locked instance are still correct
|
3859 |
assert owned_nodes.issuperset(self.cfg.GetInstanceNodes(self.instance)), \ |
3860 |
("Instance %s's nodes changed while we kept the lock" %
|
3861 |
self.op.instance_name)
|
3862 |
|
3863 |
inst_groups = CheckInstanceNodeGroups(self.cfg, self.op.instance_uuid, |
3864 |
owned_groups) |
3865 |
|
3866 |
if self.req_target_uuids: |
3867 |
# User requested specific target groups
|
3868 |
self.target_uuids = frozenset(self.req_target_uuids) |
3869 |
else:
|
3870 |
# All groups except those used by the instance are potential targets
|
3871 |
self.target_uuids = owned_groups - inst_groups
|
3872 |
|
3873 |
conflicting_groups = self.target_uuids & inst_groups
|
3874 |
if conflicting_groups:
|
3875 |
raise errors.OpPrereqError("Can't use group(s) '%s' as targets, they are" |
3876 |
" used by the instance '%s'" %
|
3877 |
(utils.CommaJoin(conflicting_groups), |
3878 |
self.op.instance_name),
|
3879 |
errors.ECODE_INVAL) |
3880 |
|
3881 |
if not self.target_uuids: |
3882 |
raise errors.OpPrereqError("There are no possible target groups", |
3883 |
errors.ECODE_INVAL) |
3884 |
|
3885 |
def BuildHooksEnv(self): |
3886 |
"""Build hooks env.
|
3887 |
|
3888 |
"""
|
3889 |
assert self.target_uuids |
3890 |
|
3891 |
env = { |
3892 |
"TARGET_GROUPS": " ".join(self.target_uuids), |
3893 |
} |
3894 |
|
3895 |
env.update(BuildInstanceHookEnvByObject(self, self.instance)) |
3896 |
|
3897 |
return env
|
3898 |
|
3899 |
def BuildHooksNodes(self): |
3900 |
"""Build hooks nodes.
|
3901 |
|
3902 |
"""
|
3903 |
mn = self.cfg.GetMasterNode()
|
3904 |
return ([mn], [mn])
|
3905 |
|
3906 |
def Exec(self, feedback_fn): |
3907 |
instances = list(self.owned_locks(locking.LEVEL_INSTANCE)) |
3908 |
|
3909 |
assert instances == [self.op.instance_name], "Instance not locked" |
3910 |
|
3911 |
req = iallocator.IAReqGroupChange(instances=instances, |
3912 |
target_groups=list(self.target_uuids)) |
3913 |
ial = iallocator.IAllocator(self.cfg, self.rpc, req) |
3914 |
|
3915 |
ial.Run(self.op.iallocator)
|
3916 |
|
3917 |
if not ial.success: |
3918 |
raise errors.OpPrereqError("Can't compute solution for changing group of" |
3919 |
" instance '%s' using iallocator '%s': %s" %
|
3920 |
(self.op.instance_name, self.op.iallocator, |
3921 |
ial.info), errors.ECODE_NORES) |
3922 |
|
3923 |
jobs = LoadNodeEvacResult(self, ial.result, self.op.early_release, False) |
3924 |
|
3925 |
self.LogInfo("Iallocator returned %s job(s) for changing group of" |
3926 |
" instance '%s'", len(jobs), self.op.instance_name) |
3927 |
|
3928 |
return ResultWithJobs(jobs)
|