Statistics
| Branch: | Tag: | Revision:

root / scripts / gnt-instance @ 7d20c647

History | View | Annotate | Download (45 kB)

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