| Branch: | Tag: | Revision:

root / lib / client / @ 93f1e606

History | View | Annotate | Download (57.5 kB)

1 e792102d Michael Hanselmann
2 a8083063 Iustin Pop
3 a8083063 Iustin Pop
4 015f1517 Jose A. Lopes
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014 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
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 b459a848 Andrea Spadaccini
# pylint: disable=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 83d4ba5e René Nussbaumer
import copy
29 312ac745 Iustin Pop
import itertools
30 0d0e9090 René Nussbaumer
import simplejson
31 25ce3ec4 Michael Hanselmann
import logging
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 25ce3ec4 Michael Hanselmann
from ganeti import ssh
41 25ce3ec4 Michael Hanselmann
from ganeti import objects
42 735e1318 Michael Hanselmann
from ganeti import ht
43 312ac745 Iustin Pop
44 312ac745 Iustin Pop
45 c20efaa8 Michael Hanselmann
_EXPAND_CLUSTER = "cluster"
46 c20efaa8 Michael Hanselmann
47 c20efaa8 Michael Hanselmann
_EXPAND_NODES_PRI = "nodes-pri"
48 c20efaa8 Michael Hanselmann
_EXPAND_NODES_SEC = "nodes-sec"
49 c20efaa8 Michael Hanselmann
_EXPAND_NODES_BOTH_BY_TAGS = "nodes-by-tags"
50 c20efaa8 Michael Hanselmann
_EXPAND_NODES_PRI_BY_TAGS = "nodes-pri-by-tags"
51 c20efaa8 Michael Hanselmann
_EXPAND_NODES_SEC_BY_TAGS = "nodes-sec-by-tags"
52 c20efaa8 Michael Hanselmann
_EXPAND_INSTANCES = "instances"
53 c20efaa8 Michael Hanselmann
_EXPAND_INSTANCES_BY_TAGS = "instances-by-tags"
54 c20efaa8 Michael Hanselmann
55 b8028dcf Michael Hanselmann
_EXPAND_NODES_TAGS_MODES = compat.UniqueFrozenset([
56 c20efaa8 Michael Hanselmann
57 c20efaa8 Michael Hanselmann
58 c20efaa8 Michael Hanselmann
59 c20efaa8 Michael Hanselmann
60 312ac745 Iustin Pop
61 7232c04c Iustin Pop
#: default list of options for L{ListInstances}
62 48c4dfa8 Iustin Pop
63 e69d05fd Iustin Pop
  "name", "hypervisor", "os", "pnode", "status", "oper_ram",
64 48c4dfa8 Iustin Pop
65 48c4dfa8 Iustin Pop
66 a71f835e Michael Hanselmann
_MISSING = object()
67 b8028dcf Michael Hanselmann
_ENV_OVERRIDE = compat.UniqueFrozenset(["list"])
68 ef9fa5b9 René Nussbaumer
69 b0a8e8c2 René Nussbaumer
_INST_DATA_VAL = ht.TListOf(ht.TDict)
70 b0a8e8c2 René Nussbaumer
71 ef9fa5b9 René Nussbaumer
72 479636a3 Iustin Pop
def _ExpandMultiNames(mode, names, client=None):
73 312ac745 Iustin Pop
  """Expand the given names using the passed mode.
74 312ac745 Iustin Pop

75 c20efaa8 Michael Hanselmann
  For _EXPAND_CLUSTER, all instances will be returned. For
76 c20efaa8 Michael Hanselmann
  _EXPAND_NODES_PRI/SEC, all instances having those nodes as
77 c20efaa8 Michael Hanselmann
  primary/secondary will be returned. For _EXPAND_NODES_BOTH, all
78 312ac745 Iustin Pop
  instances having those nodes as either primary or secondary will be
79 c20efaa8 Michael Hanselmann
  returned. For _EXPAND_INSTANCES, the given instances will be
80 312ac745 Iustin Pop
81 312ac745 Iustin Pop

82 c20efaa8 Michael Hanselmann
  @param mode: one of L{_EXPAND_CLUSTER}, L{_EXPAND_NODES_BOTH},
83 c20efaa8 Michael Hanselmann
84 c20efaa8 Michael Hanselmann
85 7232c04c Iustin Pop
  @param names: a list of names; for cluster, it must be empty,
86 7232c04c Iustin Pop
      and for node and instance it must be a list of valid item
87 7232c04c Iustin Pop
      names (short names are valid as usual, e.g. node1 instead of
88 7232c04c Iustin Pop
89 7232c04c Iustin Pop
  @rtype: list
90 7232c04c Iustin Pop
  @return: the list of names after the expansion
91 7232c04c Iustin Pop
  @raise errors.ProgrammerError: for unknown selection type
92 7232c04c Iustin Pop
  @raise errors.OpPrereqError: for invalid input parameters
93 7232c04c Iustin Pop

94 312ac745 Iustin Pop
95 b459a848 Andrea Spadaccini
  # pylint: disable=W0142
96 39dfd93e René Nussbaumer
97 479636a3 Iustin Pop
  if client is None:
98 2af8b9c9 Klaus Aehlig
    client = GetClient()
99 c20efaa8 Michael Hanselmann
  if mode == _EXPAND_CLUSTER:
100 312ac745 Iustin Pop
    if names:
101 debac808 Iustin Pop
      raise errors.OpPrereqError("Cluster filter mode takes no arguments",
102 debac808 Iustin Pop
103 ec79568d Iustin Pop
    idata = client.QueryInstances([], ["name"], False)
104 312ac745 Iustin Pop
    inames = [row[0] for row in idata]
105 312ac745 Iustin Pop
106 c20efaa8 Michael Hanselmann
  elif (mode in _EXPAND_NODES_TAGS_MODES or
107 c20efaa8 Michael Hanselmann
108 c20efaa8 Michael Hanselmann
    if mode in _EXPAND_NODES_TAGS_MODES:
109 39dfd93e René Nussbaumer
      if not names:
110 39dfd93e René Nussbaumer
        raise errors.OpPrereqError("No node tags passed", errors.ECODE_INVAL)
111 39dfd93e René Nussbaumer
      ndata = client.QueryNodes([], ["name", "pinst_list",
112 39dfd93e René Nussbaumer
                                     "sinst_list", "tags"], False)
113 39dfd93e René Nussbaumer
      ndata = [row for row in ndata if set(row[3]).intersection(names)]
114 39dfd93e René Nussbaumer
115 39dfd93e René Nussbaumer
      if not names:
116 39dfd93e René Nussbaumer
        raise errors.OpPrereqError("No node names passed", errors.ECODE_INVAL)
117 39dfd93e René Nussbaumer
      ndata = client.QueryNodes(names, ["name", "pinst_list", "sinst_list"],
118 5ae4945a Iustin Pop
119 39dfd93e René Nussbaumer
120 312ac745 Iustin Pop
    ipri = [row[1] for row in ndata]
121 312ac745 Iustin Pop
    pri_names = list(itertools.chain(*ipri))
122 312ac745 Iustin Pop
    isec = [row[2] for row in ndata]
123 312ac745 Iustin Pop
    sec_names = list(itertools.chain(*isec))
124 c20efaa8 Michael Hanselmann
125 312ac745 Iustin Pop
      inames = pri_names + sec_names
126 c20efaa8 Michael Hanselmann
127 312ac745 Iustin Pop
      inames = pri_names
128 c20efaa8 Michael Hanselmann
129 312ac745 Iustin Pop
      inames = sec_names
130 312ac745 Iustin Pop
131 312ac745 Iustin Pop
      raise errors.ProgrammerError("Unhandled shutdown type")
132 c20efaa8 Michael Hanselmann
  elif mode == _EXPAND_INSTANCES:
133 312ac745 Iustin Pop
    if not names:
134 debac808 Iustin Pop
      raise errors.OpPrereqError("No instance names passed",
135 debac808 Iustin Pop
136 ec79568d Iustin Pop
    idata = client.QueryInstances(names, ["name"], False)
137 312ac745 Iustin Pop
    inames = [row[0] for row in idata]
138 c20efaa8 Michael Hanselmann
139 39dfd93e René Nussbaumer
    if not names:
140 39dfd93e René Nussbaumer
      raise errors.OpPrereqError("No instance tags passed",
141 39dfd93e René Nussbaumer
142 39dfd93e René Nussbaumer
    idata = client.QueryInstances([], ["name", "tags"], False)
143 39dfd93e René Nussbaumer
    inames = [row[0] for row in idata if set(row[1]).intersection(names)]
144 312ac745 Iustin Pop
145 debac808 Iustin Pop
    raise errors.OpPrereqError("Unknown mode '%s'" % mode, errors.ECODE_INVAL)
146 312ac745 Iustin Pop
147 312ac745 Iustin Pop
  return inames
148 a8083063 Iustin Pop
149 a8083063 Iustin Pop
150 a76f0c4a Iustin Pop
def _EnsureInstancesExist(client, names):
151 a76f0c4a Iustin Pop
  """Check for and ensure the given instance names exist.
152 a76f0c4a Iustin Pop

153 a76f0c4a Iustin Pop
  This function will raise an OpPrereqError in case they don't
154 a76f0c4a Iustin Pop
  exist. Otherwise it will exit cleanly.
155 a76f0c4a Iustin Pop

156 f2fd87d7 Iustin Pop
  @type client: L{ganeti.luxi.Client}
157 a76f0c4a Iustin Pop
  @param client: the client to use for the query
158 a76f0c4a Iustin Pop
  @type names: list
159 a76f0c4a Iustin Pop
  @param names: the list of instance names to query
160 a76f0c4a Iustin Pop
  @raise errors.OpPrereqError: in case any instance is missing
161 a76f0c4a Iustin Pop

162 a76f0c4a Iustin Pop
163 f2af0bec Iustin Pop
  # TODO: change LUInstanceQuery to that it actually returns None
164 a76f0c4a Iustin Pop
  # instead of raising an exception, or devise a better mechanism
165 ec79568d Iustin Pop
  result = client.QueryInstances(names, ["name"], False)
166 a76f0c4a Iustin Pop
  for orig_name, row in zip(names, result):
167 a76f0c4a Iustin Pop
    if row[0] is None:
168 debac808 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' does not exist" % orig_name,
169 debac808 Iustin Pop
170 a76f0c4a Iustin Pop
171 a76f0c4a Iustin Pop
172 1c5945b6 Iustin Pop
def GenericManyOps(operation, fn):
173 1c5945b6 Iustin Pop
  """Generic multi-instance operations.
174 1c5945b6 Iustin Pop

175 1c5945b6 Iustin Pop
  The will return a wrapper that processes the options and arguments
176 1c5945b6 Iustin Pop
  given, and uses the passed function to build the opcode needed for
177 1c5945b6 Iustin Pop
  the specific operation. Thus all the generic loop/confirmation code
178 1c5945b6 Iustin Pop
  is abstracted into this function.
179 1c5945b6 Iustin Pop

180 1c5945b6 Iustin Pop
181 1c5945b6 Iustin Pop
  def realfn(opts, args):
182 1c5945b6 Iustin Pop
    if opts.multi_mode is None:
183 c20efaa8 Michael Hanselmann
      opts.multi_mode = _EXPAND_INSTANCES
184 1c5945b6 Iustin Pop
    cl = GetClient()
185 2af8b9c9 Klaus Aehlig
    inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
186 1c5945b6 Iustin Pop
    if not inames:
187 c20efaa8 Michael Hanselmann
      if opts.multi_mode == _EXPAND_CLUSTER:
188 c37bb2c6 Stephen Shirley
        ToStdout("Cluster is empty, no instances to shutdown")
189 c37bb2c6 Stephen Shirley
        return 0
190 1c5945b6 Iustin Pop
      raise errors.OpPrereqError("Selection filter does not match"
191 debac808 Iustin Pop
                                 " any instances", errors.ECODE_INVAL)
192 c20efaa8 Michael Hanselmann
    multi_on = opts.multi_mode != _EXPAND_INSTANCES or len(inames) > 1
193 1c5945b6 Iustin Pop
    if not (opts.force_multi or not multi_on
194 25bd815c René Nussbaumer
            or ConfirmOperation(inames, "instances", operation)):
195 1c5945b6 Iustin Pop
      return 1
196 cb573a31 Iustin Pop
    jex = JobExecutor(verbose=multi_on, cl=cl, opts=opts)
197 1c5945b6 Iustin Pop
    for name in inames:
198 1c5945b6 Iustin Pop
      op = fn(name, opts)
199 1c5945b6 Iustin Pop
      jex.QueueJob(name, op)
200 b4e68848 Iustin Pop
    results = jex.WaitOrShow(not opts.submit_only)
201 b4e68848 Iustin Pop
    rcode = compat.all(row[0] for row in results)
202 b4e68848 Iustin Pop
    return int(not rcode)
203 1c5945b6 Iustin Pop
  return realfn
204 1c5945b6 Iustin Pop
205 1c5945b6 Iustin Pop
206 a8083063 Iustin Pop
def ListInstances(opts, args):
207 f5abe9bd Oleksiy Mishchenko
  """List instances and their properties.
208 a8083063 Iustin Pop

209 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
210 7232c04c Iustin Pop
  @type args: list
211 7232c04c Iustin Pop
  @param args: should be an empty list
212 7232c04c Iustin Pop
  @rtype: int
213 7232c04c Iustin Pop
  @return: the desired exit code
214 7232c04c Iustin Pop

215 a8083063 Iustin Pop
216 a4ebd726 Michael Hanselmann
  selected_fields = ParseFields(opts.output, _LIST_DEF_FIELDS)
217 a8083063 Iustin Pop
218 b82c5ff5 Michael Hanselmann
  fmtoverride = dict.fromkeys(["tags", "disk.sizes", "nic.macs", "nic.ips",
219 b82c5ff5 Michael Hanselmann
                               "nic.modes", "nic.links", "nic.bridges",
220 d4117a72 Apollon Oikonomopoulos
221 fab9573b Michael Hanselmann
                               "snodes", "", ""],
222 b82c5ff5 Michael Hanselmann
                              (lambda value: ",".join(str(item)
223 b82c5ff5 Michael Hanselmann
                                                      for item in value),
224 b82c5ff5 Michael Hanselmann
225 a8083063 Iustin Pop
226 2af8b9c9 Klaus Aehlig
  cl = GetClient()
227 e96c0a5c Hrvoje Ribicic
228 b82c5ff5 Michael Hanselmann
  return GenericList(constants.QR_INSTANCE, selected_fields, args, opts.units,
229 b82c5ff5 Michael Hanselmann
                     opts.separator, not opts.no_headers,
230 87e87959 Michael Hanselmann
                     format_override=fmtoverride, verbose=opts.verbose,
231 e96c0a5c Hrvoje Ribicic
                     force_filter=opts.force_filter, cl=cl)
232 b82c5ff5 Michael Hanselmann
233 b82c5ff5 Michael Hanselmann
234 b82c5ff5 Michael Hanselmann
def ListInstanceFields(opts, args):
235 b82c5ff5 Michael Hanselmann
  """List instance fields.
236 b82c5ff5 Michael Hanselmann

237 b82c5ff5 Michael Hanselmann
  @param opts: the command line options selected by the user
238 b82c5ff5 Michael Hanselmann
  @type args: list
239 b82c5ff5 Michael Hanselmann
  @param args: fields to list, or empty for all
240 b82c5ff5 Michael Hanselmann
  @rtype: int
241 b82c5ff5 Michael Hanselmann
  @return: the desired exit code
242 b82c5ff5 Michael Hanselmann

243 b82c5ff5 Michael Hanselmann
244 b82c5ff5 Michael Hanselmann
  return GenericListFields(constants.QR_INSTANCE, args, opts.separator,
245 b82c5ff5 Michael Hanselmann
                           not opts.no_headers)
246 a8083063 Iustin Pop
247 a8083063 Iustin Pop
248 a8083063 Iustin Pop
def AddInstance(opts, args):
249 a8083063 Iustin Pop
  """Add an instance to the cluster.
250 a8083063 Iustin Pop

251 002764e8 Jose A. Lopes
  This is just a wrapper over L{GenericInstanceCreate}.
252 a8083063 Iustin Pop

253 a8083063 Iustin Pop
254 d77490c5 Iustin Pop
  return GenericInstanceCreate(constants.INSTANCE_CREATE, opts, args)
255 a8083063 Iustin Pop
256 a8083063 Iustin Pop
257 0d0e9090 René Nussbaumer
def BatchCreate(opts, args):
258 7232c04c Iustin Pop
  """Create instances using a definition file.
259 7232c04c Iustin Pop

260 b0a8e8c2 René Nussbaumer
  This function reads a json file with L{opcodes.OpInstanceCreate}
261 b0a8e8c2 René Nussbaumer
262 7232c04c Iustin Pop

263 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
264 7232c04c Iustin Pop
  @type args: list
265 7232c04c Iustin Pop
  @param args: should contain one element, the json filename
266 7232c04c Iustin Pop
  @rtype: int
267 7232c04c Iustin Pop
  @return: the desired exit code
268 0d0e9090 René Nussbaumer

269 0d0e9090 René Nussbaumer
270 b0a8e8c2 René Nussbaumer
  (json_filename,) = args
271 b0a8e8c2 René Nussbaumer
  cl = GetClient()
272 0d0e9090 René Nussbaumer
273 0d0e9090 René Nussbaumer
274 13998ef2 Michael Hanselmann
    instance_data = simplejson.loads(utils.ReadFile(json_filename))
275 b459a848 Andrea Spadaccini
  except Exception, err: # pylint: disable=W0703
276 4082e6f9 Iustin Pop
    ToStderr("Can't parse the instance definition file: %s" % str(err))
277 4082e6f9 Iustin Pop
    return 1
278 0d0e9090 René Nussbaumer
279 b0a8e8c2 René Nussbaumer
  if not _INST_DATA_VAL(instance_data):
280 b0a8e8c2 René Nussbaumer
    ToStderr("The instance definition file is not %s" % _INST_DATA_VAL)
281 fe7c59d5 Guido Trotter
    return 1
282 fe7c59d5 Guido Trotter
283 b0a8e8c2 René Nussbaumer
  instances = []
284 b0a8e8c2 René Nussbaumer
  possible_params = set(opcodes.OpInstanceCreate.GetAllSlots())
285 b0a8e8c2 René Nussbaumer
  for (idx, inst) in enumerate(instance_data):
286 b0a8e8c2 René Nussbaumer
    unknown = set(inst.keys()) - possible_params
287 d4dd4b74 Iustin Pop
288 b0a8e8c2 René Nussbaumer
    if unknown:
289 b0a8e8c2 René Nussbaumer
      # TODO: Suggest closest match for more user friendly experience
290 3779121c René Nussbaumer
      raise errors.OpPrereqError("Unknown fields in definition %s: %s" %
291 3779121c René Nussbaumer
                                 (idx, utils.CommaJoin(unknown)),
292 3779121c René Nussbaumer
293 0d0e9090 René Nussbaumer
294 3779121c René Nussbaumer
    op = opcodes.OpInstanceCreate(**inst) # pylint: disable=W0142
295 b0a8e8c2 René Nussbaumer
296 b0a8e8c2 René Nussbaumer
297 0d0e9090 René Nussbaumer
298 b0a8e8c2 René Nussbaumer
  op = opcodes.OpInstanceMultiAlloc(iallocator=opts.iallocator,
299 b0a8e8c2 René Nussbaumer
300 b0a8e8c2 René Nussbaumer
  result = SubmitOrSend(op, opts, cl=cl)
301 0d0e9090 René Nussbaumer
302 b0a8e8c2 René Nussbaumer
  # Keep track of submitted jobs
303 b0a8e8c2 René Nussbaumer
  jex = JobExecutor(cl=cl, opts=opts)
304 b0a8e8c2 René Nussbaumer
305 b0a8e8c2 René Nussbaumer
  for (status, job_id) in result[constants.JOB_IDS_KEY]:
306 b0a8e8c2 René Nussbaumer
    jex.AddJobId(None, status, job_id)
307 b0a8e8c2 René Nussbaumer
308 b0a8e8c2 René Nussbaumer
  results = jex.GetResults()
309 b0a8e8c2 René Nussbaumer
  bad_cnt = len([row for row in results if not row[0]])
310 b0a8e8c2 René Nussbaumer
  if bad_cnt == 0:
311 b0a8e8c2 René Nussbaumer
    ToStdout("All instances created successfully.")
312 b0a8e8c2 René Nussbaumer
    rcode = constants.EXIT_SUCCESS
313 b0a8e8c2 René Nussbaumer
314 b0a8e8c2 René Nussbaumer
    ToStdout("There were %s errors during the creation.", bad_cnt)
315 b0a8e8c2 René Nussbaumer
    rcode = constants.EXIT_FAILURE
316 b0a8e8c2 René Nussbaumer
317 b0a8e8c2 René Nussbaumer
  return rcode
318 0d0e9090 René Nussbaumer
319 0d0e9090 René Nussbaumer
320 fe7b0351 Michael Hanselmann
def ReinstallInstance(opts, args):
321 fe7b0351 Michael Hanselmann
  """Reinstall an instance.
322 fe7b0351 Michael Hanselmann

323 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
324 7232c04c Iustin Pop
  @type args: list
325 7232c04c Iustin Pop
  @param args: should contain only one element, the name of the
326 7232c04c Iustin Pop
      instance to be reinstalled
327 7232c04c Iustin Pop
  @rtype: int
328 7232c04c Iustin Pop
  @return: the desired exit code
329 fe7b0351 Michael Hanselmann

330 fe7b0351 Michael Hanselmann
331 55efe6da Iustin Pop
  # first, compute the desired name list
332 55efe6da Iustin Pop
  if opts.multi_mode is None:
333 c20efaa8 Michael Hanselmann
    opts.multi_mode = _EXPAND_INSTANCES
334 55efe6da Iustin Pop
335 55efe6da Iustin Pop
  inames = _ExpandMultiNames(opts.multi_mode, args)
336 55efe6da Iustin Pop
  if not inames:
337 debac808 Iustin Pop
    raise errors.OpPrereqError("Selection filter does not match any instances",
338 debac808 Iustin Pop
339 fe7b0351 Michael Hanselmann
340 55efe6da Iustin Pop
  # second, if requested, ask for an OS
341 20e23543 Alexander Schreiber
  if opts.select_os is True:
342 da2d02e7 Iustin Pop
    op = opcodes.OpOsDiagnose(output_fields=["name", "variants"], names=[])
343 400ca2f7 Iustin Pop
    result = SubmitOpCode(op, opts=opts)
344 20e23543 Alexander Schreiber
345 20e23543 Alexander Schreiber
    if not result:
346 3a24c527 Iustin Pop
      ToStdout("Can't get the OS list")
347 20e23543 Alexander Schreiber
      return 1
348 20e23543 Alexander Schreiber
349 3a24c527 Iustin Pop
    ToStdout("Available OS templates:")
350 20e23543 Alexander Schreiber
    number = 0
351 20e23543 Alexander Schreiber
    choices = []
352 d22dfef7 Iustin Pop
    for (name, variants) in result:
353 d22dfef7 Iustin Pop
      for entry in CalculateOSNames(name, variants):
354 d22dfef7 Iustin Pop
        ToStdout("%3s: %s", number, entry)
355 d22dfef7 Iustin Pop
        choices.append(("%s" % number, entry, entry))
356 d22dfef7 Iustin Pop
        number += 1
357 20e23543 Alexander Schreiber
358 d0c8c01d Iustin Pop
    choices.append(("x", "exit", "Exit gnt-instance reinstall"))
359 949bdabe Iustin Pop
    selected = AskUser("Enter OS template number (or x to abort):",
360 20e23543 Alexander Schreiber
361 20e23543 Alexander Schreiber
362 d0c8c01d Iustin Pop
    if selected == "exit":
363 55efe6da Iustin Pop
      ToStderr("User aborted reinstall, exiting")
364 20e23543 Alexander Schreiber
      return 1
365 20e23543 Alexander Schreiber
366 2f79bd34 Iustin Pop
    os_name = selected
367 f86426f5 Iustin Pop
    os_msg = "change the OS to '%s'" % selected
368 20e23543 Alexander Schreiber
369 2f79bd34 Iustin Pop
    os_name = opts.os
370 f86426f5 Iustin Pop
    if opts.os is not None:
371 f86426f5 Iustin Pop
      os_msg = "change the OS to '%s'" % os_name
372 f86426f5 Iustin Pop
373 f86426f5 Iustin Pop
      os_msg = "keep the same OS"
374 20e23543 Alexander Schreiber
375 297ddce9 Iustin Pop
  # third, get confirmation: multi-reinstall requires --force-multi,
376 297ddce9 Iustin Pop
  # single-reinstall either --force or --force-multi (--force-multi is
377 297ddce9 Iustin Pop
  # a stronger --force)
378 c20efaa8 Michael Hanselmann
  multi_on = opts.multi_mode != _EXPAND_INSTANCES or len(inames) > 1
379 55efe6da Iustin Pop
  if multi_on:
380 f86426f5 Iustin Pop
    warn_msg = ("Note: this will remove *all* data for the"
381 f86426f5 Iustin Pop
                " below instances! It will %s.\n" % os_msg)
382 297ddce9 Iustin Pop
    if not (opts.force_multi or
383 25bd815c René Nussbaumer
            ConfirmOperation(inames, "instances", "reinstall", extra=warn_msg)):
384 fe7b0351 Michael Hanselmann
      return 1
385 55efe6da Iustin Pop
386 297ddce9 Iustin Pop
    if not (opts.force or opts.force_multi):
387 f86426f5 Iustin Pop
      usertext = ("This will reinstall the instance '%s' (and %s) which"
388 f86426f5 Iustin Pop
                  " removes all data. Continue?") % (inames[0], os_msg)
389 55efe6da Iustin Pop
      if not AskUser(usertext):
390 55efe6da Iustin Pop
        return 1
391 55efe6da Iustin Pop
392 cb573a31 Iustin Pop
  jex = JobExecutor(verbose=multi_on, opts=opts)
393 55efe6da Iustin Pop
  for instance_name in inames:
394 5073fd8f Iustin Pop
    op = opcodes.OpInstanceReinstall(instance_name=instance_name,
395 06073e85 Guido Trotter
396 8d8c4eff Michael Hanselmann
397 da0aa302 Santi Raffa
398 da0aa302 Santi Raffa
399 da0aa302 Santi Raffa
400 55efe6da Iustin Pop
    jex.QueueJob(instance_name, op)
401 fe7b0351 Michael Hanselmann
402 64be07b1 Michael Hanselmann
  results = jex.WaitOrShow(not opts.submit_only)
403 64be07b1 Michael Hanselmann
404 64be07b1 Michael Hanselmann
  if compat.all(map(compat.fst, results)):
405 64be07b1 Michael Hanselmann
    return constants.EXIT_SUCCESS
406 64be07b1 Michael Hanselmann
407 64be07b1 Michael Hanselmann
    return constants.EXIT_FAILURE
408 fe7b0351 Michael Hanselmann
409 fe7b0351 Michael Hanselmann
410 a8083063 Iustin Pop
def RemoveInstance(opts, args):
411 a8083063 Iustin Pop
  """Remove an instance.
412 a8083063 Iustin Pop

413 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
414 7232c04c Iustin Pop
  @type args: list
415 7232c04c Iustin Pop
  @param args: should contain only one element, the name of
416 7232c04c Iustin Pop
      the instance to be removed
417 7232c04c Iustin Pop
  @rtype: int
418 7232c04c Iustin Pop
  @return: the desired exit code
419 a8083063 Iustin Pop

420 a8083063 Iustin Pop
421 a8083063 Iustin Pop
  instance_name = args[0]
422 a8083063 Iustin Pop
  force = opts.force
423 a76f0c4a Iustin Pop
  cl = GetClient()
424 a8083063 Iustin Pop
425 a8083063 Iustin Pop
  if not force:
426 2af8b9c9 Klaus Aehlig
    _EnsureInstancesExist(cl, [instance_name])
427 a76f0c4a Iustin Pop
428 a8083063 Iustin Pop
    usertext = ("This will remove the volumes of the instance %s"
429 a8083063 Iustin Pop
                " (including mirrors), thus removing all the data"
430 a8083063 Iustin Pop
                " of the instance. Continue?") % instance_name
431 47988778 Iustin Pop
    if not AskUser(usertext):
432 a8083063 Iustin Pop
      return 1
433 a8083063 Iustin Pop
434 3cd2d4b1 Iustin Pop
  op = opcodes.OpInstanceRemove(instance_name=instance_name,
435 17c3f802 Guido Trotter
436 4d98c565 Guido Trotter
437 a76f0c4a Iustin Pop
  SubmitOrSend(op, opts, cl=cl)
438 a8083063 Iustin Pop
  return 0
439 a8083063 Iustin Pop
440 a8083063 Iustin Pop
441 decd5f45 Iustin Pop
def RenameInstance(opts, args):
442 4ab0b9e3 Guido Trotter
  """Rename an instance.
443 decd5f45 Iustin Pop

444 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
445 7232c04c Iustin Pop
  @type args: list
446 7232c04c Iustin Pop
  @param args: should contain two elements, the old and the
447 7232c04c Iustin Pop
      new instance names
448 7232c04c Iustin Pop
  @rtype: int
449 7232c04c Iustin Pop
  @return: the desired exit code
450 decd5f45 Iustin Pop

451 decd5f45 Iustin Pop
452 90ed09b0 René Nussbaumer
  if not opts.name_check:
453 1b6dddc8 René Nussbaumer
    if not AskUser("As you disabled the check of the DNS entry, please verify"
454 1b6dddc8 René Nussbaumer
                   " that '%s' is a FQDN. Continue?" % args[1]):
455 1b6dddc8 René Nussbaumer
      return 1
456 1b6dddc8 René Nussbaumer
457 5659e2e2 Iustin Pop
  op = opcodes.OpInstanceRename(instance_name=args[0],
458 decd5f45 Iustin Pop
459 3fe11ba3 Manuel Franceschini
460 3fe11ba3 Manuel Franceschini
461 6a016df9 Michael Hanselmann
  result = SubmitOrSend(op, opts)
462 6a016df9 Michael Hanselmann
463 48418fea Iustin Pop
  if result:
464 48418fea Iustin Pop
    ToStdout("Instance '%s' renamed to '%s'", args[0], result)
465 6a016df9 Michael Hanselmann
466 decd5f45 Iustin Pop
  return 0
467 decd5f45 Iustin Pop
468 decd5f45 Iustin Pop
469 a8083063 Iustin Pop
def ActivateDisks(opts, args):
470 a8083063 Iustin Pop
  """Activate an instance's disks.
471 a8083063 Iustin Pop

472 a8083063 Iustin Pop
  This serves two purposes:
473 7232c04c Iustin Pop
    - it allows (as long as the instance is not running)
474 7232c04c Iustin Pop
      mounting the disks and modifying them from the node
475 a8083063 Iustin Pop
    - it repairs inactive secondary drbds
476 a8083063 Iustin Pop

477 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
478 7232c04c Iustin Pop
  @type args: list
479 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
480 7232c04c Iustin Pop
  @rtype: int
481 7232c04c Iustin Pop
  @return: the desired exit code
482 7232c04c Iustin Pop

483 a8083063 Iustin Pop
484 a8083063 Iustin Pop
  instance_name = args[0]
485 83f5d475 Iustin Pop
  op = opcodes.OpInstanceActivateDisks(instance_name=instance_name,
486 f30d8165 Iustin Pop
487 f30d8165 Iustin Pop
488 6340bb0a Iustin Pop
  disks_info = SubmitOrSend(op, opts)
489 a8083063 Iustin Pop
  for host, iname, nname in disks_info:
490 3a24c527 Iustin Pop
    ToStdout("%s:%s:%s", host, iname, nname)
491 a8083063 Iustin Pop
  return 0
492 a8083063 Iustin Pop
493 a8083063 Iustin Pop
494 a8083063 Iustin Pop
def DeactivateDisks(opts, args):
495 bd315bfa Iustin Pop
  """Deactivate an instance's disks.
496 a8083063 Iustin Pop

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

500 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
501 7232c04c Iustin Pop
  @type args: list
502 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
503 7232c04c Iustin Pop
  @rtype: int
504 7232c04c Iustin Pop
  @return: the desired exit code
505 7232c04c Iustin Pop

506 a8083063 Iustin Pop
507 a8083063 Iustin Pop
  instance_name = args[0]
508 c9c41373 Iustin Pop
  op = opcodes.OpInstanceDeactivateDisks(instance_name=instance_name,
509 c9c41373 Iustin Pop
510 6340bb0a Iustin Pop
  SubmitOrSend(op, opts)
511 a8083063 Iustin Pop
  return 0
512 a8083063 Iustin Pop
513 a8083063 Iustin Pop
514 bd315bfa Iustin Pop
def RecreateDisks(opts, args):
515 bd315bfa Iustin Pop
  """Recreate an instance's disks.
516 bd315bfa Iustin Pop

517 bd315bfa Iustin Pop
  @param opts: the command line options selected by the user
518 bd315bfa Iustin Pop
  @type args: list
519 bd315bfa Iustin Pop
  @param args: should contain only one element, the instance name
520 bd315bfa Iustin Pop
  @rtype: int
521 bd315bfa Iustin Pop
  @return: the desired exit code
522 bd315bfa Iustin Pop

523 bd315bfa Iustin Pop
524 bd315bfa Iustin Pop
  instance_name = args[0]
525 735e1318 Michael Hanselmann
526 735e1318 Michael Hanselmann
  disks = []
527 735e1318 Michael Hanselmann
528 bd315bfa Iustin Pop
  if opts.disks:
529 735e1318 Michael Hanselmann
    for didx, ddict in opts.disks:
530 735e1318 Michael Hanselmann
      didx = int(didx)
531 735e1318 Michael Hanselmann
532 735e1318 Michael Hanselmann
      if not ht.TDict(ddict):
533 735e1318 Michael Hanselmann
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
534 2cfbc784 Iustin Pop
        raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
535 735e1318 Michael Hanselmann
536 735e1318 Michael Hanselmann
      if constants.IDISK_SIZE in ddict:
537 735e1318 Michael Hanselmann
538 735e1318 Michael Hanselmann
          ddict[constants.IDISK_SIZE] = \
539 735e1318 Michael Hanselmann
540 735e1318 Michael Hanselmann
        except ValueError, err:
541 735e1318 Michael Hanselmann
          raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
542 2cfbc784 Iustin Pop
                                     (didx, err), errors.ECODE_INVAL)
543 9e448d7f Klaus Aehlig
544 9e448d7f Klaus Aehlig
      if constants.IDISK_SPINDLES in ddict:
545 9e448d7f Klaus Aehlig
546 9e448d7f Klaus Aehlig
          ddict[constants.IDISK_SPINDLES] = \
547 9e448d7f Klaus Aehlig
548 9e448d7f Klaus Aehlig
        except ValueError, err:
549 9e448d7f Klaus Aehlig
          raise errors.OpPrereqError("Invalid spindles for disk %d: %s" %
550 9e448d7f Klaus Aehlig
                                     (didx, err), errors.ECODE_INVAL)
551 735e1318 Michael Hanselmann
552 735e1318 Michael Hanselmann
      disks.append((didx, ddict))
553 735e1318 Michael Hanselmann
554 735e1318 Michael Hanselmann
    # TODO: Verify modifyable parameters (already done in
555 735e1318 Michael Hanselmann
    # LUInstanceRecreateDisks, but it'd be nice to have in the client)
556 bd315bfa Iustin Pop
557 c8a96ae7 Iustin Pop
  if opts.node:
558 38db4e7c Adam Ingrassia
    if opts.iallocator:
559 38db4e7c Adam Ingrassia
      msg = "At most one of either --nodes or --iallocator can be passed"
560 38db4e7c Adam Ingrassia
      raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
561 c8a96ae7 Iustin Pop
    pnode, snode = SplitNodeOption(opts.node)
562 c8a96ae7 Iustin Pop
    nodes = [pnode]
563 c8a96ae7 Iustin Pop
    if snode is not None:
564 c8a96ae7 Iustin Pop
565 c8a96ae7 Iustin Pop
566 c8a96ae7 Iustin Pop
    nodes = []
567 c8a96ae7 Iustin Pop
568 6b273e78 Iustin Pop
  op = opcodes.OpInstanceRecreateDisks(instance_name=instance_name,
569 38db4e7c Adam Ingrassia
                                       disks=disks, nodes=nodes,
570 38db4e7c Adam Ingrassia
571 bd315bfa Iustin Pop
  SubmitOrSend(op, opts)
572 735e1318 Michael Hanselmann
573 bd315bfa Iustin Pop
  return 0
574 bd315bfa Iustin Pop
575 bd315bfa Iustin Pop
576 c6e911bc Iustin Pop
def GrowDisk(opts, args):
577 7232c04c Iustin Pop
  """Grow an instance's disks.
578 c6e911bc Iustin Pop

579 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
580 7232c04c Iustin Pop
  @type args: list
581 30a83755 Guido Trotter
  @param args: should contain three elements, the target instance name,
582 30a83755 Guido Trotter
      the target disk id, and the target growth
583 7232c04c Iustin Pop
  @rtype: int
584 7232c04c Iustin Pop
  @return: the desired exit code
585 c6e911bc Iustin Pop

586 c6e911bc Iustin Pop
587 c6e911bc Iustin Pop
  instance = args[0]
588 c6e911bc Iustin Pop
  disk = args[1]
589 ad24e046 Iustin Pop
590 ad24e046 Iustin Pop
    disk = int(disk)
591 691744c4 Iustin Pop
  except (TypeError, ValueError), err:
592 debac808 Iustin Pop
    raise errors.OpPrereqError("Invalid disk index: %s" % str(err),
593 debac808 Iustin Pop
594 c8bde61e Iustin Pop
595 c8bde61e Iustin Pop
    amount = utils.ParseUnit(args[2])
596 c8bde61e Iustin Pop
  except errors.UnitParseError:
597 c8bde61e Iustin Pop
    raise errors.OpPrereqError("Can't parse the given amount '%s'" % args[2],
598 c8bde61e Iustin Pop
599 60472d29 Iustin Pop
  op = opcodes.OpInstanceGrowDisk(instance_name=instance,
600 60472d29 Iustin Pop
                                  disk=disk, amount=amount,
601 ef8270dc Iustin Pop
602 ef8270dc Iustin Pop
603 6340bb0a Iustin Pop
  SubmitOrSend(op, opts)
604 c6e911bc Iustin Pop
  return 0
605 c6e911bc Iustin Pop
606 c6e911bc Iustin Pop
607 1c5945b6 Iustin Pop
def _StartupInstance(name, opts):
608 7232c04c Iustin Pop
  """Startup instances.
609 a8083063 Iustin Pop

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

613 1c5945b6 Iustin Pop
  @param name: the name of the instance to act on
614 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
615 1c5945b6 Iustin Pop
  @return: the opcode needed for the operation
616 a8083063 Iustin Pop

617 a8083063 Iustin Pop
618 c873d91c Iustin Pop
  op = opcodes.OpInstanceStartup(instance_name=name,
619 b44bd844 Michael Hanselmann
620 885a0fc4 Iustin Pop
621 323f9095 Stephen Shirley
622 323f9095 Stephen Shirley
623 1c5945b6 Iustin Pop
  # do not add these parameters to the opcode unless they're defined
624 1c5945b6 Iustin Pop
  if opts.hvparams:
625 1c5945b6 Iustin Pop
    op.hvparams = opts.hvparams
626 1c5945b6 Iustin Pop
  if opts.beparams:
627 1c5945b6 Iustin Pop
    op.beparams = opts.beparams
628 1c5945b6 Iustin Pop
  return op
629 a8083063 Iustin Pop
630 7c0d6283 Michael Hanselmann
631 1c5945b6 Iustin Pop
def _RebootInstance(name, opts):
632 7232c04c Iustin Pop
  """Reboot instance(s).
633 7232c04c Iustin Pop

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

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

641 579d4337 Alexander Schreiber
642 90ab1a95 Iustin Pop
  return opcodes.OpInstanceReboot(instance_name=name,
643 579d4337 Alexander Schreiber
644 17c3f802 Guido Trotter
645 aa922d64 Michele Tartara
646 a8083063 Iustin Pop
647 7c0d6283 Michael Hanselmann
648 1c5945b6 Iustin Pop
def _ShutdownInstance(name, opts):
649 a8083063 Iustin Pop
  """Shutdown an instance.
650 a8083063 Iustin Pop

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

654 1c5945b6 Iustin Pop
  @param name: the name of the instance to act on
655 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
656 1c5945b6 Iustin Pop
  @return: the opcode needed for the operation
657 a8083063 Iustin Pop

658 a8083063 Iustin Pop
659 ee3e37a7 Iustin Pop
  return opcodes.OpInstanceShutdown(instance_name=name,
660 0d57ce24 Guido Trotter
661 b44bd844 Michael Hanselmann
662 885a0fc4 Iustin Pop
663 885a0fc4 Iustin Pop
664 a8083063 Iustin Pop
665 a8083063 Iustin Pop
666 a8083063 Iustin Pop
def ReplaceDisks(opts, args):
667 a8083063 Iustin Pop
  """Replace the disks of an instance
668 a8083063 Iustin Pop

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

675 a8083063 Iustin Pop
676 a14db5ff Iustin Pop
  new_2ndary = opts.dst_node
677 b6e82a65 Iustin Pop
  iallocator = opts.iallocator
678 a9e0c397 Iustin Pop
  if opts.disks is None:
679 54155f52 Iustin Pop
    disks = []
680 a9e0c397 Iustin Pop
681 54155f52 Iustin Pop
682 54155f52 Iustin Pop
      disks = [int(i) for i in opts.disks.split(",")]
683 691744c4 Iustin Pop
    except (TypeError, ValueError), err:
684 debac808 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err),
685 debac808 Iustin Pop
686 05d47e33 Michael Hanselmann
  cnt = [opts.on_primary, opts.on_secondary,,
687 7e9366f7 Iustin Pop
         new_2ndary is not None, iallocator is not None].count(True)
688 7e9366f7 Iustin Pop
  if cnt != 1:
689 d8d838cb Michael Hanselmann
    raise errors.OpPrereqError("One and only one of the -p, -s, -a, -n and -I"
690 debac808 Iustin Pop
                               " options must be passed", errors.ECODE_INVAL)
691 7e9366f7 Iustin Pop
  elif opts.on_primary:
692 a9e0c397 Iustin Pop
    mode = constants.REPLACE_DISK_PRI
693 7e9366f7 Iustin Pop
  elif opts.on_secondary:
694 a9e0c397 Iustin Pop
    mode = constants.REPLACE_DISK_SEC
695 05d47e33 Michael Hanselmann
696 05d47e33 Michael Hanselmann
    mode = constants.REPLACE_DISK_AUTO
697 05d47e33 Michael Hanselmann
    if disks:
698 05d47e33 Michael Hanselmann
      raise errors.OpPrereqError("Cannot specify disks when using automatic"
699 debac808 Iustin Pop
                                 " mode", errors.ECODE_INVAL)
700 7e9366f7 Iustin Pop
  elif new_2ndary is not None or iallocator is not None:
701 7e9366f7 Iustin Pop
    # replace secondary
702 7e9366f7 Iustin Pop
    mode = constants.REPLACE_DISK_CHG
703 a9e0c397 Iustin Pop
704 668f755d Iustin Pop
  op = opcodes.OpInstanceReplaceDisks(instance_name=args[0], disks=disks,
705 668f755d Iustin Pop
                                      remote_node=new_2ndary, mode=mode,
706 668f755d Iustin Pop
707 893e8f49 René Nussbaumer
708 893e8f49 René Nussbaumer
709 6340bb0a Iustin Pop
  SubmitOrSend(op, opts)
710 a8083063 Iustin Pop
  return 0
711 a8083063 Iustin Pop
712 a8083063 Iustin Pop
713 a8083063 Iustin Pop
def FailoverInstance(opts, args):
714 a8083063 Iustin Pop
  """Failover an instance.
715 a8083063 Iustin Pop

716 a8083063 Iustin Pop
  The failover is done by shutting it down on its present node and
717 a8083063 Iustin Pop
  starting it on the secondary.
718 a8083063 Iustin Pop

719 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
720 7232c04c Iustin Pop
  @type args: list
721 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
722 7232c04c Iustin Pop
  @rtype: int
723 7232c04c Iustin Pop
  @return: the desired exit code
724 a8083063 Iustin Pop

725 a8083063 Iustin Pop
726 a76f0c4a Iustin Pop
  cl = GetClient()
727 80de0e3f Iustin Pop
  instance_name = args[0]
728 80de0e3f Iustin Pop
  force = opts.force
729 1b7761fd Apollon Oikonomopoulos
  iallocator = opts.iallocator
730 1b7761fd Apollon Oikonomopoulos
  target_node = opts.dst_node
731 1b7761fd Apollon Oikonomopoulos
732 1b7761fd Apollon Oikonomopoulos
  if iallocator and target_node:
733 1b7761fd Apollon Oikonomopoulos
    raise errors.OpPrereqError("Specify either an iallocator (-I), or a target"
734 1b7761fd Apollon Oikonomopoulos
                               " node (-n) but not both", errors.ECODE_INVAL)
735 a8083063 Iustin Pop
736 80de0e3f Iustin Pop
  if not force:
737 a76f0c4a Iustin Pop
    _EnsureInstancesExist(cl, [instance_name])
738 a76f0c4a Iustin Pop
739 80de0e3f Iustin Pop
    usertext = ("Failover will happen to image %s."
740 80de0e3f Iustin Pop
                " This requires a shutdown of the instance. Continue?" %
741 80de0e3f Iustin Pop
742 80de0e3f Iustin Pop
    if not AskUser(usertext):
743 80de0e3f Iustin Pop
      return 1
744 a8083063 Iustin Pop
745 019dbee1 Iustin Pop
  op = opcodes.OpInstanceFailover(instance_name=instance_name,
746 17c3f802 Guido Trotter
747 1b7761fd Apollon Oikonomopoulos
748 1b7761fd Apollon Oikonomopoulos
749 b6aaf437 René Nussbaumer
750 b6aaf437 René Nussbaumer
751 a76f0c4a Iustin Pop
  SubmitOrSend(op, opts, cl=cl)
752 80de0e3f Iustin Pop
  return 0
753 a8083063 Iustin Pop
754 a8083063 Iustin Pop
755 53c776b5 Iustin Pop
def MigrateInstance(opts, args):
756 53c776b5 Iustin Pop
  """Migrate an instance.
757 53c776b5 Iustin Pop

758 53c776b5 Iustin Pop
  The migrate is done without shutdown.
759 53c776b5 Iustin Pop

760 2f907a8c Iustin Pop
  @param opts: the command line options selected by the user
761 2f907a8c Iustin Pop
  @type args: list
762 2f907a8c Iustin Pop
  @param args: should contain only one element, the instance name
763 2f907a8c Iustin Pop
  @rtype: int
764 2f907a8c Iustin Pop
  @return: the desired exit code
765 53c776b5 Iustin Pop

766 53c776b5 Iustin Pop
767 a76f0c4a Iustin Pop
  cl = GetClient()
768 53c776b5 Iustin Pop
  instance_name = args[0]
769 53c776b5 Iustin Pop
  force = opts.force
770 1b7761fd Apollon Oikonomopoulos
  iallocator = opts.iallocator
771 1b7761fd Apollon Oikonomopoulos
  target_node = opts.dst_node
772 1b7761fd Apollon Oikonomopoulos
773 1b7761fd Apollon Oikonomopoulos
  if iallocator and target_node:
774 1b7761fd Apollon Oikonomopoulos
    raise errors.OpPrereqError("Specify either an iallocator (-I), or a target"
775 1b7761fd Apollon Oikonomopoulos
                               " node (-n) but not both", errors.ECODE_INVAL)
776 53c776b5 Iustin Pop
777 53c776b5 Iustin Pop
  if not force:
778 a76f0c4a Iustin Pop
    _EnsureInstancesExist(cl, [instance_name])
779 a76f0c4a Iustin Pop
780 53c776b5 Iustin Pop
    if opts.cleanup:
781 53c776b5 Iustin Pop
      usertext = ("Instance %s will be recovered from a failed migration."
782 53c776b5 Iustin Pop
                  " Note that the migration procedure (including cleanup)" %
783 53c776b5 Iustin Pop
784 53c776b5 Iustin Pop
785 53c776b5 Iustin Pop
      usertext = ("Instance %s will be migrated. Note that migration" %
786 53c776b5 Iustin Pop
787 cf29cfb6 Iustin Pop
    usertext += (" might impact the instance if anything goes wrong"
788 cf29cfb6 Iustin Pop
                 " (e.g. due to bugs in the hypervisor). Continue?")
789 53c776b5 Iustin Pop
    if not AskUser(usertext):
790 53c776b5 Iustin Pop
      return 1
791 53c776b5 Iustin Pop
792 e71b9ef4 Iustin Pop
  # this should be removed once --non-live is deprecated
793 783a6c0b Iustin Pop
  if not and opts.migration_mode is not None:
794 e71b9ef4 Iustin Pop
    raise errors.OpPrereqError("Only one of the --non-live and "
795 783a6c0b Iustin Pop
                               "--migration-mode options can be passed",
796 e71b9ef4 Iustin Pop
797 e71b9ef4 Iustin Pop
  if not # --non-live passed
798 8c35561f Iustin Pop
    mode = constants.HT_MIGRATION_NONLIVE
799 e71b9ef4 Iustin Pop
800 8c35561f Iustin Pop
    mode = opts.migration_mode
801 e71b9ef4 Iustin Pop
802 75c866c2 Iustin Pop
  op = opcodes.OpInstanceMigrate(instance_name=instance_name, mode=mode,
803 1b7761fd Apollon Oikonomopoulos
                                 cleanup=opts.cleanup, iallocator=iallocator,
804 e9c487be René Nussbaumer
805 3ed23330 René Nussbaumer
806 8c0b16f6 Guido Trotter
807 3ed23330 René Nussbaumer
808 f70bb622 Michael Hanselmann
  SubmitOrSend(op, cl=cl, opts=opts)
809 53c776b5 Iustin Pop
  return 0
810 53c776b5 Iustin Pop
811 53c776b5 Iustin Pop
812 fbf5a861 Iustin Pop
def MoveInstance(opts, args):
813 fbf5a861 Iustin Pop
  """Move an instance.
814 fbf5a861 Iustin Pop

815 fbf5a861 Iustin Pop
  @param opts: the command line options selected by the user
816 fbf5a861 Iustin Pop
  @type args: list
817 fbf5a861 Iustin Pop
  @param args: should contain only one element, the instance name
818 fbf5a861 Iustin Pop
  @rtype: int
819 fbf5a861 Iustin Pop
  @return: the desired exit code
820 fbf5a861 Iustin Pop

821 fbf5a861 Iustin Pop
822 fbf5a861 Iustin Pop
  cl = GetClient()
823 fbf5a861 Iustin Pop
  instance_name = args[0]
824 fbf5a861 Iustin Pop
  force = opts.force
825 fbf5a861 Iustin Pop
826 fbf5a861 Iustin Pop
  if not force:
827 fbf5a861 Iustin Pop
    usertext = ("Instance %s will be moved."
828 fbf5a861 Iustin Pop
                " This requires a shutdown of the instance. Continue?" %
829 fbf5a861 Iustin Pop
830 fbf5a861 Iustin Pop
    if not AskUser(usertext):
831 fbf5a861 Iustin Pop
      return 1
832 fbf5a861 Iustin Pop
833 0091b480 Iustin Pop
  op = opcodes.OpInstanceMove(instance_name=instance_name,
834 17c3f802 Guido Trotter
835 94ab995a Thomas Thrainer
836 bb851c63 Iustin Pop
837 92cf62e3 René Nussbaumer
838 92cf62e3 René Nussbaumer
839 fbf5a861 Iustin Pop
  SubmitOrSend(op, opts, cl=cl)
840 fbf5a861 Iustin Pop
  return 0
841 fbf5a861 Iustin Pop
842 fbf5a861 Iustin Pop
843 a8083063 Iustin Pop
def ConnectToInstanceConsole(opts, args):
844 a8083063 Iustin Pop
  """Connect to the console of an instance.
845 a8083063 Iustin Pop

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

852 a8083063 Iustin Pop
853 a8083063 Iustin Pop
  instance_name = args[0]
854 a8083063 Iustin Pop
855 25ce3ec4 Michael Hanselmann
  cl = GetClient()
856 25ce3ec4 Michael Hanselmann
857 25ce3ec4 Michael Hanselmann
    cluster_name = cl.QueryConfigValues(["cluster_name"])[0]
858 d6f46b6a Michael Hanselmann
    ((console_data, oper_state), ) = \
859 2af8b9c9 Klaus Aehlig
      cl.QueryInstances([instance_name], ["console", "oper_state"], False)
860 25ce3ec4 Michael Hanselmann
861 25ce3ec4 Michael Hanselmann
    # Ensure client connection is closed while external commands are run
862 25ce3ec4 Michael Hanselmann
863 25ce3ec4 Michael Hanselmann
864 25ce3ec4 Michael Hanselmann
  del cl
865 25ce3ec4 Michael Hanselmann
866 d6f46b6a Michael Hanselmann
  if not console_data:
867 d6f46b6a Michael Hanselmann
    if oper_state:
868 d6f46b6a Michael Hanselmann
      # Instance is running
869 d6f46b6a Michael Hanselmann
      raise errors.OpExecError("Console information for instance %s is"
870 d6f46b6a Michael Hanselmann
                               " unavailable" % instance_name)
871 d6f46b6a Michael Hanselmann
872 d6f46b6a Michael Hanselmann
      raise errors.OpExecError("Instance %s is not running, can't get console" %
873 d6f46b6a Michael Hanselmann
874 d6f46b6a Michael Hanselmann
875 25ce3ec4 Michael Hanselmann
  return _DoConsole(objects.InstanceConsole.FromDict(console_data),
876 25ce3ec4 Michael Hanselmann
                    opts.show_command, cluster_name)
877 25ce3ec4 Michael Hanselmann
878 25ce3ec4 Michael Hanselmann
879 25ce3ec4 Michael Hanselmann
def _DoConsole(console, show_command, cluster_name, feedback_fn=ToStdout,
880 25ce3ec4 Michael Hanselmann
881 cc0dec7b Iustin Pop
  """Acts based on the result of L{opcodes.OpInstanceConsole}.
882 25ce3ec4 Michael Hanselmann

883 25ce3ec4 Michael Hanselmann
  @type console: L{objects.InstanceConsole}
884 25ce3ec4 Michael Hanselmann
  @param console: Console object
885 25ce3ec4 Michael Hanselmann
  @type show_command: bool
886 25ce3ec4 Michael Hanselmann
  @param show_command: Whether to just display commands
887 25ce3ec4 Michael Hanselmann
  @type cluster_name: string
888 25ce3ec4 Michael Hanselmann
  @param cluster_name: Cluster name as retrieved from master daemon
889 25ce3ec4 Michael Hanselmann

890 25ce3ec4 Michael Hanselmann
891 25ce3ec4 Michael Hanselmann
  assert console.Validate()
892 25ce3ec4 Michael Hanselmann
893 25ce3ec4 Michael Hanselmann
  if console.kind == constants.CONS_MESSAGE:
894 25ce3ec4 Michael Hanselmann
895 25ce3ec4 Michael Hanselmann
  elif console.kind == constants.CONS_VNC:
896 25ce3ec4 Michael Hanselmann
    feedback_fn("Instance %s has VNC listening on %s:%s (display %s),"
897 25ce3ec4 Michael Hanselmann
                " URL <vnc://%s:%s/>",
898 25ce3ec4 Michael Hanselmann
                console.instance,, console.port,
899 25ce3ec4 Michael Hanselmann
                console.display,, console.port)
900 4d2cdb5a Andrea Spadaccini
  elif console.kind == constants.CONS_SPICE:
901 4d2cdb5a Andrea Spadaccini
    feedback_fn("Instance %s has SPICE listening on %s:%s", console.instance,
902 4d2cdb5a Andrea Spadaccini
      , console.port)
903 25ce3ec4 Michael Hanselmann
  elif console.kind == constants.CONS_SSH:
904 25ce3ec4 Michael Hanselmann
    # Convert to string if not already one
905 25ce3ec4 Michael Hanselmann
    if isinstance(console.command, basestring):
906 25ce3ec4 Michael Hanselmann
      cmd = console.command
907 25ce3ec4 Michael Hanselmann
908 25ce3ec4 Michael Hanselmann
      cmd = utils.ShellQuoteArgs(console.command)
909 25ce3ec4 Michael Hanselmann
910 25ce3ec4 Michael Hanselmann
    srun = ssh.SshRunner(cluster_name=cluster_name)
911 25ce3ec4 Michael Hanselmann
    ssh_cmd = srun.BuildCmd(, console.user, cmd,
912 a9f33339 Petr Pudlak
913 25ce3ec4 Michael Hanselmann
                            batch=True, quiet=False, tty=True)
914 25ce3ec4 Michael Hanselmann
915 25ce3ec4 Michael Hanselmann
    if show_command:
916 25ce3ec4 Michael Hanselmann
917 25ce3ec4 Michael Hanselmann
918 25ce3ec4 Michael Hanselmann
      result = _runcmd_fn(ssh_cmd, interactive=True)
919 25ce3ec4 Michael Hanselmann
      if result.failed:
920 25ce3ec4 Michael Hanselmann
        logging.error("Console command \"%s\" failed with reason '%s' and"
921 25ce3ec4 Michael Hanselmann
                      " output %r", result.cmd, result.fail_reason,
922 25ce3ec4 Michael Hanselmann
923 25ce3ec4 Michael Hanselmann
        raise errors.OpExecError("Connection to console of instance %s failed,"
924 25ce3ec4 Michael Hanselmann
                                 " please check cluster configuration" %
925 25ce3ec4 Michael Hanselmann
926 51c6e7b5 Michael Hanselmann
927 25ce3ec4 Michael Hanselmann
    raise errors.GenericError("Unknown console type '%s'" % console.kind)
928 678aa6d3 Michael Hanselmann
929 678aa6d3 Michael Hanselmann
  return constants.EXIT_SUCCESS
930 a8083063 Iustin Pop
931 a8083063 Iustin Pop
932 1c3231aa Thomas Thrainer
def _FormatDiskDetails(dev_type, dev, roman):
933 19708787 Iustin Pop
  """Formats the logical_id of a disk.
934 19708787 Iustin Pop

935 19708787 Iustin Pop
936 cd3b4ff4 Helga Velroyen
  if dev_type == constants.DT_DRBD8:
937 1c3231aa Thomas Thrainer
    drbd_info = dev["drbd_info"]
938 19708787 Iustin Pop
    data = [
939 1c3231aa Thomas Thrainer
      ("nodeA", "%s, minor=%s" %
940 1c3231aa Thomas Thrainer
941 1c3231aa Thomas Thrainer
942 1c3231aa Thomas Thrainer
943 1c3231aa Thomas Thrainer
      ("nodeB", "%s, minor=%s" %
944 1c3231aa Thomas Thrainer
945 1c3231aa Thomas Thrainer
946 1c3231aa Thomas Thrainer
947 1c3231aa Thomas Thrainer
      ("port", str(compat.TryToRoman(drbd_info["port"], convert=roman))),
948 1c3231aa Thomas Thrainer
      ("auth key", str(drbd_info["secret"])),
949 19708787 Iustin Pop
950 cd3b4ff4 Helga Velroyen
  elif dev_type == constants.DT_PLAIN:
951 1c3231aa Thomas Thrainer
    vg_name, lv_name = dev["logical_id"]
952 19708787 Iustin Pop
    data = ["%s/%s" % (vg_name, lv_name)]
953 19708787 Iustin Pop
954 1c3231aa Thomas Thrainer
    data = [str(dev["logical_id"])]
955 19708787 Iustin Pop
956 19708787 Iustin Pop
  return data
957 19708787 Iustin Pop
958 19708787 Iustin Pop
959 f965260c Michael Hanselmann
def _FormatBlockDevInfo(idx, top_level, dev, roman):
960 a8083063 Iustin Pop
  """Show block device information.
961 a8083063 Iustin Pop

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

965 19708787 Iustin Pop
  @type idx: int
966 19708787 Iustin Pop
  @param idx: the index of the current disk
967 19708787 Iustin Pop
  @type top_level: boolean
968 19708787 Iustin Pop
  @param top_level: if this a top-level disk?
969 7232c04c Iustin Pop
  @type dev: dict
970 7232c04c Iustin Pop
  @param dev: dictionary with disk information
971 e2736e40 Guido Trotter
  @type roman: boolean
972 e2736e40 Guido Trotter
  @param roman: whether to try to use roman integers
973 19708787 Iustin Pop
  @return: a list of either strings, tuples or lists
974 19708787 Iustin Pop
      (which should be formatted at a higher indent level)
975 7232c04c Iustin Pop

976 a8083063 Iustin Pop
977 19708787 Iustin Pop
  def helper(dtype, status):
978 7232c04c Iustin Pop
    """Format one line for physical device status.
979 7232c04c Iustin Pop

980 7232c04c Iustin Pop
    @type dtype: str
981 cd3b4ff4 Helga Velroyen
    @param dtype: a constant from the L{constants.DTS_BLOCK} set
982 7232c04c Iustin Pop
    @type status: tuple
983 7232c04c Iustin Pop
    @param status: a tuple as returned from L{backend.FindBlockDevice}
984 19708787 Iustin Pop
    @return: the string representing the status
985 7232c04c Iustin Pop

986 7232c04c Iustin Pop
987 a8083063 Iustin Pop
    if not status:
988 19708787 Iustin Pop
      return "not active"
989 19708787 Iustin Pop
    txt = ""
990 f208978a Michael Hanselmann
    (path, major, minor, syncp, estt, degr, ldisk_status) = status
991 19708787 Iustin Pop
    if major is None:
992 19708787 Iustin Pop
      major_string = "N/A"
993 a8083063 Iustin Pop
994 e2736e40 Guido Trotter
      major_string = str(compat.TryToRoman(major, convert=roman))
995 fd38ef95 Manuel Franceschini
996 19708787 Iustin Pop
    if minor is None:
997 19708787 Iustin Pop
      minor_string = "N/A"
998 19708787 Iustin Pop
999 e2736e40 Guido Trotter
      minor_string = str(compat.TryToRoman(minor, convert=roman))
1000 19708787 Iustin Pop
1001 19708787 Iustin Pop
    txt += ("%s (%s:%s)" % (path, major_string, minor_string))
1002 cd3b4ff4 Helga Velroyen
    if dtype in (constants.DT_DRBD8, ):
1003 19708787 Iustin Pop
      if syncp is not None:
1004 19708787 Iustin Pop
        sync_text = "*RECOVERING* %5.2f%%," % syncp
1005 19708787 Iustin Pop
        if estt:
1006 e2736e40 Guido Trotter
          sync_text += " ETA %ss" % compat.TryToRoman(estt, convert=roman)
1007 9db6dbce Iustin Pop
1008 19708787 Iustin Pop
          sync_text += " ETA unknown"
1009 19708787 Iustin Pop
1010 19708787 Iustin Pop
        sync_text = "in sync"
1011 19708787 Iustin Pop
      if degr:
1012 19708787 Iustin Pop
        degr_text = "*DEGRADED*"
1013 19708787 Iustin Pop
1014 19708787 Iustin Pop
        degr_text = "ok"
1015 f208978a Michael Hanselmann
      if ldisk_status == constants.LDS_FAULTY:
1016 19708787 Iustin Pop
        ldisk_text = " *MISSING DISK*"
1017 f208978a Michael Hanselmann
      elif ldisk_status == constants.LDS_UNKNOWN:
1018 f208978a Michael Hanselmann
        ldisk_text = " *UNCERTAIN STATE*"
1019 19708787 Iustin Pop
1020 19708787 Iustin Pop
        ldisk_text = ""
1021 19708787 Iustin Pop
      txt += (" %s, status %s%s" % (sync_text, degr_text, ldisk_text))
1022 cd3b4ff4 Helga Velroyen
    elif dtype == constants.DT_PLAIN:
1023 f208978a Michael Hanselmann
      if ldisk_status == constants.LDS_FAULTY:
1024 19708787 Iustin Pop
        ldisk_text = " *FAILED* (failed drive?)"
1025 19708787 Iustin Pop
1026 19708787 Iustin Pop
        ldisk_text = ""
1027 19708787 Iustin Pop
      txt += ldisk_text
1028 19708787 Iustin Pop
    return txt
1029 19708787 Iustin Pop
1030 19708787 Iustin Pop
  # the header
1031 19708787 Iustin Pop
  if top_level:
1032 19708787 Iustin Pop
    if dev["iv_name"] is not None:
1033 19708787 Iustin Pop
      txt = dev["iv_name"]
1034 19708787 Iustin Pop
1035 e2736e40 Guido Trotter
      txt = "disk %s" % compat.TryToRoman(idx, convert=roman)
1036 a8083063 Iustin Pop
1037 e2736e40 Guido Trotter
    txt = "child %s" % compat.TryToRoman(idx, convert=roman)
1038 c98162a7 Iustin Pop
  if isinstance(dev["size"], int):
1039 c98162a7 Iustin Pop
    nice_size = utils.FormatUnit(dev["size"], "h")
1040 c98162a7 Iustin Pop
1041 2cbcf95d Bernardo Dal Seno
    nice_size = str(dev["size"])
1042 2cbcf95d Bernardo Dal Seno
  data = [(txt, "%s, size %s" % (dev["dev_type"], nice_size))]
1043 19708787 Iustin Pop
  if top_level:
1044 75a6c8be Bernardo Dal Seno
    if dev["spindles"] is not None:
1045 75a6c8be Bernardo Dal Seno
      data.append(("spindles", dev["spindles"]))
1046 19708787 Iustin Pop
    data.append(("access mode", dev["mode"]))
1047 a8083063 Iustin Pop
  if dev["logical_id"] is not None:
1048 19708787 Iustin Pop
1049 1c3231aa Thomas Thrainer
      l_id = _FormatDiskDetails(dev["dev_type"], dev, roman)
1050 19708787 Iustin Pop
    except ValueError:
1051 19708787 Iustin Pop
      l_id = [str(dev["logical_id"])]
1052 19708787 Iustin Pop
    if len(l_id) == 1:
1053 19708787 Iustin Pop
      data.append(("logical_id", l_id[0]))
1054 19708787 Iustin Pop
1055 19708787 Iustin Pop
1056 f965260c Michael Hanselmann
1057 f965260c Michael Hanselmann
  if dev["pstatus"]:
1058 19708787 Iustin Pop
    data.append(("on primary", helper(dev["dev_type"], dev["pstatus"])))
1059 f965260c Michael Hanselmann
1060 f965260c Michael Hanselmann
  if dev["sstatus"]:
1061 19708787 Iustin Pop
    data.append(("on secondary", helper(dev["dev_type"], dev["sstatus"])))
1062 a8083063 Iustin Pop
1063 fcbd025c Christos Stavrakakis
  data.append(("name", dev["name"]))
1064 fcbd025c Christos Stavrakakis
  data.append(("UUID", dev["uuid"]))
1065 fcbd025c Christos Stavrakakis
1066 a8083063 Iustin Pop
  if dev["children"]:
1067 2cbcf95d Bernardo Dal Seno
    data.append(("child devices", [
1068 2cbcf95d Bernardo Dal Seno
      _FormatBlockDevInfo(c_idx, False, child, roman)
1069 2cbcf95d Bernardo Dal Seno
      for c_idx, child in enumerate(dev["children"])
1070 2cbcf95d Bernardo Dal Seno
1071 2cbcf95d Bernardo Dal Seno
  return data
1072 19708787 Iustin Pop
1073 19708787 Iustin Pop
1074 2cbcf95d Bernardo Dal Seno
def _FormatInstanceNicInfo(idx, nic):
1075 2cbcf95d Bernardo Dal Seno
  """Helper function for L{_FormatInstanceInfo()}"""
1076 d676dbea Sebastian Gebhard
  (name, uuid, ip, mac, mode, link, vlan, _, netinfo) = nic
1077 2cbcf95d Bernardo Dal Seno
  network_name = None
1078 2cbcf95d Bernardo Dal Seno
  if netinfo:
1079 2cbcf95d Bernardo Dal Seno
    network_name = netinfo["name"]
1080 2cbcf95d Bernardo Dal Seno
  return [
1081 2cbcf95d Bernardo Dal Seno
    ("nic/%d" % idx, ""),
1082 2cbcf95d Bernardo Dal Seno
    ("MAC", str(mac)),
1083 2cbcf95d Bernardo Dal Seno
    ("IP", str(ip)),
1084 2cbcf95d Bernardo Dal Seno
    ("mode", str(mode)),
1085 2cbcf95d Bernardo Dal Seno
    ("link", str(link)),
1086 d676dbea Sebastian Gebhard
    ("vlan", str(vlan)),
1087 2cbcf95d Bernardo Dal Seno
    ("network", str(network_name)),
1088 fcbd025c Christos Stavrakakis
    ("UUID", str(uuid)),
1089 fcbd025c Christos Stavrakakis
    ("name", str(name)),
1090 2cbcf95d Bernardo Dal Seno
1091 2cbcf95d Bernardo Dal Seno
1092 2cbcf95d Bernardo Dal Seno
1093 2cbcf95d Bernardo Dal Seno
def _FormatInstanceNodesInfo(instance):
1094 2cbcf95d Bernardo Dal Seno
  """Helper function for L{_FormatInstanceInfo()}"""
1095 2cbcf95d Bernardo Dal Seno
  pgroup = ("%s (UUID %s)" %
1096 2cbcf95d Bernardo Dal Seno
            (instance["pnode_group_name"], instance["pnode_group_uuid"]))
1097 2cbcf95d Bernardo Dal Seno
  secs = utils.CommaJoin(("%s (group %s, group UUID %s)" %
1098 2cbcf95d Bernardo Dal Seno
                          (name, group_name, group_uuid))
1099 2cbcf95d Bernardo Dal Seno
                         for (name, group_name, group_uuid) in
1100 2cbcf95d Bernardo Dal Seno
1101 2cbcf95d Bernardo Dal Seno
1102 2cbcf95d Bernardo Dal Seno
1103 2cbcf95d Bernardo Dal Seno
  return [
1104 2cbcf95d Bernardo Dal Seno
1105 2cbcf95d Bernardo Dal Seno
      ("primary", instance["pnode"]),
1106 2cbcf95d Bernardo Dal Seno
      ("group", pgroup),
1107 2cbcf95d Bernardo Dal Seno
1108 2cbcf95d Bernardo Dal Seno
    [("secondaries", secs)],
1109 2cbcf95d Bernardo Dal Seno
1110 2cbcf95d Bernardo Dal Seno
1111 2cbcf95d Bernardo Dal Seno
1112 2cbcf95d Bernardo Dal Seno
def _GetVncConsoleInfo(instance):
1113 2cbcf95d Bernardo Dal Seno
  """Helper function for L{_FormatInstanceInfo()}"""
1114 2cbcf95d Bernardo Dal Seno
  vnc_bind_address = instance["hv_actual"].get(constants.HV_VNC_BIND_ADDRESS,
1115 2cbcf95d Bernardo Dal Seno
1116 2cbcf95d Bernardo Dal Seno
  if vnc_bind_address:
1117 2cbcf95d Bernardo Dal Seno
    port = instance["network_port"]
1118 2cbcf95d Bernardo Dal Seno
    display = int(port) - constants.VNC_BASE_PORT
1119 2cbcf95d Bernardo Dal Seno
    if display > 0 and vnc_bind_address == constants.IP4_ADDRESS_ANY:
1120 2cbcf95d Bernardo Dal Seno
      vnc_console_port = "%s:%s (display %s)" % (instance["pnode"],
1121 2cbcf95d Bernardo Dal Seno
1122 2cbcf95d Bernardo Dal Seno
1123 2cbcf95d Bernardo Dal Seno
    elif display > 0 and netutils.IP4Address.IsValid(vnc_bind_address):
1124 2cbcf95d Bernardo Dal Seno
      vnc_console_port = ("%s:%s (node %s) (display %s)" %
1125 2cbcf95d Bernardo Dal Seno
                           (vnc_bind_address, port,
1126 2cbcf95d Bernardo Dal Seno
                            instance["pnode"], display))
1127 2cbcf95d Bernardo Dal Seno
1128 2cbcf95d Bernardo Dal Seno
      # vnc bind address is a file
1129 2cbcf95d Bernardo Dal Seno
      vnc_console_port = "%s:%s" % (instance["pnode"],
1130 2cbcf95d Bernardo Dal Seno
1131 2cbcf95d Bernardo Dal Seno
    ret = "vnc to %s" % vnc_console_port
1132 2cbcf95d Bernardo Dal Seno
1133 2cbcf95d Bernardo Dal Seno
    ret = None
1134 2cbcf95d Bernardo Dal Seno
  return ret
1135 2cbcf95d Bernardo Dal Seno
1136 2cbcf95d Bernardo Dal Seno
1137 2cbcf95d Bernardo Dal Seno
def _FormatInstanceInfo(instance, roman_integers):
1138 2cbcf95d Bernardo Dal Seno
  """Format instance information for L{cli.PrintGenericInfo()}"""
1139 2cbcf95d Bernardo Dal Seno
  istate = "configured to be %s" % instance["config_state"]
1140 2cbcf95d Bernardo Dal Seno
  if instance["run_state"]:
1141 2cbcf95d Bernardo Dal Seno
    istate += ", actual state is %s" % instance["run_state"]
1142 2cbcf95d Bernardo Dal Seno
  info = [
1143 2cbcf95d Bernardo Dal Seno
    ("Instance name", instance["name"]),
1144 2cbcf95d Bernardo Dal Seno
    ("UUID", instance["uuid"]),
1145 2cbcf95d Bernardo Dal Seno
    ("Serial number",
1146 2cbcf95d Bernardo Dal Seno
     str(compat.TryToRoman(instance["serial_no"], convert=roman_integers))),
1147 2cbcf95d Bernardo Dal Seno
    ("Creation time", utils.FormatTime(instance["ctime"])),
1148 2cbcf95d Bernardo Dal Seno
    ("Modification time", utils.FormatTime(instance["mtime"])),
1149 2cbcf95d Bernardo Dal Seno
    ("State", istate),
1150 2cbcf95d Bernardo Dal Seno
    ("Nodes", _FormatInstanceNodesInfo(instance)),
1151 2cbcf95d Bernardo Dal Seno
    ("Operating system", instance["os"]),
1152 2cbcf95d Bernardo Dal Seno
    ("Operating system parameters",
1153 2cbcf95d Bernardo Dal Seno
     FormatParamsDictInfo(instance["os_instance"], instance["os_actual"])),
1154 2cbcf95d Bernardo Dal Seno
1155 2cbcf95d Bernardo Dal Seno
1156 2cbcf95d Bernardo Dal Seno
  if "network_port" in instance:
1157 2cbcf95d Bernardo Dal Seno
    info.append(("Allocated network port",
1158 2cbcf95d Bernardo Dal Seno
1159 2cbcf95d Bernardo Dal Seno
1160 2cbcf95d Bernardo Dal Seno
  info.append(("Hypervisor", instance["hypervisor"]))
1161 2cbcf95d Bernardo Dal Seno
  console = _GetVncConsoleInfo(instance)
1162 2cbcf95d Bernardo Dal Seno
  if console:
1163 2cbcf95d Bernardo Dal Seno
    info.append(("console connection", console))
1164 2cbcf95d Bernardo Dal Seno
  # deprecated "memory" value, kept for one version for compatibility
1165 2cbcf95d Bernardo Dal Seno
  # TODO(ganeti 2.7) remove.
1166 2cbcf95d Bernardo Dal Seno
  be_actual = copy.deepcopy(instance["be_actual"])
1167 2cbcf95d Bernardo Dal Seno
  be_actual["memory"] = be_actual[constants.BE_MAXMEM]
1168 2cbcf95d Bernardo Dal Seno
1169 2cbcf95d Bernardo Dal Seno
    ("Hypervisor parameters",
1170 2cbcf95d Bernardo Dal Seno
     FormatParamsDictInfo(instance["hv_instance"], instance["hv_actual"])),
1171 2cbcf95d Bernardo Dal Seno
    ("Back-end parameters",
1172 2cbcf95d Bernardo Dal Seno
     FormatParamsDictInfo(instance["be_instance"], be_actual)),
1173 2cbcf95d Bernardo Dal Seno
    ("NICs", [
1174 2cbcf95d Bernardo Dal Seno
      _FormatInstanceNicInfo(idx, nic)
1175 2cbcf95d Bernardo Dal Seno
      for (idx, nic) in enumerate(instance["nics"])
1176 2cbcf95d Bernardo Dal Seno
1177 2cbcf95d Bernardo Dal Seno
    ("Disk template", instance["disk_template"]),
1178 2cbcf95d Bernardo Dal Seno
    ("Disks", [
1179 2cbcf95d Bernardo Dal Seno
      _FormatBlockDevInfo(idx, True, device, roman_integers)
1180 2cbcf95d Bernardo Dal Seno
      for (idx, device) in enumerate(instance["disks"])
1181 2cbcf95d Bernardo Dal Seno
1182 2cbcf95d Bernardo Dal Seno
1183 2cbcf95d Bernardo Dal Seno
  return info
1184 19708787 Iustin Pop
1185 98825740 Michael Hanselmann
1186 a8083063 Iustin Pop
def ShowInstanceConfig(opts, args):
1187 a8083063 Iustin Pop
  """Compute instance run-time status.
1188 a8083063 Iustin Pop

1189 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
1190 7232c04c Iustin Pop
  @type args: list
1191 7232c04c Iustin Pop
  @param args: either an empty list, and then we query all
1192 7232c04c Iustin Pop
      instances, or should contain a list of instance names
1193 7232c04c Iustin Pop
  @rtype: int
1194 7232c04c Iustin Pop
  @return: the desired exit code
1195 7232c04c Iustin Pop

1196 a8083063 Iustin Pop
1197 220cde0b Guido Trotter
  if not args and not opts.show_all:
1198 220cde0b Guido Trotter
    ToStderr("No instance selected."
1199 220cde0b Guido Trotter
             " Please pass in --all if you want to query all instances.\n"
1200 220cde0b Guido Trotter
             "Note that this can take a long time on a big cluster.")
1201 220cde0b Guido Trotter
    return 1
1202 220cde0b Guido Trotter
  elif args and opts.show_all:
1203 220cde0b Guido Trotter
    ToStderr("Cannot use --all if you specify instance names.")
1204 220cde0b Guido Trotter
    return 1
1205 220cde0b Guido Trotter
1206 a8083063 Iustin Pop
  retcode = 0
1207 5c097318 Iustin Pop
  op = opcodes.OpInstanceQueryData(instances=args, static=opts.static,
1208 5c097318 Iustin Pop
                                   use_locking=not opts.static)
1209 400ca2f7 Iustin Pop
  result = SubmitOpCode(op, opts=opts)
1210 a8083063 Iustin Pop
  if not result:
1211 3a24c527 Iustin Pop
    ToStdout("No instances.")
1212 a8083063 Iustin Pop
    return 1
1213 a8083063 Iustin Pop
1214 2cbcf95d Bernardo Dal Seno
1215 2cbcf95d Bernardo Dal Seno
    _FormatInstanceInfo(instance, opts.roman_integers)
1216 2cbcf95d Bernardo Dal Seno
    for instance in result.values()
1217 2cbcf95d Bernardo Dal Seno
1218 a8083063 Iustin Pop
  return retcode
1219 a8083063 Iustin Pop
1220 a8083063 Iustin Pop
1221 a71f835e Michael Hanselmann
def _ConvertNicDiskModifications(mods):
1222 a71f835e Michael Hanselmann
  """Converts NIC/disk modifications from CLI to opcode.
1223 a71f835e Michael Hanselmann

1224 a71f835e Michael Hanselmann
  When L{opcodes.OpInstanceSetParams} was changed to support adding/removing
1225 a71f835e Michael Hanselmann
  disks at arbitrary indices, its parameter format changed. This function
1226 a71f835e Michael Hanselmann
  converts legacy requests (e.g. "--net add" or "--disk add:size=4G") to the
1227 a71f835e Michael Hanselmann
  newer format and adds support for new-style requests (e.g. "--new 4:add").
1228 a71f835e Michael Hanselmann

1229 a71f835e Michael Hanselmann
  @type mods: list of tuples
1230 a71f835e Michael Hanselmann
  @param mods: Modifications as given by command line parser
1231 a71f835e Michael Hanselmann
  @rtype: list of tuples
1232 a71f835e Michael Hanselmann
  @return: Modifications as understood by L{opcodes.OpInstanceSetParams}
1233 a71f835e Michael Hanselmann

1234 a71f835e Michael Hanselmann
1235 a71f835e Michael Hanselmann
  result = []
1236 a71f835e Michael Hanselmann
1237 b21d488b Christos Stavrakakis
  for (identifier, params) in mods:
1238 b21d488b Christos Stavrakakis
    if identifier == constants.DDM_ADD:
1239 a71f835e Michael Hanselmann
      # Add item as last item (legacy interface)
1240 a71f835e Michael Hanselmann
      action = constants.DDM_ADD
1241 b21d488b Christos Stavrakakis
      identifier = -1
1242 b21d488b Christos Stavrakakis
    elif identifier == constants.DDM_REMOVE:
1243 a71f835e Michael Hanselmann
      # Remove last item (legacy interface)
1244 a71f835e Michael Hanselmann
      action = constants.DDM_REMOVE
1245 b21d488b Christos Stavrakakis
      identifier = -1
1246 a71f835e Michael Hanselmann
1247 a71f835e Michael Hanselmann
      # Modifications and adding/removing at arbitrary indices
1248 a71f835e Michael Hanselmann
      add = params.pop(constants.DDM_ADD, _MISSING)
1249 a71f835e Michael Hanselmann
      remove = params.pop(constants.DDM_REMOVE, _MISSING)
1250 f0d22861 Constantinos Venetsanopoulos
      modify = params.pop(constants.DDM_MODIFY, _MISSING)
1251 f0d22861 Constantinos Venetsanopoulos
1252 f0d22861 Constantinos Venetsanopoulos
      if modify is _MISSING:
1253 f0d22861 Constantinos Venetsanopoulos
        if not (add is _MISSING or remove is _MISSING):
1254 f0d22861 Constantinos Venetsanopoulos
          raise errors.OpPrereqError("Cannot add and remove at the same time",
1255 f0d22861 Constantinos Venetsanopoulos
1256 f0d22861 Constantinos Venetsanopoulos
        elif add is not _MISSING:
1257 f0d22861 Constantinos Venetsanopoulos
          action = constants.DDM_ADD
1258 f0d22861 Constantinos Venetsanopoulos
        elif remove is not _MISSING:
1259 f0d22861 Constantinos Venetsanopoulos
          action = constants.DDM_REMOVE
1260 f0d22861 Constantinos Venetsanopoulos
1261 f0d22861 Constantinos Venetsanopoulos
          action = constants.DDM_MODIFY
1262 a71f835e Michael Hanselmann
1263 7a70541e Michael Hanselmann
      elif add is _MISSING and remove is _MISSING:
1264 7a70541e Michael Hanselmann
        action = constants.DDM_MODIFY
1265 a71f835e Michael Hanselmann
1266 7a70541e Michael Hanselmann
        raise errors.OpPrereqError("Cannot modify and add/remove at the"
1267 7a70541e Michael Hanselmann
                                   " same time", errors.ECODE_INVAL)
1268 a71f835e Michael Hanselmann
1269 a71f835e Michael Hanselmann
      assert not (constants.DDMS_VALUES_WITH_MODIFY & set(params.keys()))
1270 a71f835e Michael Hanselmann
1271 a71f835e Michael Hanselmann
    if action == constants.DDM_REMOVE and params:
1272 a71f835e Michael Hanselmann
      raise errors.OpPrereqError("Not accepting parameters on removal",
1273 a71f835e Michael Hanselmann
1274 a71f835e Michael Hanselmann
1275 b21d488b Christos Stavrakakis
    result.append((action, identifier, params))
1276 a71f835e Michael Hanselmann
1277 a71f835e Michael Hanselmann
  return result
1278 a71f835e Michael Hanselmann
1279 a71f835e Michael Hanselmann
1280 a71f835e Michael Hanselmann
def _ParseDiskSizes(mods):
1281 a71f835e Michael Hanselmann
  """Parses disk sizes in parameters.
1282 a71f835e Michael Hanselmann

1283 a71f835e Michael Hanselmann
1284 a71f835e Michael Hanselmann
  for (action, _, params) in mods:
1285 1c785e0b Klaus Aehlig
    if params and constants.IDISK_SPINDLES in params:
1286 1c785e0b Klaus Aehlig
      params[constants.IDISK_SPINDLES] = \
1287 1c785e0b Klaus Aehlig
1288 a71f835e Michael Hanselmann
    if params and constants.IDISK_SIZE in params:
1289 a71f835e Michael Hanselmann
      params[constants.IDISK_SIZE] = \
1290 a71f835e Michael Hanselmann
1291 a71f835e Michael Hanselmann
    elif action == constants.DDM_ADD:
1292 a71f835e Michael Hanselmann
      raise errors.OpPrereqError("Missing required parameter 'size'",
1293 a71f835e Michael Hanselmann
1294 a71f835e Michael Hanselmann
1295 a71f835e Michael Hanselmann
  return mods
1296 a71f835e Michael Hanselmann
1297 a71f835e Michael Hanselmann
1298 7767bbf5 Manuel Franceschini
def SetInstanceParams(opts, args):
1299 a8083063 Iustin Pop
  """Modifies an instance.
1300 a8083063 Iustin Pop

1301 a8083063 Iustin Pop
  All parameters take effect only at the next restart of the instance.
1302 a8083063 Iustin Pop

1303 7232c04c Iustin Pop
  @param opts: the command line options selected by the user
1304 7232c04c Iustin Pop
  @type args: list
1305 7232c04c Iustin Pop
  @param args: should contain only one element, the instance name
1306 7232c04c Iustin Pop
  @rtype: int
1307 7232c04c Iustin Pop
  @return: the desired exit code
1308 a8083063 Iustin Pop

1309 a8083063 Iustin Pop
1310 1a182390 Santi Raffa
  if not (opts.nics or opts.disks or opts.disk_template or opts.hvparams or
1311 1a182390 Santi Raffa
          opts.beparams or opts.os or opts.osparams or opts.osparams_private
1312 1a182390 Santi Raffa
          or opts.offline_inst or opts.online_inst or opts.runtime_mem or
1313 93f1e606 Jose A. Lopes
          opts.new_primary_node or opts.instance_communication is not None):
1314 3a24c527 Iustin Pop
    ToStderr("Please give at least one of the parameters.")
1315 a8083063 Iustin Pop
    return 1
1316 a8083063 Iustin Pop
1317 467ae11e Guido Trotter
  for param in opts.beparams:
1318 e9d622bc Guido Trotter
    if isinstance(opts.beparams[param], basestring):
1319 e9d622bc Guido Trotter
      if opts.beparams[param].lower() == "default":
1320 e9d622bc Guido Trotter
        opts.beparams[param] = constants.VALUE_DEFAULT
1321 a5728081 Guido Trotter
1322 b2e233a5 Guido Trotter
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_COMPAT,
1323 a5728081 Guido Trotter
1324 467ae11e Guido Trotter
1325 48f212d7 Iustin Pop
  for param in opts.hvparams:
1326 48f212d7 Iustin Pop
    if isinstance(opts.hvparams[param], basestring):
1327 48f212d7 Iustin Pop
      if opts.hvparams[param].lower() == "default":
1328 48f212d7 Iustin Pop
        opts.hvparams[param] = constants.VALUE_DEFAULT
1329 a5728081 Guido Trotter
1330 48f212d7 Iustin Pop
  utils.ForceDictType(opts.hvparams, constants.HVS_PARAMETER_TYPES,
1331 a5728081 Guido Trotter
1332 02a6b50a Michele Tartara
1333 61be6ba4 Iustin Pop
1334 a71f835e Michael Hanselmann
  nics = _ConvertNicDiskModifications(opts.nics)
1335 df58ca1c Dimitris Aragiorgis
  for action, _, __ in nics:
1336 e15a00dc Dimitris Aragiorgis
    if action == constants.DDM_MODIFY and opts.hotplug and not opts.force:
1337 df58ca1c Dimitris Aragiorgis
      usertext = ("You are about to hot-modify a NIC. This will be done"
1338 df58ca1c Dimitris Aragiorgis
                  " by removing the exisiting and then adding a new one."
1339 df58ca1c Dimitris Aragiorgis
                  " Network connection might be lost. Continue?")
1340 df58ca1c Dimitris Aragiorgis
      if not AskUser(usertext):
1341 df58ca1c Dimitris Aragiorgis
        return 1
1342 df58ca1c Dimitris Aragiorgis
1343 a71f835e Michael Hanselmann
  disks = _ParseDiskSizes(_ConvertNicDiskModifications(opts.disks))
1344 24991749 Iustin Pop
1345 e29e9550 Iustin Pop
  if (opts.disk_template and
1346 3429a076 Apollon Oikonomopoulos
      opts.disk_template in constants.DTS_INT_MIRROR and
1347 e29e9550 Iustin Pop
      not opts.node):
1348 e29e9550 Iustin Pop
    ToStderr("Changing the disk template to a mirrored one requires"
1349 e29e9550 Iustin Pop
             " specifying a secondary node")
1350 e29e9550 Iustin Pop
    return 1
1351 e29e9550 Iustin Pop
1352 3016bc1f Michael Hanselmann
  if opts.offline_inst:
1353 3016bc1f Michael Hanselmann
    offline = True
1354 3016bc1f Michael Hanselmann
  elif opts.online_inst:
1355 3016bc1f Michael Hanselmann
    offline = False
1356 3016bc1f Michael Hanselmann
1357 3016bc1f Michael Hanselmann
    offline = None
1358 3016bc1f Michael Hanselmann
1359 93f1e606 Jose A. Lopes
  instance_comm = opts.instance_communication
1360 93f1e606 Jose A. Lopes
1361 9a3cc7ae Iustin Pop
  op = opcodes.OpInstanceSetParams(instance_name=args[0],
1362 a71f835e Michael Hanselmann
1363 a71f835e Michael Hanselmann
1364 df58ca1c Dimitris Aragiorgis
1365 96ed3a3e Dimitris Aragiorgis
1366 e29e9550 Iustin Pop
1367 e29e9550 Iustin Pop
1368 3438e1f8 Klaus Aehlig
1369 48f212d7 Iustin Pop
1370 338e51e8 Iustin Pop
1371 2c0af7da Guido Trotter
1372 96b39bcc Iustin Pop
1373 1052d622 Iustin Pop
1374 1a182390 Santi Raffa
1375 96b39bcc Iustin Pop
1376 456798ab Iustin Pop
1377 57de31c0 Agata Murawska
1378 3016bc1f Michael Hanselmann
1379 9c784fb3 Dimitris Aragiorgis
1380 93f1e606 Jose A. Lopes
1381 93f1e606 Jose A. Lopes
1382 31a853d2 Iustin Pop
1383 6340bb0a Iustin Pop
  # even if here we process the result, we allow submit only
1384 6340bb0a Iustin Pop
  result = SubmitOrSend(op, opts)
1385 a8083063 Iustin Pop
1386 a8083063 Iustin Pop
  if result:
1387 3a24c527 Iustin Pop
    ToStdout("Modified instance %s", args[0])
1388 a8083063 Iustin Pop
    for param, data in result:
1389 3a24c527 Iustin Pop
      ToStdout(" - %-5s -> %s", param, data)
1390 e29e9550 Iustin Pop
    ToStdout("Please don't forget that most parameters take effect"
1391 d976957d Iustin Pop
             " only at the next (re)start of the instance initiated by"
1392 d976957d Iustin Pop
             " ganeti; restarting from within the instance will"
1393 d976957d Iustin Pop
             " not be enough.")
1394 a8083063 Iustin Pop
  return 0
1395 a8083063 Iustin Pop
1396 a8083063 Iustin Pop
1397 bd2a5569 Michael Hanselmann
def ChangeGroup(opts, args):
1398 bd2a5569 Michael Hanselmann
  """Moves an instance to another group.
1399 bd2a5569 Michael Hanselmann

1400 bd2a5569 Michael Hanselmann
1401 bd2a5569 Michael Hanselmann
  (instance_name, ) = args
1402 bd2a5569 Michael Hanselmann
1403 bd2a5569 Michael Hanselmann
  cl = GetClient()
1404 bd2a5569 Michael Hanselmann
1405 bd2a5569 Michael Hanselmann
  op = opcodes.OpInstanceChangeGroup(instance_name=instance_name,
1406 bd2a5569 Michael Hanselmann
1407 bd2a5569 Michael Hanselmann
1408 bd2a5569 Michael Hanselmann
1409 f70bb622 Michael Hanselmann
  result = SubmitOrSend(op, opts, cl=cl)
1410 bd2a5569 Michael Hanselmann
1411 bd2a5569 Michael Hanselmann
  # Keep track of submitted jobs
1412 bd2a5569 Michael Hanselmann
  jex = JobExecutor(cl=cl, opts=opts)
1413 bd2a5569 Michael Hanselmann
1414 bd2a5569 Michael Hanselmann
  for (status, job_id) in result[constants.JOB_IDS_KEY]:
1415 bd2a5569 Michael Hanselmann
    jex.AddJobId(None, status, job_id)
1416 bd2a5569 Michael Hanselmann
1417 bd2a5569 Michael Hanselmann
  results = jex.GetResults()
1418 bd2a5569 Michael Hanselmann
  bad_cnt = len([row for row in results if not row[0]])
1419 bd2a5569 Michael Hanselmann
  if bad_cnt == 0:
1420 bd2a5569 Michael Hanselmann
    ToStdout("Instance '%s' changed group successfully.", instance_name)
1421 bd2a5569 Michael Hanselmann
    rcode = constants.EXIT_SUCCESS
1422 bd2a5569 Michael Hanselmann
1423 bd2a5569 Michael Hanselmann
    ToStdout("There were %s errors while changing group of instance '%s'.",
1424 bd2a5569 Michael Hanselmann
             bad_cnt, instance_name)
1425 bd2a5569 Michael Hanselmann
    rcode = constants.EXIT_FAILURE
1426 bd2a5569 Michael Hanselmann
1427 bd2a5569 Michael Hanselmann
  return rcode
1428 bd2a5569 Michael Hanselmann
1429 bd2a5569 Michael Hanselmann
1430 312ac745 Iustin Pop
# multi-instance selection options
1431 c38c44ad Michael Hanselmann
m_force_multi = cli_option("--force-multiple", dest="force_multi",
1432 c38c44ad Michael Hanselmann
                           help="Do not ask for confirmation when more than"
1433 c38c44ad Michael Hanselmann
                           " one instance is affected",
1434 c38c44ad Michael Hanselmann
                           action="store_true", default=False)
1435 804a1e8e Iustin Pop
1436 c38c44ad Michael Hanselmann
m_pri_node_opt = cli_option("--primary", dest="multi_mode",
1437 c38c44ad Michael Hanselmann
                            help="Filter by nodes (primary only)",
1438 c20efaa8 Michael Hanselmann
                            const=_EXPAND_NODES_PRI, action="store_const")
1439 312ac745 Iustin Pop
1440 c38c44ad Michael Hanselmann
m_sec_node_opt = cli_option("--secondary", dest="multi_mode",
1441 c38c44ad Michael Hanselmann
                            help="Filter by nodes (secondary only)",
1442 c20efaa8 Michael Hanselmann
                            const=_EXPAND_NODES_SEC, action="store_const")
1443 312ac745 Iustin Pop
1444 c38c44ad Michael Hanselmann
m_node_opt = cli_option("--node", dest="multi_mode",
1445 c38c44ad Michael Hanselmann
                        help="Filter by nodes (primary and secondary)",
1446 c20efaa8 Michael Hanselmann
                        const=_EXPAND_NODES_BOTH, action="store_const")
1447 312ac745 Iustin Pop
1448 c38c44ad Michael Hanselmann
m_clust_opt = cli_option("--all", dest="multi_mode",
1449 c38c44ad Michael Hanselmann
                         help="Select all instances in the cluster",
1450 c20efaa8 Michael Hanselmann
                         const=_EXPAND_CLUSTER, action="store_const")
1451 312ac745 Iustin Pop
1452 c38c44ad Michael Hanselmann
m_inst_opt = cli_option("--instance", dest="multi_mode",
1453 c38c44ad Michael Hanselmann
                        help="Filter by instance name [default]",
1454 c20efaa8 Michael Hanselmann
                        const=_EXPAND_INSTANCES, action="store_const")
1455 312ac745 Iustin Pop
1456 39dfd93e René Nussbaumer
m_node_tags_opt = cli_option("--node-tags", dest="multi_mode",
1457 39dfd93e René Nussbaumer
                             help="Filter by node tag",
1458 c20efaa8 Michael Hanselmann
1459 39dfd93e René Nussbaumer
1460 39dfd93e René Nussbaumer
1461 39dfd93e René Nussbaumer
m_pri_node_tags_opt = cli_option("--pri-node-tags", dest="multi_mode",
1462 39dfd93e René Nussbaumer
                                 help="Filter by primary node tag",
1463 c20efaa8 Michael Hanselmann
1464 39dfd93e René Nussbaumer
1465 39dfd93e René Nussbaumer
1466 39dfd93e René Nussbaumer
m_sec_node_tags_opt = cli_option("--sec-node-tags", dest="multi_mode",
1467 39dfd93e René Nussbaumer
                                 help="Filter by secondary node tag",
1468 c20efaa8 Michael Hanselmann
1469 39dfd93e René Nussbaumer
1470 39dfd93e René Nussbaumer
1471 39dfd93e René Nussbaumer
m_inst_tags_opt = cli_option("--tags", dest="multi_mode",
1472 39dfd93e René Nussbaumer
                             help="Filter by instance tag",
1473 c20efaa8 Michael Hanselmann
1474 39dfd93e René Nussbaumer
1475 312ac745 Iustin Pop
1476 a8083063 Iustin Pop
# this is defined separately due to readability only
1477 a8083063 Iustin Pop
add_opts = [
1478 064c21f8 Iustin Pop
1479 064c21f8 Iustin Pop
1480 06073e85 Guido Trotter
1481 25a8792c Iustin Pop
1482 10889e0c René Nussbaumer
1483 015f1517 Jose A. Lopes
1484 a8083063 Iustin Pop
1485 a8083063 Iustin Pop
1486 a8083063 Iustin Pop
commands = {
1487 d0c8c01d Iustin Pop
  "add": (
1488 6bce7ba2 Santi Raffa
    AddInstance, [ArgHost(min=1, max=1)],
1489 d027b72b Jose A. Lopes
    COMMON_CREATE_OPTS + add_opts,
1490 6ea815cf Iustin Pop
    "[...] -t disk-type -n node[:secondary-node] -o os-type <name>",
1491 6ea815cf Iustin Pop
    "Creates and adds a new instance to the cluster"),
1492 d0c8c01d Iustin Pop
  "batch-create": (
1493 b0a8e8c2 René Nussbaumer
    BatchCreate, [ArgFile(min=1, max=1)],
1494 d6cd74dd Klaus Aehlig
1495 6ea815cf Iustin Pop
1496 6ea815cf Iustin Pop
    "Create a bunch of instances based on specs in the file."),
1497 d0c8c01d Iustin Pop
  "console": (
1498 6ea815cf Iustin Pop
    ConnectToInstanceConsole, ARGS_ONE_INSTANCE,
1499 aa06f8c6 Michael Hanselmann
1500 6ea815cf Iustin Pop
    "[--show-cmd] <instance>", "Opens a console on the specified instance"),
1501 d0c8c01d Iustin Pop
  "failover": (
1502 6ea815cf Iustin Pop
    FailoverInstance, ARGS_ONE_INSTANCE,
1503 d6cd74dd Klaus Aehlig
1504 d6cd74dd Klaus Aehlig
1505 b6aaf437 René Nussbaumer
1506 aa7a5c90 Michele Tartara
1507 a6a3efe4 Iustin Pop
    "[-f] <instance>", "Stops the instance, changes its primary node and"
1508 a6a3efe4 Iustin Pop
    " (if it was originally running) starts it on the new node"
1509 a6a3efe4 Iustin Pop
    " (the secondary for mirrored instances or any node"
1510 a6a3efe4 Iustin Pop
    " for shared storage)."),
1511 d0c8c01d Iustin Pop
  "migrate": (
1512 6ea815cf Iustin Pop
    MigrateInstance, ARGS_ONE_INSTANCE,
1513 aa06f8c6 Michael Hanselmann
1514 3ed23330 René Nussbaumer
1515 d6cd74dd Klaus Aehlig
1516 6ea815cf Iustin Pop
    "[-f] <instance>", "Migrate instance to its secondary node"
1517 1b7761fd Apollon Oikonomopoulos
    " (only for mirrored instances)"),
1518 d0c8c01d Iustin Pop
  "move": (
1519 6ea815cf Iustin Pop
    MoveInstance, ARGS_ONE_INSTANCE,
1520 d6cd74dd Klaus Aehlig
1521 94ab995a Thomas Thrainer
1522 d6cd74dd Klaus Aehlig
1523 d6cd74dd Klaus Aehlig
1524 6ea815cf Iustin Pop
    "[-f] <instance>", "Move instance to an arbitrary node"
1525 6ea815cf Iustin Pop
    " (only for instances of type file and lv)"),
1526 d0c8c01d Iustin Pop
  "info": (
1527 6ea815cf Iustin Pop
    ShowInstanceConfig, ARGS_MANY_INSTANCES,
1528 aa06f8c6 Michael Hanselmann
1529 6ea815cf Iustin Pop
    "[-s] {--all | <instance>...}",
1530 6ea815cf Iustin Pop
    "Show information on the specified instance(s)"),
1531 d0c8c01d Iustin Pop
  "list": (
1532 6ea815cf Iustin Pop
    ListInstances, ARGS_MANY_INSTANCES,
1533 87e87959 Michael Hanselmann
1534 87e87959 Michael Hanselmann
1535 6ea815cf Iustin Pop
1536 b82c5ff5 Michael Hanselmann
    "Lists the instances and their status. The available fields can be shown"
1537 b82c5ff5 Michael Hanselmann
    " using the \"list-fields\" command (see the man page for details)."
1538 b82c5ff5 Michael Hanselmann
    " The default field list is (in order): %s." %
1539 b82c5ff5 Michael Hanselmann
1540 6ea815cf Iustin Pop
1541 b82c5ff5 Michael Hanselmann
  "list-fields": (
1542 b82c5ff5 Michael Hanselmann
    ListInstanceFields, [ArgUnknown()],
1543 b82c5ff5 Michael Hanselmann
1544 b82c5ff5 Michael Hanselmann
1545 b82c5ff5 Michael Hanselmann
    "Lists all available fields for instances"),
1546 d0c8c01d Iustin Pop
  "reinstall": (
1547 3e54ace7 Iustin Pop
    ReinstallInstance, [ArgInstance()],
1548 06073e85 Guido Trotter
    [FORCE_OPT, OS_OPT, FORCE_VARIANT_OPT, m_force_multi, m_node_opt,
1549 39dfd93e René Nussbaumer
     m_pri_node_opt, m_sec_node_opt, m_clust_opt, m_inst_opt, m_node_tags_opt,
1550 d6cd74dd Klaus Aehlig
     m_pri_node_tags_opt, m_sec_node_tags_opt, m_inst_tags_opt, SELECT_OS_OPT]
1551 a0eeb01a Santi Raffa
1552 6bce7ba2 Santi Raffa
1553 6ea815cf Iustin Pop
    "[-f] <instance>", "Reinstall a stopped instance"),
1554 d0c8c01d Iustin Pop
  "remove": (
1555 6ea815cf Iustin Pop
    RemoveInstance, ARGS_ONE_INSTANCE,
1556 d6cd74dd Klaus Aehlig
1557 d6cd74dd Klaus Aehlig
1558 6ea815cf Iustin Pop
    "[-f] <instance>", "Shuts down the instance and removes it"),
1559 d0c8c01d Iustin Pop
  "rename": (
1560 6ea815cf Iustin Pop
1561 6ea815cf Iustin Pop
    [ArgInstance(min=1, max=1), ArgHost(min=1, max=1)],
1562 d6cd74dd Klaus Aehlig
1563 d6cd74dd Klaus Aehlig
1564 6ea815cf Iustin Pop
    "<instance> <new_name>", "Rename the instance"),
1565 d0c8c01d Iustin Pop
  "replace-disks": (
1566 6ea815cf Iustin Pop
    ReplaceDisks, ARGS_ONE_INSTANCE,
1567 7ea7bcf6 Iustin Pop
1568 d6cd74dd Klaus Aehlig
1569 d6cd74dd Klaus Aehlig
1570 50c1e351 Bernardo Dal Seno
    "[-s|-p|-a|-n NODE|-I NAME] <instance>",
1571 50c1e351 Bernardo Dal Seno
    "Replaces disks for the instance"),
1572 d0c8c01d Iustin Pop
  "modify": (
1573 6ea815cf Iustin Pop
    SetInstanceParams, ARGS_ONE_INSTANCE,
1574 d6cd74dd Klaus Aehlig
1575 d6cd74dd Klaus Aehlig
1576 6bce7ba2 Santi Raffa
1577 a0eeb01a Santi Raffa
1578 96ed3a3e Dimitris Aragiorgis
1579 93f1e606 Jose A. Lopes
1580 6ea815cf Iustin Pop
    "<instance>", "Alters the parameters of an instance"),
1581 d0c8c01d Iustin Pop
  "shutdown": (
1582 1c5945b6 Iustin Pop
    GenericManyOps("shutdown", _ShutdownInstance), [ArgInstance()],
1583 0d57ce24 Guido Trotter
    [FORCE_OPT, m_node_opt, m_pri_node_opt, m_sec_node_opt, m_clust_opt,
1584 39dfd93e René Nussbaumer
     m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt,
1585 d6cd74dd Klaus Aehlig
     m_inst_tags_opt, m_inst_opt, m_force_multi, TIMEOUT_OPT] + SUBMIT_OPTS
1586 d6cd74dd Klaus Aehlig
1587 6ea815cf Iustin Pop
    "<instance>", "Stops an instance"),
1588 d0c8c01d Iustin Pop
  "startup": (
1589 1c5945b6 Iustin Pop
    GenericManyOps("startup", _StartupInstance), [ArgInstance()],
1590 39dfd93e René Nussbaumer
    [FORCE_OPT, m_force_multi, m_node_opt, m_pri_node_opt, m_sec_node_opt,
1591 39dfd93e René Nussbaumer
     m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt,
1592 d6cd74dd Klaus Aehlig
     m_inst_tags_opt, m_clust_opt, m_inst_opt] + SUBMIT_OPTS +
1593 d6cd74dd Klaus Aehlig
1594 885a0fc4 Iustin Pop
1595 323f9095 Stephen Shirley
1596 6ea815cf Iustin Pop
    "<instance>", "Starts an instance"),
1597 d0c8c01d Iustin Pop
  "reboot": (
1598 1c5945b6 Iustin Pop
    GenericManyOps("reboot", _RebootInstance), [ArgInstance()],
1599 064c21f8 Iustin Pop
    [m_force_multi, REBOOT_TYPE_OPT, IGNORE_SECONDARIES_OPT, m_node_opt,
1600 d6cd74dd Klaus Aehlig
     m_pri_node_opt, m_sec_node_opt, m_clust_opt, m_inst_opt] + SUBMIT_OPTS +
1601 d6cd74dd Klaus Aehlig
    [m_node_tags_opt, m_pri_node_tags_opt, m_sec_node_tags_opt,
1602 aa922d64 Michele Tartara
1603 6ea815cf Iustin Pop
    "<instance>", "Reboots an instance"),
1604 d0c8c01d Iustin Pop
  "activate-disks": (
1605 db5a8a2d Iustin Pop
    ActivateDisks, ARGS_ONE_INSTANCE,
1606 d6cd74dd Klaus Aehlig
1607 6ea815cf Iustin Pop
    "<instance>", "Activate an instance's disks"),
1608 d0c8c01d Iustin Pop
  "deactivate-disks": (
1609 aa06f8c6 Michael Hanselmann
    DeactivateDisks, ARGS_ONE_INSTANCE,
1610 d6cd74dd Klaus Aehlig
1611 c9c41373 Iustin Pop
    "[-f] <instance>", "Deactivate an instance's disks"),
1612 d0c8c01d Iustin Pop
  "recreate-disks": (
1613 aa06f8c6 Michael Hanselmann
    RecreateDisks, ARGS_ONE_INSTANCE,
1614 d6cd74dd Klaus Aehlig
1615 d6cd74dd Klaus Aehlig
1616 38db4e7c Adam Ingrassia
1617 6ea815cf Iustin Pop
    "<instance>", "Recreate an instance's disks"),
1618 d0c8c01d Iustin Pop
  "grow-disk": (
1619 6ea815cf Iustin Pop
1620 6ea815cf Iustin Pop
    [ArgInstance(min=1, max=1), ArgUnknown(min=1, max=1),
1621 6ea815cf Iustin Pop
     ArgUnknown(min=1, max=1)],
1622 d6cd74dd Klaus Aehlig
1623 6ea815cf Iustin Pop
    "<instance> <disk> <size>", "Grow an instance's disk"),
1624 bd2a5569 Michael Hanselmann
  "change-group": (
1625 bd2a5569 Michael Hanselmann
    ChangeGroup, ARGS_ONE_INSTANCE,
1626 d6cd74dd Klaus Aehlig
1627 d6cd74dd Klaus Aehlig
1628 bd2a5569 Michael Hanselmann
    "[-I <iallocator>] [--to <group>]", "Change group of instance"),
1629 d0c8c01d Iustin Pop
  "list-tags": (
1630 6bc3ed14 Michael Hanselmann
    ListTags, ARGS_ONE_INSTANCE, [],
1631 6ea815cf Iustin Pop
    "<instance_name>", "List the tags of the given instance"),
1632 d0c8c01d Iustin Pop
  "add-tags": (
1633 6ea815cf Iustin Pop
    AddTags, [ArgInstance(min=1, max=1), ArgUnknown()],
1634 d6cd74dd Klaus Aehlig
1635 6ea815cf Iustin Pop
    "<instance_name> tag...", "Add tags to the given instance"),
1636 d0c8c01d Iustin Pop
  "remove-tags": (
1637 6ea815cf Iustin Pop
    RemoveTags, [ArgInstance(min=1, max=1), ArgUnknown()],
1638 d6cd74dd Klaus Aehlig
1639 6ea815cf Iustin Pop
    "<instance_name> tag...", "Remove tags from given instance"),
1640 a8083063 Iustin Pop
1641 a8083063 Iustin Pop
1642 7232c04c Iustin Pop
#: dictionary with aliases for commands
1643 dbfd89dd Guido Trotter
aliases = {
1644 d0c8c01d Iustin Pop
  "start": "startup",
1645 d0c8c01d Iustin Pop
  "stop": "shutdown",
1646 96897af7 Alexander Schreiber
  "show": "info",
1647 dbfd89dd Guido Trotter
1648 dbfd89dd Guido Trotter
1649 a8005e17 Michael Hanselmann
1650 e792102d Michael Hanselmann
def Main():
1651 e792102d Michael Hanselmann
  return GenericMain(commands, aliases=aliases,
1652 ef9fa5b9 René Nussbaumer
                     override={"tag_type": constants.TAG_INSTANCE},
1653 ef9fa5b9 René Nussbaumer