Statistics
| Branch: | Tag: | Revision:

root / scripts / gnt-instance @ 549071a0

History | View | Annotate | Download (52 kB)

1 a8083063 Iustin Pop
#!/usr/bin/python
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 a8083063 Iustin Pop
# Copyright (C) 2006, 2007 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 7260cfbe Iustin Pop
"""Instance related commands"""
22 a8083063 Iustin Pop
23 7260cfbe Iustin Pop
# pylint: disable-msg=W0401,W0614,C0103
24 2f79bd34 Iustin Pop
# W0401: Wildcard import ganeti.cli
25 2f79bd34 Iustin Pop
# W0614: Unused import %s from wildcard import (since we need cli)
26 7260cfbe Iustin Pop
# C0103: Invalid name gnt-instance
27 2f79bd34 Iustin Pop
28 a8083063 Iustin Pop
import sys
29 a8083063 Iustin Pop
import os
30 312ac745 Iustin Pop
import itertools
31 0d0e9090 René Nussbaumer
import simplejson
32 a8083063 Iustin Pop
from cStringIO import StringIO
33 a8083063 Iustin Pop
34 a8083063 Iustin Pop
from ganeti.cli import *
35 a8083063 Iustin Pop
from ganeti import opcodes
36 a8083063 Iustin Pop
from ganeti import constants
37 e2736e40 Guido Trotter
from ganeti import compat
38 a8083063 Iustin Pop
from ganeti import utils
39 312ac745 Iustin Pop
from ganeti import errors
40 312ac745 Iustin Pop
41 312ac745 Iustin Pop
42 312ac745 Iustin Pop
_SHUTDOWN_CLUSTER = "cluster"
43 312ac745 Iustin Pop
_SHUTDOWN_NODES_BOTH = "nodes"
44 312ac745 Iustin Pop
_SHUTDOWN_NODES_PRI = "nodes-pri"
45 312ac745 Iustin Pop
_SHUTDOWN_NODES_SEC = "nodes-sec"
46 39dfd93e René Nussbaumer
_SHUTDOWN_NODES_BOTH_BY_TAGS = "nodes-by-tags"
47 39dfd93e René Nussbaumer
_SHUTDOWN_NODES_PRI_BY_TAGS = "nodes-pri-by-tags"
48 39dfd93e René Nussbaumer
_SHUTDOWN_NODES_SEC_BY_TAGS = "nodes-sec-by-tags"
49 312ac745 Iustin Pop
_SHUTDOWN_INSTANCES = "instances"
50 39dfd93e René Nussbaumer
_SHUTDOWN_INSTANCES_BY_TAGS = "instances-by-tags"
51 39dfd93e René Nussbaumer
52 39dfd93e René Nussbaumer
_SHUTDOWN_NODES_TAGS_MODES = (
53 39dfd93e René Nussbaumer
    _SHUTDOWN_NODES_BOTH_BY_TAGS,
54 39dfd93e René Nussbaumer
    _SHUTDOWN_NODES_PRI_BY_TAGS,
55 39dfd93e René Nussbaumer
    _SHUTDOWN_NODES_SEC_BY_TAGS)
56 312ac745 Iustin Pop
57 7c0d6283 Michael Hanselmann
58 31a853d2 Iustin Pop
_VALUE_TRUE = "true"
59 31a853d2 Iustin Pop
60 7232c04c Iustin Pop
#: default list of options for L{ListInstances}
61 48c4dfa8 Iustin Pop
_LIST_DEF_FIELDS = [
62 e69d05fd Iustin Pop
  "name", "hypervisor", "os", "pnode", "status", "oper_ram",
63 48c4dfa8 Iustin Pop
  ]
64 48c4dfa8 Iustin Pop
65 bdb7d4e8 Michael Hanselmann
66 479636a3 Iustin Pop
def _ExpandMultiNames(mode, names, client=None):
67 312ac745 Iustin Pop
  """Expand the given names using the passed mode.
68 312ac745 Iustin Pop
69 312ac745 Iustin Pop
  For _SHUTDOWN_CLUSTER, all instances will be returned. For
70 312ac745 Iustin Pop
  _SHUTDOWN_NODES_PRI/SEC, all instances having those nodes as
71 7232c04c Iustin Pop
  primary/secondary will be returned. For _SHUTDOWN_NODES_BOTH, all
72 312ac745 Iustin Pop
  instances having those nodes as either primary or secondary will be
73 312ac745 Iustin Pop
  returned. For _SHUTDOWN_INSTANCES, the given instances will be
74 312ac745 Iustin Pop
  returned.
75 312ac745 Iustin Pop
76 7232c04c Iustin Pop
  @param mode: one of L{_SHUTDOWN_CLUSTER}, L{_SHUTDOWN_NODES_BOTH},
77 7232c04c Iustin Pop
      L{_SHUTDOWN_NODES_PRI}, L{_SHUTDOWN_NODES_SEC} or
78 7232c04c Iustin Pop
      L{_SHUTDOWN_INSTANCES}
79 7232c04c Iustin Pop
  @param names: a list of names; for cluster, it must be empty,
80 7232c04c Iustin Pop
      and for node and instance it must be a list of valid item
81 7232c04c Iustin Pop
      names (short names are valid as usual, e.g. node1 instead of
82 7232c04c Iustin Pop
      node1.example.com)
83 7232c04c Iustin Pop
  @rtype: list
84 7232c04c Iustin Pop
  @return: the list of names after the expansion
85 7232c04c Iustin Pop
  @raise errors.ProgrammerError: for unknown selection type
86 7232c04c Iustin Pop
  @raise errors.OpPrereqError: for invalid input parameters
87 7232c04c Iustin Pop
88 312ac745 Iustin Pop
  """
89 7260cfbe Iustin Pop
  # pylint: disable-msg=W0142
90 39dfd93e René Nussbaumer
91 479636a3 Iustin Pop
  if client is None:
92 479636a3 Iustin Pop
    client = GetClient()
93 312ac745 Iustin Pop
  if mode == _SHUTDOWN_CLUSTER:
94 312ac745 Iustin Pop
    if names:
95 debac808 Iustin Pop
      raise errors.OpPrereqError("Cluster filter mode takes no arguments",
96 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
97 ec79568d Iustin Pop
    idata = client.QueryInstances([], ["name"], False)
98 312ac745 Iustin Pop
    inames = [row[0] for row in idata]
99 312ac745 Iustin Pop
100 312ac745 Iustin Pop
  elif mode in (_SHUTDOWN_NODES_BOTH,
101 312ac745 Iustin Pop
                _SHUTDOWN_NODES_PRI,
102 39dfd93e René Nussbaumer
                _SHUTDOWN_NODES_SEC) + _SHUTDOWN_NODES_TAGS_MODES:
103 39dfd93e René Nussbaumer
    if mode in _SHUTDOWN_NODES_TAGS_MODES:
104 39dfd93e René Nussbaumer
      if not names:
105 39dfd93e René Nussbaumer
        raise errors.OpPrereqError("No node tags passed", errors.ECODE_INVAL)
106 39dfd93e René Nussbaumer
      ndata = client.QueryNodes([], ["name", "pinst_list",
107 39dfd93e René Nussbaumer
                                     "sinst_list", "tags"], False)
108 39dfd93e René Nussbaumer
      ndata = [row for row in ndata if set(row[3]).intersection(names)]
109 39dfd93e René Nussbaumer
    else:
110 39dfd93e René Nussbaumer
      if not names:
111 39dfd93e René Nussbaumer
        raise errors.OpPrereqError("No node names passed", errors.ECODE_INVAL)
112 39dfd93e René Nussbaumer
      ndata = client.QueryNodes(names, ["name", "pinst_list", "sinst_list"],
113 77921a95 Iustin Pop
                              False)
114 39dfd93e René Nussbaumer
115 312ac745 Iustin Pop
    ipri = [row[1] for row in ndata]
116 312ac745 Iustin Pop
    pri_names = list(itertools.chain(*ipri))
117 312ac745 Iustin Pop
    isec = [row[2] for row in ndata]
118 312ac745 Iustin Pop
    sec_names = list(itertools.chain(*isec))
119 39dfd93e René Nussbaumer
    if mode in (_SHUTDOWN_NODES_BOTH, _SHUTDOWN_NODES_BOTH_BY_TAGS):
120 312ac745 Iustin Pop
      inames = pri_names + sec_names
121 39dfd93e René Nussbaumer
    elif mode in (_SHUTDOWN_NODES_PRI, _SHUTDOWN_NODES_PRI_BY_TAGS):
122 312ac745 Iustin Pop
      inames = pri_names
123 39dfd93e René Nussbaumer
    elif mode in (_SHUTDOWN_NODES_SEC, _SHUTDOWN_NODES_SEC_BY_TAGS):
124 312ac745 Iustin Pop
      inames = sec_names
125 312ac745 Iustin Pop
    else:
126 312ac745 Iustin Pop
      raise errors.ProgrammerError("Unhandled shutdown type")
127 312ac745 Iustin Pop
  elif mode == _SHUTDOWN_INSTANCES:
128 312ac745 Iustin Pop
    if not names:
129 debac808 Iustin Pop
      raise errors.OpPrereqError("No instance names passed",
130 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
131 ec79568d Iustin Pop
    idata = client.QueryInstances(names, ["name"], False)
132 312ac745 Iustin Pop
    inames = [row[0] for row in idata]
133 39dfd93e René Nussbaumer
  elif mode == _SHUTDOWN_INSTANCES_BY_TAGS:
134 39dfd93e René Nussbaumer
    if not names:
135 39dfd93e René Nussbaumer
      raise errors.OpPrereqError("No instance tags passed",
136 39dfd93e René Nussbaumer
                                 errors.ECODE_INVAL)
137 39dfd93e René Nussbaumer
    idata = client.QueryInstances([], ["name", "tags"], False)
138 39dfd93e René Nussbaumer
    inames = [row[0] for row in idata if set(row[1]).intersection(names)]
139 312ac745 Iustin Pop
  else:
140 debac808 Iustin Pop
    raise errors.OpPrereqError("Unknown mode '%s'" % mode, errors.ECODE_INVAL)
141 312ac745 Iustin Pop
142 312ac745 Iustin Pop
  return inames
143 a8083063 Iustin Pop
144 a8083063 Iustin Pop
145 55efe6da Iustin Pop
def _ConfirmOperation(inames, text, extra=""):
146 804a1e8e Iustin Pop
  """Ask the user to confirm an operation on a list of instances.
147 804a1e8e Iustin Pop
148 804a1e8e Iustin Pop
  This function is used to request confirmation for doing an operation
149 804a1e8e Iustin Pop
  on a given list of instances.
150 804a1e8e Iustin Pop
151 7232c04c Iustin Pop
  @type inames: list
152 7232c04c Iustin Pop
  @param inames: the list of names that we display when
153 7232c04c Iustin Pop
      we ask for confirmation
154 7232c04c Iustin Pop
  @type text: str
155 7232c04c Iustin Pop
  @param text: the operation that the user should confirm
156 7232c04c Iustin Pop
      (e.g. I{shutdown} or I{startup})
157 7232c04c Iustin Pop
  @rtype: boolean
158 7232c04c Iustin Pop
  @return: True or False depending on user's confirmation.
159 804a1e8e Iustin Pop
160 804a1e8e Iustin Pop
  """
161 804a1e8e Iustin Pop
  count = len(inames)
162 55efe6da Iustin Pop
  msg = ("The %s will operate on %d instances.\n%s"
163 55efe6da Iustin Pop
         "Do you want to continue?" % (text, count, extra))
164 804a1e8e Iustin Pop
  affected = ("\nAffected instances:\n" +
165 804a1e8e Iustin Pop
              "\n".join(["  %s" % name for name in inames]))
166 804a1e8e Iustin Pop
167 804a1e8e Iustin Pop
  choices = [('y', True, 'Yes, execute the %s' % text),
168 804a1e8e Iustin Pop
             ('n', False, 'No, abort the %s' % text)]
169 804a1e8e Iustin Pop
170 804a1e8e Iustin Pop
  if count > 20:
171 804a1e8e Iustin Pop
    choices.insert(1, ('v', 'v', 'View the list of affected instances'))
172 804a1e8e Iustin Pop
    ask = msg
173 804a1e8e Iustin Pop
  else:
174 804a1e8e Iustin Pop
    ask = msg + affected
175 804a1e8e Iustin Pop
176 804a1e8e Iustin Pop
  choice = AskUser(ask, choices)
177 804a1e8e Iustin Pop
  if choice == 'v':
178 804a1e8e Iustin Pop
    choices.pop(1)
179 5e66b7e6 Iustin Pop
    choice = AskUser(msg + affected, choices)
180 804a1e8e Iustin Pop
  return choice
181 804a1e8e Iustin Pop
182 804a1e8e Iustin Pop
183 a76f0c4a Iustin Pop
def _EnsureInstancesExist(client, names):
184 a76f0c4a Iustin Pop
  """Check for and ensure the given instance names exist.
185 a76f0c4a Iustin Pop
186 a76f0c4a Iustin Pop
  This function will raise an OpPrereqError in case they don't
187 a76f0c4a Iustin Pop
  exist. Otherwise it will exit cleanly.
188 a76f0c4a Iustin Pop
189 f2fd87d7 Iustin Pop
  @type client: L{ganeti.luxi.Client}
190 a76f0c4a Iustin Pop
  @param client: the client to use for the query
191 a76f0c4a Iustin Pop
  @type names: list
192 a76f0c4a Iustin Pop
  @param names: the list of instance names to query
193 a76f0c4a Iustin Pop
  @raise errors.OpPrereqError: in case any instance is missing
194 a76f0c4a Iustin Pop
195 a76f0c4a Iustin Pop
  """
196 a76f0c4a Iustin Pop
  # TODO: change LUQueryInstances to that it actually returns None
197 a76f0c4a Iustin Pop
  # instead of raising an exception, or devise a better mechanism
198 ec79568d Iustin Pop
  result = client.QueryInstances(names, ["name"], False)
199 a76f0c4a Iustin Pop
  for orig_name, row in zip(names, result):
200 a76f0c4a Iustin Pop
    if row[0] is None:
201 debac808 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' does not exist" % orig_name,
202 debac808 Iustin Pop
                                 errors.ECODE_NOENT)
203 a76f0c4a Iustin Pop
204 a76f0c4a Iustin Pop
205 1c5945b6 Iustin Pop
def GenericManyOps(operation, fn):
206 1c5945b6 Iustin Pop
  """Generic multi-instance operations.
207 1c5945b6 Iustin Pop
208 1c5945b6 Iustin Pop
  The will return a wrapper that processes the options and arguments
209 1c5945b6 Iustin Pop
  given, and uses the passed function to build the opcode needed for
210 1c5945b6 Iustin Pop
  the specific operation. Thus all the generic loop/confirmation code
211 1c5945b6 Iustin Pop
  is abstracted into this function.
212 1c5945b6 Iustin Pop
213 1c5945b6 Iustin Pop
  """
214 1c5945b6 Iustin Pop
  def realfn(opts, args):
215 1c5945b6 Iustin Pop
    if opts.multi_mode is None:
216 1c5945b6 Iustin Pop
      opts.multi_mode = _SHUTDOWN_INSTANCES
217 1c5945b6 Iustin Pop
    cl = GetClient()
218 1c5945b6 Iustin Pop
    inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
219 1c5945b6 Iustin Pop
    if not inames:
220 1c5945b6 Iustin Pop
      raise errors.OpPrereqError("Selection filter does not match"
221 debac808 Iustin Pop
                                 " any instances", errors.ECODE_INVAL)
222 1c5945b6 Iustin Pop
    multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
223 1c5945b6 Iustin Pop
    if not (opts.force_multi or not multi_on
224 1c5945b6 Iustin Pop
            or _ConfirmOperation(inames, operation)):
225 1c5945b6 Iustin Pop
      return 1
226 cb573a31 Iustin Pop
    jex = JobExecutor(verbose=multi_on, cl=cl, opts=opts)
227 1c5945b6 Iustin Pop
    for name in inames:
228 1c5945b6 Iustin Pop
      op = fn(name, opts)
229 1c5945b6 Iustin Pop
      jex.QueueJob(name, op)
230 1c5945b6 Iustin Pop
    jex.WaitOrShow(not opts.submit_only)
231 1c5945b6 Iustin Pop
    return 0
232 1c5945b6 Iustin Pop
  return realfn
233 1c5945b6 Iustin Pop
234 1c5945b6 Iustin Pop
235 a8083063 Iustin Pop
def ListInstances(opts, args):
236 f5abe9bd Oleksiy Mishchenko
  """List instances and their properties.
237 a8083063 Iustin Pop
238 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
239 7232c04c Iustin Pop
  @type args: list
240 7232c04c Iustin Pop
  @param args: should be an empty list
241 7232c04c Iustin Pop
  @rtype: int
242 7232c04c Iustin Pop
  @return: the desired exit code
243 7232c04c Iustin Pop
244 a8083063 Iustin Pop
  """
245 a8083063 Iustin Pop
  if opts.output is None:
246 48c4dfa8 Iustin Pop
    selected_fields = _LIST_DEF_FIELDS
247 48c4dfa8 Iustin Pop
  elif opts.output.startswith("+"):
248 48c4dfa8 Iustin Pop
    selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
249 a8083063 Iustin Pop
  else:
250 a8083063 Iustin Pop
    selected_fields = opts.output.split(",")
251 a8083063 Iustin Pop
252 ec79568d Iustin Pop
  output = GetClient().QueryInstances(args, selected_fields, opts.do_locking)
253 a8083063 Iustin Pop
254 a8083063 Iustin Pop
  if not opts.no_headers:
255 d8052456 Iustin Pop
    headers = {
256 d8052456 Iustin Pop
      "name": "Instance", "os": "OS", "pnode": "Primary_node",
257 d8052456 Iustin Pop
      "snodes": "Secondary_Nodes", "admin_state": "Autostart",
258 338e51e8 Iustin Pop
      "oper_state": "Running",
259 d8052456 Iustin Pop
      "oper_ram": "Memory", "disk_template": "Disk_template",
260 3fb1e1c5 Alexander Schreiber
      "ip": "IP_address", "mac": "MAC_address",
261 638c6349 Guido Trotter
      "nic_mode": "NIC_Mode", "nic_link": "NIC_Link",
262 338e51e8 Iustin Pop
      "bridge": "Bridge",
263 d8052456 Iustin Pop
      "sda_size": "Disk/0", "sdb_size": "Disk/1",
264 024e157f Iustin Pop
      "disk_usage": "DiskUsage",
265 130a6a6f Iustin Pop
      "status": "Status", "tags": "Tags",
266 3fb1e1c5 Alexander Schreiber
      "network_port": "Network_port",
267 5018a335 Iustin Pop
      "hv/kernel_path": "Kernel_path",
268 5018a335 Iustin Pop
      "hv/initrd_path": "Initrd_path",
269 20b1bd80 Iustin Pop
      "hv/boot_order": "Boot_order",
270 20b1bd80 Iustin Pop
      "hv/acpi": "ACPI",
271 20b1bd80 Iustin Pop
      "hv/pae": "PAE",
272 20b1bd80 Iustin Pop
      "hv/cdrom_image_path": "CDROM_image_path",
273 20b1bd80 Iustin Pop
      "hv/nic_type": "NIC_type",
274 20b1bd80 Iustin Pop
      "hv/disk_type": "Disk_type",
275 7ac1fc45 Guido Trotter
      "hv/vnc_bind_address": "VNC_bind_address",
276 e69d05fd Iustin Pop
      "serial_no": "SerialNo", "hypervisor": "Hypervisor",
277 5018a335 Iustin Pop
      "hvparams": "Hypervisor_parameters",
278 338e51e8 Iustin Pop
      "be/memory": "Configured_memory",
279 338e51e8 Iustin Pop
      "be/vcpus": "VCPUs",
280 c1ce76bb Iustin Pop
      "vcpus": "VCPUs",
281 c0f2b229 Iustin Pop
      "be/auto_balance": "Auto_balance",
282 23b8c8d6 Iustin Pop
      "disk.count": "Disks", "disk.sizes": "Disk_sizes",
283 23b8c8d6 Iustin Pop
      "nic.count": "NICs", "nic.ips": "NIC_IPs",
284 638c6349 Guido Trotter
      "nic.modes": "NIC_modes", "nic.links": "NIC_links",
285 23b8c8d6 Iustin Pop
      "nic.bridges": "NIC_bridges", "nic.macs": "NIC_MACs",
286 033d58b0 Iustin Pop
      "ctime": "CTime", "mtime": "MTime", "uuid": "UUID",
287 d8052456 Iustin Pop
      }
288 137161c9 Michael Hanselmann
  else:
289 137161c9 Michael Hanselmann
    headers = None
290 137161c9 Michael Hanselmann
291 9fbfbb7b Iustin Pop
  unitfields = ["be/memory", "oper_ram", "sd(a|b)_size", "disk\.size/.*"]
292 00430f8e Iustin Pop
  numfields = ["be/memory", "oper_ram", "sd(a|b)_size", "be/vcpus",
293 23b8c8d6 Iustin Pop
               "serial_no", "(disk|nic)\.count", "disk\.size/.*"]
294 137161c9 Michael Hanselmann
295 638c6349 Guido Trotter
  list_type_fields = ("tags", "disk.sizes", "nic.macs", "nic.ips",
296 638c6349 Guido Trotter
                      "nic.modes", "nic.links", "nic.bridges")
297 8a23d2d3 Iustin Pop
  # change raw values to nicer strings
298 8a23d2d3 Iustin Pop
  for row in output:
299 8a23d2d3 Iustin Pop
    for idx, field in enumerate(selected_fields):
300 8a23d2d3 Iustin Pop
      val = row[idx]
301 8a23d2d3 Iustin Pop
      if field == "snodes":
302 8a23d2d3 Iustin Pop
        val = ",".join(val) or "-"
303 8a23d2d3 Iustin Pop
      elif field == "admin_state":
304 8a23d2d3 Iustin Pop
        if val:
305 8a23d2d3 Iustin Pop
          val = "yes"
306 8a23d2d3 Iustin Pop
        else:
307 8a23d2d3 Iustin Pop
          val = "no"
308 8a23d2d3 Iustin Pop
      elif field == "oper_state":
309 8a23d2d3 Iustin Pop
        if val is None:
310 8a23d2d3 Iustin Pop
          val = "(node down)"
311 8a23d2d3 Iustin Pop
        elif val: # True
312 8a23d2d3 Iustin Pop
          val = "running"
313 8a23d2d3 Iustin Pop
        else:
314 8a23d2d3 Iustin Pop
          val = "stopped"
315 8a23d2d3 Iustin Pop
      elif field == "oper_ram":
316 8a23d2d3 Iustin Pop
        if val is None:
317 8a23d2d3 Iustin Pop
          val = "(node down)"
318 8a23d2d3 Iustin Pop
      elif field == "sda_size" or field == "sdb_size":
319 8a23d2d3 Iustin Pop
        if val is None:
320 8a23d2d3 Iustin Pop
          val = "N/A"
321 90f72445 Iustin Pop
      elif field == "ctime" or field == "mtime":
322 90f72445 Iustin Pop
        val = utils.FormatTime(val)
323 130a6a6f Iustin Pop
      elif field in list_type_fields:
324 23b8c8d6 Iustin Pop
        val = ",".join(str(item) for item in val)
325 5018a335 Iustin Pop
      elif val is None:
326 5018a335 Iustin Pop
        val = "-"
327 e2736e40 Guido Trotter
      if opts.roman_integers and isinstance(val, int):
328 e2736e40 Guido Trotter
        val = compat.TryToRoman(val)
329 8a23d2d3 Iustin Pop
      row[idx] = str(val)
330 8a23d2d3 Iustin Pop
331 16be8703 Iustin Pop
  data = GenerateTable(separator=opts.separator, headers=headers,
332 16be8703 Iustin Pop
                       fields=selected_fields, unitfields=unitfields,
333 9fbfbb7b Iustin Pop
                       numfields=numfields, data=output, units=opts.units)
334 16be8703 Iustin Pop
335 16be8703 Iustin Pop
  for line in data:
336 3a24c527 Iustin Pop
    ToStdout(line)
337 a8083063 Iustin Pop
338 a8083063 Iustin Pop
  return 0
339 a8083063 Iustin Pop
340 a8083063 Iustin Pop
341 a8083063 Iustin Pop
def AddInstance(opts, args):
342 a8083063 Iustin Pop
  """Add an instance to the cluster.
343 a8083063 Iustin Pop
344 d77490c5 Iustin Pop
  This is just a wrapper over GenericInstanceCreate.
345 a8083063 Iustin Pop
346 a8083063 Iustin Pop
  """
347 d77490c5 Iustin Pop
  return GenericInstanceCreate(constants.INSTANCE_CREATE, opts, args)
348 a8083063 Iustin Pop
349 a8083063 Iustin Pop
350 0d0e9090 René Nussbaumer
def BatchCreate(opts, args):
351 7232c04c Iustin Pop
  """Create instances using a definition file.
352 7232c04c Iustin Pop
353 7232c04c Iustin Pop
  This function reads a json file with instances defined
354 7232c04c Iustin Pop
  in the form::
355 7232c04c Iustin Pop
356 7232c04c Iustin Pop
    {"instance-name":{
357 9939547b Iustin Pop
      "disk_size": [20480],
358 7232c04c Iustin Pop
      "template": "drbd",
359 7232c04c Iustin Pop
      "backend": {
360 7232c04c Iustin Pop
        "memory": 512,
361 7232c04c Iustin Pop
        "vcpus": 1 },
362 9939547b Iustin Pop
      "os": "debootstrap",
363 7232c04c Iustin Pop
      "primary_node": "firstnode",
364 7232c04c Iustin Pop
      "secondary_node": "secondnode",
365 7232c04c Iustin Pop
      "iallocator": "dumb"}
366 7232c04c Iustin Pop
    }
367 7232c04c Iustin Pop
368 7232c04c Iustin Pop
  Note that I{primary_node} and I{secondary_node} have precedence over
369 7232c04c Iustin Pop
  I{iallocator}.
370 7232c04c Iustin Pop
371 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
372 7232c04c Iustin Pop
  @type args: list
373 7232c04c Iustin Pop
  @param args: should contain one element, the json filename
374 7232c04c Iustin Pop
  @rtype: int
375 7232c04c Iustin Pop
  @return: the desired exit code
376 0d0e9090 René Nussbaumer
377 0d0e9090 René Nussbaumer
  """
378 9939547b Iustin Pop
  _DEFAULT_SPECS = {"disk_size": [20 * 1024],
379 0d0e9090 René Nussbaumer
                    "backend": {},
380 0d0e9090 René Nussbaumer
                    "iallocator": None,
381 0d0e9090 René Nussbaumer
                    "primary_node": None,
382 0d0e9090 René Nussbaumer
                    "secondary_node": None,
383 a379d9bd Guido Trotter
                    "nics": None,
384 0d0e9090 René Nussbaumer
                    "start": True,
385 0d0e9090 René Nussbaumer
                    "ip_check": True,
386 460d22be Iustin Pop
                    "name_check": True,
387 0d0e9090 René Nussbaumer
                    "hypervisor": None,
388 4082e6f9 Iustin Pop
                    "hvparams": {},
389 0d0e9090 René Nussbaumer
                    "file_storage_dir": None,
390 27ba7eab Guido Trotter
                    "force_variant": False,
391 0d0e9090 René Nussbaumer
                    "file_driver": 'loop'}
392 0d0e9090 René Nussbaumer
393 0d0e9090 René Nussbaumer
  def _PopulateWithDefaults(spec):
394 0d0e9090 René Nussbaumer
    """Returns a new hash combined with default values."""
395 2f79bd34 Iustin Pop
    mydict = _DEFAULT_SPECS.copy()
396 2f79bd34 Iustin Pop
    mydict.update(spec)
397 2f79bd34 Iustin Pop
    return mydict
398 0d0e9090 René Nussbaumer
399 0d0e9090 René Nussbaumer
  def _Validate(spec):
400 0d0e9090 René Nussbaumer
    """Validate the instance specs."""
401 0d0e9090 René Nussbaumer
    # Validate fields required under any circumstances
402 0d0e9090 René Nussbaumer
    for required_field in ('os', 'template'):
403 0d0e9090 René Nussbaumer
      if required_field not in spec:
404 0d0e9090 René Nussbaumer
        raise errors.OpPrereqError('Required field "%s" is missing.' %
405 debac808 Iustin Pop
                                   required_field, errors.ECODE_INVAL)
406 0d0e9090 René Nussbaumer
    # Validate special fields
407 0d0e9090 René Nussbaumer
    if spec['primary_node'] is not None:
408 0d0e9090 René Nussbaumer
      if (spec['template'] in constants.DTS_NET_MIRROR and
409 0d0e9090 René Nussbaumer
          spec['secondary_node'] is None):
410 0d0e9090 René Nussbaumer
        raise errors.OpPrereqError('Template requires secondary node, but'
411 debac808 Iustin Pop
                                   ' there was no secondary provided.',
412 debac808 Iustin Pop
                                   errors.ECODE_INVAL)
413 0d0e9090 René Nussbaumer
    elif spec['iallocator'] is None:
414 0d0e9090 René Nussbaumer
      raise errors.OpPrereqError('You have to provide at least a primary_node'
415 debac808 Iustin Pop
                                 ' or an iallocator.',
416 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
417 0d0e9090 René Nussbaumer
418 4082e6f9 Iustin Pop
    if (spec['hvparams'] and
419 4082e6f9 Iustin Pop
        not isinstance(spec['hvparams'], dict)):
420 debac808 Iustin Pop
      raise errors.OpPrereqError('Hypervisor parameters must be a dict.',
421 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
422 0d0e9090 René Nussbaumer
423 0d0e9090 René Nussbaumer
  json_filename = args[0]
424 0d0e9090 René Nussbaumer
  try:
425 13998ef2 Michael Hanselmann
    instance_data = simplejson.loads(utils.ReadFile(json_filename))
426 7260cfbe Iustin Pop
  except Exception, err: # pylint: disable-msg=W0703
427 4082e6f9 Iustin Pop
    ToStderr("Can't parse the instance definition file: %s" % str(err))
428 4082e6f9 Iustin Pop
    return 1
429 0d0e9090 René Nussbaumer
430 fe7c59d5 Guido Trotter
  if not isinstance(instance_data, dict):
431 fe7c59d5 Guido Trotter
    ToStderr("The instance definition file is not in dict format.")
432 fe7c59d5 Guido Trotter
    return 1
433 fe7c59d5 Guido Trotter
434 cb573a31 Iustin Pop
  jex = JobExecutor(opts=opts)
435 d4dd4b74 Iustin Pop
436 0d0e9090 René Nussbaumer
  # Iterate over the instances and do:
437 0d0e9090 René Nussbaumer
  #  * Populate the specs with default value
438 0d0e9090 René Nussbaumer
  #  * Validate the instance specs
439 fe7c59d5 Guido Trotter
  i_names = utils.NiceSort(instance_data.keys()) # pylint: disable-msg=E1103
440 7312b33d Iustin Pop
  for name in i_names:
441 7312b33d Iustin Pop
    specs = instance_data[name]
442 0d0e9090 René Nussbaumer
    specs = _PopulateWithDefaults(specs)
443 0d0e9090 René Nussbaumer
    _Validate(specs)
444 0d0e9090 René Nussbaumer
445 4082e6f9 Iustin Pop
    hypervisor = specs['hypervisor']
446 4082e6f9 Iustin Pop
    hvparams = specs['hvparams']
447 0d0e9090 René Nussbaumer
448 9939547b Iustin Pop
    disks = []
449 9939547b Iustin Pop
    for elem in specs['disk_size']:
450 9939547b Iustin Pop
      try:
451 9939547b Iustin Pop
        size = utils.ParseUnit(elem)
452 691744c4 Iustin Pop
      except (TypeError, ValueError), err:
453 9939547b Iustin Pop
        raise errors.OpPrereqError("Invalid disk size '%s' for"
454 9939547b Iustin Pop
                                   " instance %s: %s" %
455 debac808 Iustin Pop
                                   (elem, name, err), errors.ECODE_INVAL)
456 9939547b Iustin Pop
      disks.append({"size": size})
457 9939547b Iustin Pop
458 a5728081 Guido Trotter
    utils.ForceDictType(specs['backend'], constants.BES_PARAMETER_TYPES)
459 a5728081 Guido Trotter
    utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
460 a5728081 Guido Trotter
461 a379d9bd Guido Trotter
    tmp_nics = []
462 a379d9bd Guido Trotter
    for field in ('ip', 'mac', 'mode', 'link', 'bridge'):
463 a379d9bd Guido Trotter
      if field in specs:
464 a379d9bd Guido Trotter
        if not tmp_nics:
465 a379d9bd Guido Trotter
          tmp_nics.append({})
466 a379d9bd Guido Trotter
        tmp_nics[0][field] = specs[field]
467 a379d9bd Guido Trotter
468 a379d9bd Guido Trotter
    if specs['nics'] is not None and tmp_nics:
469 a379d9bd Guido Trotter
      raise errors.OpPrereqError("'nics' list incompatible with using"
470 debac808 Iustin Pop
                                 " individual nic fields as well",
471 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
472 a379d9bd Guido Trotter
    elif specs['nics'] is not None:
473 a379d9bd Guido Trotter
      tmp_nics = specs['nics']
474 a379d9bd Guido Trotter
    elif not tmp_nics:
475 a379d9bd Guido Trotter
      tmp_nics = [{}]
476 a379d9bd Guido Trotter
477 0d0e9090 René Nussbaumer
    op = opcodes.OpCreateInstance(instance_name=name,
478 9939547b Iustin Pop
                                  disks=disks,
479 0d0e9090 René Nussbaumer
                                  disk_template=specs['template'],
480 0d0e9090 René Nussbaumer
                                  mode=constants.INSTANCE_CREATE,
481 0d0e9090 René Nussbaumer
                                  os_type=specs['os'],
482 de372295 Guido Trotter
                                  force_variant=specs["force_variant"],
483 0d0e9090 René Nussbaumer
                                  pnode=specs['primary_node'],
484 0d0e9090 René Nussbaumer
                                  snode=specs['secondary_node'],
485 a379d9bd Guido Trotter
                                  nics=tmp_nics,
486 0d0e9090 René Nussbaumer
                                  start=specs['start'],
487 0d0e9090 René Nussbaumer
                                  ip_check=specs['ip_check'],
488 460d22be Iustin Pop
                                  name_check=specs['name_check'],
489 0d0e9090 René Nussbaumer
                                  wait_for_sync=True,
490 0d0e9090 René Nussbaumer
                                  iallocator=specs['iallocator'],
491 0d0e9090 René Nussbaumer
                                  hypervisor=hypervisor,
492 0d0e9090 René Nussbaumer
                                  hvparams=hvparams,
493 0d0e9090 René Nussbaumer
                                  beparams=specs['backend'],
494 0d0e9090 René Nussbaumer
                                  file_storage_dir=specs['file_storage_dir'],
495 0d0e9090 René Nussbaumer
                                  file_driver=specs['file_driver'])
496 0d0e9090 René Nussbaumer
497 d4dd4b74 Iustin Pop
    jex.QueueJob(name, op)
498 d4dd4b74 Iustin Pop
  # we never want to wait, just show the submitted job IDs
499 d4dd4b74 Iustin Pop
  jex.WaitOrShow(False)
500 0d0e9090 René Nussbaumer
501 0d0e9090 René Nussbaumer
  return 0
502 0d0e9090 René Nussbaumer
503 0d0e9090 René Nussbaumer
504 fe7b0351 Michael Hanselmann
def ReinstallInstance(opts, args):
505 fe7b0351 Michael Hanselmann
  """Reinstall an instance.
506 fe7b0351 Michael Hanselmann
507 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
508 7232c04c Iustin Pop
  @type args: list
509 7232c04c Iustin Pop
  @param args: should contain only one element, the name of the
510 7232c04c Iustin Pop
      instance to be reinstalled
511 7232c04c Iustin Pop
  @rtype: int
512 7232c04c Iustin Pop
  @return: the desired exit code
513 fe7b0351 Michael Hanselmann
514 fe7b0351 Michael Hanselmann
  """
515 55efe6da Iustin Pop
  # first, compute the desired name list
516 55efe6da Iustin Pop
  if opts.multi_mode is None:
517 55efe6da Iustin Pop
    opts.multi_mode = _SHUTDOWN_INSTANCES
518 55efe6da Iustin Pop
519 55efe6da Iustin Pop
  inames = _ExpandMultiNames(opts.multi_mode, args)
520 55efe6da Iustin Pop
  if not inames:
521 debac808 Iustin Pop
    raise errors.OpPrereqError("Selection filter does not match any instances",
522 debac808 Iustin Pop
                               errors.ECODE_INVAL)
523 fe7b0351 Michael Hanselmann
524 55efe6da Iustin Pop
  # second, if requested, ask for an OS
525 20e23543 Alexander Schreiber
  if opts.select_os is True:
526 e3ac208c Guido Trotter
    op = opcodes.OpDiagnoseOS(output_fields=["name", "valid", "variants"],
527 e3ac208c Guido Trotter
                              names=[])
528 400ca2f7 Iustin Pop
    result = SubmitOpCode(op, opts=opts)
529 20e23543 Alexander Schreiber
530 20e23543 Alexander Schreiber
    if not result:
531 3a24c527 Iustin Pop
      ToStdout("Can't get the OS list")
532 20e23543 Alexander Schreiber
      return 1
533 20e23543 Alexander Schreiber
534 3a24c527 Iustin Pop
    ToStdout("Available OS templates:")
535 20e23543 Alexander Schreiber
    number = 0
536 20e23543 Alexander Schreiber
    choices = []
537 e3ac208c Guido Trotter
    for (name, valid, variants) in result:
538 e3ac208c Guido Trotter
      if valid:
539 e3ac208c Guido Trotter
        for entry in CalculateOSNames(name, variants):
540 e3ac208c Guido Trotter
          ToStdout("%3s: %s", number, entry)
541 e3ac208c Guido Trotter
          choices.append(("%s" % number, entry, entry))
542 e3ac208c Guido Trotter
          number += 1
543 20e23543 Alexander Schreiber
544 20e23543 Alexander Schreiber
    choices.append(('x', 'exit', 'Exit gnt-instance reinstall'))
545 949bdabe Iustin Pop
    selected = AskUser("Enter OS template number (or x to abort):",
546 20e23543 Alexander Schreiber
                       choices)
547 20e23543 Alexander Schreiber
548 20e23543 Alexander Schreiber
    if selected == 'exit':
549 55efe6da Iustin Pop
      ToStderr("User aborted reinstall, exiting")
550 20e23543 Alexander Schreiber
      return 1
551 20e23543 Alexander Schreiber
552 2f79bd34 Iustin Pop
    os_name = selected
553 20e23543 Alexander Schreiber
  else:
554 2f79bd34 Iustin Pop
    os_name = opts.os
555 20e23543 Alexander Schreiber
556 55efe6da Iustin Pop
  # third, get confirmation: multi-reinstall requires --force-multi
557 55efe6da Iustin Pop
  # *and* --force, single-reinstall just --force
558 55efe6da Iustin Pop
  multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
559 55efe6da Iustin Pop
  if multi_on:
560 55efe6da Iustin Pop
    warn_msg = "Note: this will remove *all* data for the below instances!\n"
561 55efe6da Iustin Pop
    if not ((opts.force_multi and opts.force) or
562 55efe6da Iustin Pop
            _ConfirmOperation(inames, "reinstall", extra=warn_msg)):
563 fe7b0351 Michael Hanselmann
      return 1
564 55efe6da Iustin Pop
  else:
565 55efe6da Iustin Pop
    if not opts.force:
566 55efe6da Iustin Pop
      usertext = ("This will reinstall the instance %s and remove"
567 b6e243ab Iustin Pop
                  " all data. Continue?") % inames[0]
568 55efe6da Iustin Pop
      if not AskUser(usertext):
569 55efe6da Iustin Pop
        return 1
570 55efe6da Iustin Pop
571 cb573a31 Iustin Pop
  jex = JobExecutor(verbose=multi_on, opts=opts)
572 55efe6da Iustin Pop
  for instance_name in inames:
573 55efe6da Iustin Pop
    op = opcodes.OpReinstallInstance(instance_name=instance_name,
574 06073e85 Guido Trotter
                                     os_type=os_name,
575 06073e85 Guido Trotter
                                     force_variant=opts.force_variant)
576 55efe6da Iustin Pop
    jex.QueueJob(instance_name, op)
577 fe7b0351 Michael Hanselmann
578 55efe6da Iustin Pop
  jex.WaitOrShow(not opts.submit_only)
579 fe7b0351 Michael Hanselmann
  return 0
580 fe7b0351 Michael Hanselmann
581 fe7b0351 Michael Hanselmann
582 a8083063 Iustin Pop
def RemoveInstance(opts, args):
583 a8083063 Iustin Pop
  """Remove an instance.
584 a8083063 Iustin Pop
585 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
586 7232c04c Iustin Pop
  @type args: list
587 7232c04c Iustin Pop
  @param args: should contain only one element, the name of
588 7232c04c Iustin Pop
      the instance to be removed
589 7232c04c Iustin Pop
  @rtype: int
590 7232c04c Iustin Pop
  @return: the desired exit code
591 a8083063 Iustin Pop
592 a8083063 Iustin Pop
  """
593 a8083063 Iustin Pop
  instance_name = args[0]
594 a8083063 Iustin Pop
  force = opts.force
595 a76f0c4a Iustin Pop
  cl = GetClient()
596 a8083063 Iustin Pop
597 a8083063 Iustin Pop
  if not force:
598 a76f0c4a Iustin Pop
    _EnsureInstancesExist(cl, [instance_name])
599 a76f0c4a Iustin Pop
600 a8083063 Iustin Pop
    usertext = ("This will remove the volumes of the instance %s"
601 a8083063 Iustin Pop
                " (including mirrors), thus removing all the data"
602 a8083063 Iustin Pop
                " of the instance. Continue?") % instance_name
603 47988778 Iustin Pop
    if not AskUser(usertext):
604 a8083063 Iustin Pop
      return 1
605 a8083063 Iustin Pop
606 1d67656e Iustin Pop
  op = opcodes.OpRemoveInstance(instance_name=instance_name,
607 17c3f802 Guido Trotter
                                ignore_failures=opts.ignore_failures,
608 4d98c565 Guido Trotter
                                shutdown_timeout=opts.shutdown_timeout)
609 a76f0c4a Iustin Pop
  SubmitOrSend(op, opts, cl=cl)
610 a8083063 Iustin Pop
  return 0
611 a8083063 Iustin Pop
612 a8083063 Iustin Pop
613 decd5f45 Iustin Pop
def RenameInstance(opts, args):
614 4ab0b9e3 Guido Trotter
  """Rename an instance.
615 decd5f45 Iustin Pop
616 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
617 7232c04c Iustin Pop
  @type args: list
618 7232c04c Iustin Pop
  @param args: should contain two elements, the old and the
619 7232c04c Iustin Pop
      new instance names
620 7232c04c Iustin Pop
  @rtype: int
621 7232c04c Iustin Pop
  @return: the desired exit code
622 decd5f45 Iustin Pop
623 decd5f45 Iustin Pop
  """
624 90ed09b0 René Nussbaumer
  if not opts.name_check:
625 1b6dddc8 René Nussbaumer
    if not AskUser("As you disabled the check of the DNS entry, please verify"
626 1b6dddc8 René Nussbaumer
                   " that '%s' is a FQDN. Continue?" % args[1]):
627 1b6dddc8 René Nussbaumer
      return 1
628 1b6dddc8 René Nussbaumer
629 decd5f45 Iustin Pop
  op = opcodes.OpRenameInstance(instance_name=args[0],
630 decd5f45 Iustin Pop
                                new_name=args[1],
631 1b6dddc8 René Nussbaumer
                                ignore_ip=not opts.ip_check,
632 90ed09b0 René Nussbaumer
                                check_name=opts.name_check)
633 6340bb0a Iustin Pop
  SubmitOrSend(op, opts)
634 decd5f45 Iustin Pop
  return 0
635 decd5f45 Iustin Pop
636 decd5f45 Iustin Pop
637 a8083063 Iustin Pop
def ActivateDisks(opts, args):
638 a8083063 Iustin Pop
  """Activate an instance's disks.
639 a8083063 Iustin Pop
640 a8083063 Iustin Pop
  This serves two purposes:
641 7232c04c Iustin Pop
    - it allows (as long as the instance is not running)
642 7232c04c Iustin Pop
      mounting the disks and modifying them from the node
643 a8083063 Iustin Pop
    - it repairs inactive secondary drbds
644 a8083063 Iustin Pop
645 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
646 7232c04c Iustin Pop
  @type args: list
647 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
648 7232c04c Iustin Pop
  @rtype: int
649 7232c04c Iustin Pop
  @return: the desired exit code
650 7232c04c Iustin Pop
651 a8083063 Iustin Pop
  """
652 a8083063 Iustin Pop
  instance_name = args[0]
653 b4ec07f8 Iustin Pop
  op = opcodes.OpActivateInstanceDisks(instance_name=instance_name,
654 b4ec07f8 Iustin Pop
                                       ignore_size=opts.ignore_size)
655 6340bb0a Iustin Pop
  disks_info = SubmitOrSend(op, opts)
656 a8083063 Iustin Pop
  for host, iname, nname in disks_info:
657 3a24c527 Iustin Pop
    ToStdout("%s:%s:%s", host, iname, nname)
658 a8083063 Iustin Pop
  return 0
659 a8083063 Iustin Pop
660 a8083063 Iustin Pop
661 a8083063 Iustin Pop
def DeactivateDisks(opts, args):
662 bd315bfa Iustin Pop
  """Deactivate an instance's disks.
663 a8083063 Iustin Pop
664 a8083063 Iustin Pop
  This function takes the instance name, looks for its primary node
665 a8083063 Iustin Pop
  and the tries to shutdown its block devices on that node.
666 a8083063 Iustin Pop
667 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
668 7232c04c Iustin Pop
  @type args: list
669 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
670 7232c04c Iustin Pop
  @rtype: int
671 7232c04c Iustin Pop
  @return: the desired exit code
672 7232c04c Iustin Pop
673 a8083063 Iustin Pop
  """
674 a8083063 Iustin Pop
  instance_name = args[0]
675 a8083063 Iustin Pop
  op = opcodes.OpDeactivateInstanceDisks(instance_name=instance_name)
676 6340bb0a Iustin Pop
  SubmitOrSend(op, opts)
677 a8083063 Iustin Pop
  return 0
678 a8083063 Iustin Pop
679 a8083063 Iustin Pop
680 bd315bfa Iustin Pop
def RecreateDisks(opts, args):
681 bd315bfa Iustin Pop
  """Recreate an instance's disks.
682 bd315bfa Iustin Pop
683 bd315bfa Iustin Pop
  @param opts: the command line options selected by the user
684 bd315bfa Iustin Pop
  @type args: list
685 bd315bfa Iustin Pop
  @param args: should contain only one element, the instance name
686 bd315bfa Iustin Pop
  @rtype: int
687 bd315bfa Iustin Pop
  @return: the desired exit code
688 bd315bfa Iustin Pop
689 bd315bfa Iustin Pop
  """
690 bd315bfa Iustin Pop
  instance_name = args[0]
691 bd315bfa Iustin Pop
  if opts.disks:
692 bd315bfa Iustin Pop
    try:
693 bd315bfa Iustin Pop
      opts.disks = [int(v) for v in opts.disks.split(",")]
694 bd315bfa Iustin Pop
    except (ValueError, TypeError), err:
695 bd315bfa Iustin Pop
      ToStderr("Invalid disks value: %s" % str(err))
696 bd315bfa Iustin Pop
      return 1
697 bd315bfa Iustin Pop
  else:
698 bd315bfa Iustin Pop
    opts.disks = []
699 bd315bfa Iustin Pop
700 bd315bfa Iustin Pop
  op = opcodes.OpRecreateInstanceDisks(instance_name=instance_name,
701 bd315bfa Iustin Pop
                                       disks=opts.disks)
702 bd315bfa Iustin Pop
  SubmitOrSend(op, opts)
703 bd315bfa Iustin Pop
  return 0
704 bd315bfa Iustin Pop
705 bd315bfa Iustin Pop
706 c6e911bc Iustin Pop
def GrowDisk(opts, args):
707 7232c04c Iustin Pop
  """Grow an instance's disks.
708 c6e911bc Iustin Pop
709 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
710 7232c04c Iustin Pop
  @type args: list
711 7232c04c Iustin Pop
  @param args: should contain two elements, the instance name
712 7232c04c Iustin Pop
      whose disks we grow and the disk name, e.g. I{sda}
713 7232c04c Iustin Pop
  @rtype: int
714 7232c04c Iustin Pop
  @return: the desired exit code
715 c6e911bc Iustin Pop
716 c6e911bc Iustin Pop
  """
717 c6e911bc Iustin Pop
  instance = args[0]
718 c6e911bc Iustin Pop
  disk = args[1]
719 ad24e046 Iustin Pop
  try:
720 ad24e046 Iustin Pop
    disk = int(disk)
721 691744c4 Iustin Pop
  except (TypeError, ValueError), err:
722 debac808 Iustin Pop
    raise errors.OpPrereqError("Invalid disk index: %s" % str(err),
723 debac808 Iustin Pop
                               errors.ECODE_INVAL)
724 c6e911bc Iustin Pop
  amount = utils.ParseUnit(args[2])
725 6605411d Iustin Pop
  op = opcodes.OpGrowDisk(instance_name=instance, disk=disk, amount=amount,
726 6605411d Iustin Pop
                          wait_for_sync=opts.wait_for_sync)
727 6340bb0a Iustin Pop
  SubmitOrSend(op, opts)
728 c6e911bc Iustin Pop
  return 0
729 c6e911bc Iustin Pop
730 c6e911bc Iustin Pop
731 1c5945b6 Iustin Pop
def _StartupInstance(name, opts):
732 7232c04c Iustin Pop
  """Startup instances.
733 a8083063 Iustin Pop
734 1c5945b6 Iustin Pop
  This returns the opcode to start an instance, and its decorator will
735 1c5945b6 Iustin Pop
  wrap this into a loop starting all desired instances.
736 7232c04c Iustin Pop
737 1c5945b6 Iustin Pop
  @param name: the name of the instance to act on
738 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
739 1c5945b6 Iustin Pop
  @return: the opcode needed for the operation
740 a8083063 Iustin Pop
741 a8083063 Iustin Pop
  """
742 1c5945b6 Iustin Pop
  op = opcodes.OpStartupInstance(instance_name=name,
743 1c5945b6 Iustin Pop
                                 force=opts.force)
744 1c5945b6 Iustin Pop
  # do not add these parameters to the opcode unless they're defined
745 1c5945b6 Iustin Pop
  if opts.hvparams:
746 1c5945b6 Iustin Pop
    op.hvparams = opts.hvparams
747 1c5945b6 Iustin Pop
  if opts.beparams:
748 1c5945b6 Iustin Pop
    op.beparams = opts.beparams
749 1c5945b6 Iustin Pop
  return op
750 a8083063 Iustin Pop
751 7c0d6283 Michael Hanselmann
752 1c5945b6 Iustin Pop
def _RebootInstance(name, opts):
753 7232c04c Iustin Pop
  """Reboot instance(s).
754 7232c04c Iustin Pop
755 1c5945b6 Iustin Pop
  This returns the opcode to reboot an instance, and its decorator
756 1c5945b6 Iustin Pop
  will wrap this into a loop rebooting all desired instances.
757 579d4337 Alexander Schreiber
758 1c5945b6 Iustin Pop
  @param name: the name of the instance to act on
759 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
760 1c5945b6 Iustin Pop
  @return: the opcode needed for the operation
761 579d4337 Alexander Schreiber
762 579d4337 Alexander Schreiber
  """
763 1c5945b6 Iustin Pop
  return opcodes.OpRebootInstance(instance_name=name,
764 579d4337 Alexander Schreiber
                                  reboot_type=opts.reboot_type,
765 17c3f802 Guido Trotter
                                  ignore_secondaries=opts.ignore_secondaries,
766 4d98c565 Guido Trotter
                                  shutdown_timeout=opts.shutdown_timeout)
767 a8083063 Iustin Pop
768 7c0d6283 Michael Hanselmann
769 1c5945b6 Iustin Pop
def _ShutdownInstance(name, opts):
770 a8083063 Iustin Pop
  """Shutdown an instance.
771 a8083063 Iustin Pop
772 1c5945b6 Iustin Pop
  This returns the opcode to shutdown an instance, and its decorator
773 1c5945b6 Iustin Pop
  will wrap this into a loop shutting down all desired instances.
774 1c5945b6 Iustin Pop
775 1c5945b6 Iustin Pop
  @param name: the name of the instance to act on
776 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
777 1c5945b6 Iustin Pop
  @return: the opcode needed for the operation
778 a8083063 Iustin Pop
779 a8083063 Iustin Pop
  """
780 6263189c Guido Trotter
  return opcodes.OpShutdownInstance(instance_name=name,
781 6263189c Guido Trotter
                                    timeout=opts.timeout)
782 a8083063 Iustin Pop
783 a8083063 Iustin Pop
784 a8083063 Iustin Pop
def ReplaceDisks(opts, args):
785 a8083063 Iustin Pop
  """Replace the disks of an instance
786 a8083063 Iustin Pop
787 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
788 7232c04c Iustin Pop
  @type args: list
789 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
790 7232c04c Iustin Pop
  @rtype: int
791 7232c04c Iustin Pop
  @return: the desired exit code
792 a8083063 Iustin Pop
793 a8083063 Iustin Pop
  """
794 a14db5ff Iustin Pop
  new_2ndary = opts.dst_node
795 b6e82a65 Iustin Pop
  iallocator = opts.iallocator
796 a9e0c397 Iustin Pop
  if opts.disks is None:
797 54155f52 Iustin Pop
    disks = []
798 a9e0c397 Iustin Pop
  else:
799 54155f52 Iustin Pop
    try:
800 54155f52 Iustin Pop
      disks = [int(i) for i in opts.disks.split(",")]
801 691744c4 Iustin Pop
    except (TypeError, ValueError), err:
802 debac808 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err),
803 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
804 05d47e33 Michael Hanselmann
  cnt = [opts.on_primary, opts.on_secondary, opts.auto,
805 7e9366f7 Iustin Pop
         new_2ndary is not None, iallocator is not None].count(True)
806 7e9366f7 Iustin Pop
  if cnt != 1:
807 05d47e33 Michael Hanselmann
    raise errors.OpPrereqError("One and only one of the -p, -s, -a, -n and -i"
808 debac808 Iustin Pop
                               " options must be passed", errors.ECODE_INVAL)
809 7e9366f7 Iustin Pop
  elif opts.on_primary:
810 a9e0c397 Iustin Pop
    mode = constants.REPLACE_DISK_PRI
811 7e9366f7 Iustin Pop
  elif opts.on_secondary:
812 a9e0c397 Iustin Pop
    mode = constants.REPLACE_DISK_SEC
813 05d47e33 Michael Hanselmann
  elif opts.auto:
814 05d47e33 Michael Hanselmann
    mode = constants.REPLACE_DISK_AUTO
815 05d47e33 Michael Hanselmann
    if disks:
816 05d47e33 Michael Hanselmann
      raise errors.OpPrereqError("Cannot specify disks when using automatic"
817 debac808 Iustin Pop
                                 " mode", errors.ECODE_INVAL)
818 7e9366f7 Iustin Pop
  elif new_2ndary is not None or iallocator is not None:
819 7e9366f7 Iustin Pop
    # replace secondary
820 7e9366f7 Iustin Pop
    mode = constants.REPLACE_DISK_CHG
821 a9e0c397 Iustin Pop
822 a9e0c397 Iustin Pop
  op = opcodes.OpReplaceDisks(instance_name=args[0], disks=disks,
823 b6e82a65 Iustin Pop
                              remote_node=new_2ndary, mode=mode,
824 7ea7bcf6 Iustin Pop
                              iallocator=iallocator,
825 7ea7bcf6 Iustin Pop
                              early_release=opts.early_release)
826 6340bb0a Iustin Pop
  SubmitOrSend(op, opts)
827 a8083063 Iustin Pop
  return 0
828 a8083063 Iustin Pop
829 a8083063 Iustin Pop
830 a8083063 Iustin Pop
def FailoverInstance(opts, args):
831 a8083063 Iustin Pop
  """Failover an instance.
832 a8083063 Iustin Pop
833 a8083063 Iustin Pop
  The failover is done by shutting it down on its present node and
834 a8083063 Iustin Pop
  starting it on the secondary.
835 a8083063 Iustin Pop
836 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
837 7232c04c Iustin Pop
  @type args: list
838 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
839 7232c04c Iustin Pop
  @rtype: int
840 7232c04c Iustin Pop
  @return: the desired exit code
841 a8083063 Iustin Pop
842 a8083063 Iustin Pop
  """
843 a76f0c4a Iustin Pop
  cl = GetClient()
844 80de0e3f Iustin Pop
  instance_name = args[0]
845 80de0e3f Iustin Pop
  force = opts.force
846 a8083063 Iustin Pop
847 80de0e3f Iustin Pop
  if not force:
848 a76f0c4a Iustin Pop
    _EnsureInstancesExist(cl, [instance_name])
849 a76f0c4a Iustin Pop
850 80de0e3f Iustin Pop
    usertext = ("Failover will happen to image %s."
851 80de0e3f Iustin Pop
                " This requires a shutdown of the instance. Continue?" %
852 80de0e3f Iustin Pop
                (instance_name,))
853 80de0e3f Iustin Pop
    if not AskUser(usertext):
854 80de0e3f Iustin Pop
      return 1
855 a8083063 Iustin Pop
856 80de0e3f Iustin Pop
  op = opcodes.OpFailoverInstance(instance_name=instance_name,
857 17c3f802 Guido Trotter
                                  ignore_consistency=opts.ignore_consistency,
858 4d98c565 Guido Trotter
                                  shutdown_timeout=opts.shutdown_timeout)
859 a76f0c4a Iustin Pop
  SubmitOrSend(op, opts, cl=cl)
860 80de0e3f Iustin Pop
  return 0
861 a8083063 Iustin Pop
862 a8083063 Iustin Pop
863 53c776b5 Iustin Pop
def MigrateInstance(opts, args):
864 53c776b5 Iustin Pop
  """Migrate an instance.
865 53c776b5 Iustin Pop
866 53c776b5 Iustin Pop
  The migrate is done without shutdown.
867 53c776b5 Iustin Pop
868 2f907a8c Iustin Pop
  @param opts: the command line options selected by the user
869 2f907a8c Iustin Pop
  @type args: list
870 2f907a8c Iustin Pop
  @param args: should contain only one element, the instance name
871 2f907a8c Iustin Pop
  @rtype: int
872 2f907a8c Iustin Pop
  @return: the desired exit code
873 53c776b5 Iustin Pop
874 53c776b5 Iustin Pop
  """
875 a76f0c4a Iustin Pop
  cl = GetClient()
876 53c776b5 Iustin Pop
  instance_name = args[0]
877 53c776b5 Iustin Pop
  force = opts.force
878 53c776b5 Iustin Pop
879 53c776b5 Iustin Pop
  if not force:
880 a76f0c4a Iustin Pop
    _EnsureInstancesExist(cl, [instance_name])
881 a76f0c4a Iustin Pop
882 53c776b5 Iustin Pop
    if opts.cleanup:
883 53c776b5 Iustin Pop
      usertext = ("Instance %s will be recovered from a failed migration."
884 53c776b5 Iustin Pop
                  " Note that the migration procedure (including cleanup)" %
885 53c776b5 Iustin Pop
                  (instance_name,))
886 53c776b5 Iustin Pop
    else:
887 53c776b5 Iustin Pop
      usertext = ("Instance %s will be migrated. Note that migration" %
888 53c776b5 Iustin Pop
                  (instance_name,))
889 cf29cfb6 Iustin Pop
    usertext += (" might impact the instance if anything goes wrong"
890 cf29cfb6 Iustin Pop
                 " (e.g. due to bugs in the hypervisor). Continue?")
891 53c776b5 Iustin Pop
    if not AskUser(usertext):
892 53c776b5 Iustin Pop
      return 1
893 53c776b5 Iustin Pop
894 53c776b5 Iustin Pop
  op = opcodes.OpMigrateInstance(instance_name=instance_name, live=opts.live,
895 53c776b5 Iustin Pop
                                 cleanup=opts.cleanup)
896 400ca2f7 Iustin Pop
  SubmitOpCode(op, cl=cl, opts=opts)
897 53c776b5 Iustin Pop
  return 0
898 53c776b5 Iustin Pop
899 53c776b5 Iustin Pop
900 fbf5a861 Iustin Pop
def MoveInstance(opts, args):
901 fbf5a861 Iustin Pop
  """Move an instance.
902 fbf5a861 Iustin Pop
903 fbf5a861 Iustin Pop
  @param opts: the command line options selected by the user
904 fbf5a861 Iustin Pop
  @type args: list
905 fbf5a861 Iustin Pop
  @param args: should contain only one element, the instance name
906 fbf5a861 Iustin Pop
  @rtype: int
907 fbf5a861 Iustin Pop
  @return: the desired exit code
908 fbf5a861 Iustin Pop
909 fbf5a861 Iustin Pop
  """
910 fbf5a861 Iustin Pop
  cl = GetClient()
911 fbf5a861 Iustin Pop
  instance_name = args[0]
912 fbf5a861 Iustin Pop
  force = opts.force
913 fbf5a861 Iustin Pop
914 fbf5a861 Iustin Pop
  if not force:
915 fbf5a861 Iustin Pop
    usertext = ("Instance %s will be moved."
916 fbf5a861 Iustin Pop
                " This requires a shutdown of the instance. Continue?" %
917 fbf5a861 Iustin Pop
                (instance_name,))
918 fbf5a861 Iustin Pop
    if not AskUser(usertext):
919 fbf5a861 Iustin Pop
      return 1
920 fbf5a861 Iustin Pop
921 fbf5a861 Iustin Pop
  op = opcodes.OpMoveInstance(instance_name=instance_name,
922 17c3f802 Guido Trotter
                              target_node=opts.node,
923 4d98c565 Guido Trotter
                              shutdown_timeout=opts.shutdown_timeout)
924 fbf5a861 Iustin Pop
  SubmitOrSend(op, opts, cl=cl)
925 fbf5a861 Iustin Pop
  return 0
926 fbf5a861 Iustin Pop
927 fbf5a861 Iustin Pop
928 a8083063 Iustin Pop
def ConnectToInstanceConsole(opts, args):
929 a8083063 Iustin Pop
  """Connect to the console of an instance.
930 a8083063 Iustin Pop
931 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
932 7232c04c Iustin Pop
  @type args: list
933 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
934 7232c04c Iustin Pop
  @rtype: int
935 7232c04c Iustin Pop
  @return: the desired exit code
936 a8083063 Iustin Pop
937 a8083063 Iustin Pop
  """
938 a8083063 Iustin Pop
  instance_name = args[0]
939 a8083063 Iustin Pop
940 a8083063 Iustin Pop
  op = opcodes.OpConnectConsole(instance_name=instance_name)
941 400ca2f7 Iustin Pop
  cmd = SubmitOpCode(op, opts=opts)
942 51c6e7b5 Michael Hanselmann
943 51c6e7b5 Michael Hanselmann
  if opts.show_command:
944 3a24c527 Iustin Pop
    ToStdout("%s", utils.ShellQuoteArgs(cmd))
945 51c6e7b5 Michael Hanselmann
  else:
946 51c6e7b5 Michael Hanselmann
    try:
947 51c6e7b5 Michael Hanselmann
      os.execvp(cmd[0], cmd)
948 51c6e7b5 Michael Hanselmann
    finally:
949 3a24c527 Iustin Pop
      ToStderr("Can't run console command %s with arguments:\n'%s'",
950 2f79bd34 Iustin Pop
               cmd[0], " ".join(cmd))
951 7260cfbe Iustin Pop
      os._exit(1) # pylint: disable-msg=W0212
952 a8083063 Iustin Pop
953 a8083063 Iustin Pop
954 e2736e40 Guido Trotter
def _FormatLogicalID(dev_type, logical_id, roman):
955 19708787 Iustin Pop
  """Formats the logical_id of a disk.
956 19708787 Iustin Pop
957 19708787 Iustin Pop
  """
958 19708787 Iustin Pop
  if dev_type == constants.LD_DRBD8:
959 19708787 Iustin Pop
    node_a, node_b, port, minor_a, minor_b, key = logical_id
960 19708787 Iustin Pop
    data = [
961 e2736e40 Guido Trotter
      ("nodeA", "%s, minor=%s" % (node_a, compat.TryToRoman(minor_a,
962 e2736e40 Guido Trotter
                                                            convert=roman))),
963 e2736e40 Guido Trotter
      ("nodeB", "%s, minor=%s" % (node_b, compat.TryToRoman(minor_b,
964 e2736e40 Guido Trotter
                                                            convert=roman))),
965 e2736e40 Guido Trotter
      ("port", compat.TryToRoman(port, convert=roman)),
966 19708787 Iustin Pop
      ("auth key", key),
967 19708787 Iustin Pop
      ]
968 19708787 Iustin Pop
  elif dev_type == constants.LD_LV:
969 19708787 Iustin Pop
    vg_name, lv_name = logical_id
970 19708787 Iustin Pop
    data = ["%s/%s" % (vg_name, lv_name)]
971 19708787 Iustin Pop
  else:
972 19708787 Iustin Pop
    data = [str(logical_id)]
973 19708787 Iustin Pop
974 19708787 Iustin Pop
  return data
975 19708787 Iustin Pop
976 19708787 Iustin Pop
977 e2736e40 Guido Trotter
def _FormatBlockDevInfo(idx, top_level, dev, static, roman):
978 a8083063 Iustin Pop
  """Show block device information.
979 a8083063 Iustin Pop
980 7232c04c Iustin Pop
  This is only used by L{ShowInstanceConfig}, but it's too big to be
981 a8083063 Iustin Pop
  left for an inline definition.
982 a8083063 Iustin Pop
983 19708787 Iustin Pop
  @type idx: int
984 19708787 Iustin Pop
  @param idx: the index of the current disk
985 19708787 Iustin Pop
  @type top_level: boolean
986 19708787 Iustin Pop
  @param top_level: if this a top-level disk?
987 7232c04c Iustin Pop
  @type dev: dict
988 7232c04c Iustin Pop
  @param dev: dictionary with disk information
989 7232c04c Iustin Pop
  @type static: boolean
990 7232c04c Iustin Pop
  @param static: wheter the device information doesn't contain
991 7232c04c Iustin Pop
      runtime information but only static data
992 e2736e40 Guido Trotter
  @type roman: boolean
993 e2736e40 Guido Trotter
  @param roman: whether to try to use roman integers
994 19708787 Iustin Pop
  @return: a list of either strings, tuples or lists
995 19708787 Iustin Pop
      (which should be formatted at a higher indent level)
996 7232c04c Iustin Pop
997 a8083063 Iustin Pop
  """
998 19708787 Iustin Pop
  def helper(dtype, status):
999 7232c04c Iustin Pop
    """Format one line for physical device status.
1000 7232c04c Iustin Pop
1001 7232c04c Iustin Pop
    @type dtype: str
1002 7232c04c Iustin Pop
    @param dtype: a constant from the L{constants.LDS_BLOCK} set
1003 7232c04c Iustin Pop
    @type status: tuple
1004 7232c04c Iustin Pop
    @param status: a tuple as returned from L{backend.FindBlockDevice}
1005 19708787 Iustin Pop
    @return: the string representing the status
1006 7232c04c Iustin Pop
1007 7232c04c Iustin Pop
    """
1008 a8083063 Iustin Pop
    if not status:
1009 19708787 Iustin Pop
      return "not active"
1010 19708787 Iustin Pop
    txt = ""
1011 f208978a Michael Hanselmann
    (path, major, minor, syncp, estt, degr, ldisk_status) = status
1012 19708787 Iustin Pop
    if major is None:
1013 19708787 Iustin Pop
      major_string = "N/A"
1014 a8083063 Iustin Pop
    else:
1015 e2736e40 Guido Trotter
      major_string = str(compat.TryToRoman(major, convert=roman))
1016 fd38ef95 Manuel Franceschini
1017 19708787 Iustin Pop
    if minor is None:
1018 19708787 Iustin Pop
      minor_string = "N/A"
1019 19708787 Iustin Pop
    else:
1020 e2736e40 Guido Trotter
      minor_string = str(compat.TryToRoman(minor, convert=roman))
1021 19708787 Iustin Pop
1022 19708787 Iustin Pop
    txt += ("%s (%s:%s)" % (path, major_string, minor_string))
1023 19708787 Iustin Pop
    if dtype in (constants.LD_DRBD8, ):
1024 19708787 Iustin Pop
      if syncp is not None:
1025 19708787 Iustin Pop
        sync_text = "*RECOVERING* %5.2f%%," % syncp
1026 19708787 Iustin Pop
        if estt:
1027 e2736e40 Guido Trotter
          sync_text += " ETA %ss" % compat.TryToRoman(estt, convert=roman)
1028 9db6dbce Iustin Pop
        else:
1029 19708787 Iustin Pop
          sync_text += " ETA unknown"
1030 19708787 Iustin Pop
      else:
1031 19708787 Iustin Pop
        sync_text = "in sync"
1032 19708787 Iustin Pop
      if degr:
1033 19708787 Iustin Pop
        degr_text = "*DEGRADED*"
1034 19708787 Iustin Pop
      else:
1035 19708787 Iustin Pop
        degr_text = "ok"
1036 f208978a Michael Hanselmann
      if ldisk_status == constants.LDS_FAULTY:
1037 19708787 Iustin Pop
        ldisk_text = " *MISSING DISK*"
1038 f208978a Michael Hanselmann
      elif ldisk_status == constants.LDS_UNKNOWN:
1039 f208978a Michael Hanselmann
        ldisk_text = " *UNCERTAIN STATE*"
1040 19708787 Iustin Pop
      else:
1041 19708787 Iustin Pop
        ldisk_text = ""
1042 19708787 Iustin Pop
      txt += (" %s, status %s%s" % (sync_text, degr_text, ldisk_text))
1043 19708787 Iustin Pop
    elif dtype == constants.LD_LV:
1044 f208978a Michael Hanselmann
      if ldisk_status == constants.LDS_FAULTY:
1045 19708787 Iustin Pop
        ldisk_text = " *FAILED* (failed drive?)"
1046 19708787 Iustin Pop
      else:
1047 19708787 Iustin Pop
        ldisk_text = ""
1048 19708787 Iustin Pop
      txt += ldisk_text
1049 19708787 Iustin Pop
    return txt
1050 19708787 Iustin Pop
1051 19708787 Iustin Pop
  # the header
1052 19708787 Iustin Pop
  if top_level:
1053 19708787 Iustin Pop
    if dev["iv_name"] is not None:
1054 19708787 Iustin Pop
      txt = dev["iv_name"]
1055 19708787 Iustin Pop
    else:
1056 e2736e40 Guido Trotter
      txt = "disk %s" % compat.TryToRoman(idx, convert=roman)
1057 a8083063 Iustin Pop
  else:
1058 e2736e40 Guido Trotter
    txt = "child %s" % compat.TryToRoman(idx, convert=roman)
1059 c98162a7 Iustin Pop
  if isinstance(dev["size"], int):
1060 c98162a7 Iustin Pop
    nice_size = utils.FormatUnit(dev["size"], "h")
1061 c98162a7 Iustin Pop
  else:
1062 c98162a7 Iustin Pop
    nice_size = dev["size"]
1063 c98162a7 Iustin Pop
  d1 = ["- %s: %s, size %s" % (txt, dev["dev_type"], nice_size)]
1064 19708787 Iustin Pop
  data = []
1065 19708787 Iustin Pop
  if top_level:
1066 19708787 Iustin Pop
    data.append(("access mode", dev["mode"]))
1067 a8083063 Iustin Pop
  if dev["logical_id"] is not None:
1068 19708787 Iustin Pop
    try:
1069 e2736e40 Guido Trotter
      l_id = _FormatLogicalID(dev["dev_type"], dev["logical_id"], roman)
1070 19708787 Iustin Pop
    except ValueError:
1071 19708787 Iustin Pop
      l_id = [str(dev["logical_id"])]
1072 19708787 Iustin Pop
    if len(l_id) == 1:
1073 19708787 Iustin Pop
      data.append(("logical_id", l_id[0]))
1074 19708787 Iustin Pop
    else:
1075 19708787 Iustin Pop
      data.extend(l_id)
1076 a8083063 Iustin Pop
  elif dev["physical_id"] is not None:
1077 19708787 Iustin Pop
    data.append("physical_id:")
1078 19708787 Iustin Pop
    data.append([dev["physical_id"]])
1079 57821cac Iustin Pop
  if not static:
1080 19708787 Iustin Pop
    data.append(("on primary", helper(dev["dev_type"], dev["pstatus"])))
1081 57821cac Iustin Pop
  if dev["sstatus"] and not static:
1082 19708787 Iustin Pop
    data.append(("on secondary", helper(dev["dev_type"], dev["sstatus"])))
1083 a8083063 Iustin Pop
1084 a8083063 Iustin Pop
  if dev["children"]:
1085 19708787 Iustin Pop
    data.append("child devices:")
1086 19708787 Iustin Pop
    for c_idx, child in enumerate(dev["children"]):
1087 e2736e40 Guido Trotter
      data.append(_FormatBlockDevInfo(c_idx, False, child, static, roman))
1088 19708787 Iustin Pop
  d1.append(data)
1089 19708787 Iustin Pop
  return d1
1090 a8083063 Iustin Pop
1091 a8083063 Iustin Pop
1092 19708787 Iustin Pop
def _FormatList(buf, data, indent_level):
1093 19708787 Iustin Pop
  """Formats a list of data at a given indent level.
1094 19708787 Iustin Pop
1095 19708787 Iustin Pop
  If the element of the list is:
1096 19708787 Iustin Pop
    - a string, it is simply formatted as is
1097 19708787 Iustin Pop
    - a tuple, it will be split into key, value and the all the
1098 19708787 Iustin Pop
      values in a list will be aligned all at the same start column
1099 19708787 Iustin Pop
    - a list, will be recursively formatted
1100 19708787 Iustin Pop
1101 19708787 Iustin Pop
  @type buf: StringIO
1102 19708787 Iustin Pop
  @param buf: the buffer into which we write the output
1103 19708787 Iustin Pop
  @param data: the list to format
1104 19708787 Iustin Pop
  @type indent_level: int
1105 19708787 Iustin Pop
  @param indent_level: the indent level to format at
1106 19708787 Iustin Pop
1107 19708787 Iustin Pop
  """
1108 19708787 Iustin Pop
  max_tlen = max([len(elem[0]) for elem in data
1109 19708787 Iustin Pop
                 if isinstance(elem, tuple)] or [0])
1110 19708787 Iustin Pop
  for elem in data:
1111 19708787 Iustin Pop
    if isinstance(elem, basestring):
1112 19708787 Iustin Pop
      buf.write("%*s%s\n" % (2*indent_level, "", elem))
1113 19708787 Iustin Pop
    elif isinstance(elem, tuple):
1114 19708787 Iustin Pop
      key, value = elem
1115 19708787 Iustin Pop
      spacer = "%*s" % (max_tlen - len(key), "")
1116 19708787 Iustin Pop
      buf.write("%*s%s:%s %s\n" % (2*indent_level, "", key, spacer, value))
1117 19708787 Iustin Pop
    elif isinstance(elem, list):
1118 19708787 Iustin Pop
      _FormatList(buf, elem, indent_level+1)
1119 19708787 Iustin Pop
1120 98825740 Michael Hanselmann
1121 dbb24ec7 Iustin Pop
def _FormatParameterDict(buf, per_inst, actual):
1122 dbb24ec7 Iustin Pop
  """Formats a parameter dictionary.
1123 dbb24ec7 Iustin Pop
1124 dbb24ec7 Iustin Pop
  @type buf: L{StringIO}
1125 dbb24ec7 Iustin Pop
  @param buf: the buffer into which to write
1126 dbb24ec7 Iustin Pop
  @type per_inst: dict
1127 dbb24ec7 Iustin Pop
  @param per_inst: the instance's own parameters
1128 dbb24ec7 Iustin Pop
  @type actual: dict
1129 dbb24ec7 Iustin Pop
  @param actual: the current parameter set (including defaults)
1130 dbb24ec7 Iustin Pop
1131 dbb24ec7 Iustin Pop
  """
1132 dbb24ec7 Iustin Pop
  for key in sorted(actual):
1133 dbb24ec7 Iustin Pop
    val = per_inst.get(key, "default (%s)" % actual[key])
1134 dbb24ec7 Iustin Pop
    buf.write("    - %s: %s\n" % (key, val))
1135 dbb24ec7 Iustin Pop
1136 a8083063 Iustin Pop
def ShowInstanceConfig(opts, args):
1137 a8083063 Iustin Pop
  """Compute instance run-time status.
1138 a8083063 Iustin Pop
1139 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
1140 7232c04c Iustin Pop
  @type args: list
1141 7232c04c Iustin Pop
  @param args: either an empty list, and then we query all
1142 7232c04c Iustin Pop
      instances, or should contain a list of instance names
1143 7232c04c Iustin Pop
  @rtype: int
1144 7232c04c Iustin Pop
  @return: the desired exit code
1145 7232c04c Iustin Pop
1146 a8083063 Iustin Pop
  """
1147 220cde0b Guido Trotter
  if not args and not opts.show_all:
1148 220cde0b Guido Trotter
    ToStderr("No instance selected."
1149 220cde0b Guido Trotter
             " Please pass in --all if you want to query all instances.\n"
1150 220cde0b Guido Trotter
             "Note that this can take a long time on a big cluster.")
1151 220cde0b Guido Trotter
    return 1
1152 220cde0b Guido Trotter
  elif args and opts.show_all:
1153 220cde0b Guido Trotter
    ToStderr("Cannot use --all if you specify instance names.")
1154 220cde0b Guido Trotter
    return 1
1155 220cde0b Guido Trotter
1156 a8083063 Iustin Pop
  retcode = 0
1157 57821cac Iustin Pop
  op = opcodes.OpQueryInstanceData(instances=args, static=opts.static)
1158 400ca2f7 Iustin Pop
  result = SubmitOpCode(op, opts=opts)
1159 a8083063 Iustin Pop
  if not result:
1160 3a24c527 Iustin Pop
    ToStdout("No instances.")
1161 a8083063 Iustin Pop
    return 1
1162 a8083063 Iustin Pop
1163 a8083063 Iustin Pop
  buf = StringIO()
1164 a8083063 Iustin Pop
  retcode = 0
1165 a8083063 Iustin Pop
  for instance_name in result:
1166 a8083063 Iustin Pop
    instance = result[instance_name]
1167 a8083063 Iustin Pop
    buf.write("Instance name: %s\n" % instance["name"])
1168 033d58b0 Iustin Pop
    buf.write("UUID: %s\n" % instance["uuid"])
1169 e2736e40 Guido Trotter
    buf.write("Serial number: %s\n" %
1170 e2736e40 Guido Trotter
              compat.TryToRoman(instance["serial_no"],
1171 e2736e40 Guido Trotter
                                convert=opts.roman_integers))
1172 90f72445 Iustin Pop
    buf.write("Creation time: %s\n" % utils.FormatTime(instance["ctime"]))
1173 90f72445 Iustin Pop
    buf.write("Modification time: %s\n" % utils.FormatTime(instance["mtime"]))
1174 57821cac Iustin Pop
    buf.write("State: configured to be %s" % instance["config_state"])
1175 57821cac Iustin Pop
    if not opts.static:
1176 57821cac Iustin Pop
      buf.write(", actual state is %s" % instance["run_state"])
1177 57821cac Iustin Pop
    buf.write("\n")
1178 57821cac Iustin Pop
    ##buf.write("Considered for memory checks in cluster verify: %s\n" %
1179 57821cac Iustin Pop
    ##          instance["auto_balance"])
1180 a8083063 Iustin Pop
    buf.write("  Nodes:\n")
1181 a8083063 Iustin Pop
    buf.write("    - primary: %s\n" % instance["pnode"])
1182 1f864b60 Iustin Pop
    buf.write("    - secondaries: %s\n" % utils.CommaJoin(instance["snodes"]))
1183 a8083063 Iustin Pop
    buf.write("  Operating system: %s\n" % instance["os"])
1184 dbb24ec7 Iustin Pop
    _FormatParameterDict(buf, instance["os_instance"], instance["os_actual"])
1185 a8340917 Iustin Pop
    if instance.has_key("network_port"):
1186 e2736e40 Guido Trotter
      buf.write("  Allocated network port: %s\n" %
1187 e2736e40 Guido Trotter
                compat.TryToRoman(instance["network_port"],
1188 e2736e40 Guido Trotter
                                  convert=opts.roman_integers))
1189 24838135 Iustin Pop
    buf.write("  Hypervisor: %s\n" % instance["hypervisor"])
1190 dfff41f8 Guido Trotter
1191 dfff41f8 Guido Trotter
    # custom VNC console information
1192 dfff41f8 Guido Trotter
    vnc_bind_address = instance["hv_actual"].get(constants.HV_VNC_BIND_ADDRESS,
1193 dfff41f8 Guido Trotter
                                                 None)
1194 dfff41f8 Guido Trotter
    if vnc_bind_address:
1195 dfff41f8 Guido Trotter
      port = instance["network_port"]
1196 dfff41f8 Guido Trotter
      display = int(port) - constants.VNC_BASE_PORT
1197 9769bb78 Manuel Franceschini
      if display > 0 and vnc_bind_address == constants.IP4_ADDRESS_ANY:
1198 dfff41f8 Guido Trotter
        vnc_console_port = "%s:%s (display %s)" % (instance["pnode"],
1199 dfff41f8 Guido Trotter
                                                   port,
1200 dfff41f8 Guido Trotter
                                                   display)
1201 c0c3fa27 Manuel Franceschini
      elif display > 0 and utils.IsValidIP4(vnc_bind_address):
1202 dfff41f8 Guido Trotter
        vnc_console_port = ("%s:%s (node %s) (display %s)" %
1203 dfff41f8 Guido Trotter
                             (vnc_bind_address, port,
1204 dfff41f8 Guido Trotter
                              instance["pnode"], display))
1205 a8340917 Iustin Pop
      else:
1206 dfff41f8 Guido Trotter
        # vnc bind address is a file
1207 dfff41f8 Guido Trotter
        vnc_console_port = "%s:%s" % (instance["pnode"],
1208 dfff41f8 Guido Trotter
                                      vnc_bind_address)
1209 24838135 Iustin Pop
      buf.write("    - console connection: vnc to %s\n" % vnc_console_port)
1210 24838135 Iustin Pop
1211 dbb24ec7 Iustin Pop
    _FormatParameterDict(buf, instance["hv_instance"], instance["hv_actual"])
1212 a8083063 Iustin Pop
    buf.write("  Hardware:\n")
1213 e2736e40 Guido Trotter
    buf.write("    - VCPUs: %s\n" %
1214 e2736e40 Guido Trotter
              compat.TryToRoman(instance["be_actual"][constants.BE_VCPUS],
1215 e2736e40 Guido Trotter
                                convert=opts.roman_integers))
1216 e2736e40 Guido Trotter
    buf.write("    - memory: %sMiB\n" %
1217 e2736e40 Guido Trotter
              compat.TryToRoman(instance["be_actual"][constants.BE_MEMORY],
1218 e2736e40 Guido Trotter
                                convert=opts.roman_integers))
1219 d2acfe27 Iustin Pop
    buf.write("    - NICs:\n")
1220 14ea9302 Guido Trotter
    for idx, (ip, mac, mode, link) in enumerate(instance["nics"]):
1221 0b13832c Guido Trotter
      buf.write("      - nic/%d: MAC: %s, IP: %s, mode: %s, link: %s\n" %
1222 0b13832c Guido Trotter
                (idx, mac, ip, mode, link))
1223 19708787 Iustin Pop
    buf.write("  Disks:\n")
1224 a8083063 Iustin Pop
1225 19708787 Iustin Pop
    for idx, device in enumerate(instance["disks"]):
1226 e2736e40 Guido Trotter
      _FormatList(buf, _FormatBlockDevInfo(idx, True, device, opts.static,
1227 e2736e40 Guido Trotter
                  opts.roman_integers), 2)
1228 a8083063 Iustin Pop
1229 3a24c527 Iustin Pop
  ToStdout(buf.getvalue().rstrip('\n'))
1230 a8083063 Iustin Pop
  return retcode
1231 a8083063 Iustin Pop
1232 a8083063 Iustin Pop
1233 7767bbf5 Manuel Franceschini
def SetInstanceParams(opts, args):
1234 a8083063 Iustin Pop
  """Modifies an instance.
1235 a8083063 Iustin Pop
1236 a8083063 Iustin Pop
  All parameters take effect only at the next restart of the instance.
1237 a8083063 Iustin Pop
1238 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
1239 7232c04c Iustin Pop
  @type args: list
1240 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
1241 7232c04c Iustin Pop
  @rtype: int
1242 7232c04c Iustin Pop
  @return: the desired exit code
1243 a8083063 Iustin Pop
1244 a8083063 Iustin Pop
  """
1245 e29e9550 Iustin Pop
  if not (opts.nics or opts.disks or opts.disk_template or
1246 1052d622 Iustin Pop
          opts.hvparams or opts.beparams or opts.os or opts.osparams):
1247 3a24c527 Iustin Pop
    ToStderr("Please give at least one of the parameters.")
1248 a8083063 Iustin Pop
    return 1
1249 a8083063 Iustin Pop
1250 467ae11e Guido Trotter
  for param in opts.beparams:
1251 e9d622bc Guido Trotter
    if isinstance(opts.beparams[param], basestring):
1252 e9d622bc Guido Trotter
      if opts.beparams[param].lower() == "default":
1253 e9d622bc Guido Trotter
        opts.beparams[param] = constants.VALUE_DEFAULT
1254 a5728081 Guido Trotter
1255 a5728081 Guido Trotter
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES,
1256 a5728081 Guido Trotter
                      allowed_values=[constants.VALUE_DEFAULT])
1257 467ae11e Guido Trotter
1258 48f212d7 Iustin Pop
  for param in opts.hvparams:
1259 48f212d7 Iustin Pop
    if isinstance(opts.hvparams[param], basestring):
1260 48f212d7 Iustin Pop
      if opts.hvparams[param].lower() == "default":
1261 48f212d7 Iustin Pop
        opts.hvparams[param] = constants.VALUE_DEFAULT
1262 a5728081 Guido Trotter
1263 48f212d7 Iustin Pop
  utils.ForceDictType(opts.hvparams, constants.HVS_PARAMETER_TYPES,
1264 a5728081 Guido Trotter
                      allowed_values=[constants.VALUE_DEFAULT])
1265 61be6ba4 Iustin Pop
1266 24991749 Iustin Pop
  for idx, (nic_op, nic_dict) in enumerate(opts.nics):
1267 24991749 Iustin Pop
    try:
1268 24991749 Iustin Pop
      nic_op = int(nic_op)
1269 24991749 Iustin Pop
      opts.nics[idx] = (nic_op, nic_dict)
1270 691744c4 Iustin Pop
    except (TypeError, ValueError):
1271 24991749 Iustin Pop
      pass
1272 24991749 Iustin Pop
1273 24991749 Iustin Pop
  for idx, (disk_op, disk_dict) in enumerate(opts.disks):
1274 24991749 Iustin Pop
    try:
1275 24991749 Iustin Pop
      disk_op = int(disk_op)
1276 24991749 Iustin Pop
      opts.disks[idx] = (disk_op, disk_dict)
1277 691744c4 Iustin Pop
    except (TypeError, ValueError):
1278 24991749 Iustin Pop
      pass
1279 24991749 Iustin Pop
    if disk_op == constants.DDM_ADD:
1280 24991749 Iustin Pop
      if 'size' not in disk_dict:
1281 debac808 Iustin Pop
        raise errors.OpPrereqError("Missing required parameter 'size'",
1282 debac808 Iustin Pop
                                   errors.ECODE_INVAL)
1283 24991749 Iustin Pop
      disk_dict['size'] = utils.ParseUnit(disk_dict['size'])
1284 24991749 Iustin Pop
1285 e29e9550 Iustin Pop
  if (opts.disk_template and
1286 e29e9550 Iustin Pop
      opts.disk_template in constants.DTS_NET_MIRROR and
1287 e29e9550 Iustin Pop
      not opts.node):
1288 e29e9550 Iustin Pop
    ToStderr("Changing the disk template to a mirrored one requires"
1289 e29e9550 Iustin Pop
             " specifying a secondary node")
1290 e29e9550 Iustin Pop
    return 1
1291 e29e9550 Iustin Pop
1292 338e51e8 Iustin Pop
  op = opcodes.OpSetInstanceParams(instance_name=args[0],
1293 24991749 Iustin Pop
                                   nics=opts.nics,
1294 24991749 Iustin Pop
                                   disks=opts.disks,
1295 e29e9550 Iustin Pop
                                   disk_template=opts.disk_template,
1296 e29e9550 Iustin Pop
                                   remote_node=opts.node,
1297 48f212d7 Iustin Pop
                                   hvparams=opts.hvparams,
1298 338e51e8 Iustin Pop
                                   beparams=opts.beparams,
1299 96b39bcc Iustin Pop
                                   os_name=opts.os,
1300 1052d622 Iustin Pop
                                   osparams=opts.osparams,
1301 96b39bcc Iustin Pop
                                   force_variant=opts.force_variant,
1302 4300c4b6 Guido Trotter
                                   force=opts.force)
1303 31a853d2 Iustin Pop
1304 6340bb0a Iustin Pop
  # even if here we process the result, we allow submit only
1305 6340bb0a Iustin Pop
  result = SubmitOrSend(op, opts)
1306 a8083063 Iustin Pop
1307 a8083063 Iustin Pop
  if result:
1308 3a24c527 Iustin Pop
    ToStdout("Modified instance %s", args[0])
1309 a8083063 Iustin Pop
    for param, data in result:
1310 3a24c527 Iustin Pop
      ToStdout(" - %-5s -> %s", param, data)
1311 e29e9550 Iustin Pop
    ToStdout("Please don't forget that most parameters take effect"
1312 3a24c527 Iustin Pop
             " only at the next start of the instance.")
1313 a8083063 Iustin Pop
  return 0
1314 a8083063 Iustin Pop
1315 a8083063 Iustin Pop
1316 312ac745 Iustin Pop
# multi-instance selection options
1317 c38c44ad Michael Hanselmann
m_force_multi = cli_option("--force-multiple", dest="force_multi",
1318 c38c44ad Michael Hanselmann
                           help="Do not ask for confirmation when more than"
1319 c38c44ad Michael Hanselmann
                           " one instance is affected",
1320 c38c44ad Michael Hanselmann
                           action="store_true", default=False)
1321 804a1e8e Iustin Pop
1322 c38c44ad Michael Hanselmann
m_pri_node_opt = cli_option("--primary", dest="multi_mode",
1323 c38c44ad Michael Hanselmann
                            help="Filter by nodes (primary only)",
1324 c38c44ad Michael Hanselmann
                            const=_SHUTDOWN_NODES_PRI, action="store_const")
1325 312ac745 Iustin Pop
1326 c38c44ad Michael Hanselmann
m_sec_node_opt = cli_option("--secondary", dest="multi_mode",
1327 c38c44ad Michael Hanselmann
                            help="Filter by nodes (secondary only)",
1328 c38c44ad Michael Hanselmann
                            const=_SHUTDOWN_NODES_SEC, action="store_const")
1329 312ac745 Iustin Pop
1330 c38c44ad Michael Hanselmann
m_node_opt = cli_option("--node", dest="multi_mode",
1331 c38c44ad Michael Hanselmann
                        help="Filter by nodes (primary and secondary)",
1332 c38c44ad Michael Hanselmann
                        const=_SHUTDOWN_NODES_BOTH, action="store_const")
1333 312ac745 Iustin Pop
1334 c38c44ad Michael Hanselmann
m_clust_opt = cli_option("--all", dest="multi_mode",
1335 c38c44ad Michael Hanselmann
                         help="Select all instances in the cluster",
1336 c38c44ad Michael Hanselmann
                         const=_SHUTDOWN_CLUSTER, action="store_const")
1337 312ac745 Iustin Pop
1338 c38c44ad Michael Hanselmann
m_inst_opt = cli_option("--instance", dest="multi_mode",
1339 c38c44ad Michael Hanselmann
                        help="Filter by instance name [default]",
1340 c38c44ad Michael Hanselmann
                        const=_SHUTDOWN_INSTANCES, action="store_const")
1341 312ac745 Iustin Pop
1342 39dfd93e René Nussbaumer
m_node_tags_opt = cli_option("--node-tags", dest="multi_mode",
1343 39dfd93e René Nussbaumer
                             help="Filter by node tag",
1344 39dfd93e René Nussbaumer
                             const=_SHUTDOWN_NODES_BOTH_BY_TAGS,
1345 39dfd93e René Nussbaumer
                             action="store_const")
1346 39dfd93e René Nussbaumer
1347 39dfd93e René Nussbaumer
m_pri_node_tags_opt = cli_option("--pri-node-tags", dest="multi_mode",
1348 39dfd93e René Nussbaumer
                                 help="Filter by primary node tag",
1349 39dfd93e René Nussbaumer
                                 const=_SHUTDOWN_NODES_PRI_BY_TAGS,
1350 39dfd93e René Nussbaumer
                                 action="store_const")
1351 39dfd93e René Nussbaumer
1352 39dfd93e René Nussbaumer
m_sec_node_tags_opt = cli_option("--sec-node-tags", dest="multi_mode",
1353 39dfd93e René Nussbaumer
                                 help="Filter by secondary node tag",
1354 39dfd93e René Nussbaumer
                                 const=_SHUTDOWN_NODES_SEC_BY_TAGS,
1355 39dfd93e René Nussbaumer
                                 action="store_const")
1356 39dfd93e René Nussbaumer
1357 39dfd93e René Nussbaumer
m_inst_tags_opt = cli_option("--tags", dest="multi_mode",
1358 39dfd93e René Nussbaumer
                             help="Filter by instance tag",
1359 39dfd93e René Nussbaumer
                             const=_SHUTDOWN_INSTANCES_BY_TAGS,
1360 39dfd93e René Nussbaumer
                             action="store_const")
1361 312ac745 Iustin Pop
1362 a8083063 Iustin Pop
# this is defined separately due to readability only
1363 a8083063 Iustin Pop
add_opts = [
1364 087ed2ed Iustin Pop
  BACKEND_OPT,
1365 e3876ccb Iustin Pop
  DISK_OPT,
1366 064c21f8 Iustin Pop
  DISK_TEMPLATE_OPT,
1367 4a25828c Iustin Pop
  FILESTORE_DIR_OPT,
1368 0f87c43e Iustin Pop
  FILESTORE_DRIVER_OPT,
1369 236fd9c4 Iustin Pop
  HYPERVISOR_OPT,
1370 064c21f8 Iustin Pop
  IALLOCATOR_OPT,
1371 064c21f8 Iustin Pop
  NET_OPT,
1372 064c21f8 Iustin Pop
  NODE_PLACEMENT_OPT,
1373 064c21f8 Iustin Pop
  NOIPCHECK_OPT,
1374 460d22be Iustin Pop
  NONAMECHECK_OPT,
1375 064c21f8 Iustin Pop
  NONICS_OPT,
1376 064c21f8 Iustin Pop
  NOSTART_OPT,
1377 064c21f8 Iustin Pop
  NWSYNC_OPT,
1378 062a7100 Iustin Pop
  OSPARAMS_OPT,
1379 064c21f8 Iustin Pop
  OS_OPT,
1380 06073e85 Guido Trotter
  FORCE_VARIANT_OPT,
1381 25a8792c Iustin Pop
  NO_INSTALL_OPT,
1382 064c21f8 Iustin Pop
  OS_SIZE_OPT,
1383 6340bb0a Iustin Pop
  SUBMIT_OPT,
1384 a8083063 Iustin Pop
  ]
1385 a8083063 Iustin Pop
1386 a8083063 Iustin Pop
commands = {
1387 6ea815cf Iustin Pop
  'add': (
1388 6ea815cf Iustin Pop
    AddInstance, [ArgHost(min=1, max=1)], add_opts,
1389 6ea815cf Iustin Pop
    "[...] -t disk-type -n node[:secondary-node] -o os-type <name>",
1390 6ea815cf Iustin Pop
    "Creates and adds a new instance to the cluster"),
1391 6ea815cf Iustin Pop
  'batch-create': (
1392 064c21f8 Iustin Pop
    BatchCreate, [ArgFile(min=1, max=1)], [],
1393 6ea815cf Iustin Pop
    "<instances.json>",
1394 6ea815cf Iustin Pop
    "Create a bunch of instances based on specs in the file."),
1395 6ea815cf Iustin Pop
  'console': (
1396 6ea815cf Iustin Pop
    ConnectToInstanceConsole, ARGS_ONE_INSTANCE,
1397 064c21f8 Iustin Pop
    [SHOWCMD_OPT],
1398 6ea815cf Iustin Pop
    "[--show-cmd] <instance>", "Opens a console on the specified instance"),
1399 6ea815cf Iustin Pop
  'failover': (
1400 6ea815cf Iustin Pop
    FailoverInstance, ARGS_ONE_INSTANCE,
1401 17c3f802 Guido Trotter
    [FORCE_OPT, IGNORE_CONSIST_OPT, SUBMIT_OPT, SHUTDOWN_TIMEOUT_OPT],
1402 6ea815cf Iustin Pop
    "[-f] <instance>", "Stops the instance and starts it on the backup node,"
1403 6ea815cf Iustin Pop
    " using the remote mirror (only for instances of type drbd)"),
1404 6ea815cf Iustin Pop
  'migrate': (
1405 6ea815cf Iustin Pop
    MigrateInstance, ARGS_ONE_INSTANCE,
1406 064c21f8 Iustin Pop
    [FORCE_OPT, NONLIVE_OPT, CLEANUP_OPT],
1407 6ea815cf Iustin Pop
    "[-f] <instance>", "Migrate instance to its secondary node"
1408 6ea815cf Iustin Pop
    " (only for instances of type drbd)"),
1409 6ea815cf Iustin Pop
  'move': (
1410 6ea815cf Iustin Pop
    MoveInstance, ARGS_ONE_INSTANCE,
1411 17c3f802 Guido Trotter
    [FORCE_OPT, SUBMIT_OPT, SINGLE_NODE_OPT, SHUTDOWN_TIMEOUT_OPT],
1412 6ea815cf Iustin Pop
    "[-f] <instance>", "Move instance to an arbitrary node"
1413 6ea815cf Iustin Pop
    " (only for instances of type file and lv)"),
1414 6ea815cf Iustin Pop
  'info': (
1415 6ea815cf Iustin Pop
    ShowInstanceConfig, ARGS_MANY_INSTANCES,
1416 e2736e40 Guido Trotter
    [STATIC_OPT, ALL_OPT, ROMAN_OPT],
1417 6ea815cf Iustin Pop
    "[-s] {--all | <instance>...}",
1418 6ea815cf Iustin Pop
    "Show information on the specified instance(s)"),
1419 6ea815cf Iustin Pop
  'list': (
1420 6ea815cf Iustin Pop
    ListInstances, ARGS_MANY_INSTANCES,
1421 e2736e40 Guido Trotter
    [NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, SYNC_OPT, ROMAN_OPT],
1422 6ea815cf Iustin Pop
    "[<instance>...]",
1423 6ea815cf Iustin Pop
    "Lists the instances and their status. The available fields are"
1424 6ea815cf Iustin Pop
    " (see the man page for details): status, oper_state, oper_ram,"
1425 6ea815cf Iustin Pop
    " name, os, pnode, snodes, admin_state, admin_ram, disk_template,"
1426 8619a3bd Guido Trotter
    " ip, mac, nic_mode, nic_link, sda_size, sdb_size, vcpus, serial_no,"
1427 8619a3bd Guido Trotter
    " nic.count, nic.mac/N, nic.ip/N, nic.mode/N, nic.link/N,"
1428 8619a3bd Guido Trotter
    " nic.macs, nic.ips, nic.modes, nic.links,"
1429 8619a3bd Guido Trotter
    " disk.count, disk.size/N, disk.sizes,"
1430 8619a3bd Guido Trotter
    " hv/NAME, be/memory, be/vcpus, be/auto_balance,"
1431 6ea815cf Iustin Pop
    " hypervisor."
1432 6ea815cf Iustin Pop
    " The default field"
1433 1f864b60 Iustin Pop
    " list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS),
1434 6ea815cf Iustin Pop
    ),
1435 6ea815cf Iustin Pop
  'reinstall': (
1436 3e54ace7 Iustin Pop
    ReinstallInstance, [ArgInstance()],
1437 06073e85 Guido Trotter
    [FORCE_OPT, OS_OPT, FORCE_VARIANT_OPT, m_force_multi, m_node_opt,
1438 39dfd93e René Nussbaumer
     m_pri_node_opt, m_sec_node_opt, m_clust_opt, m_inst_opt, m_node_tags_opt,
1439 39dfd93e René Nussbaumer
     m_pri_node_tags_opt, m_sec_node_tags_opt, m_inst_tags_opt, SELECT_OS_OPT,
1440 06073e85 Guido Trotter
     SUBMIT_OPT],
1441 6ea815cf Iustin Pop
    "[-f] <instance>", "Reinstall a stopped instance"),
1442 6ea815cf Iustin Pop
  'remove': (
1443 6ea815cf Iustin Pop
    RemoveInstance, ARGS_ONE_INSTANCE,
1444 17c3f802 Guido Trotter
    [FORCE_OPT, SHUTDOWN_TIMEOUT_OPT, IGNORE_FAILURES_OPT, SUBMIT_OPT],
1445 6ea815cf Iustin Pop
    "[-f] <instance>", "Shuts down the instance and removes it"),
1446 6ea815cf Iustin Pop
  'rename': (
1447 6ea815cf Iustin Pop
    RenameInstance,
1448 6ea815cf Iustin Pop
    [ArgInstance(min=1, max=1), ArgHost(min=1, max=1)],
1449 1b6dddc8 René Nussbaumer
    [NOIPCHECK_OPT, NONAMECHECK_OPT, SUBMIT_OPT],
1450 6ea815cf Iustin Pop
    "<instance> <new_name>", "Rename the instance"),
1451 6ea815cf Iustin Pop
  'replace-disks': (
1452 6ea815cf Iustin Pop
    ReplaceDisks, ARGS_ONE_INSTANCE,
1453 7ea7bcf6 Iustin Pop
    [AUTO_REPLACE_OPT, DISKIDX_OPT, IALLOCATOR_OPT, EARLY_RELEASE_OPT,
1454 6ea815cf Iustin Pop
     NEW_SECONDARY_OPT, ON_PRIMARY_OPT, ON_SECONDARY_OPT, SUBMIT_OPT],
1455 6ea815cf Iustin Pop
    "[-s|-p|-n NODE|-I NAME] <instance>",
1456 6ea815cf Iustin Pop
    "Replaces all disks for the instance"),
1457 6ea815cf Iustin Pop
  'modify': (
1458 6ea815cf Iustin Pop
    SetInstanceParams, ARGS_ONE_INSTANCE,
1459 e29e9550 Iustin Pop
    [BACKEND_OPT, DISK_OPT, FORCE_OPT, HVOPTS_OPT, NET_OPT, SUBMIT_OPT,
1460 1052d622 Iustin Pop
     DISK_TEMPLATE_OPT, SINGLE_NODE_OPT, OS_OPT, FORCE_VARIANT_OPT,
1461 1052d622 Iustin Pop
     OSPARAMS_OPT],
1462 6ea815cf Iustin Pop
    "<instance>", "Alters the parameters of an instance"),
1463 6ea815cf Iustin Pop
  'shutdown': (
1464 1c5945b6 Iustin Pop
    GenericManyOps("shutdown", _ShutdownInstance), [ArgInstance()],
1465 064c21f8 Iustin Pop
    [m_node_opt, m_pri_node_opt, m_sec_node_opt, m_clust_opt,
1466 39dfd93e René Nussbaumer
     m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt,
1467 39dfd93e René Nussbaumer
     m_inst_tags_opt, m_inst_opt, m_force_multi, TIMEOUT_OPT, SUBMIT_OPT],
1468 6ea815cf Iustin Pop
    "<instance>", "Stops an instance"),
1469 6ea815cf Iustin Pop
  'startup': (
1470 1c5945b6 Iustin Pop
    GenericManyOps("startup", _StartupInstance), [ArgInstance()],
1471 39dfd93e René Nussbaumer
    [FORCE_OPT, m_force_multi, m_node_opt, m_pri_node_opt, m_sec_node_opt,
1472 39dfd93e René Nussbaumer
     m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt,
1473 39dfd93e René Nussbaumer
     m_inst_tags_opt, m_clust_opt, m_inst_opt, SUBMIT_OPT, HVOPTS_OPT,
1474 6ea815cf Iustin Pop
     BACKEND_OPT],
1475 6ea815cf Iustin Pop
    "<instance>", "Starts an instance"),
1476 6ea815cf Iustin Pop
  'reboot': (
1477 1c5945b6 Iustin Pop
    GenericManyOps("reboot", _RebootInstance), [ArgInstance()],
1478 064c21f8 Iustin Pop
    [m_force_multi, REBOOT_TYPE_OPT, IGNORE_SECONDARIES_OPT, m_node_opt,
1479 17c3f802 Guido Trotter
     m_pri_node_opt, m_sec_node_opt, m_clust_opt, m_inst_opt, SUBMIT_OPT,
1480 39dfd93e René Nussbaumer
     m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt,
1481 39dfd93e René Nussbaumer
     m_inst_tags_opt, SHUTDOWN_TIMEOUT_OPT],
1482 6ea815cf Iustin Pop
    "<instance>", "Reboots an instance"),
1483 6ea815cf Iustin Pop
  'activate-disks': (
1484 064c21f8 Iustin Pop
    ActivateDisks, ARGS_ONE_INSTANCE, [SUBMIT_OPT, IGNORE_SIZE_OPT],
1485 6ea815cf Iustin Pop
    "<instance>", "Activate an instance's disks"),
1486 6ea815cf Iustin Pop
  'deactivate-disks': (
1487 064c21f8 Iustin Pop
    DeactivateDisks, ARGS_ONE_INSTANCE, [SUBMIT_OPT],
1488 6ea815cf Iustin Pop
    "<instance>", "Deactivate an instance's disks"),
1489 6ea815cf Iustin Pop
  'recreate-disks': (
1490 064c21f8 Iustin Pop
    RecreateDisks, ARGS_ONE_INSTANCE, [SUBMIT_OPT, DISKIDX_OPT],
1491 6ea815cf Iustin Pop
    "<instance>", "Recreate an instance's disks"),
1492 6ea815cf Iustin Pop
  'grow-disk': (
1493 6ea815cf Iustin Pop
    GrowDisk,
1494 6ea815cf Iustin Pop
    [ArgInstance(min=1, max=1), ArgUnknown(min=1, max=1),
1495 6ea815cf Iustin Pop
     ArgUnknown(min=1, max=1)],
1496 064c21f8 Iustin Pop
    [SUBMIT_OPT, NWSYNC_OPT],
1497 6ea815cf Iustin Pop
    "<instance> <disk> <size>", "Grow an instance's disk"),
1498 6ea815cf Iustin Pop
  'list-tags': (
1499 064c21f8 Iustin Pop
    ListTags, ARGS_ONE_INSTANCE, [],
1500 6ea815cf Iustin Pop
    "<instance_name>", "List the tags of the given instance"),
1501 6ea815cf Iustin Pop
  'add-tags': (
1502 6ea815cf Iustin Pop
    AddTags, [ArgInstance(min=1, max=1), ArgUnknown()],
1503 064c21f8 Iustin Pop
    [TAG_SRC_OPT],
1504 6ea815cf Iustin Pop
    "<instance_name> tag...", "Add tags to the given instance"),
1505 6ea815cf Iustin Pop
  'remove-tags': (
1506 6ea815cf Iustin Pop
    RemoveTags, [ArgInstance(min=1, max=1), ArgUnknown()],
1507 064c21f8 Iustin Pop
    [TAG_SRC_OPT],
1508 6ea815cf Iustin Pop
    "<instance_name> tag...", "Remove tags from given instance"),
1509 a8083063 Iustin Pop
  }
1510 a8083063 Iustin Pop
1511 7232c04c Iustin Pop
#: dictionary with aliases for commands
1512 dbfd89dd Guido Trotter
aliases = {
1513 dbfd89dd Guido Trotter
  'activate_block_devs': 'activate-disks',
1514 00ce8b29 Guido Trotter
  'replace_disks': 'replace-disks',
1515 536fda25 Guido Trotter
  'start': 'startup',
1516 536fda25 Guido Trotter
  'stop': 'shutdown',
1517 dbfd89dd Guido Trotter
  }
1518 dbfd89dd Guido Trotter
1519 a8005e17 Michael Hanselmann
1520 a8083063 Iustin Pop
if __name__ == '__main__':
1521 dbfd89dd Guido Trotter
  sys.exit(GenericMain(commands, aliases=aliases,
1522 846baef9 Iustin Pop
                       override={"tag_type": constants.TAG_INSTANCE}))