Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_instance.py @ eb28ecf6

History | View | Annotate | Download (53 kB)

1 e792102d Michael Hanselmann
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 783a6c0b Iustin Pop
# Copyright (C) 2006, 2007, 2008, 2009, 2010 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 os
29 312ac745 Iustin Pop
import itertools
30 0d0e9090 René Nussbaumer
import simplejson
31 a8083063 Iustin Pop
from cStringIO import StringIO
32 a8083063 Iustin Pop
33 a8083063 Iustin Pop
from ganeti.cli import *
34 a8083063 Iustin Pop
from ganeti import opcodes
35 a8083063 Iustin Pop
from ganeti import constants
36 e2736e40 Guido Trotter
from ganeti import compat
37 a8083063 Iustin Pop
from ganeti import utils
38 312ac745 Iustin Pop
from ganeti import errors
39 a744b676 Manuel Franceschini
from ganeti import netutils
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 b4e68848 Iustin Pop
    results = jex.WaitOrShow(not opts.submit_only)
231 b4e68848 Iustin Pop
    rcode = compat.all(row[0] for row in results)
232 b4e68848 Iustin Pop
    return int(not rcode)
233 1c5945b6 Iustin Pop
  return realfn
234 1c5945b6 Iustin Pop
235 1c5945b6 Iustin Pop
236 a8083063 Iustin Pop
def ListInstances(opts, args):
237 f5abe9bd Oleksiy Mishchenko
  """List instances and their properties.
238 a8083063 Iustin Pop

239 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
240 7232c04c Iustin Pop
  @type args: list
241 7232c04c Iustin Pop
  @param args: should be an empty list
242 7232c04c Iustin Pop
  @rtype: int
243 7232c04c Iustin Pop
  @return: the desired exit code
244 7232c04c Iustin Pop

245 a8083063 Iustin Pop
  """
246 a4ebd726 Michael Hanselmann
  selected_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
247 a8083063 Iustin Pop
248 ec79568d Iustin Pop
  output = GetClient().QueryInstances(args, selected_fields, opts.do_locking)
249 a8083063 Iustin Pop
250 a8083063 Iustin Pop
  if not opts.no_headers:
251 d8052456 Iustin Pop
    headers = {
252 d8052456 Iustin Pop
      "name": "Instance", "os": "OS", "pnode": "Primary_node",
253 d8052456 Iustin Pop
      "snodes": "Secondary_Nodes", "admin_state": "Autostart",
254 338e51e8 Iustin Pop
      "oper_state": "Running",
255 d8052456 Iustin Pop
      "oper_ram": "Memory", "disk_template": "Disk_template",
256 4ea3de4e Balazs Lecz
      "oper_vcpus": "VCPUs",
257 3fb1e1c5 Alexander Schreiber
      "ip": "IP_address", "mac": "MAC_address",
258 638c6349 Guido Trotter
      "nic_mode": "NIC_Mode", "nic_link": "NIC_Link",
259 338e51e8 Iustin Pop
      "bridge": "Bridge",
260 d8052456 Iustin Pop
      "sda_size": "Disk/0", "sdb_size": "Disk/1",
261 024e157f Iustin Pop
      "disk_usage": "DiskUsage",
262 130a6a6f Iustin Pop
      "status": "Status", "tags": "Tags",
263 3fb1e1c5 Alexander Schreiber
      "network_port": "Network_port",
264 5018a335 Iustin Pop
      "hv/kernel_path": "Kernel_path",
265 5018a335 Iustin Pop
      "hv/initrd_path": "Initrd_path",
266 20b1bd80 Iustin Pop
      "hv/boot_order": "Boot_order",
267 20b1bd80 Iustin Pop
      "hv/acpi": "ACPI",
268 20b1bd80 Iustin Pop
      "hv/pae": "PAE",
269 20b1bd80 Iustin Pop
      "hv/cdrom_image_path": "CDROM_image_path",
270 20b1bd80 Iustin Pop
      "hv/nic_type": "NIC_type",
271 20b1bd80 Iustin Pop
      "hv/disk_type": "Disk_type",
272 7ac1fc45 Guido Trotter
      "hv/vnc_bind_address": "VNC_bind_address",
273 e69d05fd Iustin Pop
      "serial_no": "SerialNo", "hypervisor": "Hypervisor",
274 5018a335 Iustin Pop
      "hvparams": "Hypervisor_parameters",
275 338e51e8 Iustin Pop
      "be/memory": "Configured_memory",
276 338e51e8 Iustin Pop
      "be/vcpus": "VCPUs",
277 c1ce76bb Iustin Pop
      "vcpus": "VCPUs",
278 c0f2b229 Iustin Pop
      "be/auto_balance": "Auto_balance",
279 23b8c8d6 Iustin Pop
      "disk.count": "Disks", "disk.sizes": "Disk_sizes",
280 23b8c8d6 Iustin Pop
      "nic.count": "NICs", "nic.ips": "NIC_IPs",
281 638c6349 Guido Trotter
      "nic.modes": "NIC_modes", "nic.links": "NIC_links",
282 23b8c8d6 Iustin Pop
      "nic.bridges": "NIC_bridges", "nic.macs": "NIC_MACs",
283 033d58b0 Iustin Pop
      "ctime": "CTime", "mtime": "MTime", "uuid": "UUID",
284 d8052456 Iustin Pop
      }
285 137161c9 Michael Hanselmann
  else:
286 137161c9 Michael Hanselmann
    headers = None
287 137161c9 Michael Hanselmann
288 9fbfbb7b Iustin Pop
  unitfields = ["be/memory", "oper_ram", "sd(a|b)_size", "disk\.size/.*"]
289 00430f8e Iustin Pop
  numfields = ["be/memory", "oper_ram", "sd(a|b)_size", "be/vcpus",
290 23b8c8d6 Iustin Pop
               "serial_no", "(disk|nic)\.count", "disk\.size/.*"]
291 137161c9 Michael Hanselmann
292 638c6349 Guido Trotter
  list_type_fields = ("tags", "disk.sizes", "nic.macs", "nic.ips",
293 638c6349 Guido Trotter
                      "nic.modes", "nic.links", "nic.bridges")
294 8a23d2d3 Iustin Pop
  # change raw values to nicer strings
295 8a23d2d3 Iustin Pop
  for row in output:
296 8a23d2d3 Iustin Pop
    for idx, field in enumerate(selected_fields):
297 8a23d2d3 Iustin Pop
      val = row[idx]
298 8a23d2d3 Iustin Pop
      if field == "snodes":
299 8a23d2d3 Iustin Pop
        val = ",".join(val) or "-"
300 8a23d2d3 Iustin Pop
      elif field == "admin_state":
301 8a23d2d3 Iustin Pop
        if val:
302 8a23d2d3 Iustin Pop
          val = "yes"
303 8a23d2d3 Iustin Pop
        else:
304 8a23d2d3 Iustin Pop
          val = "no"
305 8a23d2d3 Iustin Pop
      elif field == "oper_state":
306 8a23d2d3 Iustin Pop
        if val is None:
307 8a23d2d3 Iustin Pop
          val = "(node down)"
308 8a23d2d3 Iustin Pop
        elif val: # True
309 8a23d2d3 Iustin Pop
          val = "running"
310 8a23d2d3 Iustin Pop
        else:
311 8a23d2d3 Iustin Pop
          val = "stopped"
312 8a23d2d3 Iustin Pop
      elif field == "oper_ram":
313 8a23d2d3 Iustin Pop
        if val is None:
314 8a23d2d3 Iustin Pop
          val = "(node down)"
315 4ea3de4e Balazs Lecz
      elif field == "oper_vcpus":
316 4ea3de4e Balazs Lecz
        if val is None:
317 4ea3de4e Balazs Lecz
          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 d22dfef7 Iustin Pop
    op = opcodes.OpDiagnoseOS(output_fields=["name", "variants"], names=[])
527 400ca2f7 Iustin Pop
    result = SubmitOpCode(op, opts=opts)
528 20e23543 Alexander Schreiber
529 20e23543 Alexander Schreiber
    if not result:
530 3a24c527 Iustin Pop
      ToStdout("Can't get the OS list")
531 20e23543 Alexander Schreiber
      return 1
532 20e23543 Alexander Schreiber
533 3a24c527 Iustin Pop
    ToStdout("Available OS templates:")
534 20e23543 Alexander Schreiber
    number = 0
535 20e23543 Alexander Schreiber
    choices = []
536 d22dfef7 Iustin Pop
    for (name, variants) in result:
537 d22dfef7 Iustin Pop
      for entry in CalculateOSNames(name, variants):
538 d22dfef7 Iustin Pop
        ToStdout("%3s: %s", number, entry)
539 d22dfef7 Iustin Pop
        choices.append(("%s" % number, entry, entry))
540 d22dfef7 Iustin Pop
        number += 1
541 20e23543 Alexander Schreiber
542 20e23543 Alexander Schreiber
    choices.append(('x', 'exit', 'Exit gnt-instance reinstall'))
543 949bdabe Iustin Pop
    selected = AskUser("Enter OS template number (or x to abort):",
544 20e23543 Alexander Schreiber
                       choices)
545 20e23543 Alexander Schreiber
546 20e23543 Alexander Schreiber
    if selected == 'exit':
547 55efe6da Iustin Pop
      ToStderr("User aborted reinstall, exiting")
548 20e23543 Alexander Schreiber
      return 1
549 20e23543 Alexander Schreiber
550 2f79bd34 Iustin Pop
    os_name = selected
551 20e23543 Alexander Schreiber
  else:
552 2f79bd34 Iustin Pop
    os_name = opts.os
553 20e23543 Alexander Schreiber
554 297ddce9 Iustin Pop
  # third, get confirmation: multi-reinstall requires --force-multi,
555 297ddce9 Iustin Pop
  # single-reinstall either --force or --force-multi (--force-multi is
556 297ddce9 Iustin Pop
  # a stronger --force)
557 55efe6da Iustin Pop
  multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
558 55efe6da Iustin Pop
  if multi_on:
559 55efe6da Iustin Pop
    warn_msg = "Note: this will remove *all* data for the below instances!\n"
560 297ddce9 Iustin Pop
    if not (opts.force_multi or
561 55efe6da Iustin Pop
            _ConfirmOperation(inames, "reinstall", extra=warn_msg)):
562 fe7b0351 Michael Hanselmann
      return 1
563 55efe6da Iustin Pop
  else:
564 297ddce9 Iustin Pop
    if not (opts.force or opts.force_multi):
565 55efe6da Iustin Pop
      usertext = ("This will reinstall the instance %s and remove"
566 b6e243ab Iustin Pop
                  " all data. Continue?") % inames[0]
567 55efe6da Iustin Pop
      if not AskUser(usertext):
568 55efe6da Iustin Pop
        return 1
569 55efe6da Iustin Pop
570 cb573a31 Iustin Pop
  jex = JobExecutor(verbose=multi_on, opts=opts)
571 55efe6da Iustin Pop
  for instance_name in inames:
572 55efe6da Iustin Pop
    op = opcodes.OpReinstallInstance(instance_name=instance_name,
573 06073e85 Guido Trotter
                                     os_type=os_name,
574 8d8c4eff Michael Hanselmann
                                     force_variant=opts.force_variant,
575 8d8c4eff Michael Hanselmann
                                     osparams=opts.osparams)
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 3fe11ba3 Manuel Franceschini
                                ip_check=opts.ip_check,
632 3fe11ba3 Manuel Franceschini
                                name_check=opts.name_check)
633 6a016df9 Michael Hanselmann
  result = SubmitOrSend(op, opts)
634 6a016df9 Michael Hanselmann
635 48418fea Iustin Pop
  if result:
636 48418fea Iustin Pop
    ToStdout("Instance '%s' renamed to '%s'", args[0], result)
637 6a016df9 Michael Hanselmann
638 decd5f45 Iustin Pop
  return 0
639 decd5f45 Iustin Pop
640 decd5f45 Iustin Pop
641 a8083063 Iustin Pop
def ActivateDisks(opts, args):
642 a8083063 Iustin Pop
  """Activate an instance's disks.
643 a8083063 Iustin Pop

644 a8083063 Iustin Pop
  This serves two purposes:
645 7232c04c Iustin Pop
    - it allows (as long as the instance is not running)
646 7232c04c Iustin Pop
      mounting the disks and modifying them from the node
647 a8083063 Iustin Pop
    - it repairs inactive secondary drbds
648 a8083063 Iustin Pop

649 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
650 7232c04c Iustin Pop
  @type args: list
651 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
652 7232c04c Iustin Pop
  @rtype: int
653 7232c04c Iustin Pop
  @return: the desired exit code
654 7232c04c Iustin Pop

655 a8083063 Iustin Pop
  """
656 a8083063 Iustin Pop
  instance_name = args[0]
657 b4ec07f8 Iustin Pop
  op = opcodes.OpActivateInstanceDisks(instance_name=instance_name,
658 b4ec07f8 Iustin Pop
                                       ignore_size=opts.ignore_size)
659 6340bb0a Iustin Pop
  disks_info = SubmitOrSend(op, opts)
660 a8083063 Iustin Pop
  for host, iname, nname in disks_info:
661 3a24c527 Iustin Pop
    ToStdout("%s:%s:%s", host, iname, nname)
662 a8083063 Iustin Pop
  return 0
663 a8083063 Iustin Pop
664 a8083063 Iustin Pop
665 a8083063 Iustin Pop
def DeactivateDisks(opts, args):
666 bd315bfa Iustin Pop
  """Deactivate an instance's disks.
667 a8083063 Iustin Pop

668 a8083063 Iustin Pop
  This function takes the instance name, looks for its primary node
669 a8083063 Iustin Pop
  and the tries to shutdown its block devices on that node.
670 a8083063 Iustin Pop

671 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
672 7232c04c Iustin Pop
  @type args: list
673 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
674 7232c04c Iustin Pop
  @rtype: int
675 7232c04c Iustin Pop
  @return: the desired exit code
676 7232c04c Iustin Pop

677 a8083063 Iustin Pop
  """
678 a8083063 Iustin Pop
  instance_name = args[0]
679 a8083063 Iustin Pop
  op = opcodes.OpDeactivateInstanceDisks(instance_name=instance_name)
680 6340bb0a Iustin Pop
  SubmitOrSend(op, opts)
681 a8083063 Iustin Pop
  return 0
682 a8083063 Iustin Pop
683 a8083063 Iustin Pop
684 bd315bfa Iustin Pop
def RecreateDisks(opts, args):
685 bd315bfa Iustin Pop
  """Recreate an instance's disks.
686 bd315bfa Iustin Pop

687 bd315bfa Iustin Pop
  @param opts: the command line options selected by the user
688 bd315bfa Iustin Pop
  @type args: list
689 bd315bfa Iustin Pop
  @param args: should contain only one element, the instance name
690 bd315bfa Iustin Pop
  @rtype: int
691 bd315bfa Iustin Pop
  @return: the desired exit code
692 bd315bfa Iustin Pop

693 bd315bfa Iustin Pop
  """
694 bd315bfa Iustin Pop
  instance_name = args[0]
695 bd315bfa Iustin Pop
  if opts.disks:
696 bd315bfa Iustin Pop
    try:
697 bd315bfa Iustin Pop
      opts.disks = [int(v) for v in opts.disks.split(",")]
698 bd315bfa Iustin Pop
    except (ValueError, TypeError), err:
699 bd315bfa Iustin Pop
      ToStderr("Invalid disks value: %s" % str(err))
700 bd315bfa Iustin Pop
      return 1
701 bd315bfa Iustin Pop
  else:
702 bd315bfa Iustin Pop
    opts.disks = []
703 bd315bfa Iustin Pop
704 bd315bfa Iustin Pop
  op = opcodes.OpRecreateInstanceDisks(instance_name=instance_name,
705 bd315bfa Iustin Pop
                                       disks=opts.disks)
706 bd315bfa Iustin Pop
  SubmitOrSend(op, opts)
707 bd315bfa Iustin Pop
  return 0
708 bd315bfa Iustin Pop
709 bd315bfa Iustin Pop
710 c6e911bc Iustin Pop
def GrowDisk(opts, args):
711 7232c04c Iustin Pop
  """Grow an instance's disks.
712 c6e911bc Iustin Pop

713 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
714 7232c04c Iustin Pop
  @type args: list
715 7232c04c Iustin Pop
  @param args: should contain two elements, the instance name
716 7232c04c Iustin Pop
      whose disks we grow and the disk name, e.g. I{sda}
717 7232c04c Iustin Pop
  @rtype: int
718 7232c04c Iustin Pop
  @return: the desired exit code
719 c6e911bc Iustin Pop

720 c6e911bc Iustin Pop
  """
721 c6e911bc Iustin Pop
  instance = args[0]
722 c6e911bc Iustin Pop
  disk = args[1]
723 ad24e046 Iustin Pop
  try:
724 ad24e046 Iustin Pop
    disk = int(disk)
725 691744c4 Iustin Pop
  except (TypeError, ValueError), err:
726 debac808 Iustin Pop
    raise errors.OpPrereqError("Invalid disk index: %s" % str(err),
727 debac808 Iustin Pop
                               errors.ECODE_INVAL)
728 c6e911bc Iustin Pop
  amount = utils.ParseUnit(args[2])
729 6605411d Iustin Pop
  op = opcodes.OpGrowDisk(instance_name=instance, disk=disk, amount=amount,
730 6605411d Iustin Pop
                          wait_for_sync=opts.wait_for_sync)
731 6340bb0a Iustin Pop
  SubmitOrSend(op, opts)
732 c6e911bc Iustin Pop
  return 0
733 c6e911bc Iustin Pop
734 c6e911bc Iustin Pop
735 1c5945b6 Iustin Pop
def _StartupInstance(name, opts):
736 7232c04c Iustin Pop
  """Startup instances.
737 a8083063 Iustin Pop

738 1c5945b6 Iustin Pop
  This returns the opcode to start an instance, and its decorator will
739 1c5945b6 Iustin Pop
  wrap this into a loop starting all desired instances.
740 7232c04c Iustin Pop

741 1c5945b6 Iustin Pop
  @param name: the name of the instance to act on
742 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
743 1c5945b6 Iustin Pop
  @return: the opcode needed for the operation
744 a8083063 Iustin Pop

745 a8083063 Iustin Pop
  """
746 1c5945b6 Iustin Pop
  op = opcodes.OpStartupInstance(instance_name=name,
747 b44bd844 Michael Hanselmann
                                 force=opts.force,
748 b44bd844 Michael Hanselmann
                                 ignore_offline_nodes=opts.ignore_offline)
749 1c5945b6 Iustin Pop
  # do not add these parameters to the opcode unless they're defined
750 1c5945b6 Iustin Pop
  if opts.hvparams:
751 1c5945b6 Iustin Pop
    op.hvparams = opts.hvparams
752 1c5945b6 Iustin Pop
  if opts.beparams:
753 1c5945b6 Iustin Pop
    op.beparams = opts.beparams
754 1c5945b6 Iustin Pop
  return op
755 a8083063 Iustin Pop
756 7c0d6283 Michael Hanselmann
757 1c5945b6 Iustin Pop
def _RebootInstance(name, opts):
758 7232c04c Iustin Pop
  """Reboot instance(s).
759 7232c04c Iustin Pop

760 1c5945b6 Iustin Pop
  This returns the opcode to reboot an instance, and its decorator
761 1c5945b6 Iustin Pop
  will wrap this into a loop rebooting all desired instances.
762 579d4337 Alexander Schreiber

763 1c5945b6 Iustin Pop
  @param name: the name of the instance to act on
764 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
765 1c5945b6 Iustin Pop
  @return: the opcode needed for the operation
766 579d4337 Alexander Schreiber

767 579d4337 Alexander Schreiber
  """
768 1c5945b6 Iustin Pop
  return opcodes.OpRebootInstance(instance_name=name,
769 579d4337 Alexander Schreiber
                                  reboot_type=opts.reboot_type,
770 17c3f802 Guido Trotter
                                  ignore_secondaries=opts.ignore_secondaries,
771 4d98c565 Guido Trotter
                                  shutdown_timeout=opts.shutdown_timeout)
772 a8083063 Iustin Pop
773 7c0d6283 Michael Hanselmann
774 1c5945b6 Iustin Pop
def _ShutdownInstance(name, opts):
775 a8083063 Iustin Pop
  """Shutdown an instance.
776 a8083063 Iustin Pop

777 1c5945b6 Iustin Pop
  This returns the opcode to shutdown an instance, and its decorator
778 1c5945b6 Iustin Pop
  will wrap this into a loop shutting down all desired instances.
779 1c5945b6 Iustin Pop

780 1c5945b6 Iustin Pop
  @param name: the name of the instance to act on
781 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
782 1c5945b6 Iustin Pop
  @return: the opcode needed for the operation
783 a8083063 Iustin Pop

784 a8083063 Iustin Pop
  """
785 6263189c Guido Trotter
  return opcodes.OpShutdownInstance(instance_name=name,
786 b44bd844 Michael Hanselmann
                                    timeout=opts.timeout,
787 b44bd844 Michael Hanselmann
                                    ignore_offline_nodes=opts.ignore_offline)
788 a8083063 Iustin Pop
789 a8083063 Iustin Pop
790 a8083063 Iustin Pop
def ReplaceDisks(opts, args):
791 a8083063 Iustin Pop
  """Replace the disks of an instance
792 a8083063 Iustin Pop

793 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
794 7232c04c Iustin Pop
  @type args: list
795 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
796 7232c04c Iustin Pop
  @rtype: int
797 7232c04c Iustin Pop
  @return: the desired exit code
798 a8083063 Iustin Pop

799 a8083063 Iustin Pop
  """
800 a14db5ff Iustin Pop
  new_2ndary = opts.dst_node
801 b6e82a65 Iustin Pop
  iallocator = opts.iallocator
802 a9e0c397 Iustin Pop
  if opts.disks is None:
803 54155f52 Iustin Pop
    disks = []
804 a9e0c397 Iustin Pop
  else:
805 54155f52 Iustin Pop
    try:
806 54155f52 Iustin Pop
      disks = [int(i) for i in opts.disks.split(",")]
807 691744c4 Iustin Pop
    except (TypeError, ValueError), err:
808 debac808 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err),
809 debac808 Iustin Pop
                                 errors.ECODE_INVAL)
810 05d47e33 Michael Hanselmann
  cnt = [opts.on_primary, opts.on_secondary, opts.auto,
811 7e9366f7 Iustin Pop
         new_2ndary is not None, iallocator is not None].count(True)
812 7e9366f7 Iustin Pop
  if cnt != 1:
813 05d47e33 Michael Hanselmann
    raise errors.OpPrereqError("One and only one of the -p, -s, -a, -n and -i"
814 debac808 Iustin Pop
                               " options must be passed", errors.ECODE_INVAL)
815 7e9366f7 Iustin Pop
  elif opts.on_primary:
816 a9e0c397 Iustin Pop
    mode = constants.REPLACE_DISK_PRI
817 7e9366f7 Iustin Pop
  elif opts.on_secondary:
818 a9e0c397 Iustin Pop
    mode = constants.REPLACE_DISK_SEC
819 05d47e33 Michael Hanselmann
  elif opts.auto:
820 05d47e33 Michael Hanselmann
    mode = constants.REPLACE_DISK_AUTO
821 05d47e33 Michael Hanselmann
    if disks:
822 05d47e33 Michael Hanselmann
      raise errors.OpPrereqError("Cannot specify disks when using automatic"
823 debac808 Iustin Pop
                                 " mode", errors.ECODE_INVAL)
824 7e9366f7 Iustin Pop
  elif new_2ndary is not None or iallocator is not None:
825 7e9366f7 Iustin Pop
    # replace secondary
826 7e9366f7 Iustin Pop
    mode = constants.REPLACE_DISK_CHG
827 a9e0c397 Iustin Pop
828 a9e0c397 Iustin Pop
  op = opcodes.OpReplaceDisks(instance_name=args[0], disks=disks,
829 b6e82a65 Iustin Pop
                              remote_node=new_2ndary, mode=mode,
830 7ea7bcf6 Iustin Pop
                              iallocator=iallocator,
831 7ea7bcf6 Iustin Pop
                              early_release=opts.early_release)
832 6340bb0a Iustin Pop
  SubmitOrSend(op, opts)
833 a8083063 Iustin Pop
  return 0
834 a8083063 Iustin Pop
835 a8083063 Iustin Pop
836 a8083063 Iustin Pop
def FailoverInstance(opts, args):
837 a8083063 Iustin Pop
  """Failover an instance.
838 a8083063 Iustin Pop

839 a8083063 Iustin Pop
  The failover is done by shutting it down on its present node and
840 a8083063 Iustin Pop
  starting it on the secondary.
841 a8083063 Iustin Pop

842 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
843 7232c04c Iustin Pop
  @type args: list
844 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
845 7232c04c Iustin Pop
  @rtype: int
846 7232c04c Iustin Pop
  @return: the desired exit code
847 a8083063 Iustin Pop

848 a8083063 Iustin Pop
  """
849 a76f0c4a Iustin Pop
  cl = GetClient()
850 80de0e3f Iustin Pop
  instance_name = args[0]
851 80de0e3f Iustin Pop
  force = opts.force
852 a8083063 Iustin Pop
853 80de0e3f Iustin Pop
  if not force:
854 a76f0c4a Iustin Pop
    _EnsureInstancesExist(cl, [instance_name])
855 a76f0c4a Iustin Pop
856 80de0e3f Iustin Pop
    usertext = ("Failover will happen to image %s."
857 80de0e3f Iustin Pop
                " This requires a shutdown of the instance. Continue?" %
858 80de0e3f Iustin Pop
                (instance_name,))
859 80de0e3f Iustin Pop
    if not AskUser(usertext):
860 80de0e3f Iustin Pop
      return 1
861 a8083063 Iustin Pop
862 80de0e3f Iustin Pop
  op = opcodes.OpFailoverInstance(instance_name=instance_name,
863 17c3f802 Guido Trotter
                                  ignore_consistency=opts.ignore_consistency,
864 4d98c565 Guido Trotter
                                  shutdown_timeout=opts.shutdown_timeout)
865 a76f0c4a Iustin Pop
  SubmitOrSend(op, opts, cl=cl)
866 80de0e3f Iustin Pop
  return 0
867 a8083063 Iustin Pop
868 a8083063 Iustin Pop
869 53c776b5 Iustin Pop
def MigrateInstance(opts, args):
870 53c776b5 Iustin Pop
  """Migrate an instance.
871 53c776b5 Iustin Pop

872 53c776b5 Iustin Pop
  The migrate is done without shutdown.
873 53c776b5 Iustin Pop

874 2f907a8c Iustin Pop
  @param opts: the command line options selected by the user
875 2f907a8c Iustin Pop
  @type args: list
876 2f907a8c Iustin Pop
  @param args: should contain only one element, the instance name
877 2f907a8c Iustin Pop
  @rtype: int
878 2f907a8c Iustin Pop
  @return: the desired exit code
879 53c776b5 Iustin Pop

880 53c776b5 Iustin Pop
  """
881 a76f0c4a Iustin Pop
  cl = GetClient()
882 53c776b5 Iustin Pop
  instance_name = args[0]
883 53c776b5 Iustin Pop
  force = opts.force
884 53c776b5 Iustin Pop
885 53c776b5 Iustin Pop
  if not force:
886 a76f0c4a Iustin Pop
    _EnsureInstancesExist(cl, [instance_name])
887 a76f0c4a Iustin Pop
888 53c776b5 Iustin Pop
    if opts.cleanup:
889 53c776b5 Iustin Pop
      usertext = ("Instance %s will be recovered from a failed migration."
890 53c776b5 Iustin Pop
                  " Note that the migration procedure (including cleanup)" %
891 53c776b5 Iustin Pop
                  (instance_name,))
892 53c776b5 Iustin Pop
    else:
893 53c776b5 Iustin Pop
      usertext = ("Instance %s will be migrated. Note that migration" %
894 53c776b5 Iustin Pop
                  (instance_name,))
895 cf29cfb6 Iustin Pop
    usertext += (" might impact the instance if anything goes wrong"
896 cf29cfb6 Iustin Pop
                 " (e.g. due to bugs in the hypervisor). Continue?")
897 53c776b5 Iustin Pop
    if not AskUser(usertext):
898 53c776b5 Iustin Pop
      return 1
899 53c776b5 Iustin Pop
900 e71b9ef4 Iustin Pop
  # this should be removed once --non-live is deprecated
901 783a6c0b Iustin Pop
  if not opts.live and opts.migration_mode is not None:
902 e71b9ef4 Iustin Pop
    raise errors.OpPrereqError("Only one of the --non-live and "
903 783a6c0b Iustin Pop
                               "--migration-mode options can be passed",
904 e71b9ef4 Iustin Pop
                               errors.ECODE_INVAL)
905 e71b9ef4 Iustin Pop
  if not opts.live: # --non-live passed
906 8c35561f Iustin Pop
    mode = constants.HT_MIGRATION_NONLIVE
907 e71b9ef4 Iustin Pop
  else:
908 8c35561f Iustin Pop
    mode = opts.migration_mode
909 e71b9ef4 Iustin Pop
910 8c35561f Iustin Pop
  op = opcodes.OpMigrateInstance(instance_name=instance_name, mode=mode,
911 53c776b5 Iustin Pop
                                 cleanup=opts.cleanup)
912 400ca2f7 Iustin Pop
  SubmitOpCode(op, cl=cl, opts=opts)
913 53c776b5 Iustin Pop
  return 0
914 53c776b5 Iustin Pop
915 53c776b5 Iustin Pop
916 fbf5a861 Iustin Pop
def MoveInstance(opts, args):
917 fbf5a861 Iustin Pop
  """Move an instance.
918 fbf5a861 Iustin Pop

919 fbf5a861 Iustin Pop
  @param opts: the command line options selected by the user
920 fbf5a861 Iustin Pop
  @type args: list
921 fbf5a861 Iustin Pop
  @param args: should contain only one element, the instance name
922 fbf5a861 Iustin Pop
  @rtype: int
923 fbf5a861 Iustin Pop
  @return: the desired exit code
924 fbf5a861 Iustin Pop

925 fbf5a861 Iustin Pop
  """
926 fbf5a861 Iustin Pop
  cl = GetClient()
927 fbf5a861 Iustin Pop
  instance_name = args[0]
928 fbf5a861 Iustin Pop
  force = opts.force
929 fbf5a861 Iustin Pop
930 fbf5a861 Iustin Pop
  if not force:
931 fbf5a861 Iustin Pop
    usertext = ("Instance %s will be moved."
932 fbf5a861 Iustin Pop
                " This requires a shutdown of the instance. Continue?" %
933 fbf5a861 Iustin Pop
                (instance_name,))
934 fbf5a861 Iustin Pop
    if not AskUser(usertext):
935 fbf5a861 Iustin Pop
      return 1
936 fbf5a861 Iustin Pop
937 fbf5a861 Iustin Pop
  op = opcodes.OpMoveInstance(instance_name=instance_name,
938 17c3f802 Guido Trotter
                              target_node=opts.node,
939 4d98c565 Guido Trotter
                              shutdown_timeout=opts.shutdown_timeout)
940 fbf5a861 Iustin Pop
  SubmitOrSend(op, opts, cl=cl)
941 fbf5a861 Iustin Pop
  return 0
942 fbf5a861 Iustin Pop
943 fbf5a861 Iustin Pop
944 a8083063 Iustin Pop
def ConnectToInstanceConsole(opts, args):
945 a8083063 Iustin Pop
  """Connect to the console of an instance.
946 a8083063 Iustin Pop

947 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
948 7232c04c Iustin Pop
  @type args: list
949 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
950 7232c04c Iustin Pop
  @rtype: int
951 7232c04c Iustin Pop
  @return: the desired exit code
952 a8083063 Iustin Pop

953 a8083063 Iustin Pop
  """
954 a8083063 Iustin Pop
  instance_name = args[0]
955 a8083063 Iustin Pop
956 a8083063 Iustin Pop
  op = opcodes.OpConnectConsole(instance_name=instance_name)
957 400ca2f7 Iustin Pop
  cmd = SubmitOpCode(op, opts=opts)
958 51c6e7b5 Michael Hanselmann
959 51c6e7b5 Michael Hanselmann
  if opts.show_command:
960 3a24c527 Iustin Pop
    ToStdout("%s", utils.ShellQuoteArgs(cmd))
961 51c6e7b5 Michael Hanselmann
  else:
962 51c6e7b5 Michael Hanselmann
    try:
963 51c6e7b5 Michael Hanselmann
      os.execvp(cmd[0], cmd)
964 51c6e7b5 Michael Hanselmann
    finally:
965 3a24c527 Iustin Pop
      ToStderr("Can't run console command %s with arguments:\n'%s'",
966 2f79bd34 Iustin Pop
               cmd[0], " ".join(cmd))
967 7260cfbe Iustin Pop
      os._exit(1) # pylint: disable-msg=W0212
968 a8083063 Iustin Pop
969 a8083063 Iustin Pop
970 e2736e40 Guido Trotter
def _FormatLogicalID(dev_type, logical_id, roman):
971 19708787 Iustin Pop
  """Formats the logical_id of a disk.
972 19708787 Iustin Pop

973 19708787 Iustin Pop
  """
974 19708787 Iustin Pop
  if dev_type == constants.LD_DRBD8:
975 19708787 Iustin Pop
    node_a, node_b, port, minor_a, minor_b, key = logical_id
976 19708787 Iustin Pop
    data = [
977 e2736e40 Guido Trotter
      ("nodeA", "%s, minor=%s" % (node_a, compat.TryToRoman(minor_a,
978 e2736e40 Guido Trotter
                                                            convert=roman))),
979 e2736e40 Guido Trotter
      ("nodeB", "%s, minor=%s" % (node_b, compat.TryToRoman(minor_b,
980 e2736e40 Guido Trotter
                                                            convert=roman))),
981 e2736e40 Guido Trotter
      ("port", compat.TryToRoman(port, convert=roman)),
982 19708787 Iustin Pop
      ("auth key", key),
983 19708787 Iustin Pop
      ]
984 19708787 Iustin Pop
  elif dev_type == constants.LD_LV:
985 19708787 Iustin Pop
    vg_name, lv_name = logical_id
986 19708787 Iustin Pop
    data = ["%s/%s" % (vg_name, lv_name)]
987 19708787 Iustin Pop
  else:
988 19708787 Iustin Pop
    data = [str(logical_id)]
989 19708787 Iustin Pop
990 19708787 Iustin Pop
  return data
991 19708787 Iustin Pop
992 19708787 Iustin Pop
993 e2736e40 Guido Trotter
def _FormatBlockDevInfo(idx, top_level, dev, static, roman):
994 a8083063 Iustin Pop
  """Show block device information.
995 a8083063 Iustin Pop

996 7232c04c Iustin Pop
  This is only used by L{ShowInstanceConfig}, but it's too big to be
997 a8083063 Iustin Pop
  left for an inline definition.
998 a8083063 Iustin Pop

999 19708787 Iustin Pop
  @type idx: int
1000 19708787 Iustin Pop
  @param idx: the index of the current disk
1001 19708787 Iustin Pop
  @type top_level: boolean
1002 19708787 Iustin Pop
  @param top_level: if this a top-level disk?
1003 7232c04c Iustin Pop
  @type dev: dict
1004 7232c04c Iustin Pop
  @param dev: dictionary with disk information
1005 7232c04c Iustin Pop
  @type static: boolean
1006 7232c04c Iustin Pop
  @param static: wheter the device information doesn't contain
1007 7232c04c Iustin Pop
      runtime information but only static data
1008 e2736e40 Guido Trotter
  @type roman: boolean
1009 e2736e40 Guido Trotter
  @param roman: whether to try to use roman integers
1010 19708787 Iustin Pop
  @return: a list of either strings, tuples or lists
1011 19708787 Iustin Pop
      (which should be formatted at a higher indent level)
1012 7232c04c Iustin Pop

1013 a8083063 Iustin Pop
  """
1014 19708787 Iustin Pop
  def helper(dtype, status):
1015 7232c04c Iustin Pop
    """Format one line for physical device status.
1016 7232c04c Iustin Pop

1017 7232c04c Iustin Pop
    @type dtype: str
1018 7232c04c Iustin Pop
    @param dtype: a constant from the L{constants.LDS_BLOCK} set
1019 7232c04c Iustin Pop
    @type status: tuple
1020 7232c04c Iustin Pop
    @param status: a tuple as returned from L{backend.FindBlockDevice}
1021 19708787 Iustin Pop
    @return: the string representing the status
1022 7232c04c Iustin Pop

1023 7232c04c Iustin Pop
    """
1024 a8083063 Iustin Pop
    if not status:
1025 19708787 Iustin Pop
      return "not active"
1026 19708787 Iustin Pop
    txt = ""
1027 f208978a Michael Hanselmann
    (path, major, minor, syncp, estt, degr, ldisk_status) = status
1028 19708787 Iustin Pop
    if major is None:
1029 19708787 Iustin Pop
      major_string = "N/A"
1030 a8083063 Iustin Pop
    else:
1031 e2736e40 Guido Trotter
      major_string = str(compat.TryToRoman(major, convert=roman))
1032 fd38ef95 Manuel Franceschini
1033 19708787 Iustin Pop
    if minor is None:
1034 19708787 Iustin Pop
      minor_string = "N/A"
1035 19708787 Iustin Pop
    else:
1036 e2736e40 Guido Trotter
      minor_string = str(compat.TryToRoman(minor, convert=roman))
1037 19708787 Iustin Pop
1038 19708787 Iustin Pop
    txt += ("%s (%s:%s)" % (path, major_string, minor_string))
1039 19708787 Iustin Pop
    if dtype in (constants.LD_DRBD8, ):
1040 19708787 Iustin Pop
      if syncp is not None:
1041 19708787 Iustin Pop
        sync_text = "*RECOVERING* %5.2f%%," % syncp
1042 19708787 Iustin Pop
        if estt:
1043 e2736e40 Guido Trotter
          sync_text += " ETA %ss" % compat.TryToRoman(estt, convert=roman)
1044 9db6dbce Iustin Pop
        else:
1045 19708787 Iustin Pop
          sync_text += " ETA unknown"
1046 19708787 Iustin Pop
      else:
1047 19708787 Iustin Pop
        sync_text = "in sync"
1048 19708787 Iustin Pop
      if degr:
1049 19708787 Iustin Pop
        degr_text = "*DEGRADED*"
1050 19708787 Iustin Pop
      else:
1051 19708787 Iustin Pop
        degr_text = "ok"
1052 f208978a Michael Hanselmann
      if ldisk_status == constants.LDS_FAULTY:
1053 19708787 Iustin Pop
        ldisk_text = " *MISSING DISK*"
1054 f208978a Michael Hanselmann
      elif ldisk_status == constants.LDS_UNKNOWN:
1055 f208978a Michael Hanselmann
        ldisk_text = " *UNCERTAIN STATE*"
1056 19708787 Iustin Pop
      else:
1057 19708787 Iustin Pop
        ldisk_text = ""
1058 19708787 Iustin Pop
      txt += (" %s, status %s%s" % (sync_text, degr_text, ldisk_text))
1059 19708787 Iustin Pop
    elif dtype == constants.LD_LV:
1060 f208978a Michael Hanselmann
      if ldisk_status == constants.LDS_FAULTY:
1061 19708787 Iustin Pop
        ldisk_text = " *FAILED* (failed drive?)"
1062 19708787 Iustin Pop
      else:
1063 19708787 Iustin Pop
        ldisk_text = ""
1064 19708787 Iustin Pop
      txt += ldisk_text
1065 19708787 Iustin Pop
    return txt
1066 19708787 Iustin Pop
1067 19708787 Iustin Pop
  # the header
1068 19708787 Iustin Pop
  if top_level:
1069 19708787 Iustin Pop
    if dev["iv_name"] is not None:
1070 19708787 Iustin Pop
      txt = dev["iv_name"]
1071 19708787 Iustin Pop
    else:
1072 e2736e40 Guido Trotter
      txt = "disk %s" % compat.TryToRoman(idx, convert=roman)
1073 a8083063 Iustin Pop
  else:
1074 e2736e40 Guido Trotter
    txt = "child %s" % compat.TryToRoman(idx, convert=roman)
1075 c98162a7 Iustin Pop
  if isinstance(dev["size"], int):
1076 c98162a7 Iustin Pop
    nice_size = utils.FormatUnit(dev["size"], "h")
1077 c98162a7 Iustin Pop
  else:
1078 c98162a7 Iustin Pop
    nice_size = dev["size"]
1079 c98162a7 Iustin Pop
  d1 = ["- %s: %s, size %s" % (txt, dev["dev_type"], nice_size)]
1080 19708787 Iustin Pop
  data = []
1081 19708787 Iustin Pop
  if top_level:
1082 19708787 Iustin Pop
    data.append(("access mode", dev["mode"]))
1083 a8083063 Iustin Pop
  if dev["logical_id"] is not None:
1084 19708787 Iustin Pop
    try:
1085 e2736e40 Guido Trotter
      l_id = _FormatLogicalID(dev["dev_type"], dev["logical_id"], roman)
1086 19708787 Iustin Pop
    except ValueError:
1087 19708787 Iustin Pop
      l_id = [str(dev["logical_id"])]
1088 19708787 Iustin Pop
    if len(l_id) == 1:
1089 19708787 Iustin Pop
      data.append(("logical_id", l_id[0]))
1090 19708787 Iustin Pop
    else:
1091 19708787 Iustin Pop
      data.extend(l_id)
1092 a8083063 Iustin Pop
  elif dev["physical_id"] is not None:
1093 19708787 Iustin Pop
    data.append("physical_id:")
1094 19708787 Iustin Pop
    data.append([dev["physical_id"]])
1095 57821cac Iustin Pop
  if not static:
1096 19708787 Iustin Pop
    data.append(("on primary", helper(dev["dev_type"], dev["pstatus"])))
1097 57821cac Iustin Pop
  if dev["sstatus"] and not static:
1098 19708787 Iustin Pop
    data.append(("on secondary", helper(dev["dev_type"], dev["sstatus"])))
1099 a8083063 Iustin Pop
1100 a8083063 Iustin Pop
  if dev["children"]:
1101 19708787 Iustin Pop
    data.append("child devices:")
1102 19708787 Iustin Pop
    for c_idx, child in enumerate(dev["children"]):
1103 e2736e40 Guido Trotter
      data.append(_FormatBlockDevInfo(c_idx, False, child, static, roman))
1104 19708787 Iustin Pop
  d1.append(data)
1105 19708787 Iustin Pop
  return d1
1106 a8083063 Iustin Pop
1107 a8083063 Iustin Pop
1108 19708787 Iustin Pop
def _FormatList(buf, data, indent_level):
1109 19708787 Iustin Pop
  """Formats a list of data at a given indent level.
1110 19708787 Iustin Pop

1111 19708787 Iustin Pop
  If the element of the list is:
1112 19708787 Iustin Pop
    - a string, it is simply formatted as is
1113 19708787 Iustin Pop
    - a tuple, it will be split into key, value and the all the
1114 19708787 Iustin Pop
      values in a list will be aligned all at the same start column
1115 19708787 Iustin Pop
    - a list, will be recursively formatted
1116 19708787 Iustin Pop

1117 19708787 Iustin Pop
  @type buf: StringIO
1118 19708787 Iustin Pop
  @param buf: the buffer into which we write the output
1119 19708787 Iustin Pop
  @param data: the list to format
1120 19708787 Iustin Pop
  @type indent_level: int
1121 19708787 Iustin Pop
  @param indent_level: the indent level to format at
1122 19708787 Iustin Pop

1123 19708787 Iustin Pop
  """
1124 19708787 Iustin Pop
  max_tlen = max([len(elem[0]) for elem in data
1125 19708787 Iustin Pop
                 if isinstance(elem, tuple)] or [0])
1126 19708787 Iustin Pop
  for elem in data:
1127 19708787 Iustin Pop
    if isinstance(elem, basestring):
1128 19708787 Iustin Pop
      buf.write("%*s%s\n" % (2*indent_level, "", elem))
1129 19708787 Iustin Pop
    elif isinstance(elem, tuple):
1130 19708787 Iustin Pop
      key, value = elem
1131 19708787 Iustin Pop
      spacer = "%*s" % (max_tlen - len(key), "")
1132 19708787 Iustin Pop
      buf.write("%*s%s:%s %s\n" % (2*indent_level, "", key, spacer, value))
1133 19708787 Iustin Pop
    elif isinstance(elem, list):
1134 19708787 Iustin Pop
      _FormatList(buf, elem, indent_level+1)
1135 19708787 Iustin Pop
1136 98825740 Michael Hanselmann
1137 dbb24ec7 Iustin Pop
def _FormatParameterDict(buf, per_inst, actual):
1138 dbb24ec7 Iustin Pop
  """Formats a parameter dictionary.
1139 dbb24ec7 Iustin Pop

1140 dbb24ec7 Iustin Pop
  @type buf: L{StringIO}
1141 dbb24ec7 Iustin Pop
  @param buf: the buffer into which to write
1142 dbb24ec7 Iustin Pop
  @type per_inst: dict
1143 dbb24ec7 Iustin Pop
  @param per_inst: the instance's own parameters
1144 dbb24ec7 Iustin Pop
  @type actual: dict
1145 dbb24ec7 Iustin Pop
  @param actual: the current parameter set (including defaults)
1146 dbb24ec7 Iustin Pop

1147 dbb24ec7 Iustin Pop
  """
1148 dbb24ec7 Iustin Pop
  for key in sorted(actual):
1149 dbb24ec7 Iustin Pop
    val = per_inst.get(key, "default (%s)" % actual[key])
1150 dbb24ec7 Iustin Pop
    buf.write("    - %s: %s\n" % (key, val))
1151 dbb24ec7 Iustin Pop
1152 a8083063 Iustin Pop
def ShowInstanceConfig(opts, args):
1153 a8083063 Iustin Pop
  """Compute instance run-time status.
1154 a8083063 Iustin Pop

1155 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
1156 7232c04c Iustin Pop
  @type args: list
1157 7232c04c Iustin Pop
  @param args: either an empty list, and then we query all
1158 7232c04c Iustin Pop
      instances, or should contain a list of instance names
1159 7232c04c Iustin Pop
  @rtype: int
1160 7232c04c Iustin Pop
  @return: the desired exit code
1161 7232c04c Iustin Pop

1162 a8083063 Iustin Pop
  """
1163 220cde0b Guido Trotter
  if not args and not opts.show_all:
1164 220cde0b Guido Trotter
    ToStderr("No instance selected."
1165 220cde0b Guido Trotter
             " Please pass in --all if you want to query all instances.\n"
1166 220cde0b Guido Trotter
             "Note that this can take a long time on a big cluster.")
1167 220cde0b Guido Trotter
    return 1
1168 220cde0b Guido Trotter
  elif args and opts.show_all:
1169 220cde0b Guido Trotter
    ToStderr("Cannot use --all if you specify instance names.")
1170 220cde0b Guido Trotter
    return 1
1171 220cde0b Guido Trotter
1172 a8083063 Iustin Pop
  retcode = 0
1173 57821cac Iustin Pop
  op = opcodes.OpQueryInstanceData(instances=args, static=opts.static)
1174 400ca2f7 Iustin Pop
  result = SubmitOpCode(op, opts=opts)
1175 a8083063 Iustin Pop
  if not result:
1176 3a24c527 Iustin Pop
    ToStdout("No instances.")
1177 a8083063 Iustin Pop
    return 1
1178 a8083063 Iustin Pop
1179 a8083063 Iustin Pop
  buf = StringIO()
1180 a8083063 Iustin Pop
  retcode = 0
1181 a8083063 Iustin Pop
  for instance_name in result:
1182 a8083063 Iustin Pop
    instance = result[instance_name]
1183 a8083063 Iustin Pop
    buf.write("Instance name: %s\n" % instance["name"])
1184 033d58b0 Iustin Pop
    buf.write("UUID: %s\n" % instance["uuid"])
1185 e2736e40 Guido Trotter
    buf.write("Serial number: %s\n" %
1186 e2736e40 Guido Trotter
              compat.TryToRoman(instance["serial_no"],
1187 e2736e40 Guido Trotter
                                convert=opts.roman_integers))
1188 90f72445 Iustin Pop
    buf.write("Creation time: %s\n" % utils.FormatTime(instance["ctime"]))
1189 90f72445 Iustin Pop
    buf.write("Modification time: %s\n" % utils.FormatTime(instance["mtime"]))
1190 57821cac Iustin Pop
    buf.write("State: configured to be %s" % instance["config_state"])
1191 57821cac Iustin Pop
    if not opts.static:
1192 57821cac Iustin Pop
      buf.write(", actual state is %s" % instance["run_state"])
1193 57821cac Iustin Pop
    buf.write("\n")
1194 57821cac Iustin Pop
    ##buf.write("Considered for memory checks in cluster verify: %s\n" %
1195 57821cac Iustin Pop
    ##          instance["auto_balance"])
1196 a8083063 Iustin Pop
    buf.write("  Nodes:\n")
1197 a8083063 Iustin Pop
    buf.write("    - primary: %s\n" % instance["pnode"])
1198 1f864b60 Iustin Pop
    buf.write("    - secondaries: %s\n" % utils.CommaJoin(instance["snodes"]))
1199 a8083063 Iustin Pop
    buf.write("  Operating system: %s\n" % instance["os"])
1200 dbb24ec7 Iustin Pop
    _FormatParameterDict(buf, instance["os_instance"], instance["os_actual"])
1201 a8340917 Iustin Pop
    if instance.has_key("network_port"):
1202 e2736e40 Guido Trotter
      buf.write("  Allocated network port: %s\n" %
1203 e2736e40 Guido Trotter
                compat.TryToRoman(instance["network_port"],
1204 e2736e40 Guido Trotter
                                  convert=opts.roman_integers))
1205 24838135 Iustin Pop
    buf.write("  Hypervisor: %s\n" % instance["hypervisor"])
1206 dfff41f8 Guido Trotter
1207 dfff41f8 Guido Trotter
    # custom VNC console information
1208 dfff41f8 Guido Trotter
    vnc_bind_address = instance["hv_actual"].get(constants.HV_VNC_BIND_ADDRESS,
1209 dfff41f8 Guido Trotter
                                                 None)
1210 dfff41f8 Guido Trotter
    if vnc_bind_address:
1211 dfff41f8 Guido Trotter
      port = instance["network_port"]
1212 dfff41f8 Guido Trotter
      display = int(port) - constants.VNC_BASE_PORT
1213 9769bb78 Manuel Franceschini
      if display > 0 and vnc_bind_address == constants.IP4_ADDRESS_ANY:
1214 dfff41f8 Guido Trotter
        vnc_console_port = "%s:%s (display %s)" % (instance["pnode"],
1215 dfff41f8 Guido Trotter
                                                   port,
1216 dfff41f8 Guido Trotter
                                                   display)
1217 8b312c1d Manuel Franceschini
      elif display > 0 and netutils.IP4Address.IsValid(vnc_bind_address):
1218 dfff41f8 Guido Trotter
        vnc_console_port = ("%s:%s (node %s) (display %s)" %
1219 dfff41f8 Guido Trotter
                             (vnc_bind_address, port,
1220 dfff41f8 Guido Trotter
                              instance["pnode"], display))
1221 a8340917 Iustin Pop
      else:
1222 dfff41f8 Guido Trotter
        # vnc bind address is a file
1223 dfff41f8 Guido Trotter
        vnc_console_port = "%s:%s" % (instance["pnode"],
1224 dfff41f8 Guido Trotter
                                      vnc_bind_address)
1225 24838135 Iustin Pop
      buf.write("    - console connection: vnc to %s\n" % vnc_console_port)
1226 24838135 Iustin Pop
1227 dbb24ec7 Iustin Pop
    _FormatParameterDict(buf, instance["hv_instance"], instance["hv_actual"])
1228 a8083063 Iustin Pop
    buf.write("  Hardware:\n")
1229 e2736e40 Guido Trotter
    buf.write("    - VCPUs: %s\n" %
1230 e2736e40 Guido Trotter
              compat.TryToRoman(instance["be_actual"][constants.BE_VCPUS],
1231 e2736e40 Guido Trotter
                                convert=opts.roman_integers))
1232 e2736e40 Guido Trotter
    buf.write("    - memory: %sMiB\n" %
1233 e2736e40 Guido Trotter
              compat.TryToRoman(instance["be_actual"][constants.BE_MEMORY],
1234 e2736e40 Guido Trotter
                                convert=opts.roman_integers))
1235 d2acfe27 Iustin Pop
    buf.write("    - NICs:\n")
1236 14ea9302 Guido Trotter
    for idx, (ip, mac, mode, link) in enumerate(instance["nics"]):
1237 0b13832c Guido Trotter
      buf.write("      - nic/%d: MAC: %s, IP: %s, mode: %s, link: %s\n" %
1238 0b13832c Guido Trotter
                (idx, mac, ip, mode, link))
1239 19708787 Iustin Pop
    buf.write("  Disks:\n")
1240 a8083063 Iustin Pop
1241 19708787 Iustin Pop
    for idx, device in enumerate(instance["disks"]):
1242 e2736e40 Guido Trotter
      _FormatList(buf, _FormatBlockDevInfo(idx, True, device, opts.static,
1243 e2736e40 Guido Trotter
                  opts.roman_integers), 2)
1244 a8083063 Iustin Pop
1245 3a24c527 Iustin Pop
  ToStdout(buf.getvalue().rstrip('\n'))
1246 a8083063 Iustin Pop
  return retcode
1247 a8083063 Iustin Pop
1248 a8083063 Iustin Pop
1249 7767bbf5 Manuel Franceschini
def SetInstanceParams(opts, args):
1250 a8083063 Iustin Pop
  """Modifies an instance.
1251 a8083063 Iustin Pop

1252 a8083063 Iustin Pop
  All parameters take effect only at the next restart of the instance.
1253 a8083063 Iustin Pop

1254 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
1255 7232c04c Iustin Pop
  @type args: list
1256 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
1257 7232c04c Iustin Pop
  @rtype: int
1258 7232c04c Iustin Pop
  @return: the desired exit code
1259 a8083063 Iustin Pop

1260 a8083063 Iustin Pop
  """
1261 e29e9550 Iustin Pop
  if not (opts.nics or opts.disks or opts.disk_template or
1262 1052d622 Iustin Pop
          opts.hvparams or opts.beparams or opts.os or opts.osparams):
1263 3a24c527 Iustin Pop
    ToStderr("Please give at least one of the parameters.")
1264 a8083063 Iustin Pop
    return 1
1265 a8083063 Iustin Pop
1266 467ae11e Guido Trotter
  for param in opts.beparams:
1267 e9d622bc Guido Trotter
    if isinstance(opts.beparams[param], basestring):
1268 e9d622bc Guido Trotter
      if opts.beparams[param].lower() == "default":
1269 e9d622bc Guido Trotter
        opts.beparams[param] = constants.VALUE_DEFAULT
1270 a5728081 Guido Trotter
1271 a5728081 Guido Trotter
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES,
1272 a5728081 Guido Trotter
                      allowed_values=[constants.VALUE_DEFAULT])
1273 467ae11e Guido Trotter
1274 48f212d7 Iustin Pop
  for param in opts.hvparams:
1275 48f212d7 Iustin Pop
    if isinstance(opts.hvparams[param], basestring):
1276 48f212d7 Iustin Pop
      if opts.hvparams[param].lower() == "default":
1277 48f212d7 Iustin Pop
        opts.hvparams[param] = constants.VALUE_DEFAULT
1278 a5728081 Guido Trotter
1279 48f212d7 Iustin Pop
  utils.ForceDictType(opts.hvparams, constants.HVS_PARAMETER_TYPES,
1280 a5728081 Guido Trotter
                      allowed_values=[constants.VALUE_DEFAULT])
1281 61be6ba4 Iustin Pop
1282 24991749 Iustin Pop
  for idx, (nic_op, nic_dict) in enumerate(opts.nics):
1283 24991749 Iustin Pop
    try:
1284 24991749 Iustin Pop
      nic_op = int(nic_op)
1285 24991749 Iustin Pop
      opts.nics[idx] = (nic_op, nic_dict)
1286 691744c4 Iustin Pop
    except (TypeError, ValueError):
1287 24991749 Iustin Pop
      pass
1288 24991749 Iustin Pop
1289 24991749 Iustin Pop
  for idx, (disk_op, disk_dict) in enumerate(opts.disks):
1290 24991749 Iustin Pop
    try:
1291 24991749 Iustin Pop
      disk_op = int(disk_op)
1292 24991749 Iustin Pop
      opts.disks[idx] = (disk_op, disk_dict)
1293 691744c4 Iustin Pop
    except (TypeError, ValueError):
1294 24991749 Iustin Pop
      pass
1295 24991749 Iustin Pop
    if disk_op == constants.DDM_ADD:
1296 24991749 Iustin Pop
      if 'size' not in disk_dict:
1297 debac808 Iustin Pop
        raise errors.OpPrereqError("Missing required parameter 'size'",
1298 debac808 Iustin Pop
                                   errors.ECODE_INVAL)
1299 24991749 Iustin Pop
      disk_dict['size'] = utils.ParseUnit(disk_dict['size'])
1300 24991749 Iustin Pop
1301 e29e9550 Iustin Pop
  if (opts.disk_template and
1302 e29e9550 Iustin Pop
      opts.disk_template in constants.DTS_NET_MIRROR and
1303 e29e9550 Iustin Pop
      not opts.node):
1304 e29e9550 Iustin Pop
    ToStderr("Changing the disk template to a mirrored one requires"
1305 e29e9550 Iustin Pop
             " specifying a secondary node")
1306 e29e9550 Iustin Pop
    return 1
1307 e29e9550 Iustin Pop
1308 338e51e8 Iustin Pop
  op = opcodes.OpSetInstanceParams(instance_name=args[0],
1309 24991749 Iustin Pop
                                   nics=opts.nics,
1310 24991749 Iustin Pop
                                   disks=opts.disks,
1311 e29e9550 Iustin Pop
                                   disk_template=opts.disk_template,
1312 e29e9550 Iustin Pop
                                   remote_node=opts.node,
1313 48f212d7 Iustin Pop
                                   hvparams=opts.hvparams,
1314 338e51e8 Iustin Pop
                                   beparams=opts.beparams,
1315 96b39bcc Iustin Pop
                                   os_name=opts.os,
1316 1052d622 Iustin Pop
                                   osparams=opts.osparams,
1317 96b39bcc Iustin Pop
                                   force_variant=opts.force_variant,
1318 4300c4b6 Guido Trotter
                                   force=opts.force)
1319 31a853d2 Iustin Pop
1320 6340bb0a Iustin Pop
  # even if here we process the result, we allow submit only
1321 6340bb0a Iustin Pop
  result = SubmitOrSend(op, opts)
1322 a8083063 Iustin Pop
1323 a8083063 Iustin Pop
  if result:
1324 3a24c527 Iustin Pop
    ToStdout("Modified instance %s", args[0])
1325 a8083063 Iustin Pop
    for param, data in result:
1326 3a24c527 Iustin Pop
      ToStdout(" - %-5s -> %s", param, data)
1327 e29e9550 Iustin Pop
    ToStdout("Please don't forget that most parameters take effect"
1328 3a24c527 Iustin Pop
             " only at the next start of the instance.")
1329 a8083063 Iustin Pop
  return 0
1330 a8083063 Iustin Pop
1331 a8083063 Iustin Pop
1332 312ac745 Iustin Pop
# multi-instance selection options
1333 c38c44ad Michael Hanselmann
m_force_multi = cli_option("--force-multiple", dest="force_multi",
1334 c38c44ad Michael Hanselmann
                           help="Do not ask for confirmation when more than"
1335 c38c44ad Michael Hanselmann
                           " one instance is affected",
1336 c38c44ad Michael Hanselmann
                           action="store_true", default=False)
1337 804a1e8e Iustin Pop
1338 c38c44ad Michael Hanselmann
m_pri_node_opt = cli_option("--primary", dest="multi_mode",
1339 c38c44ad Michael Hanselmann
                            help="Filter by nodes (primary only)",
1340 c38c44ad Michael Hanselmann
                            const=_SHUTDOWN_NODES_PRI, action="store_const")
1341 312ac745 Iustin Pop
1342 c38c44ad Michael Hanselmann
m_sec_node_opt = cli_option("--secondary", dest="multi_mode",
1343 c38c44ad Michael Hanselmann
                            help="Filter by nodes (secondary only)",
1344 c38c44ad Michael Hanselmann
                            const=_SHUTDOWN_NODES_SEC, action="store_const")
1345 312ac745 Iustin Pop
1346 c38c44ad Michael Hanselmann
m_node_opt = cli_option("--node", dest="multi_mode",
1347 c38c44ad Michael Hanselmann
                        help="Filter by nodes (primary and secondary)",
1348 c38c44ad Michael Hanselmann
                        const=_SHUTDOWN_NODES_BOTH, action="store_const")
1349 312ac745 Iustin Pop
1350 c38c44ad Michael Hanselmann
m_clust_opt = cli_option("--all", dest="multi_mode",
1351 c38c44ad Michael Hanselmann
                         help="Select all instances in the cluster",
1352 c38c44ad Michael Hanselmann
                         const=_SHUTDOWN_CLUSTER, action="store_const")
1353 312ac745 Iustin Pop
1354 c38c44ad Michael Hanselmann
m_inst_opt = cli_option("--instance", dest="multi_mode",
1355 c38c44ad Michael Hanselmann
                        help="Filter by instance name [default]",
1356 c38c44ad Michael Hanselmann
                        const=_SHUTDOWN_INSTANCES, action="store_const")
1357 312ac745 Iustin Pop
1358 39dfd93e René Nussbaumer
m_node_tags_opt = cli_option("--node-tags", dest="multi_mode",
1359 39dfd93e René Nussbaumer
                             help="Filter by node tag",
1360 39dfd93e René Nussbaumer
                             const=_SHUTDOWN_NODES_BOTH_BY_TAGS,
1361 39dfd93e René Nussbaumer
                             action="store_const")
1362 39dfd93e René Nussbaumer
1363 39dfd93e René Nussbaumer
m_pri_node_tags_opt = cli_option("--pri-node-tags", dest="multi_mode",
1364 39dfd93e René Nussbaumer
                                 help="Filter by primary node tag",
1365 39dfd93e René Nussbaumer
                                 const=_SHUTDOWN_NODES_PRI_BY_TAGS,
1366 39dfd93e René Nussbaumer
                                 action="store_const")
1367 39dfd93e René Nussbaumer
1368 39dfd93e René Nussbaumer
m_sec_node_tags_opt = cli_option("--sec-node-tags", dest="multi_mode",
1369 39dfd93e René Nussbaumer
                                 help="Filter by secondary node tag",
1370 39dfd93e René Nussbaumer
                                 const=_SHUTDOWN_NODES_SEC_BY_TAGS,
1371 39dfd93e René Nussbaumer
                                 action="store_const")
1372 39dfd93e René Nussbaumer
1373 39dfd93e René Nussbaumer
m_inst_tags_opt = cli_option("--tags", dest="multi_mode",
1374 39dfd93e René Nussbaumer
                             help="Filter by instance tag",
1375 39dfd93e René Nussbaumer
                             const=_SHUTDOWN_INSTANCES_BY_TAGS,
1376 39dfd93e René Nussbaumer
                             action="store_const")
1377 312ac745 Iustin Pop
1378 a8083063 Iustin Pop
# this is defined separately due to readability only
1379 a8083063 Iustin Pop
add_opts = [
1380 064c21f8 Iustin Pop
  NOSTART_OPT,
1381 064c21f8 Iustin Pop
  OS_OPT,
1382 06073e85 Guido Trotter
  FORCE_VARIANT_OPT,
1383 25a8792c Iustin Pop
  NO_INSTALL_OPT,
1384 a8083063 Iustin Pop
  ]
1385 a8083063 Iustin Pop
1386 a8083063 Iustin Pop
commands = {
1387 6ea815cf Iustin Pop
  'add': (
1388 eb28ecf6 Guido Trotter
    AddInstance, [ArgHost(min=1, max=1)], COMMON_CREATE_OPTS + 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 aa06f8c6 Michael Hanselmann
    BatchCreate, [ArgFile(min=1, max=1)], [DRY_RUN_OPT, PRIORITY_OPT],
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 aa06f8c6 Michael Hanselmann
    [SHOWCMD_OPT, PRIORITY_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 db5a8a2d Iustin Pop
    [FORCE_OPT, IGNORE_CONSIST_OPT, SUBMIT_OPT, SHUTDOWN_TIMEOUT_OPT,
1402 aa06f8c6 Michael Hanselmann
     DRY_RUN_OPT, PRIORITY_OPT],
1403 6ea815cf Iustin Pop
    "[-f] <instance>", "Stops the instance and starts it on the backup node,"
1404 6ea815cf Iustin Pop
    " using the remote mirror (only for instances of type drbd)"),
1405 6ea815cf Iustin Pop
  'migrate': (
1406 6ea815cf Iustin Pop
    MigrateInstance, ARGS_ONE_INSTANCE,
1407 aa06f8c6 Michael Hanselmann
    [FORCE_OPT, NONLIVE_OPT, MIGRATION_MODE_OPT, CLEANUP_OPT, DRY_RUN_OPT,
1408 aa06f8c6 Michael Hanselmann
     PRIORITY_OPT],
1409 6ea815cf Iustin Pop
    "[-f] <instance>", "Migrate instance to its secondary node"
1410 6ea815cf Iustin Pop
    " (only for instances of type drbd)"),
1411 6ea815cf Iustin Pop
  'move': (
1412 6ea815cf Iustin Pop
    MoveInstance, ARGS_ONE_INSTANCE,
1413 db5a8a2d Iustin Pop
    [FORCE_OPT, SUBMIT_OPT, SINGLE_NODE_OPT, SHUTDOWN_TIMEOUT_OPT,
1414 aa06f8c6 Michael Hanselmann
     DRY_RUN_OPT, PRIORITY_OPT],
1415 6ea815cf Iustin Pop
    "[-f] <instance>", "Move instance to an arbitrary node"
1416 6ea815cf Iustin Pop
    " (only for instances of type file and lv)"),
1417 6ea815cf Iustin Pop
  'info': (
1418 6ea815cf Iustin Pop
    ShowInstanceConfig, ARGS_MANY_INSTANCES,
1419 aa06f8c6 Michael Hanselmann
    [STATIC_OPT, ALL_OPT, ROMAN_OPT, PRIORITY_OPT],
1420 6ea815cf Iustin Pop
    "[-s] {--all | <instance>...}",
1421 6ea815cf Iustin Pop
    "Show information on the specified instance(s)"),
1422 6ea815cf Iustin Pop
  'list': (
1423 6ea815cf Iustin Pop
    ListInstances, ARGS_MANY_INSTANCES,
1424 e2736e40 Guido Trotter
    [NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, SYNC_OPT, ROMAN_OPT],
1425 6ea815cf Iustin Pop
    "[<instance>...]",
1426 6ea815cf Iustin Pop
    "Lists the instances and their status. The available fields are"
1427 6ea815cf Iustin Pop
    " (see the man page for details): status, oper_state, oper_ram,"
1428 4ea3de4e Balazs Lecz
    " oper_vcpus, name, os, pnode, snodes, admin_state, admin_ram,"
1429 4ea3de4e Balazs Lecz
    " disk_template, ip, mac, nic_mode, nic_link, sda_size, sdb_size,"
1430 4ea3de4e Balazs Lecz
    " vcpus, serial_no,"
1431 8619a3bd Guido Trotter
    " nic.count, nic.mac/N, nic.ip/N, nic.mode/N, nic.link/N,"
1432 8619a3bd Guido Trotter
    " nic.macs, nic.ips, nic.modes, nic.links,"
1433 8619a3bd Guido Trotter
    " disk.count, disk.size/N, disk.sizes,"
1434 8619a3bd Guido Trotter
    " hv/NAME, be/memory, be/vcpus, be/auto_balance,"
1435 6ea815cf Iustin Pop
    " hypervisor."
1436 6ea815cf Iustin Pop
    " The default field"
1437 1f864b60 Iustin Pop
    " list is (in order): %s." % utils.CommaJoin(_LIST_DEF_FIELDS),
1438 6ea815cf Iustin Pop
    ),
1439 6ea815cf Iustin Pop
  'reinstall': (
1440 3e54ace7 Iustin Pop
    ReinstallInstance, [ArgInstance()],
1441 06073e85 Guido Trotter
    [FORCE_OPT, OS_OPT, FORCE_VARIANT_OPT, m_force_multi, m_node_opt,
1442 39dfd93e René Nussbaumer
     m_pri_node_opt, m_sec_node_opt, m_clust_opt, m_inst_opt, m_node_tags_opt,
1443 39dfd93e René Nussbaumer
     m_pri_node_tags_opt, m_sec_node_tags_opt, m_inst_tags_opt, SELECT_OS_OPT,
1444 8d8c4eff Michael Hanselmann
     SUBMIT_OPT, DRY_RUN_OPT, PRIORITY_OPT, OSPARAMS_OPT],
1445 6ea815cf Iustin Pop
    "[-f] <instance>", "Reinstall a stopped instance"),
1446 6ea815cf Iustin Pop
  'remove': (
1447 6ea815cf Iustin Pop
    RemoveInstance, ARGS_ONE_INSTANCE,
1448 db5a8a2d Iustin Pop
    [FORCE_OPT, SHUTDOWN_TIMEOUT_OPT, IGNORE_FAILURES_OPT, SUBMIT_OPT,
1449 aa06f8c6 Michael Hanselmann
     DRY_RUN_OPT, PRIORITY_OPT],
1450 6ea815cf Iustin Pop
    "[-f] <instance>", "Shuts down the instance and removes it"),
1451 6ea815cf Iustin Pop
  'rename': (
1452 6ea815cf Iustin Pop
    RenameInstance,
1453 6ea815cf Iustin Pop
    [ArgInstance(min=1, max=1), ArgHost(min=1, max=1)],
1454 aa06f8c6 Michael Hanselmann
    [NOIPCHECK_OPT, NONAMECHECK_OPT, SUBMIT_OPT, DRY_RUN_OPT, PRIORITY_OPT],
1455 6ea815cf Iustin Pop
    "<instance> <new_name>", "Rename the instance"),
1456 6ea815cf Iustin Pop
  'replace-disks': (
1457 6ea815cf Iustin Pop
    ReplaceDisks, ARGS_ONE_INSTANCE,
1458 7ea7bcf6 Iustin Pop
    [AUTO_REPLACE_OPT, DISKIDX_OPT, IALLOCATOR_OPT, EARLY_RELEASE_OPT,
1459 db5a8a2d Iustin Pop
     NEW_SECONDARY_OPT, ON_PRIMARY_OPT, ON_SECONDARY_OPT, SUBMIT_OPT,
1460 aa06f8c6 Michael Hanselmann
     DRY_RUN_OPT, PRIORITY_OPT],
1461 6ea815cf Iustin Pop
    "[-s|-p|-n NODE|-I NAME] <instance>",
1462 6ea815cf Iustin Pop
    "Replaces all disks for the instance"),
1463 6ea815cf Iustin Pop
  'modify': (
1464 6ea815cf Iustin Pop
    SetInstanceParams, ARGS_ONE_INSTANCE,
1465 e29e9550 Iustin Pop
    [BACKEND_OPT, DISK_OPT, FORCE_OPT, HVOPTS_OPT, NET_OPT, SUBMIT_OPT,
1466 1052d622 Iustin Pop
     DISK_TEMPLATE_OPT, SINGLE_NODE_OPT, OS_OPT, FORCE_VARIANT_OPT,
1467 aa06f8c6 Michael Hanselmann
     OSPARAMS_OPT, DRY_RUN_OPT, PRIORITY_OPT],
1468 6ea815cf Iustin Pop
    "<instance>", "Alters the parameters of an instance"),
1469 6ea815cf Iustin Pop
  'shutdown': (
1470 1c5945b6 Iustin Pop
    GenericManyOps("shutdown", _ShutdownInstance), [ArgInstance()],
1471 064c21f8 Iustin Pop
    [m_node_opt, m_pri_node_opt, m_sec_node_opt, m_clust_opt,
1472 39dfd93e René Nussbaumer
     m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt,
1473 db5a8a2d Iustin Pop
     m_inst_tags_opt, m_inst_opt, m_force_multi, TIMEOUT_OPT, SUBMIT_OPT,
1474 b44bd844 Michael Hanselmann
     DRY_RUN_OPT, PRIORITY_OPT, IGNORE_OFFLINE_OPT],
1475 6ea815cf Iustin Pop
    "<instance>", "Stops an instance"),
1476 6ea815cf Iustin Pop
  'startup': (
1477 1c5945b6 Iustin Pop
    GenericManyOps("startup", _StartupInstance), [ArgInstance()],
1478 39dfd93e René Nussbaumer
    [FORCE_OPT, m_force_multi, m_node_opt, m_pri_node_opt, m_sec_node_opt,
1479 39dfd93e René Nussbaumer
     m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt,
1480 39dfd93e René Nussbaumer
     m_inst_tags_opt, m_clust_opt, m_inst_opt, SUBMIT_OPT, HVOPTS_OPT,
1481 b44bd844 Michael Hanselmann
     BACKEND_OPT, DRY_RUN_OPT, PRIORITY_OPT, IGNORE_OFFLINE_OPT],
1482 6ea815cf Iustin Pop
    "<instance>", "Starts an instance"),
1483 6ea815cf Iustin Pop
  'reboot': (
1484 1c5945b6 Iustin Pop
    GenericManyOps("reboot", _RebootInstance), [ArgInstance()],
1485 064c21f8 Iustin Pop
    [m_force_multi, REBOOT_TYPE_OPT, IGNORE_SECONDARIES_OPT, m_node_opt,
1486 17c3f802 Guido Trotter
     m_pri_node_opt, m_sec_node_opt, m_clust_opt, m_inst_opt, SUBMIT_OPT,
1487 39dfd93e René Nussbaumer
     m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt,
1488 aa06f8c6 Michael Hanselmann
     m_inst_tags_opt, SHUTDOWN_TIMEOUT_OPT, DRY_RUN_OPT, PRIORITY_OPT],
1489 6ea815cf Iustin Pop
    "<instance>", "Reboots an instance"),
1490 6ea815cf Iustin Pop
  'activate-disks': (
1491 db5a8a2d Iustin Pop
    ActivateDisks, ARGS_ONE_INSTANCE,
1492 aa06f8c6 Michael Hanselmann
    [SUBMIT_OPT, IGNORE_SIZE_OPT, PRIORITY_OPT],
1493 6ea815cf Iustin Pop
    "<instance>", "Activate an instance's disks"),
1494 6ea815cf Iustin Pop
  'deactivate-disks': (
1495 aa06f8c6 Michael Hanselmann
    DeactivateDisks, ARGS_ONE_INSTANCE,
1496 aa06f8c6 Michael Hanselmann
    [SUBMIT_OPT, DRY_RUN_OPT, PRIORITY_OPT],
1497 6ea815cf Iustin Pop
    "<instance>", "Deactivate an instance's disks"),
1498 6ea815cf Iustin Pop
  'recreate-disks': (
1499 aa06f8c6 Michael Hanselmann
    RecreateDisks, ARGS_ONE_INSTANCE,
1500 aa06f8c6 Michael Hanselmann
    [SUBMIT_OPT, DISKIDX_OPT, DRY_RUN_OPT, PRIORITY_OPT],
1501 6ea815cf Iustin Pop
    "<instance>", "Recreate an instance's disks"),
1502 6ea815cf Iustin Pop
  'grow-disk': (
1503 6ea815cf Iustin Pop
    GrowDisk,
1504 6ea815cf Iustin Pop
    [ArgInstance(min=1, max=1), ArgUnknown(min=1, max=1),
1505 6ea815cf Iustin Pop
     ArgUnknown(min=1, max=1)],
1506 aa06f8c6 Michael Hanselmann
    [SUBMIT_OPT, NWSYNC_OPT, DRY_RUN_OPT, PRIORITY_OPT],
1507 6ea815cf Iustin Pop
    "<instance> <disk> <size>", "Grow an instance's disk"),
1508 6ea815cf Iustin Pop
  'list-tags': (
1509 aa06f8c6 Michael Hanselmann
    ListTags, ARGS_ONE_INSTANCE, [PRIORITY_OPT],
1510 6ea815cf Iustin Pop
    "<instance_name>", "List the tags of the given instance"),
1511 6ea815cf Iustin Pop
  'add-tags': (
1512 6ea815cf Iustin Pop
    AddTags, [ArgInstance(min=1, max=1), ArgUnknown()],
1513 aa06f8c6 Michael Hanselmann
    [TAG_SRC_OPT, PRIORITY_OPT],
1514 6ea815cf Iustin Pop
    "<instance_name> tag...", "Add tags to the given instance"),
1515 6ea815cf Iustin Pop
  'remove-tags': (
1516 6ea815cf Iustin Pop
    RemoveTags, [ArgInstance(min=1, max=1), ArgUnknown()],
1517 aa06f8c6 Michael Hanselmann
    [TAG_SRC_OPT, PRIORITY_OPT],
1518 6ea815cf Iustin Pop
    "<instance_name> tag...", "Remove tags from given instance"),
1519 a8083063 Iustin Pop
  }
1520 a8083063 Iustin Pop
1521 7232c04c Iustin Pop
#: dictionary with aliases for commands
1522 dbfd89dd Guido Trotter
aliases = {
1523 536fda25 Guido Trotter
  'start': 'startup',
1524 536fda25 Guido Trotter
  'stop': 'shutdown',
1525 dbfd89dd Guido Trotter
  }
1526 dbfd89dd Guido Trotter
1527 a8005e17 Michael Hanselmann
1528 e792102d Michael Hanselmann
def Main():
1529 e792102d Michael Hanselmann
  return GenericMain(commands, aliases=aliases,
1530 e792102d Michael Hanselmann
                     override={"tag_type": constants.TAG_INSTANCE})