Package ganeti :: Package client :: Module gnt_instance
[hide private]
[frames] | no frames]

Source Code for Module ganeti.client.gnt_instance

   1  # 
   2  # 
   3   
   4  # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014 Google Inc. 
   5  # All rights reserved. 
   6  # 
   7  # Redistribution and use in source and binary forms, with or without 
   8  # modification, are permitted provided that the following conditions are 
   9  # met: 
  10  # 
  11  # 1. Redistributions of source code must retain the above copyright notice, 
  12  # this list of conditions and the following disclaimer. 
  13  # 
  14  # 2. Redistributions in binary form must reproduce the above copyright 
  15  # notice, this list of conditions and the following disclaimer in the 
  16  # documentation and/or other materials provided with the distribution. 
  17  # 
  18  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
  19  # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 
  20  # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
  21  # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
  22  # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
  23  # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
  24  # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
  25  # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
  26  # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
  27  # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
  28  # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  29   
  30  """Instance related commands""" 
  31   
  32  # pylint: disable=W0401,W0614,C0103 
  33  # W0401: Wildcard import ganeti.cli 
  34  # W0614: Unused import %s from wildcard import (since we need cli) 
  35  # C0103: Invalid name gnt-instance 
  36   
  37  import copy 
  38  import itertools 
  39  import simplejson 
  40  import logging 
  41   
  42  from ganeti.cli import * 
  43  from ganeti import opcodes 
  44  from ganeti import constants 
  45  from ganeti import compat 
  46  from ganeti import utils 
  47  from ganeti import errors 
  48  from ganeti import netutils 
  49  from ganeti import ssh 
  50  from ganeti import objects 
  51  from ganeti import ht 
  52   
  53   
  54  _EXPAND_CLUSTER = "cluster" 
  55  _EXPAND_NODES_BOTH = "nodes" 
  56  _EXPAND_NODES_PRI = "nodes-pri" 
  57  _EXPAND_NODES_SEC = "nodes-sec" 
  58  _EXPAND_NODES_BOTH_BY_TAGS = "nodes-by-tags" 
  59  _EXPAND_NODES_PRI_BY_TAGS = "nodes-pri-by-tags" 
  60  _EXPAND_NODES_SEC_BY_TAGS = "nodes-sec-by-tags" 
  61  _EXPAND_INSTANCES = "instances" 
  62  _EXPAND_INSTANCES_BY_TAGS = "instances-by-tags" 
  63   
  64  _EXPAND_NODES_TAGS_MODES = compat.UniqueFrozenset([ 
  65    _EXPAND_NODES_BOTH_BY_TAGS, 
  66    _EXPAND_NODES_PRI_BY_TAGS, 
  67    _EXPAND_NODES_SEC_BY_TAGS, 
  68    ]) 
  69   
  70  #: default list of options for L{ListInstances} 
  71  _LIST_DEF_FIELDS = [ 
  72    "name", "hypervisor", "os", "pnode", "status", "oper_ram", 
  73    ] 
  74   
  75  _MISSING = object() 
  76  _ENV_OVERRIDE = compat.UniqueFrozenset(["list"]) 
  77   
  78  _INST_DATA_VAL = ht.TListOf(ht.TDict) 
  79   
  80   
81 -def _ExpandMultiNames(mode, names, client=None):
82 """Expand the given names using the passed mode. 83 84 For _EXPAND_CLUSTER, all instances will be returned. For 85 _EXPAND_NODES_PRI/SEC, all instances having those nodes as 86 primary/secondary will be returned. For _EXPAND_NODES_BOTH, all 87 instances having those nodes as either primary or secondary will be 88 returned. For _EXPAND_INSTANCES, the given instances will be 89 returned. 90 91 @param mode: one of L{_EXPAND_CLUSTER}, L{_EXPAND_NODES_BOTH}, 92 L{_EXPAND_NODES_PRI}, L{_EXPAND_NODES_SEC} or 93 L{_EXPAND_INSTANCES} 94 @param names: a list of names; for cluster, it must be empty, 95 and for node and instance it must be a list of valid item 96 names (short names are valid as usual, e.g. node1 instead of 97 node1.example.com) 98 @rtype: list 99 @return: the list of names after the expansion 100 @raise errors.ProgrammerError: for unknown selection type 101 @raise errors.OpPrereqError: for invalid input parameters 102 103 """ 104 # pylint: disable=W0142 105 106 if client is None: 107 client = GetClient() 108 if mode == _EXPAND_CLUSTER: 109 if names: 110 raise errors.OpPrereqError("Cluster filter mode takes no arguments", 111 errors.ECODE_INVAL) 112 idata = client.QueryInstances([], ["name"], False) 113 inames = [row[0] for row in idata] 114 115 elif (mode in _EXPAND_NODES_TAGS_MODES or 116 mode in (_EXPAND_NODES_BOTH, _EXPAND_NODES_PRI, _EXPAND_NODES_SEC)): 117 if mode in _EXPAND_NODES_TAGS_MODES: 118 if not names: 119 raise errors.OpPrereqError("No node tags passed", errors.ECODE_INVAL) 120 ndata = client.QueryNodes([], ["name", "pinst_list", 121 "sinst_list", "tags"], False) 122 ndata = [row for row in ndata if set(row[3]).intersection(names)] 123 else: 124 if not names: 125 raise errors.OpPrereqError("No node names passed", errors.ECODE_INVAL) 126 ndata = client.QueryNodes(names, ["name", "pinst_list", "sinst_list"], 127 False) 128 129 ipri = [row[1] for row in ndata] 130 pri_names = list(itertools.chain(*ipri)) 131 isec = [row[2] for row in ndata] 132 sec_names = list(itertools.chain(*isec)) 133 if mode in (_EXPAND_NODES_BOTH, _EXPAND_NODES_BOTH_BY_TAGS): 134 inames = pri_names + sec_names 135 elif mode in (_EXPAND_NODES_PRI, _EXPAND_NODES_PRI_BY_TAGS): 136 inames = pri_names 137 elif mode in (_EXPAND_NODES_SEC, _EXPAND_NODES_SEC_BY_TAGS): 138 inames = sec_names 139 else: 140 raise errors.ProgrammerError("Unhandled shutdown type") 141 elif mode == _EXPAND_INSTANCES: 142 if not names: 143 raise errors.OpPrereqError("No instance names passed", 144 errors.ECODE_INVAL) 145 idata = client.QueryInstances(names, ["name"], False) 146 inames = [row[0] for row in idata] 147 elif mode == _EXPAND_INSTANCES_BY_TAGS: 148 if not names: 149 raise errors.OpPrereqError("No instance tags passed", 150 errors.ECODE_INVAL) 151 idata = client.QueryInstances([], ["name", "tags"], False) 152 inames = [row[0] for row in idata if set(row[1]).intersection(names)] 153 else: 154 raise errors.OpPrereqError("Unknown mode '%s'" % mode, errors.ECODE_INVAL) 155 156 return inames
157 158
159 -def _EnsureInstancesExist(client, names):
160 """Check for and ensure the given instance names exist. 161 162 This function will raise an OpPrereqError in case they don't 163 exist. Otherwise it will exit cleanly. 164 165 @type client: L{ganeti.luxi.Client} 166 @param client: the client to use for the query 167 @type names: list 168 @param names: the list of instance names to query 169 @raise errors.OpPrereqError: in case any instance is missing 170 171 """ 172 # TODO: change LUInstanceQuery to that it actually returns None 173 # instead of raising an exception, or devise a better mechanism 174 result = client.QueryInstances(names, ["name"], False) 175 for orig_name, row in zip(names, result): 176 if row[0] is None: 177 raise errors.OpPrereqError("Instance '%s' does not exist" % orig_name, 178 errors.ECODE_NOENT)
179 180
181 -def GenericManyOps(operation, fn):
182 """Generic multi-instance operations. 183 184 The will return a wrapper that processes the options and arguments 185 given, and uses the passed function to build the opcode needed for 186 the specific operation. Thus all the generic loop/confirmation code 187 is abstracted into this function. 188 189 """ 190 def realfn(opts, args): 191 if opts.multi_mode is None: 192 opts.multi_mode = _EXPAND_INSTANCES 193 cl = GetClient() 194 inames = _ExpandMultiNames(opts.multi_mode, args, client=cl) 195 if not inames: 196 if opts.multi_mode == _EXPAND_CLUSTER: 197 ToStdout("Cluster is empty, no instances to shutdown") 198 return 0 199 raise errors.OpPrereqError("Selection filter does not match" 200 " any instances", errors.ECODE_INVAL) 201 multi_on = opts.multi_mode != _EXPAND_INSTANCES or len(inames) > 1 202 if not (opts.force_multi or not multi_on 203 or ConfirmOperation(inames, "instances", operation)): 204 return 1 205 jex = JobExecutor(verbose=multi_on, cl=cl, opts=opts) 206 for name in inames: 207 op = fn(name, opts) 208 jex.QueueJob(name, op) 209 results = jex.WaitOrShow(not opts.submit_only) 210 rcode = compat.all(row[0] for row in results) 211 return int(not rcode)
212 return realfn 213 214
215 -def ListInstances(opts, args):
216 """List instances and their properties. 217 218 @param opts: the command line options selected by the user 219 @type args: list 220 @param args: should be an empty list 221 @rtype: int 222 @return: the desired exit code 223 224 """ 225 selected_fields = ParseFields(opts.output, _LIST_DEF_FIELDS) 226 227 fmtoverride = dict.fromkeys(["tags", "disk.sizes", "nic.macs", "nic.ips", 228 "nic.modes", "nic.links", "nic.bridges", 229 "nic.networks", 230 "snodes", "snodes.group", "snodes.group.uuid"], 231 (lambda value: ",".join(str(item) 232 for item in value), 233 False)) 234 235 cl = GetClient() 236 237 return GenericList(constants.QR_INSTANCE, selected_fields, args, opts.units, 238 opts.separator, not opts.no_headers, 239 format_override=fmtoverride, verbose=opts.verbose, 240 force_filter=opts.force_filter, cl=cl)
241 242
243 -def ListInstanceFields(opts, args):
244 """List instance fields. 245 246 @param opts: the command line options selected by the user 247 @type args: list 248 @param args: fields to list, or empty for all 249 @rtype: int 250 @return: the desired exit code 251 252 """ 253 return GenericListFields(constants.QR_INSTANCE, args, opts.separator, 254 not opts.no_headers)
255 256
257 -def AddInstance(opts, args):
258 """Add an instance to the cluster. 259 260 This is just a wrapper over L{GenericInstanceCreate}. 261 262 """ 263 return GenericInstanceCreate(constants.INSTANCE_CREATE, opts, args)
264 265
266 -def BatchCreate(opts, args):
267 """Create instances using a definition file. 268 269 This function reads a json file with L{opcodes.OpInstanceCreate} 270 serialisations. 271 272 @param opts: the command line options selected by the user 273 @type args: list 274 @param args: should contain one element, the json filename 275 @rtype: int 276 @return: the desired exit code 277 278 """ 279 (json_filename,) = args 280 cl = GetClient() 281 282 try: 283 instance_data = simplejson.loads(utils.ReadFile(json_filename)) 284 except Exception, err: # pylint: disable=W0703 285 ToStderr("Can't parse the instance definition file: %s" % str(err)) 286 return 1 287 288 if not _INST_DATA_VAL(instance_data): 289 ToStderr("The instance definition file is not %s" % _INST_DATA_VAL) 290 return 1 291 292 instances = [] 293 possible_params = set(opcodes.OpInstanceCreate.GetAllSlots()) 294 for (idx, inst) in enumerate(instance_data): 295 unknown = set(inst.keys()) - possible_params 296 297 if unknown: 298 # TODO: Suggest closest match for more user friendly experience 299 raise errors.OpPrereqError("Unknown fields in definition %s: %s" % 300 (idx, utils.CommaJoin(unknown)), 301 errors.ECODE_INVAL) 302 303 op = opcodes.OpInstanceCreate(**inst) # pylint: disable=W0142 304 op.Validate(False) 305 instances.append(op) 306 307 op = opcodes.OpInstanceMultiAlloc(iallocator=opts.iallocator, 308 instances=instances) 309 result = SubmitOrSend(op, opts, cl=cl) 310 311 # Keep track of submitted jobs 312 jex = JobExecutor(cl=cl, opts=opts) 313 314 for (status, job_id) in result[constants.JOB_IDS_KEY]: 315 jex.AddJobId(None, status, job_id) 316 317 results = jex.GetResults() 318 bad_cnt = len([row for row in results if not row[0]]) 319 if bad_cnt == 0: 320 ToStdout("All instances created successfully.") 321 rcode = constants.EXIT_SUCCESS 322 else: 323 ToStdout("There were %s errors during the creation.", bad_cnt) 324 rcode = constants.EXIT_FAILURE 325 326 return rcode
327 328
329 -def ReinstallInstance(opts, args):
330 """Reinstall an instance. 331 332 @param opts: the command line options selected by the user 333 @type args: list 334 @param args: should contain only one element, the name of the 335 instance to be reinstalled 336 @rtype: int 337 @return: the desired exit code 338 339 """ 340 # first, compute the desired name list 341 if opts.multi_mode is None: 342 opts.multi_mode = _EXPAND_INSTANCES 343 344 inames = _ExpandMultiNames(opts.multi_mode, args) 345 if not inames: 346 raise errors.OpPrereqError("Selection filter does not match any instances", 347 errors.ECODE_INVAL) 348 349 # second, if requested, ask for an OS 350 if opts.select_os is True: 351 op = opcodes.OpOsDiagnose(output_fields=["name", "variants"], names=[]) 352 result = SubmitOpCode(op, opts=opts) 353 354 if not result: 355 ToStdout("Can't get the OS list") 356 return 1 357 358 ToStdout("Available OS templates:") 359 number = 0 360 choices = [] 361 for (name, variants) in result: 362 for entry in CalculateOSNames(name, variants): 363 ToStdout("%3s: %s", number, entry) 364 choices.append(("%s" % number, entry, entry)) 365 number += 1 366 367 choices.append(("x", "exit", "Exit gnt-instance reinstall")) 368 selected = AskUser("Enter OS template number (or x to abort):", 369 choices) 370 371 if selected == "exit": 372 ToStderr("User aborted reinstall, exiting") 373 return 1 374 375 os_name = selected 376 os_msg = "change the OS to '%s'" % selected 377 else: 378 os_name = opts.os 379 if opts.os is not None: 380 os_msg = "change the OS to '%s'" % os_name 381 else: 382 os_msg = "keep the same OS" 383 384 # third, get confirmation: multi-reinstall requires --force-multi, 385 # single-reinstall either --force or --force-multi (--force-multi is 386 # a stronger --force) 387 multi_on = opts.multi_mode != _EXPAND_INSTANCES or len(inames) > 1 388 if multi_on: 389 warn_msg = ("Note: this will remove *all* data for the" 390 " below instances! It will %s.\n" % os_msg) 391 if not (opts.force_multi or 392 ConfirmOperation(inames, "instances", "reinstall", extra=warn_msg)): 393 return 1 394 else: 395 if not (opts.force or opts.force_multi): 396 usertext = ("This will reinstall the instance '%s' (and %s) which" 397 " removes all data. Continue?") % (inames[0], os_msg) 398 if not AskUser(usertext): 399 return 1 400 401 jex = JobExecutor(verbose=multi_on, opts=opts) 402 for instance_name in inames: 403 op = opcodes.OpInstanceReinstall(instance_name=instance_name, 404 os_type=os_name, 405 force_variant=opts.force_variant, 406 osparams=opts.osparams, 407 osparams_private=opts.osparams_private, 408 osparams_secret=opts.osparams_secret) 409 jex.QueueJob(instance_name, op) 410 411 results = jex.WaitOrShow(not opts.submit_only) 412 413 if compat.all(map(compat.fst, results)): 414 return constants.EXIT_SUCCESS 415 else: 416 return constants.EXIT_FAILURE
417 418
419 -def RemoveInstance(opts, args):
420 """Remove an instance. 421 422 @param opts: the command line options selected by the user 423 @type args: list 424 @param args: should contain only one element, the name of 425 the instance to be removed 426 @rtype: int 427 @return: the desired exit code 428 429 """ 430 instance_name = args[0] 431 force = opts.force 432 cl = GetClient() 433 434 if not force: 435 _EnsureInstancesExist(cl, [instance_name]) 436 437 usertext = ("This will remove the volumes of the instance %s" 438 " (including mirrors), thus removing all the data" 439 " of the instance. Continue?") % instance_name 440 if not AskUser(usertext): 441 return 1 442 443 op = opcodes.OpInstanceRemove(instance_name=instance_name, 444 ignore_failures=opts.ignore_failures, 445 shutdown_timeout=opts.shutdown_timeout) 446 SubmitOrSend(op, opts, cl=cl) 447 return 0
448 449
450 -def RenameInstance(opts, args):
451 """Rename an instance. 452 453 @param opts: the command line options selected by the user 454 @type args: list 455 @param args: should contain two elements, the old and the 456 new instance names 457 @rtype: int 458 @return: the desired exit code 459 460 """ 461 if not opts.name_check: 462 if not AskUser("As you disabled the check of the DNS entry, please verify" 463 " that '%s' is a FQDN. Continue?" % args[1]): 464 return 1 465 466 op = opcodes.OpInstanceRename(instance_name=args[0], 467 new_name=args[1], 468 ip_check=opts.ip_check, 469 name_check=opts.name_check) 470 result = SubmitOrSend(op, opts) 471 472 if result: 473 ToStdout("Instance '%s' renamed to '%s'", args[0], result) 474 475 return 0
476 477
478 -def ActivateDisks(opts, args):
479 """Activate an instance's disks. 480 481 This serves two purposes: 482 - it allows (as long as the instance is not running) 483 mounting the disks and modifying them from the node 484 - it repairs inactive secondary drbds 485 486 @param opts: the command line options selected by the user 487 @type args: list 488 @param args: should contain only one element, the instance name 489 @rtype: int 490 @return: the desired exit code 491 492 """ 493 instance_name = args[0] 494 op = opcodes.OpInstanceActivateDisks(instance_name=instance_name, 495 ignore_size=opts.ignore_size, 496 wait_for_sync=opts.wait_for_sync) 497 disks_info = SubmitOrSend(op, opts) 498 for host, iname, nname in disks_info: 499 ToStdout("%s:%s:%s", host, iname, nname) 500 return 0
501 502
503 -def DeactivateDisks(opts, args):
504 """Deactivate an instance's disks. 505 506 This function takes the instance name, looks for its primary node 507 and the tries to shutdown its block devices on that node. 508 509 @param opts: the command line options selected by the user 510 @type args: list 511 @param args: should contain only one element, the instance name 512 @rtype: int 513 @return: the desired exit code 514 515 """ 516 instance_name = args[0] 517 op = opcodes.OpInstanceDeactivateDisks(instance_name=instance_name, 518 force=opts.force) 519 SubmitOrSend(op, opts) 520 return 0
521 522
523 -def RecreateDisks(opts, args):
524 """Recreate an instance's disks. 525 526 @param opts: the command line options selected by the user 527 @type args: list 528 @param args: should contain only one element, the instance name 529 @rtype: int 530 @return: the desired exit code 531 532 """ 533 instance_name = args[0] 534 535 disks = [] 536 537 if opts.disks: 538 for didx, ddict in opts.disks: 539 didx = int(didx) 540 541 if not ht.TDict(ddict): 542 msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict) 543 raise errors.OpPrereqError(msg, errors.ECODE_INVAL) 544 545 if constants.IDISK_SIZE in ddict: 546 try: 547 ddict[constants.IDISK_SIZE] = \ 548 utils.ParseUnit(ddict[constants.IDISK_SIZE]) 549 except ValueError, err: 550 raise errors.OpPrereqError("Invalid disk size for disk %d: %s" % 551 (didx, err), errors.ECODE_INVAL) 552 553 if constants.IDISK_SPINDLES in ddict: 554 try: 555 ddict[constants.IDISK_SPINDLES] = \ 556 int(ddict[constants.IDISK_SPINDLES]) 557 except ValueError, err: 558 raise errors.OpPrereqError("Invalid spindles for disk %d: %s" % 559 (didx, err), errors.ECODE_INVAL) 560 561 disks.append((didx, ddict)) 562 563 # TODO: Verify modifyable parameters (already done in 564 # LUInstanceRecreateDisks, but it'd be nice to have in the client) 565 566 if opts.node: 567 if opts.iallocator: 568 msg = "At most one of either --nodes or --iallocator can be passed" 569 raise errors.OpPrereqError(msg, errors.ECODE_INVAL) 570 pnode, snode = SplitNodeOption(opts.node) 571 nodes = [pnode] 572 if snode is not None: 573 nodes.append(snode) 574 else: 575 nodes = [] 576 577 op = opcodes.OpInstanceRecreateDisks(instance_name=instance_name, 578 disks=disks, nodes=nodes, 579 iallocator=opts.iallocator) 580 SubmitOrSend(op, opts) 581 582 return 0
583 584
585 -def GrowDisk(opts, args):
586 """Grow an instance's disks. 587 588 @param opts: the command line options selected by the user 589 @type args: list 590 @param args: should contain three elements, the target instance name, 591 the target disk id, and the target growth 592 @rtype: int 593 @return: the desired exit code 594 595 """ 596 instance = args[0] 597 disk = args[1] 598 try: 599 disk = int(disk) 600 except (TypeError, ValueError), err: 601 raise errors.OpPrereqError("Invalid disk index: %s" % str(err), 602 errors.ECODE_INVAL) 603 try: 604 amount = utils.ParseUnit(args[2]) 605 except errors.UnitParseError: 606 raise errors.OpPrereqError("Can't parse the given amount '%s'" % args[2], 607 errors.ECODE_INVAL) 608 op = opcodes.OpInstanceGrowDisk(instance_name=instance, 609 disk=disk, amount=amount, 610 wait_for_sync=opts.wait_for_sync, 611 absolute=opts.absolute, 612 ignore_ipolicy=opts.ignore_ipolicy 613 ) 614 SubmitOrSend(op, opts) 615 return 0
616 617
618 -def _StartupInstance(name, opts):
619 """Startup instances. 620 621 This returns the opcode to start an instance, and its decorator will 622 wrap this into a loop starting all desired instances. 623 624 @param name: the name of the instance to act on 625 @param opts: the command line options selected by the user 626 @return: the opcode needed for the operation 627 628 """ 629 op = opcodes.OpInstanceStartup(instance_name=name, 630 force=opts.force, 631 ignore_offline_nodes=opts.ignore_offline, 632 no_remember=opts.no_remember, 633 startup_paused=opts.startup_paused) 634 # do not add these parameters to the opcode unless they're defined 635 if opts.hvparams: 636 op.hvparams = opts.hvparams 637 if opts.beparams: 638 op.beparams = opts.beparams 639 return op
640 641
642 -def _RebootInstance(name, opts):
643 """Reboot instance(s). 644 645 This returns the opcode to reboot an instance, and its decorator 646 will wrap this into a loop rebooting all desired instances. 647 648 @param name: the name of the instance to act on 649 @param opts: the command line options selected by the user 650 @return: the opcode needed for the operation 651 652 """ 653 return opcodes.OpInstanceReboot(instance_name=name, 654 reboot_type=opts.reboot_type, 655 ignore_secondaries=opts.ignore_secondaries, 656 shutdown_timeout=opts.shutdown_timeout)
657 658
659 -def _ShutdownInstance(name, opts):
660 """Shutdown an instance. 661 662 This returns the opcode to shutdown an instance, and its decorator 663 will wrap this into a loop shutting down all desired instances. 664 665 @param name: the name of the instance to act on 666 @param opts: the command line options selected by the user 667 @return: the opcode needed for the operation 668 669 """ 670 return opcodes.OpInstanceShutdown(instance_name=name, 671 force=opts.force, 672 timeout=opts.timeout, 673 ignore_offline_nodes=opts.ignore_offline, 674 no_remember=opts.no_remember)
675 676
677 -def ReplaceDisks(opts, args):
678 """Replace the disks of an instance 679 680 @param opts: the command line options selected by the user 681 @type args: list 682 @param args: should contain only one element, the instance name 683 @rtype: int 684 @return: the desired exit code 685 686 """ 687 new_2ndary = opts.dst_node 688 iallocator = opts.iallocator 689 if opts.disks is None: 690 disks = [] 691 else: 692 try: 693 disks = [int(i) for i in opts.disks.split(",")] 694 except (TypeError, ValueError), err: 695 raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err), 696 errors.ECODE_INVAL) 697 cnt = [opts.on_primary, opts.on_secondary, opts.auto, 698 new_2ndary is not None, iallocator is not None].count(True) 699 if cnt != 1: 700 raise errors.OpPrereqError("One and only one of the -p, -s, -a, -n and -I" 701 " options must be passed", errors.ECODE_INVAL) 702 elif opts.on_primary: 703 mode = constants.REPLACE_DISK_PRI 704 elif opts.on_secondary: 705 mode = constants.REPLACE_DISK_SEC 706 elif opts.auto: 707 mode = constants.REPLACE_DISK_AUTO 708 if disks: 709 raise errors.OpPrereqError("Cannot specify disks when using automatic" 710 " mode", errors.ECODE_INVAL) 711 elif new_2ndary is not None or iallocator is not None: 712 # replace secondary 713 mode = constants.REPLACE_DISK_CHG 714 715 op = opcodes.OpInstanceReplaceDisks(instance_name=args[0], disks=disks, 716 remote_node=new_2ndary, mode=mode, 717 iallocator=iallocator, 718 early_release=opts.early_release, 719 ignore_ipolicy=opts.ignore_ipolicy) 720 SubmitOrSend(op, opts) 721 return 0
722 723
724 -def FailoverInstance(opts, args):
725 """Failover an instance. 726 727 The failover is done by shutting it down on its present node and 728 starting it on the secondary. 729 730 @param opts: the command line options selected by the user 731 @type args: list 732 @param args: should contain only one element, the instance name 733 @rtype: int 734 @return: the desired exit code 735 736 """ 737 cl = GetClient() 738 instance_name = args[0] 739 force = opts.force 740 iallocator = opts.iallocator 741 target_node = opts.dst_node 742 743 if iallocator and target_node: 744 raise errors.OpPrereqError("Specify either an iallocator (-I), or a target" 745 " node (-n) but not both", errors.ECODE_INVAL) 746 747 if not force: 748 _EnsureInstancesExist(cl, [instance_name]) 749 750 usertext = ("Failover will happen to image %s." 751 " This requires a shutdown of the instance. Continue?" % 752 (instance_name,)) 753 if not AskUser(usertext): 754 return 1 755 756 op = opcodes.OpInstanceFailover(instance_name=instance_name, 757 ignore_consistency=opts.ignore_consistency, 758 shutdown_timeout=opts.shutdown_timeout, 759 iallocator=iallocator, 760 target_node=target_node, 761 ignore_ipolicy=opts.ignore_ipolicy) 762 SubmitOrSend(op, opts, cl=cl) 763 return 0
764 765
766 -def MigrateInstance(opts, args):
767 """Migrate an instance. 768 769 The migrate is done without shutdown. 770 771 @param opts: the command line options selected by the user 772 @type args: list 773 @param args: should contain only one element, the instance name 774 @rtype: int 775 @return: the desired exit code 776 777 """ 778 cl = GetClient() 779 instance_name = args[0] 780 force = opts.force 781 iallocator = opts.iallocator 782 target_node = opts.dst_node 783 784 if iallocator and target_node: 785 raise errors.OpPrereqError("Specify either an iallocator (-I), or a target" 786 " node (-n) but not both", errors.ECODE_INVAL) 787 788 if not force: 789 _EnsureInstancesExist(cl, [instance_name]) 790 791 if opts.cleanup: 792 usertext = ("Instance %s will be recovered from a failed migration." 793 " Note that the migration procedure (including cleanup)" % 794 (instance_name,)) 795 else: 796 usertext = ("Instance %s will be migrated. Note that migration" % 797 (instance_name,)) 798 usertext += (" might impact the instance if anything goes wrong" 799 " (e.g. due to bugs in the hypervisor). Continue?") 800 if not AskUser(usertext): 801 return 1 802 803 # this should be removed once --non-live is deprecated 804 if not opts.live and opts.migration_mode is not None: 805 raise errors.OpPrereqError("Only one of the --non-live and " 806 "--migration-mode options can be passed", 807 errors.ECODE_INVAL) 808 if not opts.live: # --non-live passed 809 mode = constants.HT_MIGRATION_NONLIVE 810 else: 811 mode = opts.migration_mode 812 813 op = opcodes.OpInstanceMigrate(instance_name=instance_name, mode=mode, 814 cleanup=opts.cleanup, iallocator=iallocator, 815 target_node=target_node, 816 allow_failover=opts.allow_failover, 817 allow_runtime_changes=opts.allow_runtime_chgs, 818 ignore_ipolicy=opts.ignore_ipolicy) 819 SubmitOrSend(op, cl=cl, opts=opts) 820 return 0
821 822
823 -def MoveInstance(opts, args):
824 """Move an instance. 825 826 @param opts: the command line options selected by the user 827 @type args: list 828 @param args: should contain only one element, the instance name 829 @rtype: int 830 @return: the desired exit code 831 832 """ 833 cl = GetClient() 834 instance_name = args[0] 835 force = opts.force 836 837 if not force: 838 usertext = ("Instance %s will be moved." 839 " This requires a shutdown of the instance. Continue?" % 840 (instance_name,)) 841 if not AskUser(usertext): 842 return 1 843 844 op = opcodes.OpInstanceMove(instance_name=instance_name, 845 target_node=opts.node, 846 compress=opts.compress, 847 shutdown_timeout=opts.shutdown_timeout, 848 ignore_consistency=opts.ignore_consistency, 849 ignore_ipolicy=opts.ignore_ipolicy) 850 SubmitOrSend(op, opts, cl=cl) 851 return 0
852 853
854 -def ConnectToInstanceConsole(opts, args):
855 """Connect to the console of an instance. 856 857 @param opts: the command line options selected by the user 858 @type args: list 859 @param args: should contain only one element, the instance name 860 @rtype: int 861 @return: the desired exit code 862 863 """ 864 instance_name = args[0] 865 866 cl = GetClient() 867 try: 868 cluster_name = cl.QueryConfigValues(["cluster_name"])[0] 869 idata = cl.QueryInstances([instance_name], ["console", "oper_state"], False) 870 if not idata: 871 raise errors.OpPrereqError("Instance '%s' does not exist" % instance_name, 872 errors.ECODE_NOENT) 873 finally: 874 # Ensure client connection is closed while external commands are run 875 cl.Close() 876 877 del cl 878 879 ((console_data, oper_state), ) = idata 880 if not console_data: 881 if oper_state: 882 # Instance is running 883 raise errors.OpExecError("Console information for instance %s is" 884 " unavailable" % instance_name) 885 else: 886 raise errors.OpExecError("Instance %s is not running, can't get console" % 887 instance_name) 888 889 return _DoConsole(objects.InstanceConsole.FromDict(console_data), 890 opts.show_command, cluster_name)
891 892
893 -def _DoConsole(console, show_command, cluster_name, feedback_fn=ToStdout, 894 _runcmd_fn=utils.RunCmd):
895 """Acts based on the result of L{opcodes.OpInstanceConsole}. 896 897 @type console: L{objects.InstanceConsole} 898 @param console: Console object 899 @type show_command: bool 900 @param show_command: Whether to just display commands 901 @type cluster_name: string 902 @param cluster_name: Cluster name as retrieved from master daemon 903 904 """ 905 console.Validate() 906 907 if console.kind == constants.CONS_MESSAGE: 908 feedback_fn(console.message) 909 elif console.kind == constants.CONS_VNC: 910 feedback_fn("Instance %s has VNC listening on %s:%s (display %s)," 911 " URL <vnc://%s:%s/>", 912 console.instance, console.host, console.port, 913 console.display, console.host, console.port) 914 elif console.kind == constants.CONS_SPICE: 915 feedback_fn("Instance %s has SPICE listening on %s:%s", console.instance, 916 console.host, console.port) 917 elif console.kind == constants.CONS_SSH: 918 # Convert to string if not already one 919 if isinstance(console.command, basestring): 920 cmd = console.command 921 else: 922 cmd = utils.ShellQuoteArgs(console.command) 923 924 srun = ssh.SshRunner(cluster_name=cluster_name) 925 ssh_cmd = srun.BuildCmd(console.host, console.user, cmd, 926 port=console.port, 927 batch=True, quiet=False, tty=True) 928 929 if show_command: 930 feedback_fn(utils.ShellQuoteArgs(ssh_cmd)) 931 else: 932 result = _runcmd_fn(ssh_cmd, interactive=True) 933 if result.failed: 934 logging.error("Console command \"%s\" failed with reason '%s' and" 935 " output %r", result.cmd, result.fail_reason, 936 result.output) 937 raise errors.OpExecError("Connection to console of instance %s failed," 938 " please check cluster configuration" % 939 console.instance) 940 else: 941 raise errors.GenericError("Unknown console type '%s'" % console.kind) 942 943 return constants.EXIT_SUCCESS
944 945
946 -def _FormatDiskDetails(dev_type, dev, roman):
947 """Formats the logical_id of a disk. 948 949 """ 950 951 if dev_type == constants.DT_DRBD8: 952 drbd_info = dev["drbd_info"] 953 data = [ 954 ("nodeA", "%s, minor=%s" % 955 (drbd_info["primary_node"], 956 compat.TryToRoman(drbd_info["primary_minor"], 957 convert=roman))), 958 ("nodeB", "%s, minor=%s" % 959 (drbd_info["secondary_node"], 960 compat.TryToRoman(drbd_info["secondary_minor"], 961 convert=roman))), 962 ("port", str(compat.TryToRoman(drbd_info["port"], convert=roman))), 963 ] 964 elif dev_type == constants.DT_PLAIN: 965 vg_name, lv_name = dev["logical_id"] 966 data = ["%s/%s" % (vg_name, lv_name)] 967 else: 968 data = [str(dev["logical_id"])] 969 970 return data
971 972
973 -def _FormatBlockDevInfo(idx, top_level, dev, roman):
974 """Show block device information. 975 976 This is only used by L{ShowInstanceConfig}, but it's too big to be 977 left for an inline definition. 978 979 @type idx: int 980 @param idx: the index of the current disk 981 @type top_level: boolean 982 @param top_level: if this a top-level disk? 983 @type dev: dict 984 @param dev: dictionary with disk information 985 @type roman: boolean 986 @param roman: whether to try to use roman integers 987 @return: a list of either strings, tuples or lists 988 (which should be formatted at a higher indent level) 989 990 """ 991 def helper(dtype, status): 992 """Format one line for physical device status. 993 994 @type dtype: str 995 @param dtype: a constant from the L{constants.DTS_BLOCK} set 996 @type status: tuple 997 @param status: a tuple as returned from L{backend.FindBlockDevice} 998 @return: the string representing the status 999 1000 """ 1001 if not status: 1002 return "not active" 1003 txt = "" 1004 (path, major, minor, syncp, estt, degr, ldisk_status) = status 1005 if major is None: 1006 major_string = "N/A" 1007 else: 1008 major_string = str(compat.TryToRoman(major, convert=roman)) 1009 1010 if minor is None: 1011 minor_string = "N/A" 1012 else: 1013 minor_string = str(compat.TryToRoman(minor, convert=roman)) 1014 1015 txt += ("%s (%s:%s)" % (path, major_string, minor_string)) 1016 if dtype in (constants.DT_DRBD8, ): 1017 if syncp is not None: 1018 sync_text = "*RECOVERING* %5.2f%%," % syncp 1019 if estt: 1020 sync_text += " ETA %ss" % compat.TryToRoman(estt, convert=roman) 1021 else: 1022 sync_text += " ETA unknown" 1023 else: 1024 sync_text = "in sync" 1025 if degr: 1026 degr_text = "*DEGRADED*" 1027 else: 1028 degr_text = "ok" 1029 if ldisk_status == constants.LDS_FAULTY: 1030 ldisk_text = " *MISSING DISK*" 1031 elif ldisk_status == constants.LDS_UNKNOWN: 1032 ldisk_text = " *UNCERTAIN STATE*" 1033 else: 1034 ldisk_text = "" 1035 txt += (" %s, status %s%s" % (sync_text, degr_text, ldisk_text)) 1036 elif dtype == constants.DT_PLAIN: 1037 if ldisk_status == constants.LDS_FAULTY: 1038 ldisk_text = " *FAILED* (failed drive?)" 1039 else: 1040 ldisk_text = "" 1041 txt += ldisk_text 1042 return txt
1043 1044 # the header 1045 if top_level: 1046 if dev["iv_name"] is not None: 1047 txt = dev["iv_name"] 1048 else: 1049 txt = "disk %s" % compat.TryToRoman(idx, convert=roman) 1050 else: 1051 txt = "child %s" % compat.TryToRoman(idx, convert=roman) 1052 if isinstance(dev["size"], int): 1053 nice_size = utils.FormatUnit(dev["size"], "h", roman) 1054 else: 1055 nice_size = str(dev["size"]) 1056 data = [(txt, "%s, size %s" % (dev["dev_type"], nice_size))] 1057 if top_level: 1058 if dev["spindles"] is not None: 1059 data.append(("spindles", dev["spindles"])) 1060 data.append(("access mode", dev["mode"])) 1061 if dev["logical_id"] is not None: 1062 try: 1063 l_id = _FormatDiskDetails(dev["dev_type"], dev, roman) 1064 except ValueError: 1065 l_id = [str(dev["logical_id"])] 1066 if len(l_id) == 1: 1067 data.append(("logical_id", l_id[0])) 1068 else: 1069 data.extend(l_id) 1070 1071 if dev["pstatus"]: 1072 data.append(("on primary", helper(dev["dev_type"], dev["pstatus"]))) 1073 1074 if dev["sstatus"]: 1075 data.append(("on secondary", helper(dev["dev_type"], dev["sstatus"]))) 1076 1077 data.append(("name", dev["name"])) 1078 data.append(("UUID", dev["uuid"])) 1079 1080 if dev["children"]: 1081 data.append(("child devices", [ 1082 _FormatBlockDevInfo(c_idx, False, child, roman) 1083 for c_idx, child in enumerate(dev["children"]) 1084 ])) 1085 return data 1086 1087
1088 -def _FormatInstanceNicInfo(idx, nic, roman=False):
1089 """Helper function for L{_FormatInstanceInfo()}""" 1090 (name, uuid, ip, mac, mode, link, vlan, _, netinfo) = nic 1091 network_name = None 1092 if netinfo: 1093 network_name = netinfo["name"] 1094 return [ 1095 ("nic/%s" % str(compat.TryToRoman(idx, roman)), ""), 1096 ("MAC", str(mac)), 1097 ("IP", str(ip)), 1098 ("mode", str(mode)), 1099 ("link", str(link)), 1100 ("vlan", str(compat.TryToRoman(vlan, roman))), 1101 ("network", str(network_name)), 1102 ("UUID", str(uuid)), 1103 ("name", str(name)), 1104 ]
1105 1106
1107 -def _FormatInstanceNodesInfo(instance):
1108 """Helper function for L{_FormatInstanceInfo()}""" 1109 pgroup = ("%s (UUID %s)" % 1110 (instance["pnode_group_name"], instance["pnode_group_uuid"])) 1111 secs = utils.CommaJoin(("%s (group %s, group UUID %s)" % 1112 (name, group_name, group_uuid)) 1113 for (name, group_name, group_uuid) in 1114 zip(instance["snodes"], 1115 instance["snodes_group_names"], 1116 instance["snodes_group_uuids"])) 1117 return [ 1118 [ 1119 ("primary", instance["pnode"]), 1120 ("group", pgroup), 1121 ], 1122 [("secondaries", secs)], 1123 ]
1124 1125
1126 -def _GetVncConsoleInfo(instance):
1127 """Helper function for L{_FormatInstanceInfo()}""" 1128 vnc_bind_address = instance["hv_actual"].get(constants.HV_VNC_BIND_ADDRESS, 1129 None) 1130 if vnc_bind_address: 1131 port = instance["network_port"] 1132 display = int(port) - constants.VNC_BASE_PORT 1133 if display > 0 and vnc_bind_address == constants.IP4_ADDRESS_ANY: 1134 vnc_console_port = "%s:%s (display %s)" % (instance["pnode"], 1135 port, 1136 display) 1137 elif display > 0 and netutils.IP4Address.IsValid(vnc_bind_address): 1138 vnc_console_port = ("%s:%s (node %s) (display %s)" % 1139 (vnc_bind_address, port, 1140 instance["pnode"], display)) 1141 else: 1142 # vnc bind address is a file 1143 vnc_console_port = "%s:%s" % (instance["pnode"], 1144 vnc_bind_address) 1145 ret = "vnc to %s" % vnc_console_port 1146 else: 1147 ret = None 1148 return ret
1149 1150
1151 -def _FormatInstanceInfo(instance, roman_integers):
1152 """Format instance information for L{cli.PrintGenericInfo()}""" 1153 istate = "configured to be %s" % instance["config_state"] 1154 if instance["run_state"]: 1155 istate += ", actual state is %s" % instance["run_state"] 1156 info = [ 1157 ("Instance name", instance["name"]), 1158 ("UUID", instance["uuid"]), 1159 ("Serial number", 1160 str(compat.TryToRoman(instance["serial_no"], convert=roman_integers))), 1161 ("Creation time", utils.FormatTime(instance["ctime"])), 1162 ("Modification time", utils.FormatTime(instance["mtime"])), 1163 ("State", istate), 1164 ("Nodes", _FormatInstanceNodesInfo(instance)), 1165 ("Operating system", instance["os"]), 1166 ("Operating system parameters", 1167 FormatParamsDictInfo(instance["os_instance"], instance["os_actual"], 1168 roman_integers)), 1169 ] 1170 1171 if "network_port" in instance: 1172 info.append(("Allocated network port", 1173 str(compat.TryToRoman(instance["network_port"], 1174 convert=roman_integers)))) 1175 info.append(("Hypervisor", instance["hypervisor"])) 1176 console = _GetVncConsoleInfo(instance) 1177 if console: 1178 info.append(("console connection", console)) 1179 # deprecated "memory" value, kept for one version for compatibility 1180 # TODO(ganeti 2.7) remove. 1181 be_actual = copy.deepcopy(instance["be_actual"]) 1182 be_actual["memory"] = be_actual[constants.BE_MAXMEM] 1183 info.extend([ 1184 ("Hypervisor parameters", 1185 FormatParamsDictInfo(instance["hv_instance"], instance["hv_actual"], 1186 roman_integers)), 1187 ("Back-end parameters", 1188 FormatParamsDictInfo(instance["be_instance"], be_actual, 1189 roman_integers)), 1190 ("NICs", [ 1191 _FormatInstanceNicInfo(idx, nic, roman_integers) 1192 for (idx, nic) in enumerate(instance["nics"]) 1193 ]), 1194 ("Disk template", instance["disk_template"]), 1195 ("Disks", [ 1196 _FormatBlockDevInfo(idx, True, device, roman_integers) 1197 for (idx, device) in enumerate(instance["disks"]) 1198 ]), 1199 ]) 1200 return info
1201 1202
1203 -def ShowInstanceConfig(opts, args):
1204 """Compute instance run-time status. 1205 1206 @param opts: the command line options selected by the user 1207 @type args: list 1208 @param args: either an empty list, and then we query all 1209 instances, or should contain a list of instance names 1210 @rtype: int 1211 @return: the desired exit code 1212 1213 """ 1214 if not args and not opts.show_all: 1215 ToStderr("No instance selected." 1216 " Please pass in --all if you want to query all instances.\n" 1217 "Note that this can take a long time on a big cluster.") 1218 return 1 1219 elif args and opts.show_all: 1220 ToStderr("Cannot use --all if you specify instance names.") 1221 return 1 1222 1223 retcode = 0 1224 op = opcodes.OpInstanceQueryData(instances=args, static=opts.static, 1225 use_locking=not opts.static) 1226 result = SubmitOpCode(op, opts=opts) 1227 if not result: 1228 ToStdout("No instances.") 1229 return 1 1230 1231 PrintGenericInfo([ 1232 _FormatInstanceInfo(instance, opts.roman_integers) 1233 for instance in result.values() 1234 ]) 1235 return retcode
1236 1237
1238 -def _ConvertNicDiskModifications(mods):
1239 """Converts NIC/disk modifications from CLI to opcode. 1240 1241 When L{opcodes.OpInstanceSetParams} was changed to support adding/removing 1242 disks at arbitrary indices, its parameter format changed. This function 1243 converts legacy requests (e.g. "--net add" or "--disk add:size=4G") to the 1244 newer format and adds support for new-style requests (e.g. "--new 4:add"). 1245 1246 @type mods: list of tuples 1247 @param mods: Modifications as given by command line parser 1248 @rtype: list of tuples 1249 @return: Modifications as understood by L{opcodes.OpInstanceSetParams} 1250 1251 """ 1252 result = [] 1253 1254 for (identifier, params) in mods: 1255 if identifier == constants.DDM_ADD: 1256 # Add item as last item (legacy interface) 1257 action = constants.DDM_ADD 1258 identifier = -1 1259 elif identifier == constants.DDM_REMOVE: 1260 # Remove last item (legacy interface) 1261 action = constants.DDM_REMOVE 1262 identifier = -1 1263 else: 1264 # Modifications and adding/removing at arbitrary indices 1265 add = params.pop(constants.DDM_ADD, _MISSING) 1266 remove = params.pop(constants.DDM_REMOVE, _MISSING) 1267 modify = params.pop(constants.DDM_MODIFY, _MISSING) 1268 1269 if modify is _MISSING: 1270 if not (add is _MISSING or remove is _MISSING): 1271 raise errors.OpPrereqError("Cannot add and remove at the same time", 1272 errors.ECODE_INVAL) 1273 elif add is not _MISSING: 1274 action = constants.DDM_ADD 1275 elif remove is not _MISSING: 1276 action = constants.DDM_REMOVE 1277 else: 1278 action = constants.DDM_MODIFY 1279 1280 elif add is _MISSING and remove is _MISSING: 1281 action = constants.DDM_MODIFY 1282 else: 1283 raise errors.OpPrereqError("Cannot modify and add/remove at the" 1284 " same time", errors.ECODE_INVAL) 1285 1286 assert not (constants.DDMS_VALUES_WITH_MODIFY & set(params.keys())) 1287 1288 if action == constants.DDM_REMOVE and params: 1289 raise errors.OpPrereqError("Not accepting parameters on removal", 1290 errors.ECODE_INVAL) 1291 1292 result.append((action, identifier, params)) 1293 1294 return result
1295 1296
1297 -def _ParseDiskSizes(mods):
1298 """Parses disk sizes in parameters. 1299 1300 """ 1301 for (action, _, params) in mods: 1302 if params and constants.IDISK_SPINDLES in params: 1303 params[constants.IDISK_SPINDLES] = \ 1304 int(params[constants.IDISK_SPINDLES]) 1305 if params and constants.IDISK_SIZE in params: 1306 params[constants.IDISK_SIZE] = \ 1307 utils.ParseUnit(params[constants.IDISK_SIZE]) 1308 elif action == constants.DDM_ADD: 1309 raise errors.OpPrereqError("Missing required parameter 'size'", 1310 errors.ECODE_INVAL) 1311 1312 return mods
1313 1314
1315 -def SetInstanceParams(opts, args):
1316 """Modifies an instance. 1317 1318 All parameters take effect only at the next restart of the instance. 1319 1320 @param opts: the command line options selected by the user 1321 @type args: list 1322 @param args: should contain only one element, the instance name 1323 @rtype: int 1324 @return: the desired exit code 1325 1326 """ 1327 if not (opts.nics or opts.disks or opts.disk_template or opts.hvparams or 1328 opts.beparams or opts.os or opts.osparams or opts.osparams_private 1329 or opts.offline_inst or opts.online_inst or opts.runtime_mem or 1330 opts.new_primary_node or opts.instance_communication is not None): 1331 ToStderr("Please give at least one of the parameters.") 1332 return 1 1333 1334 for param in opts.beparams: 1335 if isinstance(opts.beparams[param], basestring): 1336 if opts.beparams[param].lower() == "default": 1337 opts.beparams[param] = constants.VALUE_DEFAULT 1338 1339 utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_COMPAT, 1340 allowed_values=[constants.VALUE_DEFAULT]) 1341 1342 for param in opts.hvparams: 1343 if isinstance(opts.hvparams[param], basestring): 1344 if opts.hvparams[param].lower() == "default": 1345 opts.hvparams[param] = constants.VALUE_DEFAULT 1346 1347 utils.ForceDictType(opts.hvparams, constants.HVS_PARAMETER_TYPES, 1348 allowed_values=[constants.VALUE_DEFAULT]) 1349 FixHvParams(opts.hvparams) 1350 1351 nics = _ConvertNicDiskModifications(opts.nics) 1352 for action, _, __ in nics: 1353 if action == constants.DDM_MODIFY and opts.hotplug and not opts.force: 1354 usertext = ("You are about to hot-modify a NIC. This will be done" 1355 " by removing the existing NIC and then adding a new one." 1356 " Network connection might be lost. Continue?") 1357 if not AskUser(usertext): 1358 return 1 1359 1360 disks = _ParseDiskSizes(_ConvertNicDiskModifications(opts.disks)) 1361 1362 if (opts.disk_template and 1363 opts.disk_template in constants.DTS_INT_MIRROR and 1364 not opts.node): 1365 ToStderr("Changing the disk template to a mirrored one requires" 1366 " specifying a secondary node") 1367 return 1 1368 1369 if opts.offline_inst: 1370 offline = True 1371 elif opts.online_inst: 1372 offline = False 1373 else: 1374 offline = None 1375 1376 instance_comm = opts.instance_communication 1377 1378 op = opcodes.OpInstanceSetParams(instance_name=args[0], 1379 nics=nics, 1380 disks=disks, 1381 hotplug=opts.hotplug, 1382 hotplug_if_possible=opts.hotplug_if_possible, 1383 disk_template=opts.disk_template, 1384 remote_node=opts.node, 1385 pnode=opts.new_primary_node, 1386 hvparams=opts.hvparams, 1387 beparams=opts.beparams, 1388 runtime_mem=opts.runtime_mem, 1389 os_name=opts.os, 1390 osparams=opts.osparams, 1391 osparams_private=opts.osparams_private, 1392 force_variant=opts.force_variant, 1393 force=opts.force, 1394 wait_for_sync=opts.wait_for_sync, 1395 offline=offline, 1396 conflicts_check=opts.conflicts_check, 1397 ignore_ipolicy=opts.ignore_ipolicy, 1398 instance_communication=instance_comm) 1399 1400 # even if here we process the result, we allow submit only 1401 result = SubmitOrSend(op, opts) 1402 1403 if result: 1404 ToStdout("Modified instance %s", args[0]) 1405 for param, data in result: 1406 ToStdout(" - %-5s -> %s", param, data) 1407 ToStdout("Please don't forget that most parameters take effect" 1408 " only at the next (re)start of the instance initiated by" 1409 " ganeti; restarting from within the instance will" 1410 " not be enough.") 1411 if opts.hvparams: 1412 ToStdout("Note that changing hypervisor parameters without performing a" 1413 " restart might lead to a crash while performing a live" 1414 " migration. This will be addressed in future Ganeti versions.") 1415 return 0
1416 1417
1418 -def ChangeGroup(opts, args):
1419 """Moves an instance to another group. 1420 1421 """ 1422 (instance_name, ) = args 1423 1424 cl = GetClient() 1425 1426 op = opcodes.OpInstanceChangeGroup(instance_name=instance_name, 1427 iallocator=opts.iallocator, 1428 target_groups=opts.to, 1429 early_release=opts.early_release) 1430 result = SubmitOrSend(op, opts, cl=cl) 1431 1432 # Keep track of submitted jobs 1433 jex = JobExecutor(cl=cl, opts=opts) 1434 1435 for (status, job_id) in result[constants.JOB_IDS_KEY]: 1436 jex.AddJobId(None, status, job_id) 1437 1438 results = jex.GetResults() 1439 bad_cnt = len([row for row in results if not row[0]]) 1440 if bad_cnt == 0: 1441 ToStdout("Instance '%s' changed group successfully.", instance_name) 1442 rcode = constants.EXIT_SUCCESS 1443 else: 1444 ToStdout("There were %s errors while changing group of instance '%s'.", 1445 bad_cnt, instance_name) 1446 rcode = constants.EXIT_FAILURE 1447 1448 return rcode
1449 1450 1451 # multi-instance selection options 1452 m_force_multi = cli_option("--force-multiple", dest="force_multi", 1453 help="Do not ask for confirmation when more than" 1454 " one instance is affected", 1455 action="store_true", default=False) 1456 1457 m_pri_node_opt = cli_option("--primary", dest="multi_mode", 1458 help="Filter by nodes (primary only)", 1459 const=_EXPAND_NODES_PRI, action="store_const") 1460 1461 m_sec_node_opt = cli_option("--secondary", dest="multi_mode", 1462 help="Filter by nodes (secondary only)", 1463 const=_EXPAND_NODES_SEC, action="store_const") 1464 1465 m_node_opt = cli_option("--node", dest="multi_mode", 1466 help="Filter by nodes (primary and secondary)", 1467 const=_EXPAND_NODES_BOTH, action="store_const") 1468 1469 m_clust_opt = cli_option("--all", dest="multi_mode", 1470 help="Select all instances in the cluster", 1471 const=_EXPAND_CLUSTER, action="store_const") 1472 1473 m_inst_opt = cli_option("--instance", dest="multi_mode", 1474 help="Filter by instance name [default]", 1475 const=_EXPAND_INSTANCES, action="store_const") 1476 1477 m_node_tags_opt = cli_option("--node-tags", dest="multi_mode", 1478 help="Filter by node tag", 1479 const=_EXPAND_NODES_BOTH_BY_TAGS, 1480 action="store_const") 1481 1482 m_pri_node_tags_opt = cli_option("--pri-node-tags", dest="multi_mode", 1483 help="Filter by primary node tag", 1484 const=_EXPAND_NODES_PRI_BY_TAGS, 1485 action="store_const") 1486 1487 m_sec_node_tags_opt = cli_option("--sec-node-tags", dest="multi_mode", 1488 help="Filter by secondary node tag", 1489 const=_EXPAND_NODES_SEC_BY_TAGS, 1490 action="store_const") 1491 1492 m_inst_tags_opt = cli_option("--tags", dest="multi_mode", 1493 help="Filter by instance tag", 1494 const=_EXPAND_INSTANCES_BY_TAGS, 1495 action="store_const") 1496 1497 # this is defined separately due to readability only 1498 add_opts = [ 1499 NOSTART_OPT, 1500 OS_OPT, 1501 FORCE_VARIANT_OPT, 1502 NO_INSTALL_OPT, 1503 IGNORE_IPOLICY_OPT, 1504 INSTANCE_COMMUNICATION_OPT, 1505 HELPER_STARTUP_TIMEOUT_OPT, 1506 HELPER_SHUTDOWN_TIMEOUT_OPT, 1507 ] 1508 1509 commands = { 1510 "add": ( 1511 AddInstance, [ArgHost(min=1, max=1)], 1512 COMMON_CREATE_OPTS + add_opts, 1513 "[...] -t disk-type -n node[:secondary-node] -o os-type <name>", 1514 "Creates and adds a new instance to the cluster"), 1515 "batch-create": ( 1516 BatchCreate, [ArgFile(min=1, max=1)], 1517 [DRY_RUN_OPT, PRIORITY_OPT, IALLOCATOR_OPT] + SUBMIT_OPTS, 1518 "<instances.json>", 1519 "Create a bunch of instances based on specs in the file."), 1520 "console": ( 1521 ConnectToInstanceConsole, ARGS_ONE_INSTANCE, 1522 [SHOWCMD_OPT, PRIORITY_OPT], 1523 "[--show-cmd] <instance>", "Opens a console on the specified instance"), 1524 "failover": ( 1525 FailoverInstance, ARGS_ONE_INSTANCE, 1526 [FORCE_OPT, IGNORE_CONSIST_OPT] + SUBMIT_OPTS + 1527 [SHUTDOWN_TIMEOUT_OPT, 1528 DRY_RUN_OPT, PRIORITY_OPT, DST_NODE_OPT, IALLOCATOR_OPT, 1529 IGNORE_IPOLICY_OPT, CLEANUP_OPT], 1530 "[-f] <instance>", "Stops the instance, changes its primary node and" 1531 " (if it was originally running) starts it on the new node" 1532 " (the secondary for mirrored instances or any node" 1533 " for shared storage)."), 1534 "migrate": ( 1535 MigrateInstance, ARGS_ONE_INSTANCE, 1536 [FORCE_OPT, NONLIVE_OPT, MIGRATION_MODE_OPT, CLEANUP_OPT, DRY_RUN_OPT, 1537 PRIORITY_OPT, DST_NODE_OPT, IALLOCATOR_OPT, ALLOW_FAILOVER_OPT, 1538 IGNORE_IPOLICY_OPT, NORUNTIME_CHGS_OPT] + SUBMIT_OPTS, 1539 "[-f] <instance>", "Migrate instance to its secondary node" 1540 " (only for mirrored instances)"), 1541 "move": ( 1542 MoveInstance, ARGS_ONE_INSTANCE, 1543 [FORCE_OPT] + SUBMIT_OPTS + 1544 [SINGLE_NODE_OPT, COMPRESS_OPT, 1545 SHUTDOWN_TIMEOUT_OPT, DRY_RUN_OPT, PRIORITY_OPT, IGNORE_CONSIST_OPT, 1546 IGNORE_IPOLICY_OPT], 1547 "[-f] <instance>", "Move instance to an arbitrary node" 1548 " (only for instances of type file and lv)"), 1549 "info": ( 1550 ShowInstanceConfig, ARGS_MANY_INSTANCES, 1551 [STATIC_OPT, ALL_OPT, ROMAN_OPT, PRIORITY_OPT], 1552 "[-s] {--all | <instance>...}", 1553 "Show information on the specified instance(s)"), 1554 "list": ( 1555 ListInstances, ARGS_MANY_INSTANCES, 1556 [NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, VERBOSE_OPT, 1557 FORCE_FILTER_OPT], 1558 "[<instance>...]", 1559 "Lists the instances and their status. The available fields can be shown" 1560 " using the \"list-fields\" command (see the man page for details)." 1561 " The default field list is (in order): %s." % 1562 utils.CommaJoin(_LIST_DEF_FIELDS), 1563 ), 1564 "list-fields": ( 1565 ListInstanceFields, [ArgUnknown()], 1566 [NOHDR_OPT, SEP_OPT], 1567 "[fields...]", 1568 "Lists all available fields for instances"), 1569 "reinstall": ( 1570 ReinstallInstance, [ArgInstance()], 1571 [FORCE_OPT, OS_OPT, FORCE_VARIANT_OPT, m_force_multi, m_node_opt, 1572 m_pri_node_opt, m_sec_node_opt, m_clust_opt, m_inst_opt, m_node_tags_opt, 1573 m_pri_node_tags_opt, m_sec_node_tags_opt, m_inst_tags_opt, SELECT_OS_OPT] 1574 + SUBMIT_OPTS + [DRY_RUN_OPT, PRIORITY_OPT, OSPARAMS_OPT, 1575 OSPARAMS_PRIVATE_OPT, OSPARAMS_SECRET_OPT], 1576 "[-f] <instance>", "Reinstall a stopped instance"), 1577 "remove": ( 1578 RemoveInstance, ARGS_ONE_INSTANCE, 1579 [FORCE_OPT, SHUTDOWN_TIMEOUT_OPT, IGNORE_FAILURES_OPT] + SUBMIT_OPTS 1580 + [DRY_RUN_OPT, PRIORITY_OPT], 1581 "[-f] <instance>", "Shuts down the instance and removes it"), 1582 "rename": ( 1583 RenameInstance, 1584 [ArgInstance(min=1, max=1), ArgHost(min=1, max=1)], 1585 [NOIPCHECK_OPT, NONAMECHECK_OPT] + SUBMIT_OPTS 1586 + [DRY_RUN_OPT, PRIORITY_OPT], 1587 "<instance> <new_name>", "Rename the instance"), 1588 "replace-disks": ( 1589 ReplaceDisks, ARGS_ONE_INSTANCE, 1590 [AUTO_REPLACE_OPT, DISKIDX_OPT, IALLOCATOR_OPT, EARLY_RELEASE_OPT, 1591 NEW_SECONDARY_OPT, ON_PRIMARY_OPT, ON_SECONDARY_OPT] + SUBMIT_OPTS 1592 + [DRY_RUN_OPT, PRIORITY_OPT, IGNORE_IPOLICY_OPT], 1593 "[-s|-p|-a|-n NODE|-I NAME] <instance>", 1594 "Replaces disks for the instance"), 1595 "modify": ( 1596 SetInstanceParams, ARGS_ONE_INSTANCE, 1597 [BACKEND_OPT, DISK_OPT, FORCE_OPT, HVOPTS_OPT, NET_OPT] + SUBMIT_OPTS + 1598 [DISK_TEMPLATE_OPT, SINGLE_NODE_OPT, OS_OPT, FORCE_VARIANT_OPT, 1599 OSPARAMS_OPT, OSPARAMS_PRIVATE_OPT, DRY_RUN_OPT, PRIORITY_OPT, NWSYNC_OPT, 1600 OFFLINE_INST_OPT, ONLINE_INST_OPT, IGNORE_IPOLICY_OPT, RUNTIME_MEM_OPT, 1601 NOCONFLICTSCHECK_OPT, NEW_PRIMARY_OPT, HOTPLUG_OPT, 1602 HOTPLUG_IF_POSSIBLE_OPT, INSTANCE_COMMUNICATION_OPT], 1603 "<instance>", "Alters the parameters of an instance"), 1604 "shutdown": ( 1605 GenericManyOps("shutdown", _ShutdownInstance), [ArgInstance()], 1606 [FORCE_OPT, m_node_opt, m_pri_node_opt, m_sec_node_opt, m_clust_opt, 1607 m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt, 1608 m_inst_tags_opt, m_inst_opt, m_force_multi, TIMEOUT_OPT] + SUBMIT_OPTS 1609 + [DRY_RUN_OPT, PRIORITY_OPT, IGNORE_OFFLINE_OPT, NO_REMEMBER_OPT], 1610 "<instance>", "Stops an instance"), 1611 "startup": ( 1612 GenericManyOps("startup", _StartupInstance), [ArgInstance()], 1613 [FORCE_OPT, m_force_multi, m_node_opt, m_pri_node_opt, m_sec_node_opt, 1614 m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt, 1615 m_inst_tags_opt, m_clust_opt, m_inst_opt] + SUBMIT_OPTS + 1616 [HVOPTS_OPT, 1617 BACKEND_OPT, DRY_RUN_OPT, PRIORITY_OPT, IGNORE_OFFLINE_OPT, 1618 NO_REMEMBER_OPT, STARTUP_PAUSED_OPT], 1619 "<instance>", "Starts an instance"), 1620 "reboot": ( 1621 GenericManyOps("reboot", _RebootInstance), [ArgInstance()], 1622 [m_force_multi, REBOOT_TYPE_OPT, IGNORE_SECONDARIES_OPT, m_node_opt, 1623 m_pri_node_opt, m_sec_node_opt, m_clust_opt, m_inst_opt] + SUBMIT_OPTS + 1624 [m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt, 1625 m_inst_tags_opt, SHUTDOWN_TIMEOUT_OPT, DRY_RUN_OPT, PRIORITY_OPT], 1626 "<instance>", "Reboots an instance"), 1627 "activate-disks": ( 1628 ActivateDisks, ARGS_ONE_INSTANCE, 1629 SUBMIT_OPTS + [IGNORE_SIZE_OPT, PRIORITY_OPT, WFSYNC_OPT], 1630 "<instance>", "Activate an instance's disks"), 1631 "deactivate-disks": ( 1632 DeactivateDisks, ARGS_ONE_INSTANCE, 1633 [FORCE_OPT] + SUBMIT_OPTS + [DRY_RUN_OPT, PRIORITY_OPT], 1634 "[-f] <instance>", "Deactivate an instance's disks"), 1635 "recreate-disks": ( 1636 RecreateDisks, ARGS_ONE_INSTANCE, 1637 SUBMIT_OPTS + 1638 [DISK_OPT, NODE_PLACEMENT_OPT, DRY_RUN_OPT, PRIORITY_OPT, 1639 IALLOCATOR_OPT], 1640 "<instance>", "Recreate an instance's disks"), 1641 "grow-disk": ( 1642 GrowDisk, 1643 [ArgInstance(min=1, max=1), ArgUnknown(min=1, max=1), 1644 ArgUnknown(min=1, max=1)], 1645 SUBMIT_OPTS + 1646 [NWSYNC_OPT, DRY_RUN_OPT, PRIORITY_OPT, ABSOLUTE_OPT, IGNORE_IPOLICY_OPT], 1647 "<instance> <disk> <size>", "Grow an instance's disk"), 1648 "change-group": ( 1649 ChangeGroup, ARGS_ONE_INSTANCE, 1650 [TO_GROUP_OPT, IALLOCATOR_OPT, EARLY_RELEASE_OPT, PRIORITY_OPT] 1651 + SUBMIT_OPTS, 1652 "[-I <iallocator>] [--to <group>]", "Change group of instance"), 1653 "list-tags": ( 1654 ListTags, ARGS_ONE_INSTANCE, [], 1655 "<instance_name>", "List the tags of the given instance"), 1656 "add-tags": ( 1657 AddTags, [ArgInstance(min=1, max=1), ArgUnknown()], 1658 [TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS, 1659 "<instance_name> tag...", "Add tags to the given instance"), 1660 "remove-tags": ( 1661 RemoveTags, [ArgInstance(min=1, max=1), ArgUnknown()], 1662 [TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS, 1663 "<instance_name> tag...", "Remove tags from given instance"), 1664 } 1665 1666 #: dictionary with aliases for commands 1667 aliases = { 1668 "start": "startup", 1669 "stop": "shutdown", 1670 "show": "info", 1671 } 1672 1673
1674 -def Main():
1675 return GenericMain(commands, aliases=aliases, 1676 override={"tag_type": constants.TAG_INSTANCE}, 1677 env_override=_ENV_OVERRIDE)
1678