gnt-instance 18.2 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/python
#

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


import sys
import os
from optparse import make_option
from cStringIO import StringIO

from ganeti.cli import *
from ganeti import opcodes
from ganeti import logger
from ganeti import constants
from ganeti import utils


def ListInstances(opts, args):
  """List nodes and their properties.

  """
  if opts.output is None:
    selected_fields = ["name", "os", "pnode", "admin_state",
                       "oper_state", "oper_ram"]
  else:
    selected_fields = opts.output.split(",")

  op = opcodes.OpQueryInstances(output_fields=selected_fields)
  output = SubmitOpCode(op)

  if not opts.no_headers:
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    headers = {"name": "Instance", "os": "OS", "pnode": "Primary_node",
               "snodes": "Secondary_Nodes", "admin_state": "Autostart",
               "oper_state": "Status", "admin_ram": "Configured_memory",
               "oper_ram": "Memory", "disk_template": "Disk_template",
               "ip": "IP Address", "mac": "MAC Address",
               "bridge": "Bridge"}
  else:
    headers = None

  if opts.human_readable:
    unitfields = ["admin_ram", "oper_ram"]
  else:
    unitfields = None

  numfields = ["admin_ram", "oper_ram"]

  OutputTable(separator=opts.separator, headers=headers,
      fields=selected_fields, unitfields=unitfields,
      numfields=numfields, data=output)
Iustin Pop's avatar
Iustin Pop committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97

  return 0


def AddInstance(opts, args):
  """Add an instance to the cluster.

  Args:
    opts - class with options as members
    args - list with a single element, the instance name
  Opts used:
    mem - amount of memory to allocate to instance (MiB)
    size - amount of disk space to allocate to instance (MiB)
    os - which OS to run on instance
    node - node to run new instance on

  """
  instance = args[0]

  op = opcodes.OpCreateInstance(instance_name=instance, mem_size=opts.mem,
                                disk_size=opts.size, swap_size=opts.swap,
                                disk_template=opts.disk_template,
                                mode=constants.INSTANCE_CREATE,
                                os_type=opts.os, pnode=opts.node,
                                snode=opts.snode, vcpus=opts.vcpus,
                                ip=opts.ip, bridge=opts.bridge, start=True,
                                wait_for_sync=opts.wait_for_sync)
  SubmitOpCode(op)
  return 0


98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def ReinstallInstance(opts, args):
  """Reinstall an instance.

  Args:
    opts - class with options as members
    args - list containing a single element, the instance name

  """
  instance_name = args[0]

  if not opts.force:
    usertext = ("This will reinstall the instance %s and remove "
                "all data. Continue?") % instance_name
    if not opts._ask_user(usertext):
      return 1

114
115
  op = opcodes.OpReinstallInstance(instance_name=instance_name,
                                   os_type=opts.os)
116
117
118
119
120
  SubmitOpCode(op)

  return 0


Iustin Pop's avatar
Iustin Pop committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
def RemoveInstance(opts, args):
  """Remove an instance.

  Args:
    opts - class with options as members
    args - list containing a single element, the instance name

  """
  instance_name = args[0]
  force = opts.force

  if not force:
    usertext = ("This will remove the volumes of the instance %s"
                " (including mirrors), thus removing all the data"
                " of the instance. Continue?") % instance_name
    if not opts._ask_user(usertext):
      return 1

  op = opcodes.OpRemoveInstance(instance_name=instance_name)
  SubmitOpCode(op)
  return 0


def ActivateDisks(opts, args):
  """Activate an instance's disks.

  This serves two purposes:
    - it allows one (as long as the instance is not running) to mount
    the disks and modify them from the node
    - it repairs inactive secondary drbds

  """
  instance_name = args[0]
  op = opcodes.OpActivateInstanceDisks(instance_name=instance_name)
  disks_info = SubmitOpCode(op)
  for host, iname, nname in disks_info:
    print "%s:%s:%s" % (host, iname, nname)
  return 0


def DeactivateDisks(opts, args):
  """Command-line interface for _ShutdownInstanceBlockDevices.

  This function takes the instance name, looks for its primary node
  and the tries to shutdown its block devices on that node.

  """
  instance_name = args[0]
  op = opcodes.OpDeactivateInstanceDisks(instance_name=instance_name)
  SubmitOpCode(op)
  return 0


def StartupInstance(opts, args):
  """Shutdown an instance.

  Args:
    opts - class with options as members
    args - list containing a single element, the instance name

  """
  instance_name = args[0]
  op = opcodes.OpStartupInstance(instance_name=instance_name, force=opts.force,
                                 extra_args=opts.extra_args)
  SubmitOpCode(op)
  return 0


def ShutdownInstance(opts, args):
  """Shutdown an instance.

  Args:
    opts - class with options as members
    args - list containing a single element, the instance name

  """
  instance_name = args[0]
  op = opcodes.OpShutdownInstance(instance_name=instance_name)
  SubmitOpCode(op)
  return 0


def AddMDDRBDComponent(opts, args):
  """Add a new component to a remote_raid1 disk.

  Args:
    opts - class with options as members
    args - list with a single element, the instance name

  """
  op = opcodes.OpAddMDDRBDComponent(instance_name=args[0],
                                    disk_name=opts.disk,
                                    remote_node=opts.node)
  SubmitOpCode(op)
  return 0


def RemoveMDDRBDComponent(opts, args):
  """Connect to the console of an instance

  Args:
    opts - class with options as members
    args - list with a single element, the instance name

  """
  op = opcodes.OpRemoveMDDRBDComponent(instance_name=args[0],
                                       disk_name=opts.disk,
                                       disk_id=opts.port)
  SubmitOpCode(op)
  return 0


def ReplaceDisks(opts, args):
  """Replace the disks of an instance

  Args:
    opts - class with options as members
    args - list with a single element, the instance name

  """
  instance_name = args[0]
  new_secondary = opts.new_secondary
  op = opcodes.OpReplaceDisks(instance_name=args[0],
                              remote_node=opts.new_secondary)
  SubmitOpCode(op)
  return 0


def FailoverInstance(opts, args):
  """Failover an instance.

  The failover is done by shutting it down on its present node and
  starting it on the secondary.

  Args:
    opts - class with options as members
    args - list with a single element, the instance name
  Opts used:
    force - whether to failover without asking questions.

  """
  instance_name = args[0]
  force = opts.force

  if not force:
    usertext = ("Failover will happen to image %s."
                " This requires a shutdown of the instance. Continue?" %
                (instance_name,))
    if not opts._ask_user(usertext):
      return 1

  op = opcodes.OpFailoverInstance(instance_name=instance_name,
                                  ignore_consistency=opts.ignore_consistency)
  SubmitOpCode(op)
  return 0


def ConnectToInstanceConsole(opts, args):
  """Connect to the console of an instance.

  Args:
    opts - class with options as members
    args - list with a single element, the instance name

  """
  instance_name = args[0]

  op = opcodes.OpConnectConsole(instance_name=instance_name)
  node, console_cmd = SubmitOpCode(op)
  # drop lock and exec so other commands can run while we have console
  utils.Unlock("cmd")
  try:
    os.execv("/usr/bin/ssh", ["ssh", "-qt", node, console_cmd])
  finally:
    sys.stderr.write("Can't run console command %s on node %s" %
                     (console_cmd, node))
    os._exit(1)


def _FormatBlockDevInfo(buf, dev, indent_level):
  """Show block device information.

  This is only used by ShowInstanceConfig(), but it's too big to be
  left for an inline definition.

  """
  def helper(buf, dtype, status):
    """Format one line for phsyical device status."""
    if not status:
      buf.write("not active\n")
    else:
      (path, major, minor, syncp, estt, degr) = status
      buf.write("%s (%d:%d)" % (path, major, minor))
      if dtype in ("md_raid1", "drbd"):
        if syncp is not None:
          sync_text = "*RECOVERING* %5.2f%%," % syncp
          if estt:
            sync_text += " ETA %ds" % estt
          else:
            sync_text += " ETA unknown"
        else:
          sync_text = "in sync"
        if degr:
          degr_text = "*DEGRADED*"
        else:
          degr_text = "ok"
        buf.write(" %s, status %s" % (sync_text, degr_text))
      buf.write("\n")

  if dev["iv_name"] is not None:
    data = "  - %s, " % dev["iv_name"]
  else:
    data = "  - "
  data += "type: %s" % dev["dev_type"]
  if dev["logical_id"] is not None:
    data += ", logical_id: %s" % (dev["logical_id"],)
  elif dev["physical_id"] is not None:
    data += ", physical_id: %s" % (dev["physical_id"],)
  buf.write("%*s%s\n" % (2*indent_level, "", data))
  buf.write("%*s    primary:   " % (2*indent_level, ""))
  helper(buf, dev["dev_type"], dev["pstatus"])

  if dev["sstatus"]:
    buf.write("%*s    secondary: " % (2*indent_level, ""))
    helper(buf, dev["dev_type"], dev["sstatus"])

  if dev["children"]:
    for child in dev["children"]:
      _FormatBlockDevInfo(buf, child, indent_level+1)


def ShowInstanceConfig(opts, args):
  """Compute instance run-time status.

  """
  retcode = 0
  op = opcodes.OpQueryInstanceData(instances=args)
  result = SubmitOpCode(op)

  if not result:
    logger.ToStdout("No instances.")
    return 1

  buf = StringIO()
  retcode = 0
  for instance_name in result:
    instance = result[instance_name]
    buf.write("Instance name: %s\n" % instance["name"])
    buf.write("State: configured to be %s, actual state is %s\n" %
              (instance["config_state"], instance["run_state"]))
    buf.write("  Nodes:\n")
    buf.write("    - primary: %s\n" % instance["pnode"])
    buf.write("    - secondaries: %s\n" % ", ".join(instance["snodes"]))
    buf.write("  Operating system: %s\n" % instance["os"])
    buf.write("  Hardware:\n")
    buf.write("    - memory: %dMiB\n" % instance["memory"])
    buf.write("    - NICs: %s\n" %
        ", ".join(["{MAC: %s, IP: %s, bridge: %s}" %
                   (mac, ip, bridge)
                     for mac, ip, bridge in instance["nics"]]))
    buf.write("  Block devices:\n")

    for device in instance["disks"]:
      _FormatBlockDevInfo(buf, device, 1)

  logger.ToStdout(buf.getvalue().rstrip('\n'))
  return retcode


def SetInstanceParms(opts, args):
  """Modifies an instance.

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

  Args:
    opts - class with options as members
    args - list with a single element, the instance name
  Opts used:
    memory - the new memory size
    vcpus - the new number of cpus

  """
  if not opts.mem and not opts.vcpus and not opts.ip and not opts.bridge:
    logger.ToStdout("Please give at least one of the parameters.")
    return 1

  op = opcodes.OpSetInstanceParms(instance_name=args[0], mem=opts.mem,
                                  vcpus=opts.vcpus, ip=opts.ip,
                                  bridge=opts.bridge)
  result = SubmitOpCode(op)

  if result:
    logger.ToStdout("Modified instance %s" % args[0])
    for param, data in result:
      logger.ToStdout(" - %-5s -> %s" % (param, data))
    logger.ToStdout("Please don't forget that these parameters take effect"
                    " only at the next start of the instance.")
  return 0


# options used in more than one cmd
node_opt = make_option("-n", "--node", dest="node", help="Target node",
                       metavar="<node>")

425
426
427
os_opt = cli_option("-o", "--os-type", dest="os", help="What OS to run",
                    metavar="<os>"),

Iustin Pop's avatar
Iustin Pop committed
428
429
430
431
432
433
434
435
# this is defined separately due to readability only
add_opts = [
  DEBUG_OPT,
  node_opt,
  cli_option("-s", "--os-size", dest="size", help="Disk size",
             default=20 * 1024, type="unit", metavar="<size>"),
  cli_option("--swap-size", dest="swap", help="Swap size",
             default=4 * 1024, type="unit", metavar="<size>"),
436
  os_opt,
Iustin Pop's avatar
Iustin Pop committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
  cli_option("-m", "--memory", dest="mem", help="Memory size",
              default=128, type="unit", metavar="<mem>"),
  make_option("-p", "--cpu", dest="vcpus", help="Number of virtual CPUs",
              default=1, type="int", metavar="<PROC>"),
  make_option("-t", "--disk-template", dest="disk_template",
              help="Custom disk setup (diskless, plain, local_raid1 or"
              " remote_raid1)", default=None, metavar="TEMPL"),
  make_option("-i", "--ip", dest="ip",
              help="IP address ('none' [default], 'auto', or specify address)",
              default='none', type="string", metavar="<ADDRESS>"),
  make_option("--no-wait-for-sync", dest="wait_for_sync", default=True,
              action="store_false", help="Don't wait for sync (DANGEROUS!)"),
  make_option("--secondary-node", dest="snode",
              help="Secondary node for remote_raid1 disk layout",
              metavar="<node>"),
  make_option("-b", "--bridge", dest="bridge",
              help="Bridge to connect this instance to",
              default=None, metavar="<bridge>")
  ]

commands = {
  'add': (AddInstance, ARGS_ONE, add_opts,
          "[opts...] <name>",
          "Creates and adds a new instance to the cluster"),
  'add-mirror': (AddMDDRBDComponent, ARGS_ONE,
                [DEBUG_OPT, node_opt,
                 make_option("-b", "--disk", dest="disk", metavar="sdX",
                             help=("The name of the instance disk for which to"
                                   " add the mirror"))],
                "-n node -b disk <instance>",
                "Creates a new mirror for the instance"),
  'console': (ConnectToInstanceConsole, ARGS_ONE, [DEBUG_OPT],
              "<instance>",
              "Opens a console on the specified instance"),
  'failover': (FailoverInstance, ARGS_ONE,
472
               [DEBUG_OPT, FORCE_OPT,
Iustin Pop's avatar
Iustin Pop committed
473
474
475
476
477
478
479
480
481
482
483
                make_option("--ignore-consistency", dest="ignore_consistency",
                            action="store_true", default=False,
                            help="Ignore the consistency of the disks on"
                            " the secondary"),
                ],
               "[-f] <instance>",
               "Stops the instance and starts it on the backup node, using"
               " the remote mirror (only for instances of type remote_raid1)"),
  'info': (ShowInstanceConfig, ARGS_ANY, [DEBUG_OPT], "[<instance>...]",
           "Show information on the specified instance"),
  'list': (ListInstances, ARGS_NONE,
484
           [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
Iustin Pop's avatar
Iustin Pop committed
485
           "", "Lists the instances and their status"),
486
  'reinstall': (ReinstallInstance, ARGS_ONE, [DEBUG_OPT, FORCE_OPT, os_opt],
487
488
                "[-f] <instance>", "Reinstall the instance"),
  'remove': (RemoveInstance, ARGS_ONE, [DEBUG_OPT, FORCE_OPT],
Iustin Pop's avatar
Iustin Pop committed
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
             "[-f] <instance>", "Shuts down the instance and removes it"),
  'remove-mirror': (RemoveMDDRBDComponent, ARGS_ONE,
                   [DEBUG_OPT, node_opt,
                    make_option("-b", "--disk", dest="disk", metavar="sdX",
                                help=("The name of the instance disk"
                                      " for which to add the mirror")),
                    make_option("-p", "--port", dest="port", metavar="PORT",
                                help=("The port of the drbd device"
                                      " which to remove from the mirror"),
                                type="int"),
                    ],
                   "-b disk -p port <instance>",
                   "Removes a mirror from the instance"),
  'replace-disks': (ReplaceDisks, ARGS_ONE,
                    [DEBUG_OPT,
                     make_option("-n", "--new-secondary", dest="new_secondary",
                                 metavar="NODE",
                                 help=("New secondary node (if you want to"
                                       " change the secondary)"))],
                    "[-n NODE] <instance>",
                    "Replaces all disks for the instance"),
  'modify': (SetInstanceParms, ARGS_ONE,
511
             [DEBUG_OPT, FORCE_OPT,
Iustin Pop's avatar
Iustin Pop committed
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
              cli_option("-m", "--memory", dest="mem",
                         help="Memory size",
                         default=None, type="unit", metavar="<mem>"),
              make_option("-p", "--cpu", dest="vcpus",
                          help="Number of virtual CPUs",
                          default=None, type="int", metavar="<PROC>"),
              make_option("-i", "--ip", dest="ip",
                          help="IP address ('none' or numeric IP)",
                          default=None, type="string", metavar="<ADDRESS>"),
              make_option("-b", "--bridge", dest="bridge",
                          help="Bridge to connect this instance to",
                          default=None, type="string", metavar="<bridge>")
              ],
             "<instance>", "Alters the parameters of an instance"),
  'shutdown': (ShutdownInstance, ARGS_ONE, [DEBUG_OPT],
               "<instance>", "Stops an instance"),
  'startup': (StartupInstance, ARGS_ONE,
529
              [DEBUG_OPT, FORCE_OPT,
Iustin Pop's avatar
Iustin Pop committed
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
               make_option("-e", "--extra", dest="extra_args",
                           help="Extra arguments for the instance's kernel",
                           default=None, type="string", metavar="<PARAMS>"),
               ],
            "<instance>", "Starts an instance"),
  'activate-disks': (ActivateDisks, ARGS_ONE, [DEBUG_OPT],
                     "<instance>",
                     "Activate an instance's disks"),
  'deactivate-disks': (DeactivateDisks, ARGS_ONE, [DEBUG_OPT],
                       "<instance>",
                       "Deactivate an instance's disks"),
  }

if __name__ == '__main__':
  retcode = GenericMain(commands)
  sys.exit(retcode)