Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 455a3445

History | View | Annotate | Download (166.9 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 e7c6e02b Michael Hanselmann
# Copyright (C) 2006, 2007, 2008 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 880478f8 Iustin Pop
"""Module implementing the master-side code."""
23 a8083063 Iustin Pop
24 a8083063 Iustin Pop
# pylint: disable-msg=W0613,W0201
25 a8083063 Iustin Pop
26 a8083063 Iustin Pop
import os
27 a8083063 Iustin Pop
import os.path
28 a8083063 Iustin Pop
import sha
29 a8083063 Iustin Pop
import time
30 a8083063 Iustin Pop
import tempfile
31 a8083063 Iustin Pop
import re
32 a8083063 Iustin Pop
import platform
33 a8083063 Iustin Pop
34 a8083063 Iustin Pop
from ganeti import rpc
35 a8083063 Iustin Pop
from ganeti import ssh
36 a8083063 Iustin Pop
from ganeti import logger
37 a8083063 Iustin Pop
from ganeti import utils
38 a8083063 Iustin Pop
from ganeti import errors
39 a8083063 Iustin Pop
from ganeti import hypervisor
40 a8083063 Iustin Pop
from ganeti import config
41 a8083063 Iustin Pop
from ganeti import constants
42 a8083063 Iustin Pop
from ganeti import objects
43 a8083063 Iustin Pop
from ganeti import opcodes
44 a8083063 Iustin Pop
from ganeti import ssconf
45 8d14b30d Iustin Pop
from ganeti import serializer
46 d61df03e Iustin Pop
47 d61df03e Iustin Pop
48 a8083063 Iustin Pop
class LogicalUnit(object):
49 396e1b78 Michael Hanselmann
  """Logical Unit base class.
50 a8083063 Iustin Pop

51 a8083063 Iustin Pop
  Subclasses must follow these rules:
52 a8083063 Iustin Pop
    - implement CheckPrereq which also fills in the opcode instance
53 a8083063 Iustin Pop
      with all the fields (even if as None)
54 a8083063 Iustin Pop
    - implement Exec
55 a8083063 Iustin Pop
    - implement BuildHooksEnv
56 a8083063 Iustin Pop
    - redefine HPATH and HTYPE
57 a8083063 Iustin Pop
    - optionally redefine their run requirements (REQ_CLUSTER,
58 a8083063 Iustin Pop
      REQ_MASTER); note that all commands require root permissions
59 a8083063 Iustin Pop

60 a8083063 Iustin Pop
  """
61 a8083063 Iustin Pop
  HPATH = None
62 a8083063 Iustin Pop
  HTYPE = None
63 a8083063 Iustin Pop
  _OP_REQP = []
64 a8083063 Iustin Pop
  REQ_CLUSTER = True
65 a8083063 Iustin Pop
  REQ_MASTER = True
66 a8083063 Iustin Pop
67 a8083063 Iustin Pop
  def __init__(self, processor, op, cfg, sstore):
68 a8083063 Iustin Pop
    """Constructor for LogicalUnit.
69 a8083063 Iustin Pop

70 a8083063 Iustin Pop
    This needs to be overriden in derived classes in order to check op
71 a8083063 Iustin Pop
    validity.
72 a8083063 Iustin Pop

73 a8083063 Iustin Pop
    """
74 5bfac263 Iustin Pop
    self.proc = processor
75 a8083063 Iustin Pop
    self.op = op
76 a8083063 Iustin Pop
    self.cfg = cfg
77 a8083063 Iustin Pop
    self.sstore = sstore
78 c92b310a Michael Hanselmann
    self.__ssh = None
79 c92b310a Michael Hanselmann
80 a8083063 Iustin Pop
    for attr_name in self._OP_REQP:
81 a8083063 Iustin Pop
      attr_val = getattr(op, attr_name, None)
82 a8083063 Iustin Pop
      if attr_val is None:
83 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Required parameter '%s' missing" %
84 3ecf6786 Iustin Pop
                                   attr_name)
85 a8083063 Iustin Pop
    if self.REQ_CLUSTER:
86 a8083063 Iustin Pop
      if not cfg.IsCluster():
87 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Cluster not initialized yet,"
88 3ecf6786 Iustin Pop
                                   " use 'gnt-cluster init' first.")
89 a8083063 Iustin Pop
      if self.REQ_MASTER:
90 880478f8 Iustin Pop
        master = sstore.GetMasterNode()
91 89e1fc26 Iustin Pop
        if master != utils.HostInfo().name:
92 3ecf6786 Iustin Pop
          raise errors.OpPrereqError("Commands must be run on the master"
93 3ecf6786 Iustin Pop
                                     " node %s" % master)
94 a8083063 Iustin Pop
95 c92b310a Michael Hanselmann
  def __GetSSH(self):
96 c92b310a Michael Hanselmann
    """Returns the SshRunner object
97 c92b310a Michael Hanselmann

98 c92b310a Michael Hanselmann
    """
99 c92b310a Michael Hanselmann
    if not self.__ssh:
100 1ff08570 Michael Hanselmann
      self.__ssh = ssh.SshRunner(self.sstore)
101 c92b310a Michael Hanselmann
    return self.__ssh
102 c92b310a Michael Hanselmann
103 c92b310a Michael Hanselmann
  ssh = property(fget=__GetSSH)
104 c92b310a Michael Hanselmann
105 a8083063 Iustin Pop
  def CheckPrereq(self):
106 a8083063 Iustin Pop
    """Check prerequisites for this LU.
107 a8083063 Iustin Pop

108 a8083063 Iustin Pop
    This method should check that the prerequisites for the execution
109 a8083063 Iustin Pop
    of this LU are fulfilled. It can do internode communication, but
110 a8083063 Iustin Pop
    it should be idempotent - no cluster or system changes are
111 a8083063 Iustin Pop
    allowed.
112 a8083063 Iustin Pop

113 a8083063 Iustin Pop
    The method should raise errors.OpPrereqError in case something is
114 a8083063 Iustin Pop
    not fulfilled. Its return value is ignored.
115 a8083063 Iustin Pop

116 a8083063 Iustin Pop
    This method should also update all the parameters of the opcode to
117 a8083063 Iustin Pop
    their canonical form; e.g. a short node name must be fully
118 a8083063 Iustin Pop
    expanded after this method has successfully completed (so that
119 a8083063 Iustin Pop
    hooks, logging, etc. work correctly).
120 a8083063 Iustin Pop

121 a8083063 Iustin Pop
    """
122 a8083063 Iustin Pop
    raise NotImplementedError
123 a8083063 Iustin Pop
124 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
125 a8083063 Iustin Pop
    """Execute the LU.
126 a8083063 Iustin Pop

127 a8083063 Iustin Pop
    This method should implement the actual work. It should raise
128 a8083063 Iustin Pop
    errors.OpExecError for failures that are somewhat dealt with in
129 a8083063 Iustin Pop
    code, or expected.
130 a8083063 Iustin Pop

131 a8083063 Iustin Pop
    """
132 a8083063 Iustin Pop
    raise NotImplementedError
133 a8083063 Iustin Pop
134 a8083063 Iustin Pop
  def BuildHooksEnv(self):
135 a8083063 Iustin Pop
    """Build hooks environment for this LU.
136 a8083063 Iustin Pop

137 a8083063 Iustin Pop
    This method should return a three-node tuple consisting of: a dict
138 a8083063 Iustin Pop
    containing the environment that will be used for running the
139 a8083063 Iustin Pop
    specific hook for this LU, a list of node names on which the hook
140 a8083063 Iustin Pop
    should run before the execution, and a list of node names on which
141 a8083063 Iustin Pop
    the hook should run after the execution.
142 a8083063 Iustin Pop

143 a8083063 Iustin Pop
    The keys of the dict must not have 'GANETI_' prefixed as this will
144 a8083063 Iustin Pop
    be handled in the hooks runner. Also note additional keys will be
145 a8083063 Iustin Pop
    added by the hooks runner. If the LU doesn't define any
146 a8083063 Iustin Pop
    environment, an empty dict (and not None) should be returned.
147 a8083063 Iustin Pop

148 a8083063 Iustin Pop
    As for the node lists, the master should not be included in the
149 a8083063 Iustin Pop
    them, as it will be added by the hooks runner in case this LU
150 a8083063 Iustin Pop
    requires a cluster to run on (otherwise we don't have a node
151 a8083063 Iustin Pop
    list). No nodes should be returned as an empty list (and not
152 a8083063 Iustin Pop
    None).
153 a8083063 Iustin Pop

154 a8083063 Iustin Pop
    Note that if the HPATH for a LU class is None, this function will
155 a8083063 Iustin Pop
    not be called.
156 a8083063 Iustin Pop

157 a8083063 Iustin Pop
    """
158 a8083063 Iustin Pop
    raise NotImplementedError
159 a8083063 Iustin Pop
160 a8083063 Iustin Pop
161 a8083063 Iustin Pop
class NoHooksLU(LogicalUnit):
162 a8083063 Iustin Pop
  """Simple LU which runs no hooks.
163 a8083063 Iustin Pop

164 a8083063 Iustin Pop
  This LU is intended as a parent for other LogicalUnits which will
165 a8083063 Iustin Pop
  run no hooks, in order to reduce duplicate code.
166 a8083063 Iustin Pop

167 a8083063 Iustin Pop
  """
168 a8083063 Iustin Pop
  HPATH = None
169 a8083063 Iustin Pop
  HTYPE = None
170 a8083063 Iustin Pop
171 a8083063 Iustin Pop
  def BuildHooksEnv(self):
172 a8083063 Iustin Pop
    """Build hooks env.
173 a8083063 Iustin Pop

174 a8083063 Iustin Pop
    This is a no-op, since we don't run hooks.
175 a8083063 Iustin Pop

176 a8083063 Iustin Pop
    """
177 0e137c28 Iustin Pop
    return {}, [], []
178 a8083063 Iustin Pop
179 a8083063 Iustin Pop
180 9440aeab Michael Hanselmann
def _AddHostToEtcHosts(hostname):
181 9440aeab Michael Hanselmann
  """Wrapper around utils.SetEtcHostsEntry.
182 9440aeab Michael Hanselmann

183 9440aeab Michael Hanselmann
  """
184 9440aeab Michael Hanselmann
  hi = utils.HostInfo(name=hostname)
185 9440aeab Michael Hanselmann
  utils.SetEtcHostsEntry(constants.ETC_HOSTS, hi.ip, hi.name, [hi.ShortName()])
186 9440aeab Michael Hanselmann
187 9440aeab Michael Hanselmann
188 c8a0948f Michael Hanselmann
def _RemoveHostFromEtcHosts(hostname):
189 9440aeab Michael Hanselmann
  """Wrapper around utils.RemoveEtcHostsEntry.
190 c8a0948f Michael Hanselmann

191 c8a0948f Michael Hanselmann
  """
192 c8a0948f Michael Hanselmann
  hi = utils.HostInfo(name=hostname)
193 c8a0948f Michael Hanselmann
  utils.RemoveEtcHostsEntry(constants.ETC_HOSTS, hi.name)
194 c8a0948f Michael Hanselmann
  utils.RemoveEtcHostsEntry(constants.ETC_HOSTS, hi.ShortName())
195 c8a0948f Michael Hanselmann
196 c8a0948f Michael Hanselmann
197 dcb93971 Michael Hanselmann
def _GetWantedNodes(lu, nodes):
198 a7ba5e53 Iustin Pop
  """Returns list of checked and expanded node names.
199 83120a01 Michael Hanselmann

200 83120a01 Michael Hanselmann
  Args:
201 83120a01 Michael Hanselmann
    nodes: List of nodes (strings) or None for all
202 83120a01 Michael Hanselmann

203 83120a01 Michael Hanselmann
  """
204 3312b702 Iustin Pop
  if not isinstance(nodes, list):
205 3ecf6786 Iustin Pop
    raise errors.OpPrereqError("Invalid argument type 'nodes'")
206 dcb93971 Michael Hanselmann
207 dcb93971 Michael Hanselmann
  if nodes:
208 3312b702 Iustin Pop
    wanted = []
209 dcb93971 Michael Hanselmann
210 dcb93971 Michael Hanselmann
    for name in nodes:
211 a7ba5e53 Iustin Pop
      node = lu.cfg.ExpandNodeName(name)
212 dcb93971 Michael Hanselmann
      if node is None:
213 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("No such node name '%s'" % name)
214 3312b702 Iustin Pop
      wanted.append(node)
215 dcb93971 Michael Hanselmann
216 dcb93971 Michael Hanselmann
  else:
217 a7ba5e53 Iustin Pop
    wanted = lu.cfg.GetNodeList()
218 a7ba5e53 Iustin Pop
  return utils.NiceSort(wanted)
219 3312b702 Iustin Pop
220 3312b702 Iustin Pop
221 3312b702 Iustin Pop
def _GetWantedInstances(lu, instances):
222 a7ba5e53 Iustin Pop
  """Returns list of checked and expanded instance names.
223 3312b702 Iustin Pop

224 3312b702 Iustin Pop
  Args:
225 3312b702 Iustin Pop
    instances: List of instances (strings) or None for all
226 3312b702 Iustin Pop

227 3312b702 Iustin Pop
  """
228 3312b702 Iustin Pop
  if not isinstance(instances, list):
229 3312b702 Iustin Pop
    raise errors.OpPrereqError("Invalid argument type 'instances'")
230 3312b702 Iustin Pop
231 3312b702 Iustin Pop
  if instances:
232 3312b702 Iustin Pop
    wanted = []
233 3312b702 Iustin Pop
234 3312b702 Iustin Pop
    for name in instances:
235 a7ba5e53 Iustin Pop
      instance = lu.cfg.ExpandInstanceName(name)
236 3312b702 Iustin Pop
      if instance is None:
237 3312b702 Iustin Pop
        raise errors.OpPrereqError("No such instance name '%s'" % name)
238 3312b702 Iustin Pop
      wanted.append(instance)
239 3312b702 Iustin Pop
240 3312b702 Iustin Pop
  else:
241 a7ba5e53 Iustin Pop
    wanted = lu.cfg.GetInstanceList()
242 a7ba5e53 Iustin Pop
  return utils.NiceSort(wanted)
243 dcb93971 Michael Hanselmann
244 dcb93971 Michael Hanselmann
245 dcb93971 Michael Hanselmann
def _CheckOutputFields(static, dynamic, selected):
246 83120a01 Michael Hanselmann
  """Checks whether all selected fields are valid.
247 83120a01 Michael Hanselmann

248 83120a01 Michael Hanselmann
  Args:
249 83120a01 Michael Hanselmann
    static: Static fields
250 83120a01 Michael Hanselmann
    dynamic: Dynamic fields
251 83120a01 Michael Hanselmann

252 83120a01 Michael Hanselmann
  """
253 83120a01 Michael Hanselmann
  static_fields = frozenset(static)
254 83120a01 Michael Hanselmann
  dynamic_fields = frozenset(dynamic)
255 dcb93971 Michael Hanselmann
256 83120a01 Michael Hanselmann
  all_fields = static_fields | dynamic_fields
257 dcb93971 Michael Hanselmann
258 83120a01 Michael Hanselmann
  if not all_fields.issuperset(selected):
259 3ecf6786 Iustin Pop
    raise errors.OpPrereqError("Unknown output fields selected: %s"
260 3ecf6786 Iustin Pop
                               % ",".join(frozenset(selected).
261 3ecf6786 Iustin Pop
                                          difference(all_fields)))
262 dcb93971 Michael Hanselmann
263 dcb93971 Michael Hanselmann
264 ecb215b5 Michael Hanselmann
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
265 396e1b78 Michael Hanselmann
                          memory, vcpus, nics):
266 ecb215b5 Michael Hanselmann
  """Builds instance related env variables for hooks from single variables.
267 ecb215b5 Michael Hanselmann

268 ecb215b5 Michael Hanselmann
  Args:
269 ecb215b5 Michael Hanselmann
    secondary_nodes: List of secondary nodes as strings
270 396e1b78 Michael Hanselmann
  """
271 396e1b78 Michael Hanselmann
  env = {
272 0e137c28 Iustin Pop
    "OP_TARGET": name,
273 396e1b78 Michael Hanselmann
    "INSTANCE_NAME": name,
274 396e1b78 Michael Hanselmann
    "INSTANCE_PRIMARY": primary_node,
275 396e1b78 Michael Hanselmann
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
276 ecb215b5 Michael Hanselmann
    "INSTANCE_OS_TYPE": os_type,
277 396e1b78 Michael Hanselmann
    "INSTANCE_STATUS": status,
278 396e1b78 Michael Hanselmann
    "INSTANCE_MEMORY": memory,
279 396e1b78 Michael Hanselmann
    "INSTANCE_VCPUS": vcpus,
280 396e1b78 Michael Hanselmann
  }
281 396e1b78 Michael Hanselmann
282 396e1b78 Michael Hanselmann
  if nics:
283 396e1b78 Michael Hanselmann
    nic_count = len(nics)
284 53e4e875 Guido Trotter
    for idx, (ip, bridge, mac) in enumerate(nics):
285 396e1b78 Michael Hanselmann
      if ip is None:
286 396e1b78 Michael Hanselmann
        ip = ""
287 396e1b78 Michael Hanselmann
      env["INSTANCE_NIC%d_IP" % idx] = ip
288 396e1b78 Michael Hanselmann
      env["INSTANCE_NIC%d_BRIDGE" % idx] = bridge
289 53e4e875 Guido Trotter
      env["INSTANCE_NIC%d_HWADDR" % idx] = mac
290 396e1b78 Michael Hanselmann
  else:
291 396e1b78 Michael Hanselmann
    nic_count = 0
292 396e1b78 Michael Hanselmann
293 396e1b78 Michael Hanselmann
  env["INSTANCE_NIC_COUNT"] = nic_count
294 396e1b78 Michael Hanselmann
295 396e1b78 Michael Hanselmann
  return env
296 396e1b78 Michael Hanselmann
297 396e1b78 Michael Hanselmann
298 396e1b78 Michael Hanselmann
def _BuildInstanceHookEnvByObject(instance, override=None):
299 ecb215b5 Michael Hanselmann
  """Builds instance related env variables for hooks from an object.
300 ecb215b5 Michael Hanselmann

301 ecb215b5 Michael Hanselmann
  Args:
302 ecb215b5 Michael Hanselmann
    instance: objects.Instance object of instance
303 ecb215b5 Michael Hanselmann
    override: dict of values to override
304 ecb215b5 Michael Hanselmann
  """
305 396e1b78 Michael Hanselmann
  args = {
306 396e1b78 Michael Hanselmann
    'name': instance.name,
307 396e1b78 Michael Hanselmann
    'primary_node': instance.primary_node,
308 396e1b78 Michael Hanselmann
    'secondary_nodes': instance.secondary_nodes,
309 ecb215b5 Michael Hanselmann
    'os_type': instance.os,
310 396e1b78 Michael Hanselmann
    'status': instance.os,
311 396e1b78 Michael Hanselmann
    'memory': instance.memory,
312 396e1b78 Michael Hanselmann
    'vcpus': instance.vcpus,
313 53e4e875 Guido Trotter
    'nics': [(nic.ip, nic.bridge, nic.mac) for nic in instance.nics],
314 396e1b78 Michael Hanselmann
  }
315 396e1b78 Michael Hanselmann
  if override:
316 396e1b78 Michael Hanselmann
    args.update(override)
317 396e1b78 Michael Hanselmann
  return _BuildInstanceHookEnv(**args)
318 396e1b78 Michael Hanselmann
319 396e1b78 Michael Hanselmann
320 a8083063 Iustin Pop
def _HasValidVG(vglist, vgname):
321 a8083063 Iustin Pop
  """Checks if the volume group list is valid.
322 a8083063 Iustin Pop

323 a8083063 Iustin Pop
  A non-None return value means there's an error, and the return value
324 a8083063 Iustin Pop
  is the error message.
325 a8083063 Iustin Pop

326 a8083063 Iustin Pop
  """
327 a8083063 Iustin Pop
  vgsize = vglist.get(vgname, None)
328 a8083063 Iustin Pop
  if vgsize is None:
329 a8083063 Iustin Pop
    return "volume group '%s' missing" % vgname
330 a8083063 Iustin Pop
  elif vgsize < 20480:
331 191a8385 Guido Trotter
    return ("volume group '%s' too small (20480MiB required, %dMib found)" %
332 191a8385 Guido Trotter
            (vgname, vgsize))
333 a8083063 Iustin Pop
  return None
334 a8083063 Iustin Pop
335 a8083063 Iustin Pop
336 a8083063 Iustin Pop
def _InitSSHSetup(node):
337 a8083063 Iustin Pop
  """Setup the SSH configuration for the cluster.
338 a8083063 Iustin Pop

339 a8083063 Iustin Pop

340 a8083063 Iustin Pop
  This generates a dsa keypair for root, adds the pub key to the
341 a8083063 Iustin Pop
  permitted hosts and adds the hostkey to its own known hosts.
342 a8083063 Iustin Pop

343 a8083063 Iustin Pop
  Args:
344 a8083063 Iustin Pop
    node: the name of this host as a fqdn
345 a8083063 Iustin Pop

346 a8083063 Iustin Pop
  """
347 70d9e3d8 Iustin Pop
  priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
348 a8083063 Iustin Pop
349 70d9e3d8 Iustin Pop
  for name in priv_key, pub_key:
350 70d9e3d8 Iustin Pop
    if os.path.exists(name):
351 70d9e3d8 Iustin Pop
      utils.CreateBackup(name)
352 70d9e3d8 Iustin Pop
    utils.RemoveFile(name)
353 a8083063 Iustin Pop
354 a8083063 Iustin Pop
  result = utils.RunCmd(["ssh-keygen", "-t", "dsa",
355 70d9e3d8 Iustin Pop
                         "-f", priv_key,
356 a8083063 Iustin Pop
                         "-q", "-N", ""])
357 a8083063 Iustin Pop
  if result.failed:
358 3ecf6786 Iustin Pop
    raise errors.OpExecError("Could not generate ssh keypair, error %s" %
359 3ecf6786 Iustin Pop
                             result.output)
360 a8083063 Iustin Pop
361 70d9e3d8 Iustin Pop
  f = open(pub_key, 'r')
362 a8083063 Iustin Pop
  try:
363 70d9e3d8 Iustin Pop
    utils.AddAuthorizedKey(auth_keys, f.read(8192))
364 a8083063 Iustin Pop
  finally:
365 a8083063 Iustin Pop
    f.close()
366 a8083063 Iustin Pop
367 a8083063 Iustin Pop
368 a8083063 Iustin Pop
def _InitGanetiServerSetup(ss):
369 a8083063 Iustin Pop
  """Setup the necessary configuration for the initial node daemon.
370 a8083063 Iustin Pop

371 a8083063 Iustin Pop
  This creates the nodepass file containing the shared password for
372 a8083063 Iustin Pop
  the cluster and also generates the SSL certificate.
373 a8083063 Iustin Pop

374 a8083063 Iustin Pop
  """
375 a8083063 Iustin Pop
  # Create pseudo random password
376 a8083063 Iustin Pop
  randpass = sha.new(os.urandom(64)).hexdigest()
377 a8083063 Iustin Pop
  # and write it into sstore
378 a8083063 Iustin Pop
  ss.SetKey(ss.SS_NODED_PASS, randpass)
379 a8083063 Iustin Pop
380 a8083063 Iustin Pop
  result = utils.RunCmd(["openssl", "req", "-new", "-newkey", "rsa:1024",
381 a8083063 Iustin Pop
                         "-days", str(365*5), "-nodes", "-x509",
382 a8083063 Iustin Pop
                         "-keyout", constants.SSL_CERT_FILE,
383 a8083063 Iustin Pop
                         "-out", constants.SSL_CERT_FILE, "-batch"])
384 a8083063 Iustin Pop
  if result.failed:
385 3ecf6786 Iustin Pop
    raise errors.OpExecError("could not generate server ssl cert, command"
386 3ecf6786 Iustin Pop
                             " %s had exitcode %s and error message %s" %
387 3ecf6786 Iustin Pop
                             (result.cmd, result.exit_code, result.output))
388 a8083063 Iustin Pop
389 a8083063 Iustin Pop
  os.chmod(constants.SSL_CERT_FILE, 0400)
390 a8083063 Iustin Pop
391 a8083063 Iustin Pop
  result = utils.RunCmd([constants.NODE_INITD_SCRIPT, "restart"])
392 a8083063 Iustin Pop
393 a8083063 Iustin Pop
  if result.failed:
394 3ecf6786 Iustin Pop
    raise errors.OpExecError("Could not start the node daemon, command %s"
395 3ecf6786 Iustin Pop
                             " had exitcode %s and error %s" %
396 3ecf6786 Iustin Pop
                             (result.cmd, result.exit_code, result.output))
397 a8083063 Iustin Pop
398 a8083063 Iustin Pop
399 bf6929a2 Alexander Schreiber
def _CheckInstanceBridgesExist(instance):
400 bf6929a2 Alexander Schreiber
  """Check that the brigdes needed by an instance exist.
401 bf6929a2 Alexander Schreiber

402 bf6929a2 Alexander Schreiber
  """
403 bf6929a2 Alexander Schreiber
  # check bridges existance
404 bf6929a2 Alexander Schreiber
  brlist = [nic.bridge for nic in instance.nics]
405 bf6929a2 Alexander Schreiber
  if not rpc.call_bridges_exist(instance.primary_node, brlist):
406 bf6929a2 Alexander Schreiber
    raise errors.OpPrereqError("one or more target bridges %s does not"
407 bf6929a2 Alexander Schreiber
                               " exist on destination node '%s'" %
408 bf6929a2 Alexander Schreiber
                               (brlist, instance.primary_node))
409 bf6929a2 Alexander Schreiber
410 bf6929a2 Alexander Schreiber
411 a8083063 Iustin Pop
class LUInitCluster(LogicalUnit):
412 a8083063 Iustin Pop
  """Initialise the cluster.
413 a8083063 Iustin Pop

414 a8083063 Iustin Pop
  """
415 a8083063 Iustin Pop
  HPATH = "cluster-init"
416 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_CLUSTER
417 efa14262 Manuel Franceschini
  _OP_REQP = ["cluster_name", "hypervisor_type", "mac_prefix",
418 871705db Manuel Franceschini
              "def_bridge", "master_netdev", "file_storage_dir"]
419 a8083063 Iustin Pop
  REQ_CLUSTER = False
420 a8083063 Iustin Pop
421 a8083063 Iustin Pop
  def BuildHooksEnv(self):
422 a8083063 Iustin Pop
    """Build hooks env.
423 a8083063 Iustin Pop

424 a8083063 Iustin Pop
    Notes: Since we don't require a cluster, we must manually add
425 a8083063 Iustin Pop
    ourselves in the post-run node list.
426 a8083063 Iustin Pop

427 a8083063 Iustin Pop
    """
428 0e137c28 Iustin Pop
    env = {"OP_TARGET": self.op.cluster_name}
429 0e137c28 Iustin Pop
    return env, [], [self.hostname.name]
430 a8083063 Iustin Pop
431 a8083063 Iustin Pop
  def CheckPrereq(self):
432 a8083063 Iustin Pop
    """Verify that the passed name is a valid one.
433 a8083063 Iustin Pop

434 a8083063 Iustin Pop
    """
435 a8083063 Iustin Pop
    if config.ConfigWriter.IsCluster():
436 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Cluster is already initialised")
437 a8083063 Iustin Pop
438 2a6469d5 Alexander Schreiber
    if self.op.hypervisor_type == constants.HT_XEN_HVM31:
439 2a6469d5 Alexander Schreiber
      if not os.path.exists(constants.VNC_PASSWORD_FILE):
440 2a6469d5 Alexander Schreiber
        raise errors.OpPrereqError("Please prepare the cluster VNC"
441 2a6469d5 Alexander Schreiber
                                   "password file %s" %
442 2a6469d5 Alexander Schreiber
                                   constants.VNC_PASSWORD_FILE)
443 2a6469d5 Alexander Schreiber
444 89e1fc26 Iustin Pop
    self.hostname = hostname = utils.HostInfo()
445 ff98055b Iustin Pop
446 bcf043c9 Iustin Pop
    if hostname.ip.startswith("127."):
447 130e907e Iustin Pop
      raise errors.OpPrereqError("This host's IP resolves to the private"
448 107711b0 Michael Hanselmann
                                 " range (%s). Please fix DNS or %s." %
449 107711b0 Michael Hanselmann
                                 (hostname.ip, constants.ETC_HOSTS))
450 130e907e Iustin Pop
451 b15d625f Iustin Pop
    if not utils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT,
452 b15d625f Iustin Pop
                         source=constants.LOCALHOST_IP_ADDRESS):
453 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Inconsistency: this host's name resolves"
454 3ecf6786 Iustin Pop
                                 " to %s,\nbut this ip address does not"
455 3ecf6786 Iustin Pop
                                 " belong to this host."
456 bcf043c9 Iustin Pop
                                 " Aborting." % hostname.ip)
457 a8083063 Iustin Pop
458 411f8ad0 Iustin Pop
    self.clustername = clustername = utils.HostInfo(self.op.cluster_name)
459 411f8ad0 Iustin Pop
460 411f8ad0 Iustin Pop
    if utils.TcpPing(clustername.ip, constants.DEFAULT_NODED_PORT,
461 411f8ad0 Iustin Pop
                     timeout=5):
462 411f8ad0 Iustin Pop
      raise errors.OpPrereqError("Cluster IP already active. Aborting.")
463 411f8ad0 Iustin Pop
464 a8083063 Iustin Pop
    secondary_ip = getattr(self.op, "secondary_ip", None)
465 a8083063 Iustin Pop
    if secondary_ip and not utils.IsValidIP(secondary_ip):
466 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Invalid secondary ip given")
467 16abfbc2 Alexander Schreiber
    if (secondary_ip and
468 16abfbc2 Alexander Schreiber
        secondary_ip != hostname.ip and
469 b15d625f Iustin Pop
        (not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
470 b15d625f Iustin Pop
                           source=constants.LOCALHOST_IP_ADDRESS))):
471 f4bc1f2c Michael Hanselmann
      raise errors.OpPrereqError("You gave %s as secondary IP,"
472 f4bc1f2c Michael Hanselmann
                                 " but it does not belong to this host." %
473 16abfbc2 Alexander Schreiber
                                 secondary_ip)
474 a8083063 Iustin Pop
    self.secondary_ip = secondary_ip
475 a8083063 Iustin Pop
476 efa14262 Manuel Franceschini
    if not hasattr(self.op, "vg_name"):
477 efa14262 Manuel Franceschini
      self.op.vg_name = None
478 efa14262 Manuel Franceschini
    # if vg_name not None, checks if volume group is valid
479 efa14262 Manuel Franceschini
    if self.op.vg_name:
480 efa14262 Manuel Franceschini
      vgstatus = _HasValidVG(utils.ListVolumeGroups(), self.op.vg_name)
481 efa14262 Manuel Franceschini
      if vgstatus:
482 efa14262 Manuel Franceschini
        raise errors.OpPrereqError("Error: %s\nspecify --no-lvm-storage if"
483 efa14262 Manuel Franceschini
                                   " you are not using lvm" % vgstatus)
484 a8083063 Iustin Pop
485 2872a949 Manuel Franceschini
    self.op.file_storage_dir = os.path.normpath(self.op.file_storage_dir)
486 2872a949 Manuel Franceschini
487 871705db Manuel Franceschini
    if not os.path.isabs(self.op.file_storage_dir):
488 871705db Manuel Franceschini
      raise errors.OpPrereqError("The file storage directory you have is"
489 871705db Manuel Franceschini
                                 " not an absolute path.")
490 871705db Manuel Franceschini
491 871705db Manuel Franceschini
    if not os.path.exists(self.op.file_storage_dir):
492 2872a949 Manuel Franceschini
      try:
493 2872a949 Manuel Franceschini
        os.makedirs(self.op.file_storage_dir, 0750)
494 2872a949 Manuel Franceschini
      except OSError, err:
495 2872a949 Manuel Franceschini
        raise errors.OpPrereqError("Cannot create file storage directory"
496 2872a949 Manuel Franceschini
                                   " '%s': %s" %
497 2872a949 Manuel Franceschini
                                   (self.op.file_storage_dir, err))
498 2872a949 Manuel Franceschini
499 2872a949 Manuel Franceschini
    if not os.path.isdir(self.op.file_storage_dir):
500 2872a949 Manuel Franceschini
      raise errors.OpPrereqError("The file storage directory '%s' is not"
501 2872a949 Manuel Franceschini
                                 " a directory." % self.op.file_storage_dir)
502 871705db Manuel Franceschini
503 a8083063 Iustin Pop
    if not re.match("^[0-9a-z]{2}:[0-9a-z]{2}:[0-9a-z]{2}$",
504 a8083063 Iustin Pop
                    self.op.mac_prefix):
505 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Invalid mac prefix given '%s'" %
506 3ecf6786 Iustin Pop
                                 self.op.mac_prefix)
507 a8083063 Iustin Pop
508 2584d4a4 Alexander Schreiber
    if self.op.hypervisor_type not in constants.HYPER_TYPES:
509 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Invalid hypervisor type given '%s'" %
510 3ecf6786 Iustin Pop
                                 self.op.hypervisor_type)
511 a8083063 Iustin Pop
512 880478f8 Iustin Pop
    result = utils.RunCmd(["ip", "link", "show", "dev", self.op.master_netdev])
513 880478f8 Iustin Pop
    if result.failed:
514 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Invalid master netdev given (%s): '%s'" %
515 8925faaa Iustin Pop
                                 (self.op.master_netdev,
516 8925faaa Iustin Pop
                                  result.output.strip()))
517 880478f8 Iustin Pop
518 7dd30006 Michael Hanselmann
    if not (os.path.isfile(constants.NODE_INITD_SCRIPT) and
519 7dd30006 Michael Hanselmann
            os.access(constants.NODE_INITD_SCRIPT, os.X_OK)):
520 f4bc1f2c Michael Hanselmann
      raise errors.OpPrereqError("Init.d script '%s' missing or not"
521 f4bc1f2c Michael Hanselmann
                                 " executable." % constants.NODE_INITD_SCRIPT)
522 c7b46d59 Iustin Pop
523 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
524 a8083063 Iustin Pop
    """Initialize the cluster.
525 a8083063 Iustin Pop

526 a8083063 Iustin Pop
    """
527 a8083063 Iustin Pop
    clustername = self.clustername
528 a8083063 Iustin Pop
    hostname = self.hostname
529 a8083063 Iustin Pop
530 a8083063 Iustin Pop
    # set up the simple store
531 4167825b Iustin Pop
    self.sstore = ss = ssconf.SimpleStore()
532 a8083063 Iustin Pop
    ss.SetKey(ss.SS_HYPERVISOR, self.op.hypervisor_type)
533 bcf043c9 Iustin Pop
    ss.SetKey(ss.SS_MASTER_NODE, hostname.name)
534 bcf043c9 Iustin Pop
    ss.SetKey(ss.SS_MASTER_IP, clustername.ip)
535 880478f8 Iustin Pop
    ss.SetKey(ss.SS_MASTER_NETDEV, self.op.master_netdev)
536 bcf043c9 Iustin Pop
    ss.SetKey(ss.SS_CLUSTER_NAME, clustername.name)
537 871705db Manuel Franceschini
    ss.SetKey(ss.SS_FILE_STORAGE_DIR, self.op.file_storage_dir)
538 a8083063 Iustin Pop
539 a8083063 Iustin Pop
    # set up the inter-node password and certificate
540 a8083063 Iustin Pop
    _InitGanetiServerSetup(ss)
541 a8083063 Iustin Pop
542 a8083063 Iustin Pop
    # start the master ip
543 bcf043c9 Iustin Pop
    rpc.call_node_start_master(hostname.name)
544 a8083063 Iustin Pop
545 a8083063 Iustin Pop
    # set up ssh config and /etc/hosts
546 70d9e3d8 Iustin Pop
    f = open(constants.SSH_HOST_RSA_PUB, 'r')
547 a8083063 Iustin Pop
    try:
548 a8083063 Iustin Pop
      sshline = f.read()
549 a8083063 Iustin Pop
    finally:
550 a8083063 Iustin Pop
      f.close()
551 a8083063 Iustin Pop
    sshkey = sshline.split(" ")[1]
552 a8083063 Iustin Pop
553 9440aeab Michael Hanselmann
    _AddHostToEtcHosts(hostname.name)
554 bcf043c9 Iustin Pop
    _InitSSHSetup(hostname.name)
555 a8083063 Iustin Pop
556 a8083063 Iustin Pop
    # init of cluster config file
557 4167825b Iustin Pop
    self.cfg = cfgw = config.ConfigWriter()
558 bcf043c9 Iustin Pop
    cfgw.InitConfig(hostname.name, hostname.ip, self.secondary_ip,
559 5fcdc80d Iustin Pop
                    sshkey, self.op.mac_prefix,
560 a8083063 Iustin Pop
                    self.op.vg_name, self.op.def_bridge)
561 a8083063 Iustin Pop
562 f408b346 Michael Hanselmann
    ssh.WriteKnownHostsFile(cfgw, ss, constants.SSH_KNOWN_HOSTS_FILE)
563 f408b346 Michael Hanselmann
564 a8083063 Iustin Pop
565 a8083063 Iustin Pop
class LUDestroyCluster(NoHooksLU):
566 a8083063 Iustin Pop
  """Logical unit for destroying the cluster.
567 a8083063 Iustin Pop

568 a8083063 Iustin Pop
  """
569 a8083063 Iustin Pop
  _OP_REQP = []
570 a8083063 Iustin Pop
571 a8083063 Iustin Pop
  def CheckPrereq(self):
572 a8083063 Iustin Pop
    """Check prerequisites.
573 a8083063 Iustin Pop

574 a8083063 Iustin Pop
    This checks whether the cluster is empty.
575 a8083063 Iustin Pop

576 a8083063 Iustin Pop
    Any errors are signalled by raising errors.OpPrereqError.
577 a8083063 Iustin Pop

578 a8083063 Iustin Pop
    """
579 880478f8 Iustin Pop
    master = self.sstore.GetMasterNode()
580 a8083063 Iustin Pop
581 a8083063 Iustin Pop
    nodelist = self.cfg.GetNodeList()
582 db915bd1 Michael Hanselmann
    if len(nodelist) != 1 or nodelist[0] != master:
583 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("There are still %d node(s) in"
584 3ecf6786 Iustin Pop
                                 " this cluster." % (len(nodelist) - 1))
585 db915bd1 Michael Hanselmann
    instancelist = self.cfg.GetInstanceList()
586 db915bd1 Michael Hanselmann
    if instancelist:
587 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("There are still %d instance(s) in"
588 3ecf6786 Iustin Pop
                                 " this cluster." % len(instancelist))
589 a8083063 Iustin Pop
590 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
591 a8083063 Iustin Pop
    """Destroys the cluster.
592 a8083063 Iustin Pop

593 a8083063 Iustin Pop
    """
594 c8a0948f Michael Hanselmann
    master = self.sstore.GetMasterNode()
595 c9064964 Iustin Pop
    if not rpc.call_node_stop_master(master):
596 c9064964 Iustin Pop
      raise errors.OpExecError("Could not disable the master role")
597 70d9e3d8 Iustin Pop
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
598 70d9e3d8 Iustin Pop
    utils.CreateBackup(priv_key)
599 70d9e3d8 Iustin Pop
    utils.CreateBackup(pub_key)
600 c8a0948f Michael Hanselmann
    rpc.call_node_leave_cluster(master)
601 a8083063 Iustin Pop
602 a8083063 Iustin Pop
603 a8083063 Iustin Pop
class LUVerifyCluster(NoHooksLU):
604 a8083063 Iustin Pop
  """Verifies the cluster status.
605 a8083063 Iustin Pop

606 a8083063 Iustin Pop
  """
607 e54c4c5e Guido Trotter
  _OP_REQP = ["skip_checks"]
608 a8083063 Iustin Pop
609 a8083063 Iustin Pop
  def _VerifyNode(self, node, file_list, local_cksum, vglist, node_result,
610 a8083063 Iustin Pop
                  remote_version, feedback_fn):
611 a8083063 Iustin Pop
    """Run multiple tests against a node.
612 a8083063 Iustin Pop

613 a8083063 Iustin Pop
    Test list:
614 a8083063 Iustin Pop
      - compares ganeti version
615 a8083063 Iustin Pop
      - checks vg existance and size > 20G
616 a8083063 Iustin Pop
      - checks config file checksum
617 a8083063 Iustin Pop
      - checks ssh to other nodes
618 a8083063 Iustin Pop

619 a8083063 Iustin Pop
    Args:
620 a8083063 Iustin Pop
      node: name of the node to check
621 a8083063 Iustin Pop
      file_list: required list of files
622 a8083063 Iustin Pop
      local_cksum: dictionary of local files and their checksums
623 098c0958 Michael Hanselmann

624 a8083063 Iustin Pop
    """
625 a8083063 Iustin Pop
    # compares ganeti version
626 a8083063 Iustin Pop
    local_version = constants.PROTOCOL_VERSION
627 a8083063 Iustin Pop
    if not remote_version:
628 c840ae6f Guido Trotter
      feedback_fn("  - ERROR: connection to %s failed" % (node))
629 a8083063 Iustin Pop
      return True
630 a8083063 Iustin Pop
631 a8083063 Iustin Pop
    if local_version != remote_version:
632 a8083063 Iustin Pop
      feedback_fn("  - ERROR: sw version mismatch: master %s, node(%s) %s" %
633 a8083063 Iustin Pop
                      (local_version, node, remote_version))
634 a8083063 Iustin Pop
      return True
635 a8083063 Iustin Pop
636 a8083063 Iustin Pop
    # checks vg existance and size > 20G
637 a8083063 Iustin Pop
638 a8083063 Iustin Pop
    bad = False
639 a8083063 Iustin Pop
    if not vglist:
640 a8083063 Iustin Pop
      feedback_fn("  - ERROR: unable to check volume groups on node %s." %
641 a8083063 Iustin Pop
                      (node,))
642 a8083063 Iustin Pop
      bad = True
643 a8083063 Iustin Pop
    else:
644 a8083063 Iustin Pop
      vgstatus = _HasValidVG(vglist, self.cfg.GetVGName())
645 a8083063 Iustin Pop
      if vgstatus:
646 a8083063 Iustin Pop
        feedback_fn("  - ERROR: %s on node %s" % (vgstatus, node))
647 a8083063 Iustin Pop
        bad = True
648 a8083063 Iustin Pop
649 a8083063 Iustin Pop
    # checks config file checksum
650 a8083063 Iustin Pop
    # checks ssh to any
651 a8083063 Iustin Pop
652 a8083063 Iustin Pop
    if 'filelist' not in node_result:
653 a8083063 Iustin Pop
      bad = True
654 a8083063 Iustin Pop
      feedback_fn("  - ERROR: node hasn't returned file checksum data")
655 a8083063 Iustin Pop
    else:
656 a8083063 Iustin Pop
      remote_cksum = node_result['filelist']
657 a8083063 Iustin Pop
      for file_name in file_list:
658 a8083063 Iustin Pop
        if file_name not in remote_cksum:
659 a8083063 Iustin Pop
          bad = True
660 a8083063 Iustin Pop
          feedback_fn("  - ERROR: file '%s' missing" % file_name)
661 a8083063 Iustin Pop
        elif remote_cksum[file_name] != local_cksum[file_name]:
662 a8083063 Iustin Pop
          bad = True
663 a8083063 Iustin Pop
          feedback_fn("  - ERROR: file '%s' has wrong checksum" % file_name)
664 a8083063 Iustin Pop
665 a8083063 Iustin Pop
    if 'nodelist' not in node_result:
666 a8083063 Iustin Pop
      bad = True
667 a8083063 Iustin Pop
      feedback_fn("  - ERROR: node hasn't returned node connectivity data")
668 a8083063 Iustin Pop
    else:
669 a8083063 Iustin Pop
      if node_result['nodelist']:
670 a8083063 Iustin Pop
        bad = True
671 a8083063 Iustin Pop
        for node in node_result['nodelist']:
672 a8083063 Iustin Pop
          feedback_fn("  - ERROR: communication with node '%s': %s" %
673 a8083063 Iustin Pop
                          (node, node_result['nodelist'][node]))
674 a8083063 Iustin Pop
    hyp_result = node_result.get('hypervisor', None)
675 a8083063 Iustin Pop
    if hyp_result is not None:
676 a8083063 Iustin Pop
      feedback_fn("  - ERROR: hypervisor verify failure: '%s'" % hyp_result)
677 a8083063 Iustin Pop
    return bad
678 a8083063 Iustin Pop
679 c5705f58 Guido Trotter
  def _VerifyInstance(self, instance, instanceconfig, node_vol_is,
680 c5705f58 Guido Trotter
                      node_instance, feedback_fn):
681 a8083063 Iustin Pop
    """Verify an instance.
682 a8083063 Iustin Pop

683 a8083063 Iustin Pop
    This function checks to see if the required block devices are
684 a8083063 Iustin Pop
    available on the instance's node.
685 a8083063 Iustin Pop

686 a8083063 Iustin Pop
    """
687 a8083063 Iustin Pop
    bad = False
688 a8083063 Iustin Pop
689 a8083063 Iustin Pop
    node_current = instanceconfig.primary_node
690 a8083063 Iustin Pop
691 a8083063 Iustin Pop
    node_vol_should = {}
692 a8083063 Iustin Pop
    instanceconfig.MapLVsByNode(node_vol_should)
693 a8083063 Iustin Pop
694 a8083063 Iustin Pop
    for node in node_vol_should:
695 a8083063 Iustin Pop
      for volume in node_vol_should[node]:
696 a8083063 Iustin Pop
        if node not in node_vol_is or volume not in node_vol_is[node]:
697 a8083063 Iustin Pop
          feedback_fn("  - ERROR: volume %s missing on node %s" %
698 a8083063 Iustin Pop
                          (volume, node))
699 a8083063 Iustin Pop
          bad = True
700 a8083063 Iustin Pop
701 a8083063 Iustin Pop
    if not instanceconfig.status == 'down':
702 a872dae6 Guido Trotter
      if (node_current not in node_instance or
703 a872dae6 Guido Trotter
          not instance in node_instance[node_current]):
704 a8083063 Iustin Pop
        feedback_fn("  - ERROR: instance %s not running on node %s" %
705 a8083063 Iustin Pop
                        (instance, node_current))
706 a8083063 Iustin Pop
        bad = True
707 a8083063 Iustin Pop
708 a8083063 Iustin Pop
    for node in node_instance:
709 a8083063 Iustin Pop
      if (not node == node_current):
710 a8083063 Iustin Pop
        if instance in node_instance[node]:
711 a8083063 Iustin Pop
          feedback_fn("  - ERROR: instance %s should not run on node %s" %
712 a8083063 Iustin Pop
                          (instance, node))
713 a8083063 Iustin Pop
          bad = True
714 a8083063 Iustin Pop
715 6a438c98 Michael Hanselmann
    return bad
716 a8083063 Iustin Pop
717 a8083063 Iustin Pop
  def _VerifyOrphanVolumes(self, node_vol_should, node_vol_is, feedback_fn):
718 a8083063 Iustin Pop
    """Verify if there are any unknown volumes in the cluster.
719 a8083063 Iustin Pop

720 a8083063 Iustin Pop
    The .os, .swap and backup volumes are ignored. All other volumes are
721 a8083063 Iustin Pop
    reported as unknown.
722 a8083063 Iustin Pop

723 a8083063 Iustin Pop
    """
724 a8083063 Iustin Pop
    bad = False
725 a8083063 Iustin Pop
726 a8083063 Iustin Pop
    for node in node_vol_is:
727 a8083063 Iustin Pop
      for volume in node_vol_is[node]:
728 a8083063 Iustin Pop
        if node not in node_vol_should or volume not in node_vol_should[node]:
729 a8083063 Iustin Pop
          feedback_fn("  - ERROR: volume %s on node %s should not exist" %
730 a8083063 Iustin Pop
                      (volume, node))
731 a8083063 Iustin Pop
          bad = True
732 a8083063 Iustin Pop
    return bad
733 a8083063 Iustin Pop
734 a8083063 Iustin Pop
  def _VerifyOrphanInstances(self, instancelist, node_instance, feedback_fn):
735 a8083063 Iustin Pop
    """Verify the list of running instances.
736 a8083063 Iustin Pop

737 a8083063 Iustin Pop
    This checks what instances are running but unknown to the cluster.
738 a8083063 Iustin Pop

739 a8083063 Iustin Pop
    """
740 a8083063 Iustin Pop
    bad = False
741 a8083063 Iustin Pop
    for node in node_instance:
742 a8083063 Iustin Pop
      for runninginstance in node_instance[node]:
743 a8083063 Iustin Pop
        if runninginstance not in instancelist:
744 a8083063 Iustin Pop
          feedback_fn("  - ERROR: instance %s on node %s should not exist" %
745 a8083063 Iustin Pop
                          (runninginstance, node))
746 a8083063 Iustin Pop
          bad = True
747 a8083063 Iustin Pop
    return bad
748 a8083063 Iustin Pop
749 2b3b6ddd Guido Trotter
  def _VerifyNPlusOneMemory(self, node_info, instance_cfg, feedback_fn):
750 2b3b6ddd Guido Trotter
    """Verify N+1 Memory Resilience.
751 2b3b6ddd Guido Trotter

752 2b3b6ddd Guido Trotter
    Check that if one single node dies we can still start all the instances it
753 2b3b6ddd Guido Trotter
    was primary for.
754 2b3b6ddd Guido Trotter

755 2b3b6ddd Guido Trotter
    """
756 2b3b6ddd Guido Trotter
    bad = False
757 2b3b6ddd Guido Trotter
758 2b3b6ddd Guido Trotter
    for node, nodeinfo in node_info.iteritems():
759 2b3b6ddd Guido Trotter
      # This code checks that every node which is now listed as secondary has
760 2b3b6ddd Guido Trotter
      # enough memory to host all instances it is supposed to should a single
761 2b3b6ddd Guido Trotter
      # other node in the cluster fail.
762 2b3b6ddd Guido Trotter
      # FIXME: not ready for failover to an arbitrary node
763 2b3b6ddd Guido Trotter
      # FIXME: does not support file-backed instances
764 2b3b6ddd Guido Trotter
      # WARNING: we currently take into account down instances as well as up
765 2b3b6ddd Guido Trotter
      # ones, considering that even if they're down someone might want to start
766 2b3b6ddd Guido Trotter
      # them even in the event of a node failure.
767 2b3b6ddd Guido Trotter
      for prinode, instances in nodeinfo['sinst-by-pnode'].iteritems():
768 2b3b6ddd Guido Trotter
        needed_mem = 0
769 2b3b6ddd Guido Trotter
        for instance in instances:
770 2b3b6ddd Guido Trotter
          needed_mem += instance_cfg[instance].memory
771 2b3b6ddd Guido Trotter
        if nodeinfo['mfree'] < needed_mem:
772 2b3b6ddd Guido Trotter
          feedback_fn("  - ERROR: not enough memory on node %s to accomodate"
773 2b3b6ddd Guido Trotter
                      " failovers should node %s fail" % (node, prinode))
774 2b3b6ddd Guido Trotter
          bad = True
775 2b3b6ddd Guido Trotter
    return bad
776 2b3b6ddd Guido Trotter
777 a8083063 Iustin Pop
  def CheckPrereq(self):
778 a8083063 Iustin Pop
    """Check prerequisites.
779 a8083063 Iustin Pop

780 e54c4c5e Guido Trotter
    Transform the list of checks we're going to skip into a set and check that
781 e54c4c5e Guido Trotter
    all its members are valid.
782 a8083063 Iustin Pop

783 a8083063 Iustin Pop
    """
784 e54c4c5e Guido Trotter
    self.skip_set = frozenset(self.op.skip_checks)
785 e54c4c5e Guido Trotter
    if not constants.VERIFY_OPTIONAL_CHECKS.issuperset(self.skip_set):
786 e54c4c5e Guido Trotter
      raise errors.OpPrereqError("Invalid checks to be skipped specified")
787 a8083063 Iustin Pop
788 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
789 a8083063 Iustin Pop
    """Verify integrity of cluster, performing various test on nodes.
790 a8083063 Iustin Pop

791 a8083063 Iustin Pop
    """
792 a8083063 Iustin Pop
    bad = False
793 a8083063 Iustin Pop
    feedback_fn("* Verifying global settings")
794 8522ceeb Iustin Pop
    for msg in self.cfg.VerifyConfig():
795 8522ceeb Iustin Pop
      feedback_fn("  - ERROR: %s" % msg)
796 a8083063 Iustin Pop
797 a8083063 Iustin Pop
    vg_name = self.cfg.GetVGName()
798 a8083063 Iustin Pop
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
799 a8083063 Iustin Pop
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
800 93e4c50b Guido Trotter
    i_non_redundant = [] # Non redundant instances
801 a8083063 Iustin Pop
    node_volume = {}
802 a8083063 Iustin Pop
    node_instance = {}
803 9c9c7d30 Guido Trotter
    node_info = {}
804 26b6af5e Guido Trotter
    instance_cfg = {}
805 a8083063 Iustin Pop
806 a8083063 Iustin Pop
    # FIXME: verify OS list
807 a8083063 Iustin Pop
    # do local checksums
808 cb91d46e Iustin Pop
    file_names = list(self.sstore.GetFileList())
809 cb91d46e Iustin Pop
    file_names.append(constants.SSL_CERT_FILE)
810 cb91d46e Iustin Pop
    file_names.append(constants.CLUSTER_CONF_FILE)
811 a8083063 Iustin Pop
    local_checksums = utils.FingerprintFiles(file_names)
812 a8083063 Iustin Pop
813 a8083063 Iustin Pop
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
814 a8083063 Iustin Pop
    all_volumeinfo = rpc.call_volume_list(nodelist, vg_name)
815 a8083063 Iustin Pop
    all_instanceinfo = rpc.call_instance_list(nodelist)
816 a8083063 Iustin Pop
    all_vglist = rpc.call_vg_list(nodelist)
817 a8083063 Iustin Pop
    node_verify_param = {
818 a8083063 Iustin Pop
      'filelist': file_names,
819 a8083063 Iustin Pop
      'nodelist': nodelist,
820 a8083063 Iustin Pop
      'hypervisor': None,
821 a8083063 Iustin Pop
      }
822 a8083063 Iustin Pop
    all_nvinfo = rpc.call_node_verify(nodelist, node_verify_param)
823 a8083063 Iustin Pop
    all_rversion = rpc.call_version(nodelist)
824 9c9c7d30 Guido Trotter
    all_ninfo = rpc.call_node_info(nodelist, self.cfg.GetVGName())
825 a8083063 Iustin Pop
826 a8083063 Iustin Pop
    for node in nodelist:
827 a8083063 Iustin Pop
      feedback_fn("* Verifying node %s" % node)
828 a8083063 Iustin Pop
      result = self._VerifyNode(node, file_names, local_checksums,
829 a8083063 Iustin Pop
                                all_vglist[node], all_nvinfo[node],
830 a8083063 Iustin Pop
                                all_rversion[node], feedback_fn)
831 a8083063 Iustin Pop
      bad = bad or result
832 a8083063 Iustin Pop
833 a8083063 Iustin Pop
      # node_volume
834 a8083063 Iustin Pop
      volumeinfo = all_volumeinfo[node]
835 a8083063 Iustin Pop
836 b63ed789 Iustin Pop
      if isinstance(volumeinfo, basestring):
837 b63ed789 Iustin Pop
        feedback_fn("  - ERROR: LVM problem on node %s: %s" %
838 b63ed789 Iustin Pop
                    (node, volumeinfo[-400:].encode('string_escape')))
839 b63ed789 Iustin Pop
        bad = True
840 b63ed789 Iustin Pop
        node_volume[node] = {}
841 b63ed789 Iustin Pop
      elif not isinstance(volumeinfo, dict):
842 a8083063 Iustin Pop
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
843 a8083063 Iustin Pop
        bad = True
844 a8083063 Iustin Pop
        continue
845 b63ed789 Iustin Pop
      else:
846 b63ed789 Iustin Pop
        node_volume[node] = volumeinfo
847 a8083063 Iustin Pop
848 a8083063 Iustin Pop
      # node_instance
849 a8083063 Iustin Pop
      nodeinstance = all_instanceinfo[node]
850 a8083063 Iustin Pop
      if type(nodeinstance) != list:
851 a8083063 Iustin Pop
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
852 a8083063 Iustin Pop
        bad = True
853 a8083063 Iustin Pop
        continue
854 a8083063 Iustin Pop
855 a8083063 Iustin Pop
      node_instance[node] = nodeinstance
856 a8083063 Iustin Pop
857 9c9c7d30 Guido Trotter
      # node_info
858 9c9c7d30 Guido Trotter
      nodeinfo = all_ninfo[node]
859 9c9c7d30 Guido Trotter
      if not isinstance(nodeinfo, dict):
860 9c9c7d30 Guido Trotter
        feedback_fn("  - ERROR: connection to %s failed" % (node,))
861 9c9c7d30 Guido Trotter
        bad = True
862 9c9c7d30 Guido Trotter
        continue
863 9c9c7d30 Guido Trotter
864 9c9c7d30 Guido Trotter
      try:
865 9c9c7d30 Guido Trotter
        node_info[node] = {
866 9c9c7d30 Guido Trotter
          "mfree": int(nodeinfo['memory_free']),
867 9c9c7d30 Guido Trotter
          "dfree": int(nodeinfo['vg_free']),
868 93e4c50b Guido Trotter
          "pinst": [],
869 93e4c50b Guido Trotter
          "sinst": [],
870 36e7da50 Guido Trotter
          # dictionary holding all instances this node is secondary for,
871 36e7da50 Guido Trotter
          # grouped by their primary node. Each key is a cluster node, and each
872 36e7da50 Guido Trotter
          # value is a list of instances which have the key as primary and the
873 36e7da50 Guido Trotter
          # current node as secondary.  this is handy to calculate N+1 memory
874 36e7da50 Guido Trotter
          # availability if you can only failover from a primary to its
875 36e7da50 Guido Trotter
          # secondary.
876 36e7da50 Guido Trotter
          "sinst-by-pnode": {},
877 9c9c7d30 Guido Trotter
        }
878 9c9c7d30 Guido Trotter
      except ValueError:
879 9c9c7d30 Guido Trotter
        feedback_fn("  - ERROR: invalid value returned from node %s" % (node,))
880 9c9c7d30 Guido Trotter
        bad = True
881 9c9c7d30 Guido Trotter
        continue
882 9c9c7d30 Guido Trotter
883 a8083063 Iustin Pop
    node_vol_should = {}
884 a8083063 Iustin Pop
885 a8083063 Iustin Pop
    for instance in instancelist:
886 a8083063 Iustin Pop
      feedback_fn("* Verifying instance %s" % instance)
887 a8083063 Iustin Pop
      inst_config = self.cfg.GetInstanceInfo(instance)
888 c5705f58 Guido Trotter
      result =  self._VerifyInstance(instance, inst_config, node_volume,
889 c5705f58 Guido Trotter
                                     node_instance, feedback_fn)
890 c5705f58 Guido Trotter
      bad = bad or result
891 a8083063 Iustin Pop
892 a8083063 Iustin Pop
      inst_config.MapLVsByNode(node_vol_should)
893 a8083063 Iustin Pop
894 26b6af5e Guido Trotter
      instance_cfg[instance] = inst_config
895 26b6af5e Guido Trotter
896 93e4c50b Guido Trotter
      pnode = inst_config.primary_node
897 93e4c50b Guido Trotter
      if pnode in node_info:
898 93e4c50b Guido Trotter
        node_info[pnode]['pinst'].append(instance)
899 93e4c50b Guido Trotter
      else:
900 93e4c50b Guido Trotter
        feedback_fn("  - ERROR: instance %s, connection to primary node"
901 93e4c50b Guido Trotter
                    " %s failed" % (instance, pnode))
902 93e4c50b Guido Trotter
        bad = True
903 93e4c50b Guido Trotter
904 93e4c50b Guido Trotter
      # If the instance is non-redundant we cannot survive losing its primary
905 93e4c50b Guido Trotter
      # node, so we are not N+1 compliant. On the other hand we have no disk
906 93e4c50b Guido Trotter
      # templates with more than one secondary so that situation is not well
907 93e4c50b Guido Trotter
      # supported either.
908 93e4c50b Guido Trotter
      # FIXME: does not support file-backed instances
909 93e4c50b Guido Trotter
      if len(inst_config.secondary_nodes) == 0:
910 93e4c50b Guido Trotter
        i_non_redundant.append(instance)
911 93e4c50b Guido Trotter
      elif len(inst_config.secondary_nodes) > 1:
912 93e4c50b Guido Trotter
        feedback_fn("  - WARNING: multiple secondaries for instance %s"
913 93e4c50b Guido Trotter
                    % instance)
914 93e4c50b Guido Trotter
915 93e4c50b Guido Trotter
      for snode in inst_config.secondary_nodes:
916 93e4c50b Guido Trotter
        if snode in node_info:
917 93e4c50b Guido Trotter
          node_info[snode]['sinst'].append(instance)
918 36e7da50 Guido Trotter
          if pnode not in node_info[snode]['sinst-by-pnode']:
919 36e7da50 Guido Trotter
            node_info[snode]['sinst-by-pnode'][pnode] = []
920 36e7da50 Guido Trotter
          node_info[snode]['sinst-by-pnode'][pnode].append(instance)
921 93e4c50b Guido Trotter
        else:
922 93e4c50b Guido Trotter
          feedback_fn("  - ERROR: instance %s, connection to secondary node"
923 93e4c50b Guido Trotter
                      " %s failed" % (instance, snode))
924 93e4c50b Guido Trotter
925 a8083063 Iustin Pop
    feedback_fn("* Verifying orphan volumes")
926 a8083063 Iustin Pop
    result = self._VerifyOrphanVolumes(node_vol_should, node_volume,
927 a8083063 Iustin Pop
                                       feedback_fn)
928 a8083063 Iustin Pop
    bad = bad or result
929 a8083063 Iustin Pop
930 a8083063 Iustin Pop
    feedback_fn("* Verifying remaining instances")
931 a8083063 Iustin Pop
    result = self._VerifyOrphanInstances(instancelist, node_instance,
932 a8083063 Iustin Pop
                                         feedback_fn)
933 a8083063 Iustin Pop
    bad = bad or result
934 a8083063 Iustin Pop
935 e54c4c5e Guido Trotter
    if constants.VERIFY_NPLUSONE_MEM not in self.skip_set:
936 e54c4c5e Guido Trotter
      feedback_fn("* Verifying N+1 Memory redundancy")
937 e54c4c5e Guido Trotter
      result = self._VerifyNPlusOneMemory(node_info, instance_cfg, feedback_fn)
938 e54c4c5e Guido Trotter
      bad = bad or result
939 2b3b6ddd Guido Trotter
940 2b3b6ddd Guido Trotter
    feedback_fn("* Other Notes")
941 2b3b6ddd Guido Trotter
    if i_non_redundant:
942 2b3b6ddd Guido Trotter
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
943 2b3b6ddd Guido Trotter
                  % len(i_non_redundant))
944 2b3b6ddd Guido Trotter
945 a8083063 Iustin Pop
    return int(bad)
946 a8083063 Iustin Pop
947 a8083063 Iustin Pop
948 2c95a8d4 Iustin Pop
class LUVerifyDisks(NoHooksLU):
949 2c95a8d4 Iustin Pop
  """Verifies the cluster disks status.
950 2c95a8d4 Iustin Pop

951 2c95a8d4 Iustin Pop
  """
952 2c95a8d4 Iustin Pop
  _OP_REQP = []
953 2c95a8d4 Iustin Pop
954 2c95a8d4 Iustin Pop
  def CheckPrereq(self):
955 2c95a8d4 Iustin Pop
    """Check prerequisites.
956 2c95a8d4 Iustin Pop

957 2c95a8d4 Iustin Pop
    This has no prerequisites.
958 2c95a8d4 Iustin Pop

959 2c95a8d4 Iustin Pop
    """
960 2c95a8d4 Iustin Pop
    pass
961 2c95a8d4 Iustin Pop
962 2c95a8d4 Iustin Pop
  def Exec(self, feedback_fn):
963 2c95a8d4 Iustin Pop
    """Verify integrity of cluster disks.
964 2c95a8d4 Iustin Pop

965 2c95a8d4 Iustin Pop
    """
966 b63ed789 Iustin Pop
    result = res_nodes, res_nlvm, res_instances, res_missing = [], {}, [], {}
967 2c95a8d4 Iustin Pop
968 2c95a8d4 Iustin Pop
    vg_name = self.cfg.GetVGName()
969 2c95a8d4 Iustin Pop
    nodes = utils.NiceSort(self.cfg.GetNodeList())
970 2c95a8d4 Iustin Pop
    instances = [self.cfg.GetInstanceInfo(name)
971 2c95a8d4 Iustin Pop
                 for name in self.cfg.GetInstanceList()]
972 2c95a8d4 Iustin Pop
973 2c95a8d4 Iustin Pop
    nv_dict = {}
974 2c95a8d4 Iustin Pop
    for inst in instances:
975 2c95a8d4 Iustin Pop
      inst_lvs = {}
976 2c95a8d4 Iustin Pop
      if (inst.status != "up" or
977 2c95a8d4 Iustin Pop
          inst.disk_template not in constants.DTS_NET_MIRROR):
978 2c95a8d4 Iustin Pop
        continue
979 2c95a8d4 Iustin Pop
      inst.MapLVsByNode(inst_lvs)
980 2c95a8d4 Iustin Pop
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
981 2c95a8d4 Iustin Pop
      for node, vol_list in inst_lvs.iteritems():
982 2c95a8d4 Iustin Pop
        for vol in vol_list:
983 2c95a8d4 Iustin Pop
          nv_dict[(node, vol)] = inst
984 2c95a8d4 Iustin Pop
985 2c95a8d4 Iustin Pop
    if not nv_dict:
986 2c95a8d4 Iustin Pop
      return result
987 2c95a8d4 Iustin Pop
988 2c95a8d4 Iustin Pop
    node_lvs = rpc.call_volume_list(nodes, vg_name)
989 2c95a8d4 Iustin Pop
990 2c95a8d4 Iustin Pop
    to_act = set()
991 2c95a8d4 Iustin Pop
    for node in nodes:
992 2c95a8d4 Iustin Pop
      # node_volume
993 2c95a8d4 Iustin Pop
      lvs = node_lvs[node]
994 2c95a8d4 Iustin Pop
995 b63ed789 Iustin Pop
      if isinstance(lvs, basestring):
996 b63ed789 Iustin Pop
        logger.Info("error enumerating LVs on node %s: %s" % (node, lvs))
997 b63ed789 Iustin Pop
        res_nlvm[node] = lvs
998 b63ed789 Iustin Pop
      elif not isinstance(lvs, dict):
999 2c95a8d4 Iustin Pop
        logger.Info("connection to node %s failed or invalid data returned" %
1000 2c95a8d4 Iustin Pop
                    (node,))
1001 2c95a8d4 Iustin Pop
        res_nodes.append(node)
1002 2c95a8d4 Iustin Pop
        continue
1003 2c95a8d4 Iustin Pop
1004 2c95a8d4 Iustin Pop
      for lv_name, (_, lv_inactive, lv_online) in lvs.iteritems():
1005 b63ed789 Iustin Pop
        inst = nv_dict.pop((node, lv_name), None)
1006 b63ed789 Iustin Pop
        if (not lv_online and inst is not None
1007 b63ed789 Iustin Pop
            and inst.name not in res_instances):
1008 b08d5a87 Iustin Pop
          res_instances.append(inst.name)
1009 2c95a8d4 Iustin Pop
1010 b63ed789 Iustin Pop
    # any leftover items in nv_dict are missing LVs, let's arrange the
1011 b63ed789 Iustin Pop
    # data better
1012 b63ed789 Iustin Pop
    for key, inst in nv_dict.iteritems():
1013 b63ed789 Iustin Pop
      if inst.name not in res_missing:
1014 b63ed789 Iustin Pop
        res_missing[inst.name] = []
1015 b63ed789 Iustin Pop
      res_missing[inst.name].append(key)
1016 b63ed789 Iustin Pop
1017 2c95a8d4 Iustin Pop
    return result
1018 2c95a8d4 Iustin Pop
1019 2c95a8d4 Iustin Pop
1020 07bd8a51 Iustin Pop
class LURenameCluster(LogicalUnit):
1021 07bd8a51 Iustin Pop
  """Rename the cluster.
1022 07bd8a51 Iustin Pop

1023 07bd8a51 Iustin Pop
  """
1024 07bd8a51 Iustin Pop
  HPATH = "cluster-rename"
1025 07bd8a51 Iustin Pop
  HTYPE = constants.HTYPE_CLUSTER
1026 07bd8a51 Iustin Pop
  _OP_REQP = ["name"]
1027 07bd8a51 Iustin Pop
1028 07bd8a51 Iustin Pop
  def BuildHooksEnv(self):
1029 07bd8a51 Iustin Pop
    """Build hooks env.
1030 07bd8a51 Iustin Pop

1031 07bd8a51 Iustin Pop
    """
1032 07bd8a51 Iustin Pop
    env = {
1033 488b540d Iustin Pop
      "OP_TARGET": self.sstore.GetClusterName(),
1034 07bd8a51 Iustin Pop
      "NEW_NAME": self.op.name,
1035 07bd8a51 Iustin Pop
      }
1036 07bd8a51 Iustin Pop
    mn = self.sstore.GetMasterNode()
1037 07bd8a51 Iustin Pop
    return env, [mn], [mn]
1038 07bd8a51 Iustin Pop
1039 07bd8a51 Iustin Pop
  def CheckPrereq(self):
1040 07bd8a51 Iustin Pop
    """Verify that the passed name is a valid one.
1041 07bd8a51 Iustin Pop

1042 07bd8a51 Iustin Pop
    """
1043 89e1fc26 Iustin Pop
    hostname = utils.HostInfo(self.op.name)
1044 07bd8a51 Iustin Pop
1045 bcf043c9 Iustin Pop
    new_name = hostname.name
1046 bcf043c9 Iustin Pop
    self.ip = new_ip = hostname.ip
1047 07bd8a51 Iustin Pop
    old_name = self.sstore.GetClusterName()
1048 07bd8a51 Iustin Pop
    old_ip = self.sstore.GetMasterIP()
1049 07bd8a51 Iustin Pop
    if new_name == old_name and new_ip == old_ip:
1050 07bd8a51 Iustin Pop
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
1051 07bd8a51 Iustin Pop
                                 " cluster has changed")
1052 07bd8a51 Iustin Pop
    if new_ip != old_ip:
1053 07bd8a51 Iustin Pop
      result = utils.RunCmd(["fping", "-q", new_ip])
1054 07bd8a51 Iustin Pop
      if not result.failed:
1055 07bd8a51 Iustin Pop
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
1056 07bd8a51 Iustin Pop
                                   " reachable on the network. Aborting." %
1057 07bd8a51 Iustin Pop
                                   new_ip)
1058 07bd8a51 Iustin Pop
1059 07bd8a51 Iustin Pop
    self.op.name = new_name
1060 07bd8a51 Iustin Pop
1061 07bd8a51 Iustin Pop
  def Exec(self, feedback_fn):
1062 07bd8a51 Iustin Pop
    """Rename the cluster.
1063 07bd8a51 Iustin Pop

1064 07bd8a51 Iustin Pop
    """
1065 07bd8a51 Iustin Pop
    clustername = self.op.name
1066 07bd8a51 Iustin Pop
    ip = self.ip
1067 07bd8a51 Iustin Pop
    ss = self.sstore
1068 07bd8a51 Iustin Pop
1069 07bd8a51 Iustin Pop
    # shutdown the master IP
1070 07bd8a51 Iustin Pop
    master = ss.GetMasterNode()
1071 07bd8a51 Iustin Pop
    if not rpc.call_node_stop_master(master):
1072 07bd8a51 Iustin Pop
      raise errors.OpExecError("Could not disable the master role")
1073 07bd8a51 Iustin Pop
1074 07bd8a51 Iustin Pop
    try:
1075 07bd8a51 Iustin Pop
      # modify the sstore
1076 07bd8a51 Iustin Pop
      ss.SetKey(ss.SS_MASTER_IP, ip)
1077 07bd8a51 Iustin Pop
      ss.SetKey(ss.SS_CLUSTER_NAME, clustername)
1078 07bd8a51 Iustin Pop
1079 07bd8a51 Iustin Pop
      # Distribute updated ss config to all nodes
1080 07bd8a51 Iustin Pop
      myself = self.cfg.GetNodeInfo(master)
1081 07bd8a51 Iustin Pop
      dist_nodes = self.cfg.GetNodeList()
1082 07bd8a51 Iustin Pop
      if myself.name in dist_nodes:
1083 07bd8a51 Iustin Pop
        dist_nodes.remove(myself.name)
1084 07bd8a51 Iustin Pop
1085 07bd8a51 Iustin Pop
      logger.Debug("Copying updated ssconf data to all nodes")
1086 07bd8a51 Iustin Pop
      for keyname in [ss.SS_CLUSTER_NAME, ss.SS_MASTER_IP]:
1087 07bd8a51 Iustin Pop
        fname = ss.KeyToFilename(keyname)
1088 07bd8a51 Iustin Pop
        result = rpc.call_upload_file(dist_nodes, fname)
1089 07bd8a51 Iustin Pop
        for to_node in dist_nodes:
1090 07bd8a51 Iustin Pop
          if not result[to_node]:
1091 07bd8a51 Iustin Pop
            logger.Error("copy of file %s to node %s failed" %
1092 07bd8a51 Iustin Pop
                         (fname, to_node))
1093 07bd8a51 Iustin Pop
    finally:
1094 07bd8a51 Iustin Pop
      if not rpc.call_node_start_master(master):
1095 f4bc1f2c Michael Hanselmann
        logger.Error("Could not re-enable the master role on the master,"
1096 f4bc1f2c Michael Hanselmann
                     " please restart manually.")
1097 07bd8a51 Iustin Pop
1098 07bd8a51 Iustin Pop
1099 8084f9f6 Manuel Franceschini
def _RecursiveCheckIfLVMBased(disk):
1100 8084f9f6 Manuel Franceschini
  """Check if the given disk or its children are lvm-based.
1101 8084f9f6 Manuel Franceschini

1102 8084f9f6 Manuel Franceschini
  Args:
1103 8084f9f6 Manuel Franceschini
    disk: ganeti.objects.Disk object
1104 8084f9f6 Manuel Franceschini

1105 8084f9f6 Manuel Franceschini
  Returns:
1106 8084f9f6 Manuel Franceschini
    boolean indicating whether a LD_LV dev_type was found or not
1107 8084f9f6 Manuel Franceschini

1108 8084f9f6 Manuel Franceschini
  """
1109 8084f9f6 Manuel Franceschini
  if disk.children:
1110 8084f9f6 Manuel Franceschini
    for chdisk in disk.children:
1111 8084f9f6 Manuel Franceschini
      if _RecursiveCheckIfLVMBased(chdisk):
1112 8084f9f6 Manuel Franceschini
        return True
1113 8084f9f6 Manuel Franceschini
  return disk.dev_type == constants.LD_LV
1114 8084f9f6 Manuel Franceschini
1115 8084f9f6 Manuel Franceschini
1116 8084f9f6 Manuel Franceschini
class LUSetClusterParams(LogicalUnit):
1117 8084f9f6 Manuel Franceschini
  """Change the parameters of the cluster.
1118 8084f9f6 Manuel Franceschini

1119 8084f9f6 Manuel Franceschini
  """
1120 8084f9f6 Manuel Franceschini
  HPATH = "cluster-modify"
1121 8084f9f6 Manuel Franceschini
  HTYPE = constants.HTYPE_CLUSTER
1122 8084f9f6 Manuel Franceschini
  _OP_REQP = []
1123 8084f9f6 Manuel Franceschini
1124 8084f9f6 Manuel Franceschini
  def BuildHooksEnv(self):
1125 8084f9f6 Manuel Franceschini
    """Build hooks env.
1126 8084f9f6 Manuel Franceschini

1127 8084f9f6 Manuel Franceschini
    """
1128 8084f9f6 Manuel Franceschini
    env = {
1129 8084f9f6 Manuel Franceschini
      "OP_TARGET": self.sstore.GetClusterName(),
1130 8084f9f6 Manuel Franceschini
      "NEW_VG_NAME": self.op.vg_name,
1131 8084f9f6 Manuel Franceschini
      }
1132 8084f9f6 Manuel Franceschini
    mn = self.sstore.GetMasterNode()
1133 8084f9f6 Manuel Franceschini
    return env, [mn], [mn]
1134 8084f9f6 Manuel Franceschini
1135 8084f9f6 Manuel Franceschini
  def CheckPrereq(self):
1136 8084f9f6 Manuel Franceschini
    """Check prerequisites.
1137 8084f9f6 Manuel Franceschini

1138 8084f9f6 Manuel Franceschini
    This checks whether the given params don't conflict and
1139 5f83e263 Iustin Pop
    if the given volume group is valid.
1140 8084f9f6 Manuel Franceschini

1141 8084f9f6 Manuel Franceschini
    """
1142 8084f9f6 Manuel Franceschini
    if not self.op.vg_name:
1143 8084f9f6 Manuel Franceschini
      instances = [self.cfg.GetInstanceInfo(name)
1144 8084f9f6 Manuel Franceschini
                   for name in self.cfg.GetInstanceList()]
1145 8084f9f6 Manuel Franceschini
      for inst in instances:
1146 8084f9f6 Manuel Franceschini
        for disk in inst.disks:
1147 8084f9f6 Manuel Franceschini
          if _RecursiveCheckIfLVMBased(disk):
1148 8084f9f6 Manuel Franceschini
            raise errors.OpPrereqError("Cannot disable lvm storage while"
1149 8084f9f6 Manuel Franceschini
                                       " lvm-based instances exist")
1150 8084f9f6 Manuel Franceschini
1151 8084f9f6 Manuel Franceschini
    # if vg_name not None, checks given volume group on all nodes
1152 8084f9f6 Manuel Franceschini
    if self.op.vg_name:
1153 8084f9f6 Manuel Franceschini
      node_list = self.cfg.GetNodeList()
1154 8084f9f6 Manuel Franceschini
      vglist = rpc.call_vg_list(node_list)
1155 8084f9f6 Manuel Franceschini
      for node in node_list:
1156 8084f9f6 Manuel Franceschini
        vgstatus = _HasValidVG(vglist[node], self.op.vg_name)
1157 8084f9f6 Manuel Franceschini
        if vgstatus:
1158 8084f9f6 Manuel Franceschini
          raise errors.OpPrereqError("Error on node '%s': %s" %
1159 8084f9f6 Manuel Franceschini
                                     (node, vgstatus))
1160 8084f9f6 Manuel Franceschini
1161 8084f9f6 Manuel Franceschini
  def Exec(self, feedback_fn):
1162 8084f9f6 Manuel Franceschini
    """Change the parameters of the cluster.
1163 8084f9f6 Manuel Franceschini

1164 8084f9f6 Manuel Franceschini
    """
1165 8084f9f6 Manuel Franceschini
    if self.op.vg_name != self.cfg.GetVGName():
1166 8084f9f6 Manuel Franceschini
      self.cfg.SetVGName(self.op.vg_name)
1167 8084f9f6 Manuel Franceschini
    else:
1168 8084f9f6 Manuel Franceschini
      feedback_fn("Cluster LVM configuration already in desired"
1169 8084f9f6 Manuel Franceschini
                  " state, not changing")
1170 8084f9f6 Manuel Franceschini
1171 8084f9f6 Manuel Franceschini
1172 5bfac263 Iustin Pop
def _WaitForSync(cfgw, instance, proc, oneshot=False, unlock=False):
1173 a8083063 Iustin Pop
  """Sleep and poll for an instance's disk to sync.
1174 a8083063 Iustin Pop

1175 a8083063 Iustin Pop
  """
1176 a8083063 Iustin Pop
  if not instance.disks:
1177 a8083063 Iustin Pop
    return True
1178 a8083063 Iustin Pop
1179 a8083063 Iustin Pop
  if not oneshot:
1180 5bfac263 Iustin Pop
    proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
1181 a8083063 Iustin Pop
1182 a8083063 Iustin Pop
  node = instance.primary_node
1183 a8083063 Iustin Pop
1184 a8083063 Iustin Pop
  for dev in instance.disks:
1185 a8083063 Iustin Pop
    cfgw.SetDiskID(dev, node)
1186 a8083063 Iustin Pop
1187 a8083063 Iustin Pop
  retries = 0
1188 a8083063 Iustin Pop
  while True:
1189 a8083063 Iustin Pop
    max_time = 0
1190 a8083063 Iustin Pop
    done = True
1191 a8083063 Iustin Pop
    cumul_degraded = False
1192 a8083063 Iustin Pop
    rstats = rpc.call_blockdev_getmirrorstatus(node, instance.disks)
1193 a8083063 Iustin Pop
    if not rstats:
1194 5bfac263 Iustin Pop
      proc.LogWarning("Can't get any data from node %s" % node)
1195 a8083063 Iustin Pop
      retries += 1
1196 a8083063 Iustin Pop
      if retries >= 10:
1197 3ecf6786 Iustin Pop
        raise errors.RemoteError("Can't contact node %s for mirror data,"
1198 3ecf6786 Iustin Pop
                                 " aborting." % node)
1199 a8083063 Iustin Pop
      time.sleep(6)
1200 a8083063 Iustin Pop
      continue
1201 a8083063 Iustin Pop
    retries = 0
1202 a8083063 Iustin Pop
    for i in range(len(rstats)):
1203 a8083063 Iustin Pop
      mstat = rstats[i]
1204 a8083063 Iustin Pop
      if mstat is None:
1205 5bfac263 Iustin Pop
        proc.LogWarning("Can't compute data for node %s/%s" %
1206 a8083063 Iustin Pop
                        (node, instance.disks[i].iv_name))
1207 a8083063 Iustin Pop
        continue
1208 0834c866 Iustin Pop
      # we ignore the ldisk parameter
1209 0834c866 Iustin Pop
      perc_done, est_time, is_degraded, _ = mstat
1210 a8083063 Iustin Pop
      cumul_degraded = cumul_degraded or (is_degraded and perc_done is None)
1211 a8083063 Iustin Pop
      if perc_done is not None:
1212 a8083063 Iustin Pop
        done = False
1213 a8083063 Iustin Pop
        if est_time is not None:
1214 a8083063 Iustin Pop
          rem_time = "%d estimated seconds remaining" % est_time
1215 a8083063 Iustin Pop
          max_time = est_time
1216 a8083063 Iustin Pop
        else:
1217 a8083063 Iustin Pop
          rem_time = "no time estimate"
1218 5bfac263 Iustin Pop
        proc.LogInfo("- device %s: %5.2f%% done, %s" %
1219 5bfac263 Iustin Pop
                     (instance.disks[i].iv_name, perc_done, rem_time))
1220 a8083063 Iustin Pop
    if done or oneshot:
1221 a8083063 Iustin Pop
      break
1222 a8083063 Iustin Pop
1223 a8083063 Iustin Pop
    if unlock:
1224 a8083063 Iustin Pop
      utils.Unlock('cmd')
1225 a8083063 Iustin Pop
    try:
1226 a8083063 Iustin Pop
      time.sleep(min(60, max_time))
1227 a8083063 Iustin Pop
    finally:
1228 a8083063 Iustin Pop
      if unlock:
1229 a8083063 Iustin Pop
        utils.Lock('cmd')
1230 a8083063 Iustin Pop
1231 a8083063 Iustin Pop
  if done:
1232 5bfac263 Iustin Pop
    proc.LogInfo("Instance %s's disks are in sync." % instance.name)
1233 a8083063 Iustin Pop
  return not cumul_degraded
1234 a8083063 Iustin Pop
1235 a8083063 Iustin Pop
1236 0834c866 Iustin Pop
def _CheckDiskConsistency(cfgw, dev, node, on_primary, ldisk=False):
1237 a8083063 Iustin Pop
  """Check that mirrors are not degraded.
1238 a8083063 Iustin Pop

1239 0834c866 Iustin Pop
  The ldisk parameter, if True, will change the test from the
1240 0834c866 Iustin Pop
  is_degraded attribute (which represents overall non-ok status for
1241 0834c866 Iustin Pop
  the device(s)) to the ldisk (representing the local storage status).
1242 0834c866 Iustin Pop

1243 a8083063 Iustin Pop
  """
1244 a8083063 Iustin Pop
  cfgw.SetDiskID(dev, node)
1245 0834c866 Iustin Pop
  if ldisk:
1246 0834c866 Iustin Pop
    idx = 6
1247 0834c866 Iustin Pop
  else:
1248 0834c866 Iustin Pop
    idx = 5
1249 a8083063 Iustin Pop
1250 a8083063 Iustin Pop
  result = True
1251 a8083063 Iustin Pop
  if on_primary or dev.AssembleOnSecondary():
1252 a8083063 Iustin Pop
    rstats = rpc.call_blockdev_find(node, dev)
1253 a8083063 Iustin Pop
    if not rstats:
1254 aa9d0c32 Guido Trotter
      logger.ToStderr("Node %s: Disk degraded, not found or node down" % node)
1255 a8083063 Iustin Pop
      result = False
1256 a8083063 Iustin Pop
    else:
1257 0834c866 Iustin Pop
      result = result and (not rstats[idx])
1258 a8083063 Iustin Pop
  if dev.children:
1259 a8083063 Iustin Pop
    for child in dev.children:
1260 a8083063 Iustin Pop
      result = result and _CheckDiskConsistency(cfgw, child, node, on_primary)
1261 a8083063 Iustin Pop
1262 a8083063 Iustin Pop
  return result
1263 a8083063 Iustin Pop
1264 a8083063 Iustin Pop
1265 a8083063 Iustin Pop
class LUDiagnoseOS(NoHooksLU):
1266 a8083063 Iustin Pop
  """Logical unit for OS diagnose/query.
1267 a8083063 Iustin Pop

1268 a8083063 Iustin Pop
  """
1269 1f9430d6 Iustin Pop
  _OP_REQP = ["output_fields", "names"]
1270 a8083063 Iustin Pop
1271 a8083063 Iustin Pop
  def CheckPrereq(self):
1272 a8083063 Iustin Pop
    """Check prerequisites.
1273 a8083063 Iustin Pop

1274 a8083063 Iustin Pop
    This always succeeds, since this is a pure query LU.
1275 a8083063 Iustin Pop

1276 a8083063 Iustin Pop
    """
1277 1f9430d6 Iustin Pop
    if self.op.names:
1278 1f9430d6 Iustin Pop
      raise errors.OpPrereqError("Selective OS query not supported")
1279 1f9430d6 Iustin Pop
1280 1f9430d6 Iustin Pop
    self.dynamic_fields = frozenset(["name", "valid", "node_status"])
1281 1f9430d6 Iustin Pop
    _CheckOutputFields(static=[],
1282 1f9430d6 Iustin Pop
                       dynamic=self.dynamic_fields,
1283 1f9430d6 Iustin Pop
                       selected=self.op.output_fields)
1284 1f9430d6 Iustin Pop
1285 1f9430d6 Iustin Pop
  @staticmethod
1286 1f9430d6 Iustin Pop
  def _DiagnoseByOS(node_list, rlist):
1287 1f9430d6 Iustin Pop
    """Remaps a per-node return list into an a per-os per-node dictionary
1288 1f9430d6 Iustin Pop

1289 1f9430d6 Iustin Pop
      Args:
1290 1f9430d6 Iustin Pop
        node_list: a list with the names of all nodes
1291 1f9430d6 Iustin Pop
        rlist: a map with node names as keys and OS objects as values
1292 1f9430d6 Iustin Pop

1293 1f9430d6 Iustin Pop
      Returns:
1294 1f9430d6 Iustin Pop
        map: a map with osnames as keys and as value another map, with
1295 1f9430d6 Iustin Pop
             nodes as
1296 1f9430d6 Iustin Pop
             keys and list of OS objects as values
1297 1f9430d6 Iustin Pop
             e.g. {"debian-etch": {"node1": [<object>,...],
1298 1f9430d6 Iustin Pop
                                   "node2": [<object>,]}
1299 1f9430d6 Iustin Pop
                  }
1300 1f9430d6 Iustin Pop

1301 1f9430d6 Iustin Pop
    """
1302 1f9430d6 Iustin Pop
    all_os = {}
1303 1f9430d6 Iustin Pop
    for node_name, nr in rlist.iteritems():
1304 1f9430d6 Iustin Pop
      if not nr:
1305 1f9430d6 Iustin Pop
        continue
1306 1f9430d6 Iustin Pop
      for os in nr:
1307 1f9430d6 Iustin Pop
        if os.name not in all_os:
1308 1f9430d6 Iustin Pop
          # build a list of nodes for this os containing empty lists
1309 1f9430d6 Iustin Pop
          # for each node in node_list
1310 1f9430d6 Iustin Pop
          all_os[os.name] = {}
1311 1f9430d6 Iustin Pop
          for nname in node_list:
1312 1f9430d6 Iustin Pop
            all_os[os.name][nname] = []
1313 1f9430d6 Iustin Pop
        all_os[os.name][node_name].append(os)
1314 1f9430d6 Iustin Pop
    return all_os
1315 a8083063 Iustin Pop
1316 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1317 a8083063 Iustin Pop
    """Compute the list of OSes.
1318 a8083063 Iustin Pop

1319 a8083063 Iustin Pop
    """
1320 a8083063 Iustin Pop
    node_list = self.cfg.GetNodeList()
1321 a8083063 Iustin Pop
    node_data = rpc.call_os_diagnose(node_list)
1322 a8083063 Iustin Pop
    if node_data == False:
1323 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't gather the list of OSes")
1324 1f9430d6 Iustin Pop
    pol = self._DiagnoseByOS(node_list, node_data)
1325 1f9430d6 Iustin Pop
    output = []
1326 1f9430d6 Iustin Pop
    for os_name, os_data in pol.iteritems():
1327 1f9430d6 Iustin Pop
      row = []
1328 1f9430d6 Iustin Pop
      for field in self.op.output_fields:
1329 1f9430d6 Iustin Pop
        if field == "name":
1330 1f9430d6 Iustin Pop
          val = os_name
1331 1f9430d6 Iustin Pop
        elif field == "valid":
1332 1f9430d6 Iustin Pop
          val = utils.all([osl and osl[0] for osl in os_data.values()])
1333 1f9430d6 Iustin Pop
        elif field == "node_status":
1334 1f9430d6 Iustin Pop
          val = {}
1335 1f9430d6 Iustin Pop
          for node_name, nos_list in os_data.iteritems():
1336 1f9430d6 Iustin Pop
            val[node_name] = [(v.status, v.path) for v in nos_list]
1337 1f9430d6 Iustin Pop
        else:
1338 1f9430d6 Iustin Pop
          raise errors.ParameterError(field)
1339 1f9430d6 Iustin Pop
        row.append(val)
1340 1f9430d6 Iustin Pop
      output.append(row)
1341 1f9430d6 Iustin Pop
1342 1f9430d6 Iustin Pop
    return output
1343 a8083063 Iustin Pop
1344 a8083063 Iustin Pop
1345 a8083063 Iustin Pop
class LURemoveNode(LogicalUnit):
1346 a8083063 Iustin Pop
  """Logical unit for removing a node.
1347 a8083063 Iustin Pop

1348 a8083063 Iustin Pop
  """
1349 a8083063 Iustin Pop
  HPATH = "node-remove"
1350 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_NODE
1351 a8083063 Iustin Pop
  _OP_REQP = ["node_name"]
1352 a8083063 Iustin Pop
1353 a8083063 Iustin Pop
  def BuildHooksEnv(self):
1354 a8083063 Iustin Pop
    """Build hooks env.
1355 a8083063 Iustin Pop

1356 a8083063 Iustin Pop
    This doesn't run on the target node in the pre phase as a failed
1357 a8083063 Iustin Pop
    node would not allows itself to run.
1358 a8083063 Iustin Pop

1359 a8083063 Iustin Pop
    """
1360 396e1b78 Michael Hanselmann
    env = {
1361 0e137c28 Iustin Pop
      "OP_TARGET": self.op.node_name,
1362 396e1b78 Michael Hanselmann
      "NODE_NAME": self.op.node_name,
1363 396e1b78 Michael Hanselmann
      }
1364 a8083063 Iustin Pop
    all_nodes = self.cfg.GetNodeList()
1365 a8083063 Iustin Pop
    all_nodes.remove(self.op.node_name)
1366 396e1b78 Michael Hanselmann
    return env, all_nodes, all_nodes
1367 a8083063 Iustin Pop
1368 a8083063 Iustin Pop
  def CheckPrereq(self):
1369 a8083063 Iustin Pop
    """Check prerequisites.
1370 a8083063 Iustin Pop

1371 a8083063 Iustin Pop
    This checks:
1372 a8083063 Iustin Pop
     - the node exists in the configuration
1373 a8083063 Iustin Pop
     - it does not have primary or secondary instances
1374 a8083063 Iustin Pop
     - it's not the master
1375 a8083063 Iustin Pop

1376 a8083063 Iustin Pop
    Any errors are signalled by raising errors.OpPrereqError.
1377 a8083063 Iustin Pop

1378 a8083063 Iustin Pop
    """
1379 a8083063 Iustin Pop
    node = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.node_name))
1380 a8083063 Iustin Pop
    if node is None:
1381 a02bc76e Iustin Pop
      raise errors.OpPrereqError, ("Node '%s' is unknown." % self.op.node_name)
1382 a8083063 Iustin Pop
1383 a8083063 Iustin Pop
    instance_list = self.cfg.GetInstanceList()
1384 a8083063 Iustin Pop
1385 880478f8 Iustin Pop
    masternode = self.sstore.GetMasterNode()
1386 a8083063 Iustin Pop
    if node.name == masternode:
1387 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Node is the master node,"
1388 3ecf6786 Iustin Pop
                                 " you need to failover first.")
1389 a8083063 Iustin Pop
1390 a8083063 Iustin Pop
    for instance_name in instance_list:
1391 a8083063 Iustin Pop
      instance = self.cfg.GetInstanceInfo(instance_name)
1392 a8083063 Iustin Pop
      if node.name == instance.primary_node:
1393 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Instance %s still running on the node,"
1394 3ecf6786 Iustin Pop
                                   " please remove first." % instance_name)
1395 a8083063 Iustin Pop
      if node.name in instance.secondary_nodes:
1396 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Instance %s has node as a secondary,"
1397 3ecf6786 Iustin Pop
                                   " please remove first." % instance_name)
1398 a8083063 Iustin Pop
    self.op.node_name = node.name
1399 a8083063 Iustin Pop
    self.node = node
1400 a8083063 Iustin Pop
1401 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1402 a8083063 Iustin Pop
    """Removes the node from the cluster.
1403 a8083063 Iustin Pop

1404 a8083063 Iustin Pop
    """
1405 a8083063 Iustin Pop
    node = self.node
1406 a8083063 Iustin Pop
    logger.Info("stopping the node daemon and removing configs from node %s" %
1407 a8083063 Iustin Pop
                node.name)
1408 a8083063 Iustin Pop
1409 a8083063 Iustin Pop
    rpc.call_node_leave_cluster(node.name)
1410 a8083063 Iustin Pop
1411 c92b310a Michael Hanselmann
    self.ssh.Run(node.name, 'root', "%s stop" % constants.NODE_INITD_SCRIPT)
1412 a8083063 Iustin Pop
1413 a8083063 Iustin Pop
    logger.Info("Removing node %s from config" % node.name)
1414 a8083063 Iustin Pop
1415 a8083063 Iustin Pop
    self.cfg.RemoveNode(node.name)
1416 a8083063 Iustin Pop
1417 c8a0948f Michael Hanselmann
    _RemoveHostFromEtcHosts(node.name)
1418 c8a0948f Michael Hanselmann
1419 a8083063 Iustin Pop
1420 a8083063 Iustin Pop
class LUQueryNodes(NoHooksLU):
1421 a8083063 Iustin Pop
  """Logical unit for querying nodes.
1422 a8083063 Iustin Pop

1423 a8083063 Iustin Pop
  """
1424 246e180a Iustin Pop
  _OP_REQP = ["output_fields", "names"]
1425 a8083063 Iustin Pop
1426 a8083063 Iustin Pop
  def CheckPrereq(self):
1427 a8083063 Iustin Pop
    """Check prerequisites.
1428 a8083063 Iustin Pop

1429 a8083063 Iustin Pop
    This checks that the fields required are valid output fields.
1430 a8083063 Iustin Pop

1431 a8083063 Iustin Pop
    """
1432 a8083063 Iustin Pop
    self.dynamic_fields = frozenset(["dtotal", "dfree",
1433 3ef10550 Michael Hanselmann
                                     "mtotal", "mnode", "mfree",
1434 3ef10550 Michael Hanselmann
                                     "bootid"])
1435 a8083063 Iustin Pop
1436 ec223efb Iustin Pop
    _CheckOutputFields(static=["name", "pinst_cnt", "sinst_cnt",
1437 ec223efb Iustin Pop
                               "pinst_list", "sinst_list",
1438 ec223efb Iustin Pop
                               "pip", "sip"],
1439 dcb93971 Michael Hanselmann
                       dynamic=self.dynamic_fields,
1440 dcb93971 Michael Hanselmann
                       selected=self.op.output_fields)
1441 a8083063 Iustin Pop
1442 246e180a Iustin Pop
    self.wanted = _GetWantedNodes(self, self.op.names)
1443 a8083063 Iustin Pop
1444 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1445 a8083063 Iustin Pop
    """Computes the list of nodes and their attributes.
1446 a8083063 Iustin Pop

1447 a8083063 Iustin Pop
    """
1448 246e180a Iustin Pop
    nodenames = self.wanted
1449 a8083063 Iustin Pop
    nodelist = [self.cfg.GetNodeInfo(name) for name in nodenames]
1450 a8083063 Iustin Pop
1451 a8083063 Iustin Pop
    # begin data gathering
1452 a8083063 Iustin Pop
1453 a8083063 Iustin Pop
    if self.dynamic_fields.intersection(self.op.output_fields):
1454 a8083063 Iustin Pop
      live_data = {}
1455 a8083063 Iustin Pop
      node_data = rpc.call_node_info(nodenames, self.cfg.GetVGName())
1456 a8083063 Iustin Pop
      for name in nodenames:
1457 a8083063 Iustin Pop
        nodeinfo = node_data.get(name, None)
1458 a8083063 Iustin Pop
        if nodeinfo:
1459 a8083063 Iustin Pop
          live_data[name] = {
1460 a8083063 Iustin Pop
            "mtotal": utils.TryConvert(int, nodeinfo['memory_total']),
1461 a8083063 Iustin Pop
            "mnode": utils.TryConvert(int, nodeinfo['memory_dom0']),
1462 a8083063 Iustin Pop
            "mfree": utils.TryConvert(int, nodeinfo['memory_free']),
1463 a8083063 Iustin Pop
            "dtotal": utils.TryConvert(int, nodeinfo['vg_size']),
1464 a8083063 Iustin Pop
            "dfree": utils.TryConvert(int, nodeinfo['vg_free']),
1465 3ef10550 Michael Hanselmann
            "bootid": nodeinfo['bootid'],
1466 a8083063 Iustin Pop
            }
1467 a8083063 Iustin Pop
        else:
1468 a8083063 Iustin Pop
          live_data[name] = {}
1469 a8083063 Iustin Pop
    else:
1470 a8083063 Iustin Pop
      live_data = dict.fromkeys(nodenames, {})
1471 a8083063 Iustin Pop
1472 ec223efb Iustin Pop
    node_to_primary = dict([(name, set()) for name in nodenames])
1473 ec223efb Iustin Pop
    node_to_secondary = dict([(name, set()) for name in nodenames])
1474 a8083063 Iustin Pop
1475 ec223efb Iustin Pop
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
1476 ec223efb Iustin Pop
                             "sinst_cnt", "sinst_list"))
1477 ec223efb Iustin Pop
    if inst_fields & frozenset(self.op.output_fields):
1478 a8083063 Iustin Pop
      instancelist = self.cfg.GetInstanceList()
1479 a8083063 Iustin Pop
1480 ec223efb Iustin Pop
      for instance_name in instancelist:
1481 ec223efb Iustin Pop
        inst = self.cfg.GetInstanceInfo(instance_name)
1482 ec223efb Iustin Pop
        if inst.primary_node in node_to_primary:
1483 ec223efb Iustin Pop
          node_to_primary[inst.primary_node].add(inst.name)
1484 ec223efb Iustin Pop
        for secnode in inst.secondary_nodes:
1485 ec223efb Iustin Pop
          if secnode in node_to_secondary:
1486 ec223efb Iustin Pop
            node_to_secondary[secnode].add(inst.name)
1487 a8083063 Iustin Pop
1488 a8083063 Iustin Pop
    # end data gathering
1489 a8083063 Iustin Pop
1490 a8083063 Iustin Pop
    output = []
1491 a8083063 Iustin Pop
    for node in nodelist:
1492 a8083063 Iustin Pop
      node_output = []
1493 a8083063 Iustin Pop
      for field in self.op.output_fields:
1494 a8083063 Iustin Pop
        if field == "name":
1495 a8083063 Iustin Pop
          val = node.name
1496 ec223efb Iustin Pop
        elif field == "pinst_list":
1497 ec223efb Iustin Pop
          val = list(node_to_primary[node.name])
1498 ec223efb Iustin Pop
        elif field == "sinst_list":
1499 ec223efb Iustin Pop
          val = list(node_to_secondary[node.name])
1500 ec223efb Iustin Pop
        elif field == "pinst_cnt":
1501 ec223efb Iustin Pop
          val = len(node_to_primary[node.name])
1502 ec223efb Iustin Pop
        elif field == "sinst_cnt":
1503 ec223efb Iustin Pop
          val = len(node_to_secondary[node.name])
1504 a8083063 Iustin Pop
        elif field == "pip":
1505 a8083063 Iustin Pop
          val = node.primary_ip
1506 a8083063 Iustin Pop
        elif field == "sip":
1507 a8083063 Iustin Pop
          val = node.secondary_ip
1508 a8083063 Iustin Pop
        elif field in self.dynamic_fields:
1509 ec223efb Iustin Pop
          val = live_data[node.name].get(field, None)
1510 a8083063 Iustin Pop
        else:
1511 3ecf6786 Iustin Pop
          raise errors.ParameterError(field)
1512 a8083063 Iustin Pop
        node_output.append(val)
1513 a8083063 Iustin Pop
      output.append(node_output)
1514 a8083063 Iustin Pop
1515 a8083063 Iustin Pop
    return output
1516 a8083063 Iustin Pop
1517 a8083063 Iustin Pop
1518 dcb93971 Michael Hanselmann
class LUQueryNodeVolumes(NoHooksLU):
1519 dcb93971 Michael Hanselmann
  """Logical unit for getting volumes on node(s).
1520 dcb93971 Michael Hanselmann

1521 dcb93971 Michael Hanselmann
  """
1522 dcb93971 Michael Hanselmann
  _OP_REQP = ["nodes", "output_fields"]
1523 dcb93971 Michael Hanselmann
1524 dcb93971 Michael Hanselmann
  def CheckPrereq(self):
1525 dcb93971 Michael Hanselmann
    """Check prerequisites.
1526 dcb93971 Michael Hanselmann

1527 dcb93971 Michael Hanselmann
    This checks that the fields required are valid output fields.
1528 dcb93971 Michael Hanselmann

1529 dcb93971 Michael Hanselmann
    """
1530 dcb93971 Michael Hanselmann
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1531 dcb93971 Michael Hanselmann
1532 dcb93971 Michael Hanselmann
    _CheckOutputFields(static=["node"],
1533 dcb93971 Michael Hanselmann
                       dynamic=["phys", "vg", "name", "size", "instance"],
1534 dcb93971 Michael Hanselmann
                       selected=self.op.output_fields)
1535 dcb93971 Michael Hanselmann
1536 dcb93971 Michael Hanselmann
1537 dcb93971 Michael Hanselmann
  def Exec(self, feedback_fn):
1538 dcb93971 Michael Hanselmann
    """Computes the list of nodes and their attributes.
1539 dcb93971 Michael Hanselmann

1540 dcb93971 Michael Hanselmann
    """
1541 a7ba5e53 Iustin Pop
    nodenames = self.nodes
1542 dcb93971 Michael Hanselmann
    volumes = rpc.call_node_volumes(nodenames)
1543 dcb93971 Michael Hanselmann
1544 dcb93971 Michael Hanselmann
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
1545 dcb93971 Michael Hanselmann
             in self.cfg.GetInstanceList()]
1546 dcb93971 Michael Hanselmann
1547 dcb93971 Michael Hanselmann
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
1548 dcb93971 Michael Hanselmann
1549 dcb93971 Michael Hanselmann
    output = []
1550 dcb93971 Michael Hanselmann
    for node in nodenames:
1551 37d19eb2 Michael Hanselmann
      if node not in volumes or not volumes[node]:
1552 37d19eb2 Michael Hanselmann
        continue
1553 37d19eb2 Michael Hanselmann
1554 dcb93971 Michael Hanselmann
      node_vols = volumes[node][:]
1555 dcb93971 Michael Hanselmann
      node_vols.sort(key=lambda vol: vol['dev'])
1556 dcb93971 Michael Hanselmann
1557 dcb93971 Michael Hanselmann
      for vol in node_vols:
1558 dcb93971 Michael Hanselmann
        node_output = []
1559 dcb93971 Michael Hanselmann
        for field in self.op.output_fields:
1560 dcb93971 Michael Hanselmann
          if field == "node":
1561 dcb93971 Michael Hanselmann
            val = node
1562 dcb93971 Michael Hanselmann
          elif field == "phys":
1563 dcb93971 Michael Hanselmann
            val = vol['dev']
1564 dcb93971 Michael Hanselmann
          elif field == "vg":
1565 dcb93971 Michael Hanselmann
            val = vol['vg']
1566 dcb93971 Michael Hanselmann
          elif field == "name":
1567 dcb93971 Michael Hanselmann
            val = vol['name']
1568 dcb93971 Michael Hanselmann
          elif field == "size":
1569 dcb93971 Michael Hanselmann
            val = int(float(vol['size']))
1570 dcb93971 Michael Hanselmann
          elif field == "instance":
1571 dcb93971 Michael Hanselmann
            for inst in ilist:
1572 dcb93971 Michael Hanselmann
              if node not in lv_by_node[inst]:
1573 dcb93971 Michael Hanselmann
                continue
1574 dcb93971 Michael Hanselmann
              if vol['name'] in lv_by_node[inst][node]:
1575 dcb93971 Michael Hanselmann
                val = inst.name
1576 dcb93971 Michael Hanselmann
                break
1577 dcb93971 Michael Hanselmann
            else:
1578 dcb93971 Michael Hanselmann
              val = '-'
1579 dcb93971 Michael Hanselmann
          else:
1580 3ecf6786 Iustin Pop
            raise errors.ParameterError(field)
1581 dcb93971 Michael Hanselmann
          node_output.append(str(val))
1582 dcb93971 Michael Hanselmann
1583 dcb93971 Michael Hanselmann
        output.append(node_output)
1584 dcb93971 Michael Hanselmann
1585 dcb93971 Michael Hanselmann
    return output
1586 dcb93971 Michael Hanselmann
1587 dcb93971 Michael Hanselmann
1588 a8083063 Iustin Pop
class LUAddNode(LogicalUnit):
1589 a8083063 Iustin Pop
  """Logical unit for adding node to the cluster.
1590 a8083063 Iustin Pop

1591 a8083063 Iustin Pop
  """
1592 a8083063 Iustin Pop
  HPATH = "node-add"
1593 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_NODE
1594 a8083063 Iustin Pop
  _OP_REQP = ["node_name"]
1595 a8083063 Iustin Pop
1596 a8083063 Iustin Pop
  def BuildHooksEnv(self):
1597 a8083063 Iustin Pop
    """Build hooks env.
1598 a8083063 Iustin Pop

1599 a8083063 Iustin Pop
    This will run on all nodes before, and on all nodes + the new node after.
1600 a8083063 Iustin Pop

1601 a8083063 Iustin Pop
    """
1602 a8083063 Iustin Pop
    env = {
1603 0e137c28 Iustin Pop
      "OP_TARGET": self.op.node_name,
1604 a8083063 Iustin Pop
      "NODE_NAME": self.op.node_name,
1605 a8083063 Iustin Pop
      "NODE_PIP": self.op.primary_ip,
1606 a8083063 Iustin Pop
      "NODE_SIP": self.op.secondary_ip,
1607 a8083063 Iustin Pop
      }
1608 a8083063 Iustin Pop
    nodes_0 = self.cfg.GetNodeList()
1609 a8083063 Iustin Pop
    nodes_1 = nodes_0 + [self.op.node_name, ]
1610 a8083063 Iustin Pop
    return env, nodes_0, nodes_1
1611 a8083063 Iustin Pop
1612 a8083063 Iustin Pop
  def CheckPrereq(self):
1613 a8083063 Iustin Pop
    """Check prerequisites.
1614 a8083063 Iustin Pop

1615 a8083063 Iustin Pop
    This checks:
1616 a8083063 Iustin Pop
     - the new node is not already in the config
1617 a8083063 Iustin Pop
     - it is resolvable
1618 a8083063 Iustin Pop
     - its parameters (single/dual homed) matches the cluster
1619 a8083063 Iustin Pop

1620 a8083063 Iustin Pop
    Any errors are signalled by raising errors.OpPrereqError.
1621 a8083063 Iustin Pop

1622 a8083063 Iustin Pop
    """
1623 a8083063 Iustin Pop
    node_name = self.op.node_name
1624 a8083063 Iustin Pop
    cfg = self.cfg
1625 a8083063 Iustin Pop
1626 89e1fc26 Iustin Pop
    dns_data = utils.HostInfo(node_name)
1627 a8083063 Iustin Pop
1628 bcf043c9 Iustin Pop
    node = dns_data.name
1629 bcf043c9 Iustin Pop
    primary_ip = self.op.primary_ip = dns_data.ip
1630 a8083063 Iustin Pop
    secondary_ip = getattr(self.op, "secondary_ip", None)
1631 a8083063 Iustin Pop
    if secondary_ip is None:
1632 a8083063 Iustin Pop
      secondary_ip = primary_ip
1633 a8083063 Iustin Pop
    if not utils.IsValidIP(secondary_ip):
1634 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Invalid secondary IP given")
1635 a8083063 Iustin Pop
    self.op.secondary_ip = secondary_ip
1636 e7c6e02b Michael Hanselmann
1637 a8083063 Iustin Pop
    node_list = cfg.GetNodeList()
1638 e7c6e02b Michael Hanselmann
    if not self.op.readd and node in node_list:
1639 e7c6e02b Michael Hanselmann
      raise errors.OpPrereqError("Node %s is already in the configuration" %
1640 e7c6e02b Michael Hanselmann
                                 node)
1641 e7c6e02b Michael Hanselmann
    elif self.op.readd and node not in node_list:
1642 e7c6e02b Michael Hanselmann
      raise errors.OpPrereqError("Node %s is not in the configuration" % node)
1643 a8083063 Iustin Pop
1644 a8083063 Iustin Pop
    for existing_node_name in node_list:
1645 a8083063 Iustin Pop
      existing_node = cfg.GetNodeInfo(existing_node_name)
1646 e7c6e02b Michael Hanselmann
1647 e7c6e02b Michael Hanselmann
      if self.op.readd and node == existing_node_name:
1648 e7c6e02b Michael Hanselmann
        if (existing_node.primary_ip != primary_ip or
1649 e7c6e02b Michael Hanselmann
            existing_node.secondary_ip != secondary_ip):
1650 e7c6e02b Michael Hanselmann
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
1651 e7c6e02b Michael Hanselmann
                                     " address configuration as before")
1652 e7c6e02b Michael Hanselmann
        continue
1653 e7c6e02b Michael Hanselmann
1654 a8083063 Iustin Pop
      if (existing_node.primary_ip == primary_ip or
1655 a8083063 Iustin Pop
          existing_node.secondary_ip == primary_ip or
1656 a8083063 Iustin Pop
          existing_node.primary_ip == secondary_ip or
1657 a8083063 Iustin Pop
          existing_node.secondary_ip == secondary_ip):
1658 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("New node ip address(es) conflict with"
1659 3ecf6786 Iustin Pop
                                   " existing node %s" % existing_node.name)
1660 a8083063 Iustin Pop
1661 a8083063 Iustin Pop
    # check that the type of the node (single versus dual homed) is the
1662 a8083063 Iustin Pop
    # same as for the master
1663 880478f8 Iustin Pop
    myself = cfg.GetNodeInfo(self.sstore.GetMasterNode())
1664 a8083063 Iustin Pop
    master_singlehomed = myself.secondary_ip == myself.primary_ip
1665 a8083063 Iustin Pop
    newbie_singlehomed = secondary_ip == primary_ip
1666 a8083063 Iustin Pop
    if master_singlehomed != newbie_singlehomed:
1667 a8083063 Iustin Pop
      if master_singlehomed:
1668 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The master has no private ip but the"
1669 3ecf6786 Iustin Pop
                                   " new node has one")
1670 a8083063 Iustin Pop
      else:
1671 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The master has a private ip but the"
1672 3ecf6786 Iustin Pop
                                   " new node doesn't have one")
1673 a8083063 Iustin Pop
1674 a8083063 Iustin Pop
    # checks reachablity
1675 b15d625f Iustin Pop
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
1676 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Node not reachable by ping")
1677 a8083063 Iustin Pop
1678 a8083063 Iustin Pop
    if not newbie_singlehomed:
1679 a8083063 Iustin Pop
      # check reachability from my secondary ip to newbie's secondary ip
1680 b15d625f Iustin Pop
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
1681 b15d625f Iustin Pop
                           source=myself.secondary_ip):
1682 f4bc1f2c Michael Hanselmann
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
1683 f4bc1f2c Michael Hanselmann
                                   " based ping to noded port")
1684 a8083063 Iustin Pop
1685 a8083063 Iustin Pop
    self.new_node = objects.Node(name=node,
1686 a8083063 Iustin Pop
                                 primary_ip=primary_ip,
1687 a8083063 Iustin Pop
                                 secondary_ip=secondary_ip)
1688 a8083063 Iustin Pop
1689 2a6469d5 Alexander Schreiber
    if self.sstore.GetHypervisorType() == constants.HT_XEN_HVM31:
1690 2a6469d5 Alexander Schreiber
      if not os.path.exists(constants.VNC_PASSWORD_FILE):
1691 2a6469d5 Alexander Schreiber
        raise errors.OpPrereqError("Cluster VNC password file %s missing" %
1692 2a6469d5 Alexander Schreiber
                                   constants.VNC_PASSWORD_FILE)
1693 2a6469d5 Alexander Schreiber
1694 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1695 a8083063 Iustin Pop
    """Adds the new node to the cluster.
1696 a8083063 Iustin Pop

1697 a8083063 Iustin Pop
    """
1698 a8083063 Iustin Pop
    new_node = self.new_node
1699 a8083063 Iustin Pop
    node = new_node.name
1700 a8083063 Iustin Pop
1701 a8083063 Iustin Pop
    # set up inter-node password and certificate and restarts the node daemon
1702 a8083063 Iustin Pop
    gntpass = self.sstore.GetNodeDaemonPassword()
1703 a8083063 Iustin Pop
    if not re.match('^[a-zA-Z0-9.]{1,64}$', gntpass):
1704 3ecf6786 Iustin Pop
      raise errors.OpExecError("ganeti password corruption detected")
1705 a8083063 Iustin Pop
    f = open(constants.SSL_CERT_FILE)
1706 a8083063 Iustin Pop
    try:
1707 a8083063 Iustin Pop
      gntpem = f.read(8192)
1708 a8083063 Iustin Pop
    finally:
1709 a8083063 Iustin Pop
      f.close()
1710 a8083063 Iustin Pop
    # in the base64 pem encoding, neither '!' nor '.' are valid chars,
1711 a8083063 Iustin Pop
    # so we use this to detect an invalid certificate; as long as the
1712 a8083063 Iustin Pop
    # cert doesn't contain this, the here-document will be correctly
1713 a8083063 Iustin Pop
    # parsed by the shell sequence below
1714 a8083063 Iustin Pop
    if re.search('^!EOF\.', gntpem, re.MULTILINE):
1715 3ecf6786 Iustin Pop
      raise errors.OpExecError("invalid PEM encoding in the SSL certificate")
1716 a8083063 Iustin Pop
    if not gntpem.endswith("\n"):
1717 3ecf6786 Iustin Pop
      raise errors.OpExecError("PEM must end with newline")
1718 a8083063 Iustin Pop
    logger.Info("copy cluster pass to %s and starting the node daemon" % node)
1719 a8083063 Iustin Pop
1720 a8083063 Iustin Pop
    # and then connect with ssh to set password and start ganeti-noded
1721 a8083063 Iustin Pop
    # note that all the below variables are sanitized at this point,
1722 a8083063 Iustin Pop
    # either by being constants or by the checks above
1723 a8083063 Iustin Pop
    ss = self.sstore
1724 a8083063 Iustin Pop
    mycommand = ("umask 077 && "
1725 a8083063 Iustin Pop
                 "echo '%s' > '%s' && "
1726 a8083063 Iustin Pop
                 "cat > '%s' << '!EOF.' && \n"
1727 a8083063 Iustin Pop
                 "%s!EOF.\n%s restart" %
1728 a8083063 Iustin Pop
                 (gntpass, ss.KeyToFilename(ss.SS_NODED_PASS),
1729 a8083063 Iustin Pop
                  constants.SSL_CERT_FILE, gntpem,
1730 a8083063 Iustin Pop
                  constants.NODE_INITD_SCRIPT))
1731 a8083063 Iustin Pop
1732 c92b310a Michael Hanselmann
    result = self.ssh.Run(node, 'root', mycommand, batch=False, ask_key=True)
1733 a8083063 Iustin Pop
    if result.failed:
1734 3ecf6786 Iustin Pop
      raise errors.OpExecError("Remote command on node %s, error: %s,"
1735 3ecf6786 Iustin Pop
                               " output: %s" %
1736 3ecf6786 Iustin Pop
                               (node, result.fail_reason, result.output))
1737 a8083063 Iustin Pop
1738 a8083063 Iustin Pop
    # check connectivity
1739 a8083063 Iustin Pop
    time.sleep(4)
1740 a8083063 Iustin Pop
1741 a8083063 Iustin Pop
    result = rpc.call_version([node])[node]
1742 a8083063 Iustin Pop
    if result:
1743 a8083063 Iustin Pop
      if constants.PROTOCOL_VERSION == result:
1744 a8083063 Iustin Pop
        logger.Info("communication to node %s fine, sw version %s match" %
1745 a8083063 Iustin Pop
                    (node, result))
1746 a8083063 Iustin Pop
      else:
1747 3ecf6786 Iustin Pop
        raise errors.OpExecError("Version mismatch master version %s,"
1748 3ecf6786 Iustin Pop
                                 " node version %s" %
1749 3ecf6786 Iustin Pop
                                 (constants.PROTOCOL_VERSION, result))
1750 a8083063 Iustin Pop
    else:
1751 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot get version from the new node")
1752 a8083063 Iustin Pop
1753 a8083063 Iustin Pop
    # setup ssh on node
1754 a8083063 Iustin Pop
    logger.Info("copy ssh key to node %s" % node)
1755 70d9e3d8 Iustin Pop
    priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1756 a8083063 Iustin Pop
    keyarray = []
1757 70d9e3d8 Iustin Pop
    keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
1758 70d9e3d8 Iustin Pop
                constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
1759 70d9e3d8 Iustin Pop
                priv_key, pub_key]
1760 a8083063 Iustin Pop
1761 a8083063 Iustin Pop
    for i in keyfiles:
1762 a8083063 Iustin Pop
      f = open(i, 'r')
1763 a8083063 Iustin Pop
      try:
1764 a8083063 Iustin Pop
        keyarray.append(f.read())
1765 a8083063 Iustin Pop
      finally:
1766 a8083063 Iustin Pop
        f.close()
1767 a8083063 Iustin Pop
1768 a8083063 Iustin Pop
    result = rpc.call_node_add(node, keyarray[0], keyarray[1], keyarray[2],
1769 a8083063 Iustin Pop
                               keyarray[3], keyarray[4], keyarray[5])
1770 a8083063 Iustin Pop
1771 a8083063 Iustin Pop
    if not result:
1772 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot transfer ssh keys to the new node")
1773 a8083063 Iustin Pop
1774 a8083063 Iustin Pop
    # Add node to our /etc/hosts, and add key to known_hosts
1775 9440aeab Michael Hanselmann
    _AddHostToEtcHosts(new_node.name)
1776 c8a0948f Michael Hanselmann
1777 a8083063 Iustin Pop
    if new_node.secondary_ip != new_node.primary_ip:
1778 16abfbc2 Alexander Schreiber
      if not rpc.call_node_tcp_ping(new_node.name,
1779 16abfbc2 Alexander Schreiber
                                    constants.LOCALHOST_IP_ADDRESS,
1780 16abfbc2 Alexander Schreiber
                                    new_node.secondary_ip,
1781 16abfbc2 Alexander Schreiber
                                    constants.DEFAULT_NODED_PORT,
1782 16abfbc2 Alexander Schreiber
                                    10, False):
1783 f4bc1f2c Michael Hanselmann
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
1784 f4bc1f2c Michael Hanselmann
                                 " you gave (%s). Please fix and re-run this"
1785 f4bc1f2c Michael Hanselmann
                                 " command." % new_node.secondary_ip)
1786 a8083063 Iustin Pop
1787 c92b310a Michael Hanselmann
    success, msg = self.ssh.VerifyNodeHostname(node)
1788 ff98055b Iustin Pop
    if not success:
1789 ff98055b Iustin Pop
      raise errors.OpExecError("Node '%s' claims it has a different hostname"
1790 f4bc1f2c Michael Hanselmann
                               " than the one the resolver gives: %s."
1791 f4bc1f2c Michael Hanselmann
                               " Please fix and re-run this command." %
1792 ff98055b Iustin Pop
                               (node, msg))
1793 ff98055b Iustin Pop
1794 a8083063 Iustin Pop
    # Distribute updated /etc/hosts and known_hosts to all nodes,
1795 a8083063 Iustin Pop
    # including the node just added
1796 880478f8 Iustin Pop
    myself = self.cfg.GetNodeInfo(self.sstore.GetMasterNode())
1797 a8083063 Iustin Pop
    dist_nodes = self.cfg.GetNodeList() + [node]
1798 a8083063 Iustin Pop
    if myself.name in dist_nodes:
1799 a8083063 Iustin Pop
      dist_nodes.remove(myself.name)
1800 a8083063 Iustin Pop
1801 a8083063 Iustin Pop
    logger.Debug("Copying hosts and known_hosts to all nodes")
1802 107711b0 Michael Hanselmann
    for fname in (constants.ETC_HOSTS, constants.SSH_KNOWN_HOSTS_FILE):
1803 a8083063 Iustin Pop
      result = rpc.call_upload_file(dist_nodes, fname)
1804 a8083063 Iustin Pop
      for to_node in dist_nodes:
1805 a8083063 Iustin Pop
        if not result[to_node]:
1806 a8083063 Iustin Pop
          logger.Error("copy of file %s to node %s failed" %
1807 a8083063 Iustin Pop
                       (fname, to_node))
1808 a8083063 Iustin Pop
1809 cb91d46e Iustin Pop
    to_copy = ss.GetFileList()
1810 2a6469d5 Alexander Schreiber
    if self.sstore.GetHypervisorType() == constants.HT_XEN_HVM31:
1811 2a6469d5 Alexander Schreiber
      to_copy.append(constants.VNC_PASSWORD_FILE)
1812 a8083063 Iustin Pop
    for fname in to_copy:
1813 c92b310a Michael Hanselmann
      if not self.ssh.CopyFileToNode(node, fname):
1814 a8083063 Iustin Pop
        logger.Error("could not copy file %s to node %s" % (fname, node))
1815 a8083063 Iustin Pop
1816 e7c6e02b Michael Hanselmann
    if not self.op.readd:
1817 e7c6e02b Michael Hanselmann
      logger.Info("adding node %s to cluster.conf" % node)
1818 e7c6e02b Michael Hanselmann
      self.cfg.AddNode(new_node)
1819 a8083063 Iustin Pop
1820 a8083063 Iustin Pop
1821 a8083063 Iustin Pop
class LUMasterFailover(LogicalUnit):
1822 a8083063 Iustin Pop
  """Failover the master node to the current node.
1823 a8083063 Iustin Pop

1824 a8083063 Iustin Pop
  This is a special LU in that it must run on a non-master node.
1825 a8083063 Iustin Pop

1826 a8083063 Iustin Pop
  """
1827 a8083063 Iustin Pop
  HPATH = "master-failover"
1828 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_CLUSTER
1829 a8083063 Iustin Pop
  REQ_MASTER = False
1830 a8083063 Iustin Pop
  _OP_REQP = []
1831 a8083063 Iustin Pop
1832 a8083063 Iustin Pop
  def BuildHooksEnv(self):
1833 a8083063 Iustin Pop
    """Build hooks env.
1834 a8083063 Iustin Pop

1835 a8083063 Iustin Pop
    This will run on the new master only in the pre phase, and on all
1836 a8083063 Iustin Pop
    the nodes in the post phase.
1837 a8083063 Iustin Pop

1838 a8083063 Iustin Pop
    """
1839 a8083063 Iustin Pop
    env = {
1840 0e137c28 Iustin Pop
      "OP_TARGET": self.new_master,
1841 a8083063 Iustin Pop
      "NEW_MASTER": self.new_master,
1842 a8083063 Iustin Pop
      "OLD_MASTER": self.old_master,
1843 a8083063 Iustin Pop
      }
1844 a8083063 Iustin Pop
    return env, [self.new_master], self.cfg.GetNodeList()
1845 a8083063 Iustin Pop
1846 a8083063 Iustin Pop
  def CheckPrereq(self):
1847 a8083063 Iustin Pop
    """Check prerequisites.
1848 a8083063 Iustin Pop

1849 a8083063 Iustin Pop
    This checks that we are not already the master.
1850 a8083063 Iustin Pop

1851 a8083063 Iustin Pop
    """
1852 89e1fc26 Iustin Pop
    self.new_master = utils.HostInfo().name
1853 880478f8 Iustin Pop
    self.old_master = self.sstore.GetMasterNode()
1854 a8083063 Iustin Pop
1855 a8083063 Iustin Pop
    if self.old_master == self.new_master:
1856 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("This commands must be run on the node"
1857 f4bc1f2c Michael Hanselmann
                                 " where you want the new master to be."
1858 f4bc1f2c Michael Hanselmann
                                 " %s is already the master" %
1859 3ecf6786 Iustin Pop
                                 self.old_master)
1860 a8083063 Iustin Pop
1861 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1862 a8083063 Iustin Pop
    """Failover the master node.
1863 a8083063 Iustin Pop

1864 a8083063 Iustin Pop
    This command, when run on a non-master node, will cause the current
1865 a8083063 Iustin Pop
    master to cease being master, and the non-master to become new
1866 a8083063 Iustin Pop
    master.
1867 a8083063 Iustin Pop

1868 a8083063 Iustin Pop
    """
1869 a8083063 Iustin Pop
    #TODO: do not rely on gethostname returning the FQDN
1870 a8083063 Iustin Pop
    logger.Info("setting master to %s, old master: %s" %
1871 a8083063 Iustin Pop
                (self.new_master, self.old_master))
1872 a8083063 Iustin Pop
1873 a8083063 Iustin Pop
    if not rpc.call_node_stop_master(self.old_master):
1874 a8083063 Iustin Pop
      logger.Error("could disable the master role on the old master"
1875 a8083063 Iustin Pop
                   " %s, please disable manually" % self.old_master)
1876 a8083063 Iustin Pop
1877 880478f8 Iustin Pop
    ss = self.sstore
1878 880478f8 Iustin Pop
    ss.SetKey(ss.SS_MASTER_NODE, self.new_master)
1879 880478f8 Iustin Pop
    if not rpc.call_upload_file(self.cfg.GetNodeList(),
1880 880478f8 Iustin Pop
                                ss.KeyToFilename(ss.SS_MASTER_NODE)):
1881 880478f8 Iustin Pop
      logger.Error("could not distribute the new simple store master file"
1882 880478f8 Iustin Pop
                   " to the other nodes, please check.")
1883 880478f8 Iustin Pop
1884 a8083063 Iustin Pop
    if not rpc.call_node_start_master(self.new_master):
1885 a8083063 Iustin Pop
      logger.Error("could not start the master role on the new master"
1886 a8083063 Iustin Pop
                   " %s, please check" % self.new_master)
1887 f4bc1f2c Michael Hanselmann
      feedback_fn("Error in activating the master IP on the new master,"
1888 f4bc1f2c Michael Hanselmann
                  " please fix manually.")
1889 a8083063 Iustin Pop
1890 a8083063 Iustin Pop
1891 a8083063 Iustin Pop
1892 a8083063 Iustin Pop
class LUQueryClusterInfo(NoHooksLU):
1893 a8083063 Iustin Pop
  """Query cluster configuration.
1894 a8083063 Iustin Pop

1895 a8083063 Iustin Pop
  """
1896 a8083063 Iustin Pop
  _OP_REQP = []
1897 59322403 Iustin Pop
  REQ_MASTER = False
1898 a8083063 Iustin Pop
1899 a8083063 Iustin Pop
  def CheckPrereq(self):
1900 a8083063 Iustin Pop
    """No prerequsites needed for this LU.
1901 a8083063 Iustin Pop

1902 a8083063 Iustin Pop
    """
1903 a8083063 Iustin Pop
    pass
1904 a8083063 Iustin Pop
1905 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1906 a8083063 Iustin Pop
    """Return cluster config.
1907 a8083063 Iustin Pop

1908 a8083063 Iustin Pop
    """
1909 a8083063 Iustin Pop
    result = {
1910 5fcdc80d Iustin Pop
      "name": self.sstore.GetClusterName(),
1911 a8083063 Iustin Pop
      "software_version": constants.RELEASE_VERSION,
1912 a8083063 Iustin Pop
      "protocol_version": constants.PROTOCOL_VERSION,
1913 a8083063 Iustin Pop
      "config_version": constants.CONFIG_VERSION,
1914 a8083063 Iustin Pop
      "os_api_version": constants.OS_API_VERSION,
1915 a8083063 Iustin Pop
      "export_version": constants.EXPORT_VERSION,
1916 880478f8 Iustin Pop
      "master": self.sstore.GetMasterNode(),
1917 a8083063 Iustin Pop
      "architecture": (platform.architecture()[0], platform.machine()),
1918 a8083063 Iustin Pop
      }
1919 a8083063 Iustin Pop
1920 a8083063 Iustin Pop
    return result
1921 a8083063 Iustin Pop
1922 a8083063 Iustin Pop
1923 a8083063 Iustin Pop
class LUClusterCopyFile(NoHooksLU):
1924 a8083063 Iustin Pop
  """Copy file to cluster.
1925 a8083063 Iustin Pop

1926 a8083063 Iustin Pop
  """
1927 a8083063 Iustin Pop
  _OP_REQP = ["nodes", "filename"]
1928 a8083063 Iustin Pop
1929 a8083063 Iustin Pop
  def CheckPrereq(self):
1930 a8083063 Iustin Pop
    """Check prerequisites.
1931 a8083063 Iustin Pop

1932 a8083063 Iustin Pop
    It should check that the named file exists and that the given list
1933 a8083063 Iustin Pop
    of nodes is valid.
1934 a8083063 Iustin Pop

1935 a8083063 Iustin Pop
    """
1936 a8083063 Iustin Pop
    if not os.path.exists(self.op.filename):
1937 a8083063 Iustin Pop
      raise errors.OpPrereqError("No such filename '%s'" % self.op.filename)
1938 dcb93971 Michael Hanselmann
1939 dcb93971 Michael Hanselmann
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1940 a8083063 Iustin Pop
1941 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1942 a8083063 Iustin Pop
    """Copy a file from master to some nodes.
1943 a8083063 Iustin Pop

1944 a8083063 Iustin Pop
    Args:
1945 a8083063 Iustin Pop
      opts - class with options as members
1946 a8083063 Iustin Pop
      args - list containing a single element, the file name
1947 a8083063 Iustin Pop
    Opts used:
1948 a8083063 Iustin Pop
      nodes - list containing the name of target nodes; if empty, all nodes
1949 a8083063 Iustin Pop

1950 a8083063 Iustin Pop
    """
1951 a8083063 Iustin Pop
    filename = self.op.filename
1952 a8083063 Iustin Pop
1953 89e1fc26 Iustin Pop
    myname = utils.HostInfo().name
1954 a8083063 Iustin Pop
1955 a7ba5e53 Iustin Pop
    for node in self.nodes:
1956 a8083063 Iustin Pop
      if node == myname:
1957 a8083063 Iustin Pop
        continue
1958 c92b310a Michael Hanselmann
      if not self.ssh.CopyFileToNode(node, filename):
1959 a8083063 Iustin Pop
        logger.Error("Copy of file %s to node %s failed" % (filename, node))
1960 a8083063 Iustin Pop
1961 a8083063 Iustin Pop
1962 a8083063 Iustin Pop
class LUDumpClusterConfig(NoHooksLU):
1963 a8083063 Iustin Pop
  """Return a text-representation of the cluster-config.
1964 a8083063 Iustin Pop

1965 a8083063 Iustin Pop
  """
1966 a8083063 Iustin Pop
  _OP_REQP = []
1967 a8083063 Iustin Pop
1968 a8083063 Iustin Pop
  def CheckPrereq(self):
1969 a8083063 Iustin Pop
    """No prerequisites.
1970 a8083063 Iustin Pop

1971 a8083063 Iustin Pop
    """
1972 a8083063 Iustin Pop
    pass
1973 a8083063 Iustin Pop
1974 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1975 a8083063 Iustin Pop
    """Dump a representation of the cluster config to the standard output.
1976 a8083063 Iustin Pop

1977 a8083063 Iustin Pop
    """
1978 a8083063 Iustin Pop
    return self.cfg.DumpConfig()
1979 a8083063 Iustin Pop
1980 a8083063 Iustin Pop
1981 a8083063 Iustin Pop
class LURunClusterCommand(NoHooksLU):
1982 a8083063 Iustin Pop
  """Run a command on some nodes.
1983 a8083063 Iustin Pop

1984 a8083063 Iustin Pop
  """
1985 a8083063 Iustin Pop
  _OP_REQP = ["command", "nodes"]
1986 a8083063 Iustin Pop
1987 a8083063 Iustin Pop
  def CheckPrereq(self):
1988 a8083063 Iustin Pop
    """Check prerequisites.
1989 a8083063 Iustin Pop

1990 a8083063 Iustin Pop
    It checks that the given list of nodes is valid.
1991 a8083063 Iustin Pop

1992 a8083063 Iustin Pop
    """
1993 dcb93971 Michael Hanselmann
    self.nodes = _GetWantedNodes(self, self.op.nodes)
1994 a8083063 Iustin Pop
1995 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
1996 a8083063 Iustin Pop
    """Run a command on some nodes.
1997 a8083063 Iustin Pop

1998 a8083063 Iustin Pop
    """
1999 5f83e263 Iustin Pop
    # put the master at the end of the nodes list
2000 5f83e263 Iustin Pop
    master_node = self.sstore.GetMasterNode()
2001 5f83e263 Iustin Pop
    if master_node in self.nodes:
2002 5f83e263 Iustin Pop
      self.nodes.remove(master_node)
2003 5f83e263 Iustin Pop
      self.nodes.append(master_node)
2004 5f83e263 Iustin Pop
2005 a8083063 Iustin Pop
    data = []
2006 a8083063 Iustin Pop
    for node in self.nodes:
2007 c92b310a Michael Hanselmann
      result = self.ssh.Run(node, "root", self.op.command)
2008 a7ba5e53 Iustin Pop
      data.append((node, result.output, result.exit_code))
2009 a8083063 Iustin Pop
2010 a8083063 Iustin Pop
    return data
2011 a8083063 Iustin Pop
2012 a8083063 Iustin Pop
2013 a8083063 Iustin Pop
class LUActivateInstanceDisks(NoHooksLU):
2014 a8083063 Iustin Pop
  """Bring up an instance's disks.
2015 a8083063 Iustin Pop

2016 a8083063 Iustin Pop
  """
2017 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
2018 a8083063 Iustin Pop
2019 a8083063 Iustin Pop
  def CheckPrereq(self):
2020 a8083063 Iustin Pop
    """Check prerequisites.
2021 a8083063 Iustin Pop

2022 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2023 a8083063 Iustin Pop

2024 a8083063 Iustin Pop
    """
2025 a8083063 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
2026 a8083063 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
2027 a8083063 Iustin Pop
    if instance is None:
2028 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
2029 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2030 a8083063 Iustin Pop
    self.instance = instance
2031 a8083063 Iustin Pop
2032 a8083063 Iustin Pop
2033 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2034 a8083063 Iustin Pop
    """Activate the disks.
2035 a8083063 Iustin Pop

2036 a8083063 Iustin Pop
    """
2037 a8083063 Iustin Pop
    disks_ok, disks_info = _AssembleInstanceDisks(self.instance, self.cfg)
2038 a8083063 Iustin Pop
    if not disks_ok:
2039 3ecf6786 Iustin Pop
      raise errors.OpExecError("Cannot activate block devices")
2040 a8083063 Iustin Pop
2041 a8083063 Iustin Pop
    return disks_info
2042 a8083063 Iustin Pop
2043 a8083063 Iustin Pop
2044 a8083063 Iustin Pop
def _AssembleInstanceDisks(instance, cfg, ignore_secondaries=False):
2045 a8083063 Iustin Pop
  """Prepare the block devices for an instance.
2046 a8083063 Iustin Pop

2047 a8083063 Iustin Pop
  This sets up the block devices on all nodes.
2048 a8083063 Iustin Pop

2049 a8083063 Iustin Pop
  Args:
2050 a8083063 Iustin Pop
    instance: a ganeti.objects.Instance object
2051 a8083063 Iustin Pop
    ignore_secondaries: if true, errors on secondary nodes won't result
2052 a8083063 Iustin Pop
                        in an error return from the function
2053 a8083063 Iustin Pop

2054 a8083063 Iustin Pop
  Returns:
2055 a8083063 Iustin Pop
    false if the operation failed
2056 a8083063 Iustin Pop
    list of (host, instance_visible_name, node_visible_name) if the operation
2057 a8083063 Iustin Pop
         suceeded with the mapping from node devices to instance devices
2058 a8083063 Iustin Pop
  """
2059 a8083063 Iustin Pop
  device_info = []
2060 a8083063 Iustin Pop
  disks_ok = True
2061 fdbd668d Iustin Pop
  iname = instance.name
2062 fdbd668d Iustin Pop
  # With the two passes mechanism we try to reduce the window of
2063 fdbd668d Iustin Pop
  # opportunity for the race condition of switching DRBD to primary
2064 fdbd668d Iustin Pop
  # before handshaking occured, but we do not eliminate it
2065 fdbd668d Iustin Pop
2066 fdbd668d Iustin Pop
  # The proper fix would be to wait (with some limits) until the
2067 fdbd668d Iustin Pop
  # connection has been made and drbd transitions from WFConnection
2068 fdbd668d Iustin Pop
  # into any other network-connected state (Connected, SyncTarget,
2069 fdbd668d Iustin Pop
  # SyncSource, etc.)
2070 fdbd668d Iustin Pop
2071 fdbd668d Iustin Pop
  # 1st pass, assemble on all nodes in secondary mode
2072 a8083063 Iustin Pop
  for inst_disk in instance.disks:
2073 a8083063 Iustin Pop
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2074 a8083063 Iustin Pop
      cfg.SetDiskID(node_disk, node)
2075 fdbd668d Iustin Pop
      result = rpc.call_blockdev_assemble(node, node_disk, iname, False)
2076 a8083063 Iustin Pop
      if not result:
2077 f4bc1f2c Michael Hanselmann
        logger.Error("could not prepare block device %s on node %s"
2078 fdbd668d Iustin Pop
                     " (is_primary=False, pass=1)" % (inst_disk.iv_name, node))
2079 fdbd668d Iustin Pop
        if not ignore_secondaries:
2080 a8083063 Iustin Pop
          disks_ok = False
2081 fdbd668d Iustin Pop
2082 fdbd668d Iustin Pop
  # FIXME: race condition on drbd migration to primary
2083 fdbd668d Iustin Pop
2084 fdbd668d Iustin Pop
  # 2nd pass, do only the primary node
2085 fdbd668d Iustin Pop
  for inst_disk in instance.disks:
2086 fdbd668d Iustin Pop
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
2087 fdbd668d Iustin Pop
      if node != instance.primary_node:
2088 fdbd668d Iustin Pop
        continue
2089 fdbd668d Iustin Pop
      cfg.SetDiskID(node_disk, node)
2090 fdbd668d Iustin Pop
      result = rpc.call_blockdev_assemble(node, node_disk, iname, True)
2091 fdbd668d Iustin Pop
      if not result:
2092 fdbd668d Iustin Pop
        logger.Error("could not prepare block device %s on node %s"
2093 fdbd668d Iustin Pop
                     " (is_primary=True, pass=2)" % (inst_disk.iv_name, node))
2094 fdbd668d Iustin Pop
        disks_ok = False
2095 fdbd668d Iustin Pop
    device_info.append((instance.primary_node, inst_disk.iv_name, result))
2096 a8083063 Iustin Pop
2097 b352ab5b Iustin Pop
  # leave the disks configured for the primary node
2098 b352ab5b Iustin Pop
  # this is a workaround that would be fixed better by
2099 b352ab5b Iustin Pop
  # improving the logical/physical id handling
2100 b352ab5b Iustin Pop
  for disk in instance.disks:
2101 b352ab5b Iustin Pop
    cfg.SetDiskID(disk, instance.primary_node)
2102 b352ab5b Iustin Pop
2103 a8083063 Iustin Pop
  return disks_ok, device_info
2104 a8083063 Iustin Pop
2105 a8083063 Iustin Pop
2106 fe7b0351 Michael Hanselmann
def _StartInstanceDisks(cfg, instance, force):
2107 3ecf6786 Iustin Pop
  """Start the disks of an instance.
2108 3ecf6786 Iustin Pop

2109 3ecf6786 Iustin Pop
  """
2110 fe7b0351 Michael Hanselmann
  disks_ok, dummy = _AssembleInstanceDisks(instance, cfg,
2111 fe7b0351 Michael Hanselmann
                                           ignore_secondaries=force)
2112 fe7b0351 Michael Hanselmann
  if not disks_ok:
2113 fe7b0351 Michael Hanselmann
    _ShutdownInstanceDisks(instance, cfg)
2114 fe7b0351 Michael Hanselmann
    if force is not None and not force:
2115 fe7b0351 Michael Hanselmann
      logger.Error("If the message above refers to a secondary node,"
2116 fe7b0351 Michael Hanselmann
                   " you can retry the operation using '--force'.")
2117 3ecf6786 Iustin Pop
    raise errors.OpExecError("Disk consistency error")
2118 fe7b0351 Michael Hanselmann
2119 fe7b0351 Michael Hanselmann
2120 a8083063 Iustin Pop
class LUDeactivateInstanceDisks(NoHooksLU):
2121 a8083063 Iustin Pop
  """Shutdown an instance's disks.
2122 a8083063 Iustin Pop

2123 a8083063 Iustin Pop
  """
2124 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
2125 a8083063 Iustin Pop
2126 a8083063 Iustin Pop
  def CheckPrereq(self):
2127 a8083063 Iustin Pop
    """Check prerequisites.
2128 a8083063 Iustin Pop

2129 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2130 a8083063 Iustin Pop

2131 a8083063 Iustin Pop
    """
2132 a8083063 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
2133 a8083063 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
2134 a8083063 Iustin Pop
    if instance is None:
2135 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
2136 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2137 a8083063 Iustin Pop
    self.instance = instance
2138 a8083063 Iustin Pop
2139 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2140 a8083063 Iustin Pop
    """Deactivate the disks
2141 a8083063 Iustin Pop

2142 a8083063 Iustin Pop
    """
2143 a8083063 Iustin Pop
    instance = self.instance
2144 a8083063 Iustin Pop
    ins_l = rpc.call_instance_list([instance.primary_node])
2145 a8083063 Iustin Pop
    ins_l = ins_l[instance.primary_node]
2146 a8083063 Iustin Pop
    if not type(ins_l) is list:
2147 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't contact node '%s'" %
2148 3ecf6786 Iustin Pop
                               instance.primary_node)
2149 a8083063 Iustin Pop
2150 a8083063 Iustin Pop
    if self.instance.name in ins_l:
2151 3ecf6786 Iustin Pop
      raise errors.OpExecError("Instance is running, can't shutdown"
2152 3ecf6786 Iustin Pop
                               " block devices.")
2153 a8083063 Iustin Pop
2154 a8083063 Iustin Pop
    _ShutdownInstanceDisks(instance, self.cfg)
2155 a8083063 Iustin Pop
2156 a8083063 Iustin Pop
2157 a8083063 Iustin Pop
def _ShutdownInstanceDisks(instance, cfg, ignore_primary=False):
2158 a8083063 Iustin Pop
  """Shutdown block devices of an instance.
2159 a8083063 Iustin Pop

2160 a8083063 Iustin Pop
  This does the shutdown on all nodes of the instance.
2161 a8083063 Iustin Pop

2162 a8083063 Iustin Pop
  If the ignore_primary is false, errors on the primary node are
2163 a8083063 Iustin Pop
  ignored.
2164 a8083063 Iustin Pop

2165 a8083063 Iustin Pop
  """
2166 a8083063 Iustin Pop
  result = True
2167 a8083063 Iustin Pop
  for disk in instance.disks:
2168 a8083063 Iustin Pop
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
2169 a8083063 Iustin Pop
      cfg.SetDiskID(top_disk, node)
2170 a8083063 Iustin Pop
      if not rpc.call_blockdev_shutdown(node, top_disk):
2171 a8083063 Iustin Pop
        logger.Error("could not shutdown block device %s on node %s" %
2172 a8083063 Iustin Pop
                     (disk.iv_name, node))
2173 a8083063 Iustin Pop
        if not ignore_primary or node != instance.primary_node:
2174 a8083063 Iustin Pop
          result = False
2175 a8083063 Iustin Pop
  return result
2176 a8083063 Iustin Pop
2177 a8083063 Iustin Pop
2178 d4f16fd9 Iustin Pop
def _CheckNodeFreeMemory(cfg, node, reason, requested):
2179 d4f16fd9 Iustin Pop
  """Checks if a node has enough free memory.
2180 d4f16fd9 Iustin Pop

2181 d4f16fd9 Iustin Pop
  This function check if a given node has the needed amount of free
2182 d4f16fd9 Iustin Pop
  memory. In case the node has less memory or we cannot get the
2183 d4f16fd9 Iustin Pop
  information from the node, this function raise an OpPrereqError
2184 d4f16fd9 Iustin Pop
  exception.
2185 d4f16fd9 Iustin Pop

2186 d4f16fd9 Iustin Pop
  Args:
2187 d4f16fd9 Iustin Pop
    - cfg: a ConfigWriter instance
2188 d4f16fd9 Iustin Pop
    - node: the node name
2189 d4f16fd9 Iustin Pop
    - reason: string to use in the error message
2190 d4f16fd9 Iustin Pop
    - requested: the amount of memory in MiB
2191 d4f16fd9 Iustin Pop

2192 d4f16fd9 Iustin Pop
  """
2193 d4f16fd9 Iustin Pop
  nodeinfo = rpc.call_node_info([node], cfg.GetVGName())
2194 d4f16fd9 Iustin Pop
  if not nodeinfo or not isinstance(nodeinfo, dict):
2195 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Could not contact node %s for resource"
2196 d4f16fd9 Iustin Pop
                             " information" % (node,))
2197 d4f16fd9 Iustin Pop
2198 d4f16fd9 Iustin Pop
  free_mem = nodeinfo[node].get('memory_free')
2199 d4f16fd9 Iustin Pop
  if not isinstance(free_mem, int):
2200 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
2201 d4f16fd9 Iustin Pop
                             " was '%s'" % (node, free_mem))
2202 d4f16fd9 Iustin Pop
  if requested > free_mem:
2203 d4f16fd9 Iustin Pop
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
2204 d4f16fd9 Iustin Pop
                             " needed %s MiB, available %s MiB" %
2205 d4f16fd9 Iustin Pop
                             (node, reason, requested, free_mem))
2206 d4f16fd9 Iustin Pop
2207 d4f16fd9 Iustin Pop
2208 a8083063 Iustin Pop
class LUStartupInstance(LogicalUnit):
2209 a8083063 Iustin Pop
  """Starts an instance.
2210 a8083063 Iustin Pop

2211 a8083063 Iustin Pop
  """
2212 a8083063 Iustin Pop
  HPATH = "instance-start"
2213 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2214 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "force"]
2215 a8083063 Iustin Pop
2216 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2217 a8083063 Iustin Pop
    """Build hooks env.
2218 a8083063 Iustin Pop

2219 a8083063 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
2220 a8083063 Iustin Pop

2221 a8083063 Iustin Pop
    """
2222 a8083063 Iustin Pop
    env = {
2223 a8083063 Iustin Pop
      "FORCE": self.op.force,
2224 a8083063 Iustin Pop
      }
2225 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2226 880478f8 Iustin Pop
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2227 a8083063 Iustin Pop
          list(self.instance.secondary_nodes))
2228 a8083063 Iustin Pop
    return env, nl, nl
2229 a8083063 Iustin Pop
2230 a8083063 Iustin Pop
  def CheckPrereq(self):
2231 a8083063 Iustin Pop
    """Check prerequisites.
2232 a8083063 Iustin Pop

2233 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2234 a8083063 Iustin Pop

2235 a8083063 Iustin Pop
    """
2236 a8083063 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
2237 a8083063 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
2238 a8083063 Iustin Pop
    if instance is None:
2239 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
2240 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2241 a8083063 Iustin Pop
2242 a8083063 Iustin Pop
    # check bridges existance
2243 bf6929a2 Alexander Schreiber
    _CheckInstanceBridgesExist(instance)
2244 a8083063 Iustin Pop
2245 d4f16fd9 Iustin Pop
    _CheckNodeFreeMemory(self.cfg, instance.primary_node,
2246 d4f16fd9 Iustin Pop
                         "starting instance %s" % instance.name,
2247 d4f16fd9 Iustin Pop
                         instance.memory)
2248 d4f16fd9 Iustin Pop
2249 a8083063 Iustin Pop
    self.instance = instance
2250 a8083063 Iustin Pop
    self.op.instance_name = instance.name
2251 a8083063 Iustin Pop
2252 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2253 a8083063 Iustin Pop
    """Start the instance.
2254 a8083063 Iustin Pop

2255 a8083063 Iustin Pop
    """
2256 a8083063 Iustin Pop
    instance = self.instance
2257 a8083063 Iustin Pop
    force = self.op.force
2258 a8083063 Iustin Pop
    extra_args = getattr(self.op, "extra_args", "")
2259 a8083063 Iustin Pop
2260 fe482621 Iustin Pop
    self.cfg.MarkInstanceUp(instance.name)
2261 fe482621 Iustin Pop
2262 a8083063 Iustin Pop
    node_current = instance.primary_node
2263 a8083063 Iustin Pop
2264 fe7b0351 Michael Hanselmann
    _StartInstanceDisks(self.cfg, instance, force)
2265 a8083063 Iustin Pop
2266 a8083063 Iustin Pop
    if not rpc.call_instance_start(node_current, instance, extra_args):
2267 a8083063 Iustin Pop
      _ShutdownInstanceDisks(instance, self.cfg)
2268 3ecf6786 Iustin Pop
      raise errors.OpExecError("Could not start instance")
2269 a8083063 Iustin Pop
2270 a8083063 Iustin Pop
2271 bf6929a2 Alexander Schreiber
class LURebootInstance(LogicalUnit):
2272 bf6929a2 Alexander Schreiber
  """Reboot an instance.
2273 bf6929a2 Alexander Schreiber

2274 bf6929a2 Alexander Schreiber
  """
2275 bf6929a2 Alexander Schreiber
  HPATH = "instance-reboot"
2276 bf6929a2 Alexander Schreiber
  HTYPE = constants.HTYPE_INSTANCE
2277 bf6929a2 Alexander Schreiber
  _OP_REQP = ["instance_name", "ignore_secondaries", "reboot_type"]
2278 bf6929a2 Alexander Schreiber
2279 bf6929a2 Alexander Schreiber
  def BuildHooksEnv(self):
2280 bf6929a2 Alexander Schreiber
    """Build hooks env.
2281 bf6929a2 Alexander Schreiber

2282 bf6929a2 Alexander Schreiber
    This runs on master, primary and secondary nodes of the instance.
2283 bf6929a2 Alexander Schreiber

2284 bf6929a2 Alexander Schreiber
    """
2285 bf6929a2 Alexander Schreiber
    env = {
2286 bf6929a2 Alexander Schreiber
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
2287 bf6929a2 Alexander Schreiber
      }
2288 bf6929a2 Alexander Schreiber
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2289 bf6929a2 Alexander Schreiber
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2290 bf6929a2 Alexander Schreiber
          list(self.instance.secondary_nodes))
2291 bf6929a2 Alexander Schreiber
    return env, nl, nl
2292 bf6929a2 Alexander Schreiber
2293 bf6929a2 Alexander Schreiber
  def CheckPrereq(self):
2294 bf6929a2 Alexander Schreiber
    """Check prerequisites.
2295 bf6929a2 Alexander Schreiber

2296 bf6929a2 Alexander Schreiber
    This checks that the instance is in the cluster.
2297 bf6929a2 Alexander Schreiber

2298 bf6929a2 Alexander Schreiber
    """
2299 bf6929a2 Alexander Schreiber
    instance = self.cfg.GetInstanceInfo(
2300 bf6929a2 Alexander Schreiber
      self.cfg.ExpandInstanceName(self.op.instance_name))
2301 bf6929a2 Alexander Schreiber
    if instance is None:
2302 bf6929a2 Alexander Schreiber
      raise errors.OpPrereqError("Instance '%s' not known" %
2303 bf6929a2 Alexander Schreiber
                                 self.op.instance_name)
2304 bf6929a2 Alexander Schreiber
2305 bf6929a2 Alexander Schreiber
    # check bridges existance
2306 bf6929a2 Alexander Schreiber
    _CheckInstanceBridgesExist(instance)
2307 bf6929a2 Alexander Schreiber
2308 bf6929a2 Alexander Schreiber
    self.instance = instance
2309 bf6929a2 Alexander Schreiber
    self.op.instance_name = instance.name
2310 bf6929a2 Alexander Schreiber
2311 bf6929a2 Alexander Schreiber
  def Exec(self, feedback_fn):
2312 bf6929a2 Alexander Schreiber
    """Reboot the instance.
2313 bf6929a2 Alexander Schreiber

2314 bf6929a2 Alexander Schreiber
    """
2315 bf6929a2 Alexander Schreiber
    instance = self.instance
2316 bf6929a2 Alexander Schreiber
    ignore_secondaries = self.op.ignore_secondaries
2317 bf6929a2 Alexander Schreiber
    reboot_type = self.op.reboot_type
2318 bf6929a2 Alexander Schreiber
    extra_args = getattr(self.op, "extra_args", "")
2319 bf6929a2 Alexander Schreiber
2320 bf6929a2 Alexander Schreiber
    node_current = instance.primary_node
2321 bf6929a2 Alexander Schreiber
2322 bf6929a2 Alexander Schreiber
    if reboot_type not in [constants.INSTANCE_REBOOT_SOFT,
2323 bf6929a2 Alexander Schreiber
                           constants.INSTANCE_REBOOT_HARD,
2324 bf6929a2 Alexander Schreiber
                           constants.INSTANCE_REBOOT_FULL]:
2325 bf6929a2 Alexander Schreiber
      raise errors.ParameterError("reboot type not in [%s, %s, %s]" %
2326 bf6929a2 Alexander Schreiber
                                  (constants.INSTANCE_REBOOT_SOFT,
2327 bf6929a2 Alexander Schreiber
                                   constants.INSTANCE_REBOOT_HARD,
2328 bf6929a2 Alexander Schreiber
                                   constants.INSTANCE_REBOOT_FULL))
2329 bf6929a2 Alexander Schreiber
2330 bf6929a2 Alexander Schreiber
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
2331 bf6929a2 Alexander Schreiber
                       constants.INSTANCE_REBOOT_HARD]:
2332 bf6929a2 Alexander Schreiber
      if not rpc.call_instance_reboot(node_current, instance,
2333 bf6929a2 Alexander Schreiber
                                      reboot_type, extra_args):
2334 bf6929a2 Alexander Schreiber
        raise errors.OpExecError("Could not reboot instance")
2335 bf6929a2 Alexander Schreiber
    else:
2336 bf6929a2 Alexander Schreiber
      if not rpc.call_instance_shutdown(node_current, instance):
2337 bf6929a2 Alexander Schreiber
        raise errors.OpExecError("could not shutdown instance for full reboot")
2338 bf6929a2 Alexander Schreiber
      _ShutdownInstanceDisks(instance, self.cfg)
2339 bf6929a2 Alexander Schreiber
      _StartInstanceDisks(self.cfg, instance, ignore_secondaries)
2340 bf6929a2 Alexander Schreiber
      if not rpc.call_instance_start(node_current, instance, extra_args):
2341 bf6929a2 Alexander Schreiber
        _ShutdownInstanceDisks(instance, self.cfg)
2342 bf6929a2 Alexander Schreiber
        raise errors.OpExecError("Could not start instance for full reboot")
2343 bf6929a2 Alexander Schreiber
2344 bf6929a2 Alexander Schreiber
    self.cfg.MarkInstanceUp(instance.name)
2345 bf6929a2 Alexander Schreiber
2346 bf6929a2 Alexander Schreiber
2347 a8083063 Iustin Pop
class LUShutdownInstance(LogicalUnit):
2348 a8083063 Iustin Pop
  """Shutdown an instance.
2349 a8083063 Iustin Pop

2350 a8083063 Iustin Pop
  """
2351 a8083063 Iustin Pop
  HPATH = "instance-stop"
2352 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2353 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
2354 a8083063 Iustin Pop
2355 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2356 a8083063 Iustin Pop
    """Build hooks env.
2357 a8083063 Iustin Pop

2358 a8083063 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
2359 a8083063 Iustin Pop

2360 a8083063 Iustin Pop
    """
2361 396e1b78 Michael Hanselmann
    env = _BuildInstanceHookEnvByObject(self.instance)
2362 880478f8 Iustin Pop
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2363 a8083063 Iustin Pop
          list(self.instance.secondary_nodes))
2364 a8083063 Iustin Pop
    return env, nl, nl
2365 a8083063 Iustin Pop
2366 a8083063 Iustin Pop
  def CheckPrereq(self):
2367 a8083063 Iustin Pop
    """Check prerequisites.
2368 a8083063 Iustin Pop

2369 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2370 a8083063 Iustin Pop

2371 a8083063 Iustin Pop
    """
2372 a8083063 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
2373 a8083063 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
2374 a8083063 Iustin Pop
    if instance is None:
2375 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
2376 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2377 a8083063 Iustin Pop
    self.instance = instance
2378 a8083063 Iustin Pop
2379 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2380 a8083063 Iustin Pop
    """Shutdown the instance.
2381 a8083063 Iustin Pop

2382 a8083063 Iustin Pop
    """
2383 a8083063 Iustin Pop
    instance = self.instance
2384 a8083063 Iustin Pop
    node_current = instance.primary_node
2385 fe482621 Iustin Pop
    self.cfg.MarkInstanceDown(instance.name)
2386 a8083063 Iustin Pop
    if not rpc.call_instance_shutdown(node_current, instance):
2387 a8083063 Iustin Pop
      logger.Error("could not shutdown instance")
2388 a8083063 Iustin Pop
2389 a8083063 Iustin Pop
    _ShutdownInstanceDisks(instance, self.cfg)
2390 a8083063 Iustin Pop
2391 a8083063 Iustin Pop
2392 fe7b0351 Michael Hanselmann
class LUReinstallInstance(LogicalUnit):
2393 fe7b0351 Michael Hanselmann
  """Reinstall an instance.
2394 fe7b0351 Michael Hanselmann

2395 fe7b0351 Michael Hanselmann
  """
2396 fe7b0351 Michael Hanselmann
  HPATH = "instance-reinstall"
2397 fe7b0351 Michael Hanselmann
  HTYPE = constants.HTYPE_INSTANCE
2398 fe7b0351 Michael Hanselmann
  _OP_REQP = ["instance_name"]
2399 fe7b0351 Michael Hanselmann
2400 fe7b0351 Michael Hanselmann
  def BuildHooksEnv(self):
2401 fe7b0351 Michael Hanselmann
    """Build hooks env.
2402 fe7b0351 Michael Hanselmann

2403 fe7b0351 Michael Hanselmann
    This runs on master, primary and secondary nodes of the instance.
2404 fe7b0351 Michael Hanselmann

2405 fe7b0351 Michael Hanselmann
    """
2406 396e1b78 Michael Hanselmann
    env = _BuildInstanceHookEnvByObject(self.instance)
2407 fe7b0351 Michael Hanselmann
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2408 fe7b0351 Michael Hanselmann
          list(self.instance.secondary_nodes))
2409 fe7b0351 Michael Hanselmann
    return env, nl, nl
2410 fe7b0351 Michael Hanselmann
2411 fe7b0351 Michael Hanselmann
  def CheckPrereq(self):
2412 fe7b0351 Michael Hanselmann
    """Check prerequisites.
2413 fe7b0351 Michael Hanselmann

2414 fe7b0351 Michael Hanselmann
    This checks that the instance is in the cluster and is not running.
2415 fe7b0351 Michael Hanselmann

2416 fe7b0351 Michael Hanselmann
    """
2417 fe7b0351 Michael Hanselmann
    instance = self.cfg.GetInstanceInfo(
2418 fe7b0351 Michael Hanselmann
      self.cfg.ExpandInstanceName(self.op.instance_name))
2419 fe7b0351 Michael Hanselmann
    if instance is None:
2420 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
2421 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2422 fe7b0351 Michael Hanselmann
    if instance.disk_template == constants.DT_DISKLESS:
2423 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' has no disks" %
2424 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2425 fe7b0351 Michael Hanselmann
    if instance.status != "down":
2426 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2427 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2428 fe7b0351 Michael Hanselmann
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2429 fe7b0351 Michael Hanselmann
    if remote_info:
2430 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2431 3ecf6786 Iustin Pop
                                 (self.op.instance_name,
2432 3ecf6786 Iustin Pop
                                  instance.primary_node))
2433 d0834de3 Michael Hanselmann
2434 d0834de3 Michael Hanselmann
    self.op.os_type = getattr(self.op, "os_type", None)
2435 d0834de3 Michael Hanselmann
    if self.op.os_type is not None:
2436 d0834de3 Michael Hanselmann
      # OS verification
2437 d0834de3 Michael Hanselmann
      pnode = self.cfg.GetNodeInfo(
2438 d0834de3 Michael Hanselmann
        self.cfg.ExpandNodeName(instance.primary_node))
2439 d0834de3 Michael Hanselmann
      if pnode is None:
2440 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Primary node '%s' is unknown" %
2441 3ecf6786 Iustin Pop
                                   self.op.pnode)
2442 00fe9e38 Guido Trotter
      os_obj = rpc.call_os_get(pnode.name, self.op.os_type)
2443 dfa96ded Guido Trotter
      if not os_obj:
2444 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("OS '%s' not in supported OS list for"
2445 3ecf6786 Iustin Pop
                                   " primary node"  % self.op.os_type)
2446 d0834de3 Michael Hanselmann
2447 fe7b0351 Michael Hanselmann
    self.instance = instance
2448 fe7b0351 Michael Hanselmann
2449 fe7b0351 Michael Hanselmann
  def Exec(self, feedback_fn):
2450 fe7b0351 Michael Hanselmann
    """Reinstall the instance.
2451 fe7b0351 Michael Hanselmann

2452 fe7b0351 Michael Hanselmann
    """
2453 fe7b0351 Michael Hanselmann
    inst = self.instance
2454 fe7b0351 Michael Hanselmann
2455 d0834de3 Michael Hanselmann
    if self.op.os_type is not None:
2456 d0834de3 Michael Hanselmann
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
2457 d0834de3 Michael Hanselmann
      inst.os = self.op.os_type
2458 d0834de3 Michael Hanselmann
      self.cfg.AddInstance(inst)
2459 d0834de3 Michael Hanselmann
2460 fe7b0351 Michael Hanselmann
    _StartInstanceDisks(self.cfg, inst, None)
2461 fe7b0351 Michael Hanselmann
    try:
2462 fe7b0351 Michael Hanselmann
      feedback_fn("Running the instance OS create scripts...")
2463 fe7b0351 Michael Hanselmann
      if not rpc.call_instance_os_add(inst.primary_node, inst, "sda", "sdb"):
2464 f4bc1f2c Michael Hanselmann
        raise errors.OpExecError("Could not install OS for instance %s"
2465 f4bc1f2c Michael Hanselmann
                                 " on node %s" %
2466 3ecf6786 Iustin Pop
                                 (inst.name, inst.primary_node))
2467 fe7b0351 Michael Hanselmann
    finally:
2468 fe7b0351 Michael Hanselmann
      _ShutdownInstanceDisks(inst, self.cfg)
2469 fe7b0351 Michael Hanselmann
2470 fe7b0351 Michael Hanselmann
2471 decd5f45 Iustin Pop
class LURenameInstance(LogicalUnit):
2472 decd5f45 Iustin Pop
  """Rename an instance.
2473 decd5f45 Iustin Pop

2474 decd5f45 Iustin Pop
  """
2475 decd5f45 Iustin Pop
  HPATH = "instance-rename"
2476 decd5f45 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2477 decd5f45 Iustin Pop
  _OP_REQP = ["instance_name", "new_name"]
2478 decd5f45 Iustin Pop
2479 decd5f45 Iustin Pop
  def BuildHooksEnv(self):
2480 decd5f45 Iustin Pop
    """Build hooks env.
2481 decd5f45 Iustin Pop

2482 decd5f45 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
2483 decd5f45 Iustin Pop

2484 decd5f45 Iustin Pop
    """
2485 decd5f45 Iustin Pop
    env = _BuildInstanceHookEnvByObject(self.instance)
2486 decd5f45 Iustin Pop
    env["INSTANCE_NEW_NAME"] = self.op.new_name
2487 decd5f45 Iustin Pop
    nl = ([self.sstore.GetMasterNode(), self.instance.primary_node] +
2488 decd5f45 Iustin Pop
          list(self.instance.secondary_nodes))
2489 decd5f45 Iustin Pop
    return env, nl, nl
2490 decd5f45 Iustin Pop
2491 decd5f45 Iustin Pop
  def CheckPrereq(self):
2492 decd5f45 Iustin Pop
    """Check prerequisites.
2493 decd5f45 Iustin Pop

2494 decd5f45 Iustin Pop
    This checks that the instance is in the cluster and is not running.
2495 decd5f45 Iustin Pop

2496 decd5f45 Iustin Pop
    """
2497 decd5f45 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
2498 decd5f45 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
2499 decd5f45 Iustin Pop
    if instance is None:
2500 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
2501 decd5f45 Iustin Pop
                                 self.op.instance_name)
2502 decd5f45 Iustin Pop
    if instance.status != "down":
2503 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is marked to be up" %
2504 decd5f45 Iustin Pop
                                 self.op.instance_name)
2505 decd5f45 Iustin Pop
    remote_info = rpc.call_instance_info(instance.primary_node, instance.name)
2506 decd5f45 Iustin Pop
    if remote_info:
2507 decd5f45 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is running on the node %s" %
2508 decd5f45 Iustin Pop
                                 (self.op.instance_name,
2509 decd5f45 Iustin Pop
                                  instance.primary_node))
2510 decd5f45 Iustin Pop
    self.instance = instance
2511 decd5f45 Iustin Pop
2512 decd5f45 Iustin Pop
    # new name verification
2513 89e1fc26 Iustin Pop
    name_info = utils.HostInfo(self.op.new_name)
2514 decd5f45 Iustin Pop
2515 89e1fc26 Iustin Pop
    self.op.new_name = new_name = name_info.name
2516 7bde3275 Guido Trotter
    instance_list = self.cfg.GetInstanceList()
2517 7bde3275 Guido Trotter
    if new_name in instance_list:
2518 7bde3275 Guido Trotter
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
2519 c09f363f Manuel Franceschini
                                 new_name)
2520 7bde3275 Guido Trotter
2521 decd5f45 Iustin Pop
    if not getattr(self.op, "ignore_ip", False):
2522 89e1fc26 Iustin Pop
      command = ["fping", "-q", name_info.ip]
2523 decd5f45 Iustin Pop
      result = utils.RunCmd(command)
2524 decd5f45 Iustin Pop
      if not result.failed:
2525 decd5f45 Iustin Pop
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
2526 89e1fc26 Iustin Pop
                                   (name_info.ip, new_name))
2527 decd5f45 Iustin Pop
2528 decd5f45 Iustin Pop
2529 decd5f45 Iustin Pop
  def Exec(self, feedback_fn):
2530 decd5f45 Iustin Pop
    """Reinstall the instance.
2531 decd5f45 Iustin Pop

2532 decd5f45 Iustin Pop
    """
2533 decd5f45 Iustin Pop
    inst = self.instance
2534 decd5f45 Iustin Pop
    old_name = inst.name
2535 decd5f45 Iustin Pop
2536 b23c4333 Manuel Franceschini
    if inst.disk_template == constants.DT_FILE:
2537 b23c4333 Manuel Franceschini
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2538 b23c4333 Manuel Franceschini
2539 decd5f45 Iustin Pop
    self.cfg.RenameInstance(inst.name, self.op.new_name)
2540 decd5f45 Iustin Pop
2541 decd5f45 Iustin Pop
    # re-read the instance from the configuration after rename
2542 decd5f45 Iustin Pop
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
2543 decd5f45 Iustin Pop
2544 b23c4333 Manuel Franceschini
    if inst.disk_template == constants.DT_FILE:
2545 b23c4333 Manuel Franceschini
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
2546 b23c4333 Manuel Franceschini
      result = rpc.call_file_storage_dir_rename(inst.primary_node,
2547 b23c4333 Manuel Franceschini
                                                old_file_storage_dir,
2548 b23c4333 Manuel Franceschini
                                                new_file_storage_dir)
2549 b23c4333 Manuel Franceschini
2550 b23c4333 Manuel Franceschini
      if not result:
2551 b23c4333 Manuel Franceschini
        raise errors.OpExecError("Could not connect to node '%s' to rename"
2552 b23c4333 Manuel Franceschini
                                 " directory '%s' to '%s' (but the instance"
2553 b23c4333 Manuel Franceschini
                                 " has been renamed in Ganeti)" % (
2554 b23c4333 Manuel Franceschini
                                 inst.primary_node, old_file_storage_dir,
2555 b23c4333 Manuel Franceschini
                                 new_file_storage_dir))
2556 b23c4333 Manuel Franceschini
2557 b23c4333 Manuel Franceschini
      if not result[0]:
2558 b23c4333 Manuel Franceschini
        raise errors.OpExecError("Could not rename directory '%s' to '%s'"
2559 b23c4333 Manuel Franceschini
                                 " (but the instance has been renamed in"
2560 b23c4333 Manuel Franceschini
                                 " Ganeti)" % (old_file_storage_dir,
2561 b23c4333 Manuel Franceschini
                                               new_file_storage_dir))
2562 b23c4333 Manuel Franceschini
2563 decd5f45 Iustin Pop
    _StartInstanceDisks(self.cfg, inst, None)
2564 decd5f45 Iustin Pop
    try:
2565 decd5f45 Iustin Pop
      if not rpc.call_instance_run_rename(inst.primary_node, inst, old_name,
2566 decd5f45 Iustin Pop
                                          "sda", "sdb"):
2567 f4bc1f2c Michael Hanselmann
        msg = ("Could run OS rename script for instance %s on node %s (but the"
2568 f4bc1f2c Michael Hanselmann
               " instance has been renamed in Ganeti)" %
2569 decd5f45 Iustin Pop
               (inst.name, inst.primary_node))
2570 decd5f45 Iustin Pop
        logger.Error(msg)
2571 decd5f45 Iustin Pop
    finally:
2572 decd5f45 Iustin Pop
      _ShutdownInstanceDisks(inst, self.cfg)
2573 decd5f45 Iustin Pop
2574 decd5f45 Iustin Pop
2575 a8083063 Iustin Pop
class LURemoveInstance(LogicalUnit):
2576 a8083063 Iustin Pop
  """Remove an instance.
2577 a8083063 Iustin Pop

2578 a8083063 Iustin Pop
  """
2579 a8083063 Iustin Pop
  HPATH = "instance-remove"
2580 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2581 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
2582 a8083063 Iustin Pop
2583 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2584 a8083063 Iustin Pop
    """Build hooks env.
2585 a8083063 Iustin Pop

2586 a8083063 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
2587 a8083063 Iustin Pop

2588 a8083063 Iustin Pop
    """
2589 396e1b78 Michael Hanselmann
    env = _BuildInstanceHookEnvByObject(self.instance)
2590 1d67656e Iustin Pop
    nl = [self.sstore.GetMasterNode()]
2591 a8083063 Iustin Pop
    return env, nl, nl
2592 a8083063 Iustin Pop
2593 a8083063 Iustin Pop
  def CheckPrereq(self):
2594 a8083063 Iustin Pop
    """Check prerequisites.
2595 a8083063 Iustin Pop

2596 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2597 a8083063 Iustin Pop

2598 a8083063 Iustin Pop
    """
2599 a8083063 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
2600 a8083063 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
2601 a8083063 Iustin Pop
    if instance is None:
2602 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
2603 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2604 a8083063 Iustin Pop
    self.instance = instance
2605 a8083063 Iustin Pop
2606 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2607 a8083063 Iustin Pop
    """Remove the instance.
2608 a8083063 Iustin Pop

2609 a8083063 Iustin Pop
    """
2610 a8083063 Iustin Pop
    instance = self.instance
2611 a8083063 Iustin Pop
    logger.Info("shutting down instance %s on node %s" %
2612 a8083063 Iustin Pop
                (instance.name, instance.primary_node))
2613 a8083063 Iustin Pop
2614 a8083063 Iustin Pop
    if not rpc.call_instance_shutdown(instance.primary_node, instance):
2615 1d67656e Iustin Pop
      if self.op.ignore_failures:
2616 1d67656e Iustin Pop
        feedback_fn("Warning: can't shutdown instance")
2617 1d67656e Iustin Pop
      else:
2618 1d67656e Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2619 1d67656e Iustin Pop
                                 (instance.name, instance.primary_node))
2620 a8083063 Iustin Pop
2621 a8083063 Iustin Pop
    logger.Info("removing block devices for instance %s" % instance.name)
2622 a8083063 Iustin Pop
2623 1d67656e Iustin Pop
    if not _RemoveDisks(instance, self.cfg):
2624 1d67656e Iustin Pop
      if self.op.ignore_failures:
2625 1d67656e Iustin Pop
        feedback_fn("Warning: can't remove instance's disks")
2626 1d67656e Iustin Pop
      else:
2627 1d67656e Iustin Pop
        raise errors.OpExecError("Can't remove instance's disks")
2628 a8083063 Iustin Pop
2629 a8083063 Iustin Pop
    logger.Info("removing instance %s out of cluster config" % instance.name)
2630 a8083063 Iustin Pop
2631 a8083063 Iustin Pop
    self.cfg.RemoveInstance(instance.name)
2632 a8083063 Iustin Pop
2633 a8083063 Iustin Pop
2634 a8083063 Iustin Pop
class LUQueryInstances(NoHooksLU):
2635 a8083063 Iustin Pop
  """Logical unit for querying instances.
2636 a8083063 Iustin Pop

2637 a8083063 Iustin Pop
  """
2638 069dcc86 Iustin Pop
  _OP_REQP = ["output_fields", "names"]
2639 a8083063 Iustin Pop
2640 a8083063 Iustin Pop
  def CheckPrereq(self):
2641 a8083063 Iustin Pop
    """Check prerequisites.
2642 a8083063 Iustin Pop

2643 a8083063 Iustin Pop
    This checks that the fields required are valid output fields.
2644 a8083063 Iustin Pop

2645 a8083063 Iustin Pop
    """
2646 d8052456 Iustin Pop
    self.dynamic_fields = frozenset(["oper_state", "oper_ram", "status"])
2647 dcb93971 Michael Hanselmann
    _CheckOutputFields(static=["name", "os", "pnode", "snodes",
2648 dcb93971 Michael Hanselmann
                               "admin_state", "admin_ram",
2649 644eeef9 Iustin Pop
                               "disk_template", "ip", "mac", "bridge",
2650 d6d415e8 Iustin Pop
                               "sda_size", "sdb_size", "vcpus"],
2651 dcb93971 Michael Hanselmann
                       dynamic=self.dynamic_fields,
2652 dcb93971 Michael Hanselmann
                       selected=self.op.output_fields)
2653 a8083063 Iustin Pop
2654 069dcc86 Iustin Pop
    self.wanted = _GetWantedInstances(self, self.op.names)
2655 069dcc86 Iustin Pop
2656 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2657 a8083063 Iustin Pop
    """Computes the list of nodes and their attributes.
2658 a8083063 Iustin Pop

2659 a8083063 Iustin Pop
    """
2660 069dcc86 Iustin Pop
    instance_names = self.wanted
2661 a8083063 Iustin Pop
    instance_list = [self.cfg.GetInstanceInfo(iname) for iname
2662 a8083063 Iustin Pop
                     in instance_names]
2663 a8083063 Iustin Pop
2664 a8083063 Iustin Pop
    # begin data gathering
2665 a8083063 Iustin Pop
2666 a8083063 Iustin Pop
    nodes = frozenset([inst.primary_node for inst in instance_list])
2667 a8083063 Iustin Pop
2668 a8083063 Iustin Pop
    bad_nodes = []
2669 a8083063 Iustin Pop
    if self.dynamic_fields.intersection(self.op.output_fields):
2670 a8083063 Iustin Pop
      live_data = {}
2671 a8083063 Iustin Pop
      node_data = rpc.call_all_instances_info(nodes)
2672 a8083063 Iustin Pop
      for name in nodes:
2673 a8083063 Iustin Pop
        result = node_data[name]
2674 a8083063 Iustin Pop
        if result:
2675 a8083063 Iustin Pop
          live_data.update(result)
2676 a8083063 Iustin Pop
        elif result == False:
2677 a8083063 Iustin Pop
          bad_nodes.append(name)
2678 a8083063 Iustin Pop
        # else no instance is alive
2679 a8083063 Iustin Pop
    else:
2680 a8083063 Iustin Pop
      live_data = dict([(name, {}) for name in instance_names])
2681 a8083063 Iustin Pop
2682 a8083063 Iustin Pop
    # end data gathering
2683 a8083063 Iustin Pop
2684 a8083063 Iustin Pop
    output = []
2685 a8083063 Iustin Pop
    for instance in instance_list:
2686 a8083063 Iustin Pop
      iout = []
2687 a8083063 Iustin Pop
      for field in self.op.output_fields:
2688 a8083063 Iustin Pop
        if field == "name":
2689 a8083063 Iustin Pop
          val = instance.name
2690 a8083063 Iustin Pop
        elif field == "os":
2691 a8083063 Iustin Pop
          val = instance.os
2692 a8083063 Iustin Pop
        elif field == "pnode":
2693 a8083063 Iustin Pop
          val = instance.primary_node
2694 a8083063 Iustin Pop
        elif field == "snodes":
2695 8a23d2d3 Iustin Pop
          val = list(instance.secondary_nodes)
2696 a8083063 Iustin Pop
        elif field == "admin_state":
2697 8a23d2d3 Iustin Pop
          val = (instance.status != "down")
2698 a8083063 Iustin Pop
        elif field == "oper_state":
2699 a8083063 Iustin Pop
          if instance.primary_node in bad_nodes:
2700 8a23d2d3 Iustin Pop
            val = None
2701 a8083063 Iustin Pop
          else:
2702 8a23d2d3 Iustin Pop
            val = bool(live_data.get(instance.name))
2703 d8052456 Iustin Pop
        elif field == "status":
2704 d8052456 Iustin Pop
          if instance.primary_node in bad_nodes:
2705 d8052456 Iustin Pop
            val = "ERROR_nodedown"
2706 d8052456 Iustin Pop
          else:
2707 d8052456 Iustin Pop
            running = bool(live_data.get(instance.name))
2708 d8052456 Iustin Pop
            if running:
2709 d8052456 Iustin Pop
              if instance.status != "down":
2710 d8052456 Iustin Pop
                val = "running"
2711 d8052456 Iustin Pop
              else:
2712 d8052456 Iustin Pop
                val = "ERROR_up"
2713 d8052456 Iustin Pop
            else:
2714 d8052456 Iustin Pop
              if instance.status != "down":
2715 d8052456 Iustin Pop
                val = "ERROR_down"
2716 d8052456 Iustin Pop
              else:
2717 d8052456 Iustin Pop
                val = "ADMIN_down"
2718 a8083063 Iustin Pop
        elif field == "admin_ram":
2719 a8083063 Iustin Pop
          val = instance.memory
2720 a8083063 Iustin Pop
        elif field == "oper_ram":
2721 a8083063 Iustin Pop
          if instance.primary_node in bad_nodes:
2722 8a23d2d3 Iustin Pop
            val = None
2723 a8083063 Iustin Pop
          elif instance.name in live_data:
2724 a8083063 Iustin Pop
            val = live_data[instance.name].get("memory", "?")
2725 a8083063 Iustin Pop
          else:
2726 a8083063 Iustin Pop
            val = "-"
2727 a8083063 Iustin Pop
        elif field == "disk_template":
2728 a8083063 Iustin Pop
          val = instance.disk_template
2729 a8083063 Iustin Pop
        elif field == "ip":
2730 a8083063 Iustin Pop
          val = instance.nics[0].ip
2731 a8083063 Iustin Pop
        elif field == "bridge":
2732 a8083063 Iustin Pop
          val = instance.nics[0].bridge
2733 a8083063 Iustin Pop
        elif field == "mac":
2734 a8083063 Iustin Pop
          val = instance.nics[0].mac
2735 644eeef9 Iustin Pop
        elif field == "sda_size" or field == "sdb_size":
2736 644eeef9 Iustin Pop
          disk = instance.FindDisk(field[:3])
2737 644eeef9 Iustin Pop
          if disk is None:
2738 8a23d2d3 Iustin Pop
            val = None
2739 644eeef9 Iustin Pop
          else:
2740 644eeef9 Iustin Pop
            val = disk.size
2741 d6d415e8 Iustin Pop
        elif field == "vcpus":
2742 d6d415e8 Iustin Pop
          val = instance.vcpus
2743 a8083063 Iustin Pop
        else:
2744 3ecf6786 Iustin Pop
          raise errors.ParameterError(field)
2745 a8083063 Iustin Pop
        iout.append(val)
2746 a8083063 Iustin Pop
      output.append(iout)
2747 a8083063 Iustin Pop
2748 a8083063 Iustin Pop
    return output
2749 a8083063 Iustin Pop
2750 a8083063 Iustin Pop
2751 a8083063 Iustin Pop
class LUFailoverInstance(LogicalUnit):
2752 a8083063 Iustin Pop
  """Failover an instance.
2753 a8083063 Iustin Pop

2754 a8083063 Iustin Pop
  """
2755 a8083063 Iustin Pop
  HPATH = "instance-failover"
2756 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
2757 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "ignore_consistency"]
2758 a8083063 Iustin Pop
2759 a8083063 Iustin Pop
  def BuildHooksEnv(self):
2760 a8083063 Iustin Pop
    """Build hooks env.
2761 a8083063 Iustin Pop

2762 a8083063 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
2763 a8083063 Iustin Pop

2764 a8083063 Iustin Pop
    """
2765 a8083063 Iustin Pop
    env = {
2766 a8083063 Iustin Pop
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
2767 a8083063 Iustin Pop
      }
2768 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnvByObject(self.instance))
2769 880478f8 Iustin Pop
    nl = [self.sstore.GetMasterNode()] + list(self.instance.secondary_nodes)
2770 a8083063 Iustin Pop
    return env, nl, nl
2771 a8083063 Iustin Pop
2772 a8083063 Iustin Pop
  def CheckPrereq(self):
2773 a8083063 Iustin Pop
    """Check prerequisites.
2774 a8083063 Iustin Pop

2775 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
2776 a8083063 Iustin Pop

2777 a8083063 Iustin Pop
    """
2778 a8083063 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
2779 a8083063 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
2780 a8083063 Iustin Pop
    if instance is None:
2781 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
2782 3ecf6786 Iustin Pop
                                 self.op.instance_name)
2783 a8083063 Iustin Pop
2784 a1f445d3 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
2785 2a710df1 Michael Hanselmann
      raise errors.OpPrereqError("Instance's disk layout is not"
2786 a1f445d3 Iustin Pop
                                 " network mirrored, cannot failover.")
2787 2a710df1 Michael Hanselmann
2788 2a710df1 Michael Hanselmann
    secondary_nodes = instance.secondary_nodes
2789 2a710df1 Michael Hanselmann
    if not secondary_nodes:
2790 2a710df1 Michael Hanselmann
      raise errors.ProgrammerError("no secondary node but using "
2791 2a710df1 Michael Hanselmann
                                   "DT_REMOTE_RAID1 template")
2792 2a710df1 Michael Hanselmann
2793 2a710df1 Michael Hanselmann
    target_node = secondary_nodes[0]
2794 d4f16fd9 Iustin Pop
    # check memory requirements on the secondary node
2795 d4f16fd9 Iustin Pop
    _CheckNodeFreeMemory(self.cfg, target_node, "failing over instance %s" %
2796 d4f16fd9 Iustin Pop
                         instance.name, instance.memory)
2797 3a7c308e Guido Trotter
2798 a8083063 Iustin Pop
    # check bridge existance
2799 a8083063 Iustin Pop
    brlist = [nic.bridge for nic in instance.nics]
2800 50ff9a7a Iustin Pop
    if not rpc.call_bridges_exist(target_node, brlist):
2801 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("One or more target bridges %s does not"
2802 3ecf6786 Iustin Pop
                                 " exist on destination node '%s'" %
2803 50ff9a7a Iustin Pop
                                 (brlist, target_node))
2804 a8083063 Iustin Pop
2805 a8083063 Iustin Pop
    self.instance = instance
2806 a8083063 Iustin Pop
2807 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
2808 a8083063 Iustin Pop
    """Failover an instance.
2809 a8083063 Iustin Pop

2810 a8083063 Iustin Pop
    The failover is done by shutting it down on its present node and
2811 a8083063 Iustin Pop
    starting it on the secondary.
2812 a8083063 Iustin Pop

2813 a8083063 Iustin Pop
    """
2814 a8083063 Iustin Pop
    instance = self.instance
2815 a8083063 Iustin Pop
2816 a8083063 Iustin Pop
    source_node = instance.primary_node
2817 a8083063 Iustin Pop
    target_node = instance.secondary_nodes[0]
2818 a8083063 Iustin Pop
2819 a8083063 Iustin Pop
    feedback_fn("* checking disk consistency between source and target")
2820 a8083063 Iustin Pop
    for dev in instance.disks:
2821 a8083063 Iustin Pop
      # for remote_raid1, these are md over drbd
2822 a8083063 Iustin Pop
      if not _CheckDiskConsistency(self.cfg, dev, target_node, False):
2823 a0aaa0d0 Guido Trotter
        if instance.status == "up" and not self.op.ignore_consistency:
2824 3ecf6786 Iustin Pop
          raise errors.OpExecError("Disk %s is degraded on target node,"
2825 3ecf6786 Iustin Pop
                                   " aborting failover." % dev.iv_name)
2826 a8083063 Iustin Pop
2827 a8083063 Iustin Pop
    feedback_fn("* shutting down instance on source node")
2828 a8083063 Iustin Pop
    logger.Info("Shutting down instance %s on node %s" %
2829 a8083063 Iustin Pop
                (instance.name, source_node))
2830 a8083063 Iustin Pop
2831 a8083063 Iustin Pop
    if not rpc.call_instance_shutdown(source_node, instance):
2832 24a40d57 Iustin Pop
      if self.op.ignore_consistency:
2833 24a40d57 Iustin Pop
        logger.Error("Could not shutdown instance %s on node %s. Proceeding"
2834 24a40d57 Iustin Pop
                     " anyway. Please make sure node %s is down"  %
2835 24a40d57 Iustin Pop
                     (instance.name, source_node, source_node))
2836 24a40d57 Iustin Pop
      else:
2837 24a40d57 Iustin Pop
        raise errors.OpExecError("Could not shutdown instance %s on node %s" %
2838 24a40d57 Iustin Pop
                                 (instance.name, source_node))
2839 a8083063 Iustin Pop
2840 a8083063 Iustin Pop
    feedback_fn("* deactivating the instance's disks on source node")
2841 a8083063 Iustin Pop
    if not _ShutdownInstanceDisks(instance, self.cfg, ignore_primary=True):
2842 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't shut down the instance's disks.")
2843 a8083063 Iustin Pop
2844 a8083063 Iustin Pop
    instance.primary_node = target_node
2845 a8083063 Iustin Pop
    # distribute new instance config to the other nodes
2846 a8083063 Iustin Pop
    self.cfg.AddInstance(instance)
2847 a8083063 Iustin Pop
2848 12a0cfbe Guido Trotter
    # Only start the instance if it's marked as up
2849 12a0cfbe Guido Trotter
    if instance.status == "up":
2850 12a0cfbe Guido Trotter
      feedback_fn("* activating the instance's disks on target node")
2851 12a0cfbe Guido Trotter
      logger.Info("Starting instance %s on node %s" %
2852 12a0cfbe Guido Trotter
                  (instance.name, target_node))
2853 12a0cfbe Guido Trotter
2854 12a0cfbe Guido Trotter
      disks_ok, dummy = _AssembleInstanceDisks(instance, self.cfg,
2855 12a0cfbe Guido Trotter
                                               ignore_secondaries=True)
2856 12a0cfbe Guido Trotter
      if not disks_ok:
2857 12a0cfbe Guido Trotter
        _ShutdownInstanceDisks(instance, self.cfg)
2858 12a0cfbe Guido Trotter
        raise errors.OpExecError("Can't activate the instance's disks")
2859 a8083063 Iustin Pop
2860 12a0cfbe Guido Trotter
      feedback_fn("* starting the instance on the target node")
2861 12a0cfbe Guido Trotter
      if not rpc.call_instance_start(target_node, instance, None):
2862 12a0cfbe Guido Trotter
        _ShutdownInstanceDisks(instance, self.cfg)
2863 12a0cfbe Guido Trotter
        raise errors.OpExecError("Could not start instance %s on node %s." %
2864 12a0cfbe Guido Trotter
                                 (instance.name, target_node))
2865 a8083063 Iustin Pop
2866 a8083063 Iustin Pop
2867 3f78eef2 Iustin Pop
def _CreateBlockDevOnPrimary(cfg, node, instance, device, info):
2868 a8083063 Iustin Pop
  """Create a tree of block devices on the primary node.
2869 a8083063 Iustin Pop

2870 a8083063 Iustin Pop
  This always creates all devices.
2871 a8083063 Iustin Pop

2872 a8083063 Iustin Pop
  """
2873 a8083063 Iustin Pop
  if device.children:
2874 a8083063 Iustin Pop
    for child in device.children:
2875 3f78eef2 Iustin Pop
      if not _CreateBlockDevOnPrimary(cfg, node, instance, child, info):
2876 a8083063 Iustin Pop
        return False
2877 a8083063 Iustin Pop
2878 a8083063 Iustin Pop
  cfg.SetDiskID(device, node)
2879 3f78eef2 Iustin Pop
  new_id = rpc.call_blockdev_create(node, device, device.size,
2880 3f78eef2 Iustin Pop
                                    instance.name, True, info)
2881 a8083063 Iustin Pop
  if not new_id:
2882 a8083063 Iustin Pop
    return False
2883 a8083063 Iustin Pop
  if device.physical_id is None:
2884 a8083063 Iustin Pop
    device.physical_id = new_id
2885 a8083063 Iustin Pop
  return True
2886 a8083063 Iustin Pop
2887 a8083063 Iustin Pop
2888 3f78eef2 Iustin Pop
def _CreateBlockDevOnSecondary(cfg, node, instance, device, force, info):
2889 a8083063 Iustin Pop
  """Create a tree of block devices on a secondary node.
2890 a8083063 Iustin Pop

2891 a8083063 Iustin Pop
  If this device type has to be created on secondaries, create it and
2892 a8083063 Iustin Pop
  all its children.
2893 a8083063 Iustin Pop

2894 a8083063 Iustin Pop
  If not, just recurse to children keeping the same 'force' value.
2895 a8083063 Iustin Pop

2896 a8083063 Iustin Pop
  """
2897 a8083063 Iustin Pop
  if device.CreateOnSecondary():
2898 a8083063 Iustin Pop
    force = True
2899 a8083063 Iustin Pop
  if device.children:
2900 a8083063 Iustin Pop
    for child in device.children:
2901 3f78eef2 Iustin Pop
      if not _CreateBlockDevOnSecondary(cfg, node, instance,
2902 3f78eef2 Iustin Pop
                                        child, force, info):
2903 a8083063 Iustin Pop
        return False
2904 a8083063 Iustin Pop
2905 a8083063 Iustin Pop
  if not force:
2906 a8083063 Iustin Pop
    return True
2907 a8083063 Iustin Pop
  cfg.SetDiskID(device, node)
2908 3f78eef2 Iustin Pop
  new_id = rpc.call_blockdev_create(node, device, device.size,
2909 3f78eef2 Iustin Pop
                                    instance.name, False, info)
2910 a8083063 Iustin Pop
  if not new_id:
2911 a8083063 Iustin Pop
    return False
2912 a8083063 Iustin Pop
  if device.physical_id is None:
2913 a8083063 Iustin Pop
    device.physical_id = new_id
2914 a8083063 Iustin Pop
  return True
2915 a8083063 Iustin Pop
2916 a8083063 Iustin Pop
2917 923b1523 Iustin Pop
def _GenerateUniqueNames(cfg, exts):
2918 923b1523 Iustin Pop
  """Generate a suitable LV name.
2919 923b1523 Iustin Pop

2920 923b1523 Iustin Pop
  This will generate a logical volume name for the given instance.
2921 923b1523 Iustin Pop

2922 923b1523 Iustin Pop
  """
2923 923b1523 Iustin Pop
  results = []
2924 923b1523 Iustin Pop
  for val in exts:
2925 923b1523 Iustin Pop
    new_id = cfg.GenerateUniqueID()
2926 923b1523 Iustin Pop
    results.append("%s%s" % (new_id, val))
2927 923b1523 Iustin Pop
  return results
2928 923b1523 Iustin Pop
2929 923b1523 Iustin Pop
2930 923b1523 Iustin Pop
def _GenerateMDDRBDBranch(cfg, primary, secondary, size, names):
2931 a8083063 Iustin Pop
  """Generate a drbd device complete with its children.
2932 a8083063 Iustin Pop

2933 a8083063 Iustin Pop
  """
2934 a8083063 Iustin Pop
  port = cfg.AllocatePort()
2935 923b1523 Iustin Pop
  vgname = cfg.GetVGName()
2936 fe96220b Iustin Pop
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
2937 923b1523 Iustin Pop
                          logical_id=(vgname, names[0]))
2938 fe96220b Iustin Pop
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
2939 923b1523 Iustin Pop
                          logical_id=(vgname, names[1]))
2940 fe96220b Iustin Pop
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD7, size=size,
2941 a8083063 Iustin Pop
                          logical_id = (primary, secondary, port),
2942 a8083063 Iustin Pop
                          children = [dev_data, dev_meta])
2943 a8083063 Iustin Pop
  return drbd_dev
2944 a8083063 Iustin Pop
2945 a8083063 Iustin Pop
2946 a1f445d3 Iustin Pop
def _GenerateDRBD8Branch(cfg, primary, secondary, size, names, iv_name):
2947 a1f445d3 Iustin Pop
  """Generate a drbd8 device complete with its children.
2948 a1f445d3 Iustin Pop

2949 a1f445d3 Iustin Pop
  """
2950 a1f445d3 Iustin Pop
  port = cfg.AllocatePort()
2951 a1f445d3 Iustin Pop
  vgname = cfg.GetVGName()
2952 a1f445d3 Iustin Pop
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
2953 a1f445d3 Iustin Pop
                          logical_id=(vgname, names[0]))
2954 a1f445d3 Iustin Pop
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
2955 a1f445d3 Iustin Pop
                          logical_id=(vgname, names[1]))
2956 a1f445d3 Iustin Pop
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
2957 a1f445d3 Iustin Pop
                          logical_id = (primary, secondary, port),
2958 a1f445d3 Iustin Pop
                          children = [dev_data, dev_meta],
2959 a1f445d3 Iustin Pop
                          iv_name=iv_name)
2960 a1f445d3 Iustin Pop
  return drbd_dev
2961 a1f445d3 Iustin Pop
2962 7c0d6283 Michael Hanselmann
2963 923b1523 Iustin Pop
def _GenerateDiskTemplate(cfg, template_name,
2964 a8083063 Iustin Pop
                          instance_name, primary_node,
2965 0f1a06e3 Manuel Franceschini
                          secondary_nodes, disk_sz, swap_sz,
2966 0f1a06e3 Manuel Franceschini
                          file_storage_dir, file_driver):
2967 a8083063 Iustin Pop
  """Generate the entire disk layout for a given template type.
2968 a8083063 Iustin Pop

2969 a8083063 Iustin Pop
  """
2970 a8083063 Iustin Pop
  #TODO: compute space requirements
2971 a8083063 Iustin Pop
2972 923b1523 Iustin Pop
  vgname = cfg.GetVGName()
2973 3517d9b9 Manuel Franceschini
  if template_name == constants.DT_DISKLESS:
2974 a8083063 Iustin Pop
    disks = []
2975 3517d9b9 Manuel Franceschini
  elif template_name == constants.DT_PLAIN:
2976 a8083063 Iustin Pop
    if len(secondary_nodes) != 0:
2977 a8083063 Iustin Pop
      raise errors.ProgrammerError("Wrong template configuration")
2978 923b1523 Iustin Pop
2979 923b1523 Iustin Pop
    names = _GenerateUniqueNames(cfg, [".sda", ".sdb"])
2980 fe96220b Iustin Pop
    sda_dev = objects.Disk(dev_type=constants.LD_LV, size=disk_sz,
2981 923b1523 Iustin Pop
                           logical_id=(vgname, names[0]),
2982 a8083063 Iustin Pop
                           iv_name = "sda")
2983 fe96220b Iustin Pop
    sdb_dev = objects.Disk(dev_type=constants.LD_LV, size=swap_sz,
2984 923b1523 Iustin Pop
                           logical_id=(vgname, names[1]),
2985 a8083063 Iustin Pop
                           iv_name = "sdb")
2986 a8083063 Iustin Pop
    disks = [sda_dev, sdb_dev]
2987 a1f445d3 Iustin Pop
  elif template_name == constants.DT_DRBD8:
2988 a1f445d3 Iustin Pop
    if len(secondary_nodes) != 1:
2989 a1f445d3 Iustin Pop
      raise errors.ProgrammerError("Wrong template configuration")
2990 a1f445d3 Iustin Pop
    remote_node = secondary_nodes[0]
2991 a1f445d3 Iustin Pop
    names = _GenerateUniqueNames(cfg, [".sda_data", ".sda_meta",
2992 a1f445d3 Iustin Pop
                                       ".sdb_data", ".sdb_meta"])
2993 a1f445d3 Iustin Pop
    drbd_sda_dev = _GenerateDRBD8Branch(cfg, primary_node, remote_node,
2994 a1f445d3 Iustin Pop
                                         disk_sz, names[0:2], "sda")
2995 a1f445d3 Iustin Pop
    drbd_sdb_dev = _GenerateDRBD8Branch(cfg, primary_node, remote_node,
2996 a1f445d3 Iustin Pop
                                         swap_sz, names[2:4], "sdb")
2997 a1f445d3 Iustin Pop
    disks = [drbd_sda_dev, drbd_sdb_dev]
2998 0f1a06e3 Manuel Franceschini
  elif template_name == constants.DT_FILE:
2999 0f1a06e3 Manuel Franceschini
    if len(secondary_nodes) != 0:
3000 0f1a06e3 Manuel Franceschini
      raise errors.ProgrammerError("Wrong template configuration")
3001 0f1a06e3 Manuel Franceschini
3002 0f1a06e3 Manuel Franceschini
    file_sda_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk_sz,
3003 0f1a06e3 Manuel Franceschini
                                iv_name="sda", logical_id=(file_driver,
3004 0f1a06e3 Manuel Franceschini
                                "%s/sda" % file_storage_dir))
3005 0f1a06e3 Manuel Franceschini
    file_sdb_dev = objects.Disk(dev_type=constants.LD_FILE, size=swap_sz,
3006 0f1a06e3 Manuel Franceschini
                                iv_name="sdb", logical_id=(file_driver,
3007 0f1a06e3 Manuel Franceschini
                                "%s/sdb" % file_storage_dir))
3008 0f1a06e3 Manuel Franceschini
    disks = [file_sda_dev, file_sdb_dev]
3009 a8083063 Iustin Pop
  else:
3010 a8083063 Iustin Pop
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
3011 a8083063 Iustin Pop
  return disks
3012 a8083063 Iustin Pop
3013 a8083063 Iustin Pop
3014 a0c3fea1 Michael Hanselmann
def _GetInstanceInfoText(instance):
3015 3ecf6786 Iustin Pop
  """Compute that text that should be added to the disk's metadata.
3016 3ecf6786 Iustin Pop

3017 3ecf6786 Iustin Pop
  """
3018 a0c3fea1 Michael Hanselmann
  return "originstname+%s" % instance.name
3019 a0c3fea1 Michael Hanselmann
3020 a0c3fea1 Michael Hanselmann
3021 a8083063 Iustin Pop
def _CreateDisks(cfg, instance):
3022 a8083063 Iustin Pop
  """Create all disks for an instance.
3023 a8083063 Iustin Pop

3024 a8083063 Iustin Pop
  This abstracts away some work from AddInstance.
3025 a8083063 Iustin Pop

3026 a8083063 Iustin Pop
  Args:
3027 a8083063 Iustin Pop
    instance: the instance object
3028 a8083063 Iustin Pop

3029 a8083063 Iustin Pop
  Returns:
3030 a8083063 Iustin Pop
    True or False showing the success of the creation process
3031 a8083063 Iustin Pop

3032 a8083063 Iustin Pop
  """
3033 a0c3fea1 Michael Hanselmann
  info = _GetInstanceInfoText(instance)
3034 a0c3fea1 Michael Hanselmann
3035 0f1a06e3 Manuel Franceschini
  if instance.disk_template == constants.DT_FILE:
3036 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3037 0f1a06e3 Manuel Franceschini
    result = rpc.call_file_storage_dir_create(instance.primary_node,
3038 0f1a06e3 Manuel Franceschini
                                              file_storage_dir)
3039 0f1a06e3 Manuel Franceschini
3040 0f1a06e3 Manuel Franceschini
    if not result:
3041 b62ddbe5 Guido Trotter
      logger.Error("Could not connect to node '%s'" % instance.primary_node)
3042 0f1a06e3 Manuel Franceschini
      return False
3043 0f1a06e3 Manuel Franceschini
3044 0f1a06e3 Manuel Franceschini
    if not result[0]:
3045 0f1a06e3 Manuel Franceschini
      logger.Error("failed to create directory '%s'" % file_storage_dir)
3046 0f1a06e3 Manuel Franceschini
      return False
3047 0f1a06e3 Manuel Franceschini
3048 a8083063 Iustin Pop
  for device in instance.disks:
3049 a8083063 Iustin Pop
    logger.Info("creating volume %s for instance %s" %
3050 1c6e3627 Manuel Franceschini
                (device.iv_name, instance.name))
3051 a8083063 Iustin Pop
    #HARDCODE
3052 a8083063 Iustin Pop
    for secondary_node in instance.secondary_nodes:
3053 3f78eef2 Iustin Pop
      if not _CreateBlockDevOnSecondary(cfg, secondary_node, instance,
3054 3f78eef2 Iustin Pop
                                        device, False, info):
3055 a8083063 Iustin Pop
        logger.Error("failed to create volume %s (%s) on secondary node %s!" %
3056 a8083063 Iustin Pop
                     (device.iv_name, device, secondary_node))
3057 a8083063 Iustin Pop
        return False
3058 a8083063 Iustin Pop
    #HARDCODE
3059 3f78eef2 Iustin Pop
    if not _CreateBlockDevOnPrimary(cfg, instance.primary_node,
3060 3f78eef2 Iustin Pop
                                    instance, device, info):
3061 a8083063 Iustin Pop
      logger.Error("failed to create volume %s on primary!" %
3062 a8083063 Iustin Pop
                   device.iv_name)
3063 a8083063 Iustin Pop
      return False
3064 1c6e3627 Manuel Franceschini
3065 a8083063 Iustin Pop
  return True
3066 a8083063 Iustin Pop
3067 a8083063 Iustin Pop
3068 a8083063 Iustin Pop
def _RemoveDisks(instance, cfg):
3069 a8083063 Iustin Pop
  """Remove all disks for an instance.
3070 a8083063 Iustin Pop

3071 a8083063 Iustin Pop
  This abstracts away some work from `AddInstance()` and
3072 a8083063 Iustin Pop
  `RemoveInstance()`. Note that in case some of the devices couldn't
3073 1d67656e Iustin Pop
  be removed, the removal will continue with the other ones (compare
3074 a8083063 Iustin Pop
  with `_CreateDisks()`).
3075 a8083063 Iustin Pop

3076 a8083063 Iustin Pop
  Args:
3077 a8083063 Iustin Pop
    instance: the instance object
3078 a8083063 Iustin Pop

3079 a8083063 Iustin Pop
  Returns:
3080 a8083063 Iustin Pop
    True or False showing the success of the removal proces
3081 a8083063 Iustin Pop

3082 a8083063 Iustin Pop
  """
3083 a8083063 Iustin Pop
  logger.Info("removing block devices for instance %s" % instance.name)
3084 a8083063 Iustin Pop
3085 a8083063 Iustin Pop
  result = True
3086 a8083063 Iustin Pop
  for device in instance.disks:
3087 a8083063 Iustin Pop
    for node, disk in device.ComputeNodeTree(instance.primary_node):
3088 a8083063 Iustin Pop
      cfg.SetDiskID(disk, node)
3089 a8083063 Iustin Pop
      if not rpc.call_blockdev_remove(node, disk):
3090 a8083063 Iustin Pop
        logger.Error("could not remove block device %s on node %s,"
3091 a8083063 Iustin Pop
                     " continuing anyway" %
3092 a8083063 Iustin Pop
                     (device.iv_name, node))
3093 a8083063 Iustin Pop
        result = False
3094 0f1a06e3 Manuel Franceschini
3095 0f1a06e3 Manuel Franceschini
  if instance.disk_template == constants.DT_FILE:
3096 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
3097 0f1a06e3 Manuel Franceschini
    if not rpc.call_file_storage_dir_remove(instance.primary_node,
3098 0f1a06e3 Manuel Franceschini
                                            file_storage_dir):
3099 0f1a06e3 Manuel Franceschini
      logger.Error("could not remove directory '%s'" % file_storage_dir)
3100 0f1a06e3 Manuel Franceschini
      result = False
3101 0f1a06e3 Manuel Franceschini
3102 a8083063 Iustin Pop
  return result
3103 a8083063 Iustin Pop
3104 a8083063 Iustin Pop
3105 e2fe6369 Iustin Pop
def _ComputeDiskSize(disk_template, disk_size, swap_size):
3106 e2fe6369 Iustin Pop
  """Compute disk size requirements in the volume group
3107 e2fe6369 Iustin Pop

3108 e2fe6369 Iustin Pop
  This is currently hard-coded for the two-drive layout.
3109 e2fe6369 Iustin Pop

3110 e2fe6369 Iustin Pop
  """
3111 e2fe6369 Iustin Pop
  # Required free disk space as a function of disk and swap space
3112 e2fe6369 Iustin Pop
  req_size_dict = {
3113 e2fe6369 Iustin Pop
    constants.DT_DISKLESS: None,
3114 e2fe6369 Iustin Pop
    constants.DT_PLAIN: disk_size + swap_size,
3115 e2fe6369 Iustin Pop
    # 256 MB are added for drbd metadata, 128MB for each drbd device
3116 e2fe6369 Iustin Pop
    constants.DT_DRBD8: disk_size + swap_size + 256,
3117 e2fe6369 Iustin Pop
    constants.DT_FILE: None,
3118 e2fe6369 Iustin Pop
  }
3119 e2fe6369 Iustin Pop
3120 e2fe6369 Iustin Pop
  if disk_template not in req_size_dict:
3121 e2fe6369 Iustin Pop
    raise errors.ProgrammerError("Disk template '%s' size requirement"
3122 e2fe6369 Iustin Pop
                                 " is unknown" %  disk_template)
3123 e2fe6369 Iustin Pop
3124 e2fe6369 Iustin Pop
  return req_size_dict[disk_template]
3125 e2fe6369 Iustin Pop
3126 e2fe6369 Iustin Pop
3127 a8083063 Iustin Pop
class LUCreateInstance(LogicalUnit):
3128 a8083063 Iustin Pop
  """Create an instance.
3129 a8083063 Iustin Pop

3130 a8083063 Iustin Pop
  """
3131 a8083063 Iustin Pop
  HPATH = "instance-add"
3132 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
3133 538475ca Iustin Pop
  _OP_REQP = ["instance_name", "mem_size", "disk_size",
3134 a8083063 Iustin Pop
              "disk_template", "swap_size", "mode", "start", "vcpus",
3135 1862d460 Alexander Schreiber
              "wait_for_sync", "ip_check", "mac"]
3136 a8083063 Iustin Pop
3137 538475ca Iustin Pop
  def _RunAllocator(self):
3138 538475ca Iustin Pop
    """Run the allocator based on input opcode.
3139 538475ca Iustin Pop

3140 538475ca Iustin Pop
    """
3141 538475ca Iustin Pop
    al_data = _IAllocatorGetClusterData(self.cfg, self.sstore)
3142 538475ca Iustin Pop
    disks = [{"size": self.op.disk_size, "mode": "w"},
3143 538475ca Iustin Pop
             {"size": self.op.swap_size, "mode": "w"}]
3144 538475ca Iustin Pop
    nics = [{"mac": self.op.mac, "ip": getattr(self.op, "ip", None),
3145 538475ca Iustin Pop
             "bridge": self.op.bridge}]
3146 538475ca Iustin Pop
    op = opcodes.OpTestAllocator(name=self.op.instance_name,
3147 538475ca Iustin Pop
                                 disk_template=self.op.disk_template,
3148 538475ca Iustin Pop
                                 tags=[],
3149 538475ca Iustin Pop
                                 os=self.op.os_type,
3150 538475ca Iustin Pop
                                 vcpus=self.op.vcpus,
3151 538475ca Iustin Pop
                                 mem_size=self.op.mem_size,
3152 538475ca Iustin Pop
                                 disks=disks,
3153 538475ca Iustin Pop
                                 nics=nics)
3154 538475ca Iustin Pop
3155 538475ca Iustin Pop
    _IAllocatorAddNewInstance(al_data, op)
3156 538475ca Iustin Pop
3157 8d14b30d Iustin Pop
    text = serializer.Dump(al_data)
3158 538475ca Iustin Pop
3159 538475ca Iustin Pop
    result = _IAllocatorRun(self.op.iallocator, text)
3160 538475ca Iustin Pop
3161 538475ca Iustin Pop
    result = _IAllocatorValidateResult(result)
3162 538475ca Iustin Pop
3163 538475ca Iustin Pop
    if not result["success"]:
3164 538475ca Iustin Pop
      raise errors.OpPrereqError("Can't compute nodes using"
3165 538475ca Iustin Pop
                                 " iallocator '%s': %s" % (self.op.iallocator,
3166 538475ca Iustin Pop
                                                           result["info"]))
3167 538475ca Iustin Pop
    req_nodes = 1
3168 538475ca Iustin Pop
    if self.op.disk_template in constants.DTS_NET_MIRROR:
3169 538475ca Iustin Pop
      req_nodes += 1
3170 538475ca Iustin Pop
3171 538475ca Iustin Pop
    if len(result["nodes"]) != req_nodes:
3172 538475ca Iustin Pop
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
3173 538475ca Iustin Pop
                                 " of nodes (%s), required %s" %
3174 538475ca Iustin Pop
                                 (len(result["nodes"]), req_nodes))
3175 538475ca Iustin Pop
    self.op.pnode = result["nodes"][0]
3176 538475ca Iustin Pop
    logger.ToStdout("Selected nodes for the instance: %s" %
3177 538475ca Iustin Pop
                    (", ".join(result["nodes"]),))
3178 538475ca Iustin Pop
    logger.Info("Selected nodes for instance %s via iallocator %s: %s" %
3179 538475ca Iustin Pop
                (self.op.instance_name, self.op.iallocator, result["nodes"]))
3180 538475ca Iustin Pop
    if req_nodes == 2:
3181 538475ca Iustin Pop
      self.op.snode = result["nodes"][1]
3182 538475ca Iustin Pop
3183 a8083063 Iustin Pop
  def BuildHooksEnv(self):
3184 a8083063 Iustin Pop
    """Build hooks env.
3185 a8083063 Iustin Pop

3186 a8083063 Iustin Pop
    This runs on master, primary and secondary nodes of the instance.
3187 a8083063 Iustin Pop

3188 a8083063 Iustin Pop
    """
3189 a8083063 Iustin Pop
    env = {
3190 396e1b78 Michael Hanselmann
      "INSTANCE_DISK_TEMPLATE": self.op.disk_template,
3191 396e1b78 Michael Hanselmann
      "INSTANCE_DISK_SIZE": self.op.disk_size,
3192 396e1b78 Michael Hanselmann
      "INSTANCE_SWAP_SIZE": self.op.swap_size,
3193 a8083063 Iustin Pop
      "INSTANCE_ADD_MODE": self.op.mode,
3194 a8083063 Iustin Pop
      }
3195 a8083063 Iustin Pop
    if self.op.mode == constants.INSTANCE_IMPORT:
3196 396e1b78 Michael Hanselmann
      env["INSTANCE_SRC_NODE"] = self.op.src_node
3197 396e1b78 Michael Hanselmann
      env["INSTANCE_SRC_PATH"] = self.op.src_path
3198 396e1b78 Michael Hanselmann
      env["INSTANCE_SRC_IMAGE"] = self.src_image
3199 396e1b78 Michael Hanselmann
3200 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnv(name=self.op.instance_name,
3201 396e1b78 Michael Hanselmann
      primary_node=self.op.pnode,
3202 396e1b78 Michael Hanselmann
      secondary_nodes=self.secondaries,
3203 396e1b78 Michael Hanselmann
      status=self.instance_status,
3204 ecb215b5 Michael Hanselmann
      os_type=self.op.os_type,
3205 396e1b78 Michael Hanselmann
      memory=self.op.mem_size,
3206 396e1b78 Michael Hanselmann
      vcpus=self.op.vcpus,
3207 c7b27e9e Iustin Pop
      nics=[(self.inst_ip, self.op.bridge, self.op.mac)],
3208 396e1b78 Michael Hanselmann
    ))
3209 a8083063 Iustin Pop
3210 880478f8 Iustin Pop
    nl = ([self.sstore.GetMasterNode(), self.op.pnode] +
3211 a8083063 Iustin Pop
          self.secondaries)
3212 a8083063 Iustin Pop
    return env, nl, nl
3213 a8083063 Iustin Pop
3214 a8083063 Iustin Pop
3215 a8083063 Iustin Pop
  def CheckPrereq(self):
3216 a8083063 Iustin Pop
    """Check prerequisites.
3217 a8083063 Iustin Pop

3218 a8083063 Iustin Pop
    """
3219 538475ca Iustin Pop
    # set optional parameters to none if they don't exist
3220 538475ca Iustin Pop
    for attr in ["kernel_path", "initrd_path", "hvm_boot_order", "pnode",
3221 538475ca Iustin Pop
                 "iallocator"]:
3222 40ed12dd Guido Trotter
      if not hasattr(self.op, attr):
3223 40ed12dd Guido Trotter
        setattr(self.op, attr, None)
3224 40ed12dd Guido Trotter
3225 a8083063 Iustin Pop
    if self.op.mode not in (constants.INSTANCE_CREATE,
3226 a8083063 Iustin Pop
                            constants.INSTANCE_IMPORT):
3227 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Invalid instance creation mode '%s'" %
3228 3ecf6786 Iustin Pop
                                 self.op.mode)
3229 a8083063 Iustin Pop
3230 eedc99de Manuel Franceschini
    if (not self.cfg.GetVGName() and
3231 eedc99de Manuel Franceschini
        self.op.disk_template not in constants.DTS_NOT_LVM):
3232 eedc99de Manuel Franceschini
      raise errors.OpPrereqError("Cluster does not support lvm-based"
3233 eedc99de Manuel Franceschini
                                 " instances")
3234 eedc99de Manuel Franceschini
3235 a8083063 Iustin Pop
    if self.op.mode == constants.INSTANCE_IMPORT:
3236 a8083063 Iustin Pop
      src_node = getattr(self.op, "src_node", None)
3237 a8083063 Iustin Pop
      src_path = getattr(self.op, "src_path", None)
3238 a8083063 Iustin Pop
      if src_node is None or src_path is None:
3239 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Importing an instance requires source"
3240 3ecf6786 Iustin Pop
                                   " node and path options")
3241 a8083063 Iustin Pop
      src_node_full = self.cfg.ExpandNodeName(src_node)
3242 a8083063 Iustin Pop
      if src_node_full is None:
3243 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Unknown source node '%s'" % src_node)
3244 a8083063 Iustin Pop
      self.op.src_node = src_node = src_node_full
3245 a8083063 Iustin Pop
3246 a8083063 Iustin Pop
      if not os.path.isabs(src_path):
3247 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The source path must be absolute")
3248 a8083063 Iustin Pop
3249 a8083063 Iustin Pop
      export_info = rpc.call_export_info(src_node, src_path)
3250 a8083063 Iustin Pop
3251 a8083063 Iustin Pop
      if not export_info:
3252 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("No export found in dir %s" % src_path)
3253 a8083063 Iustin Pop
3254 a8083063 Iustin Pop
      if not export_info.has_section(constants.INISECT_EXP):
3255 3ecf6786 Iustin Pop
        raise errors.ProgrammerError("Corrupted export config")
3256 a8083063 Iustin Pop
3257 a8083063 Iustin Pop
      ei_version = export_info.get(constants.INISECT_EXP, 'version')
3258 a8083063 Iustin Pop
      if (int(ei_version) != constants.EXPORT_VERSION):
3259 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
3260 3ecf6786 Iustin Pop
                                   (ei_version, constants.EXPORT_VERSION))
3261 a8083063 Iustin Pop
3262 a8083063 Iustin Pop
      if int(export_info.get(constants.INISECT_INS, 'disk_count')) > 1:
3263 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Can't import instance with more than"
3264 3ecf6786 Iustin Pop
                                   " one data disk")
3265 a8083063 Iustin Pop
3266 a8083063 Iustin Pop
      # FIXME: are the old os-es, disk sizes, etc. useful?
3267 a8083063 Iustin Pop
      self.op.os_type = export_info.get(constants.INISECT_EXP, 'os')
3268 a8083063 Iustin Pop
      diskimage = os.path.join(src_path, export_info.get(constants.INISECT_INS,
3269 a8083063 Iustin Pop
                                                         'disk0_dump'))
3270 a8083063 Iustin Pop
      self.src_image = diskimage
3271 a8083063 Iustin Pop
    else: # INSTANCE_CREATE
3272 a8083063 Iustin Pop
      if getattr(self.op, "os_type", None) is None:
3273 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("No guest OS specified")
3274 a8083063 Iustin Pop
3275 901a65c1 Iustin Pop
    #### instance parameters check
3276 901a65c1 Iustin Pop
3277 a8083063 Iustin Pop
    # disk template and mirror node verification
3278 a8083063 Iustin Pop
    if self.op.disk_template not in constants.DISK_TEMPLATES:
3279 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Invalid disk template name")
3280 a8083063 Iustin Pop
3281 901a65c1 Iustin Pop
    # instance name verification
3282 901a65c1 Iustin Pop
    hostname1 = utils.HostInfo(self.op.instance_name)
3283 901a65c1 Iustin Pop
3284 901a65c1 Iustin Pop
    self.op.instance_name = instance_name = hostname1.name
3285 901a65c1 Iustin Pop
    instance_list = self.cfg.GetInstanceList()
3286 901a65c1 Iustin Pop
    if instance_name in instance_list:
3287 901a65c1 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
3288 901a65c1 Iustin Pop
                                 instance_name)
3289 901a65c1 Iustin Pop
3290 901a65c1 Iustin Pop
    # ip validity checks
3291 901a65c1 Iustin Pop
    ip = getattr(self.op, "ip", None)
3292 901a65c1 Iustin Pop
    if ip is None or ip.lower() == "none":
3293 901a65c1 Iustin Pop
      inst_ip = None
3294 901a65c1 Iustin Pop
    elif ip.lower() == "auto":
3295 901a65c1 Iustin Pop
      inst_ip = hostname1.ip
3296 901a65c1 Iustin Pop
    else:
3297 901a65c1 Iustin Pop
      if not utils.IsValidIP(ip):
3298 901a65c1 Iustin Pop
        raise errors.OpPrereqError("given IP address '%s' doesn't look"
3299 901a65c1 Iustin Pop
                                   " like a valid IP" % ip)
3300 901a65c1 Iustin Pop
      inst_ip = ip
3301 901a65c1 Iustin Pop
    self.inst_ip = self.op.ip = inst_ip
3302 901a65c1 Iustin Pop
3303 901a65c1 Iustin Pop
    if self.op.start and not self.op.ip_check:
3304 901a65c1 Iustin Pop
      raise errors.OpPrereqError("Cannot ignore IP address conflicts when"
3305 901a65c1 Iustin Pop
                                 " adding an instance in start mode")
3306 901a65c1 Iustin Pop
3307 901a65c1 Iustin Pop
    if self.op.ip_check:
3308 901a65c1 Iustin Pop
      if utils.TcpPing(hostname1.ip, constants.DEFAULT_NODED_PORT):
3309 901a65c1 Iustin Pop
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
3310 901a65c1 Iustin Pop
                                   (hostname1.ip, instance_name))
3311 901a65c1 Iustin Pop
3312 901a65c1 Iustin Pop
    # MAC address verification
3313 901a65c1 Iustin Pop
    if self.op.mac != "auto":
3314 901a65c1 Iustin Pop
      if not utils.IsValidMac(self.op.mac.lower()):
3315 901a65c1 Iustin Pop
        raise errors.OpPrereqError("invalid MAC address specified: %s" %
3316 901a65c1 Iustin Pop
                                   self.op.mac)
3317 901a65c1 Iustin Pop
3318 901a65c1 Iustin Pop
    # bridge verification
3319 901a65c1 Iustin Pop
    bridge = getattr(self.op, "bridge", None)
3320 901a65c1 Iustin Pop
    if bridge is None:
3321 901a65c1 Iustin Pop
      self.op.bridge = self.cfg.GetDefBridge()
3322 901a65c1 Iustin Pop
    else:
3323 901a65c1 Iustin Pop
      self.op.bridge = bridge
3324 901a65c1 Iustin Pop
3325 901a65c1 Iustin Pop
    # boot order verification
3326 901a65c1 Iustin Pop
    if self.op.hvm_boot_order is not None:
3327 901a65c1 Iustin Pop
      if len(self.op.hvm_boot_order.strip("acdn")) != 0:
3328 901a65c1 Iustin Pop
        raise errors.OpPrereqError("invalid boot order specified,"
3329 901a65c1 Iustin Pop
                                   " must be one or more of [acdn]")
3330 901a65c1 Iustin Pop
    # file storage checks
3331 0f1a06e3 Manuel Franceschini
    if (self.op.file_driver and
3332 0f1a06e3 Manuel Franceschini
        not self.op.file_driver in constants.FILE_DRIVER):
3333 0f1a06e3 Manuel Franceschini
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
3334 0f1a06e3 Manuel Franceschini
                                 self.op.file_driver)
3335 0f1a06e3 Manuel Franceschini
3336 0f1a06e3 Manuel Franceschini
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
3337 0f1a06e3 Manuel Franceschini
        raise errors.OpPrereqError("File storage directory not a relative"
3338 0f1a06e3 Manuel Franceschini
                                   " path")
3339 538475ca Iustin Pop
    #### allocator run
3340 538475ca Iustin Pop
3341 538475ca Iustin Pop
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
3342 538475ca Iustin Pop
      raise errors.OpPrereqError("One and only one of iallocator and primary"
3343 538475ca Iustin Pop
                                 " node must be given")
3344 538475ca Iustin Pop
3345 538475ca Iustin Pop
    if self.op.iallocator is not None:
3346 538475ca Iustin Pop
      self._RunAllocator()
3347 0f1a06e3 Manuel Franceschini
3348 901a65c1 Iustin Pop
    #### node related checks
3349 901a65c1 Iustin Pop
3350 901a65c1 Iustin Pop
    # check primary node
3351 901a65c1 Iustin Pop
    pnode = self.cfg.GetNodeInfo(self.cfg.ExpandNodeName(self.op.pnode))
3352 901a65c1 Iustin Pop
    if pnode is None:
3353 901a65c1 Iustin Pop
      raise errors.OpPrereqError("Primary node '%s' is unknown" %
3354 901a65c1 Iustin Pop
                                 self.op.pnode)
3355 901a65c1 Iustin Pop
    self.op.pnode = pnode.name
3356 901a65c1 Iustin Pop
    self.pnode = pnode
3357 901a65c1 Iustin Pop
    self.secondaries = []
3358 901a65c1 Iustin Pop
3359 901a65c1 Iustin Pop
    # mirror node verification
3360 a1f445d3 Iustin Pop
    if self.op.disk_template in constants.DTS_NET_MIRROR:
3361 a8083063 Iustin Pop
      if getattr(self.op, "snode", None) is None:
3362 a1f445d3 Iustin Pop
        raise errors.OpPrereqError("The networked disk templates need"
3363 3ecf6786 Iustin Pop
                                   " a mirror node")
3364 a8083063 Iustin Pop
3365 a8083063 Iustin Pop
      snode_name = self.cfg.ExpandNodeName(self.op.snode)
3366 a8083063 Iustin Pop
      if snode_name is None:
3367 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Unknown secondary node '%s'" %
3368 3ecf6786 Iustin Pop
                                   self.op.snode)
3369 a8083063 Iustin Pop
      elif snode_name == pnode.name:
3370 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("The secondary node cannot be"
3371 3ecf6786 Iustin Pop
                                   " the primary node.")
3372 a8083063 Iustin Pop
      self.secondaries.append(snode_name)
3373 a8083063 Iustin Pop
3374 e2fe6369 Iustin Pop
    req_size = _ComputeDiskSize(self.op.disk_template,
3375 e2fe6369 Iustin Pop
                                self.op.disk_size, self.op.swap_size)
3376 ed1ebc60 Guido Trotter
3377 8d75db10 Iustin Pop
    # Check lv size requirements
3378 8d75db10 Iustin Pop
    if req_size is not None:
3379 8d75db10 Iustin Pop
      nodenames = [pnode.name] + self.secondaries
3380 8d75db10 Iustin Pop
      nodeinfo = rpc.call_node_info(nodenames, self.cfg.GetVGName())
3381 8d75db10 Iustin Pop
      for node in nodenames:
3382 8d75db10 Iustin Pop
        info = nodeinfo.get(node, None)
3383 8d75db10 Iustin Pop
        if not info:
3384 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Cannot get current information"
3385 8d75db10 Iustin Pop
                                     " from node '%s'" % nodeinfo)
3386 8d75db10 Iustin Pop
        vg_free = info.get('vg_free', None)
3387 8d75db10 Iustin Pop
        if not isinstance(vg_free, int):
3388 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Can't compute free disk space on"
3389 8d75db10 Iustin Pop
                                     " node %s" % node)
3390 8d75db10 Iustin Pop
        if req_size > info['vg_free']:
3391 8d75db10 Iustin Pop
          raise errors.OpPrereqError("Not enough disk space on target node %s."
3392 8d75db10 Iustin Pop
                                     " %d MB available, %d MB required" %
3393 8d75db10 Iustin Pop
                                     (node, info['vg_free'], req_size))
3394 ed1ebc60 Guido Trotter
3395 a8083063 Iustin Pop
    # os verification
3396 00fe9e38 Guido Trotter
    os_obj = rpc.call_os_get(pnode.name, self.op.os_type)
3397 dfa96ded Guido Trotter
    if not os_obj:
3398 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("OS '%s' not in supported os list for"
3399 3ecf6786 Iustin Pop
                                 " primary node"  % self.op.os_type)
3400 a8083063 Iustin Pop
3401 3b6d8c9b Iustin Pop
    if self.op.kernel_path == constants.VALUE_NONE:
3402 3b6d8c9b Iustin Pop
      raise errors.OpPrereqError("Can't set instance kernel to none")
3403 3b6d8c9b Iustin Pop
3404 a8083063 Iustin Pop
3405 901a65c1 Iustin Pop
    # bridge check on primary node
3406 a8083063 Iustin Pop
    if not rpc.call_bridges_exist(self.pnode.name, [self.op.bridge]):
3407 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("target bridge '%s' does not exist on"
3408 3ecf6786 Iustin Pop
                                 " destination node '%s'" %
3409 3ecf6786 Iustin Pop
                                 (self.op.bridge, pnode.name))
3410 a8083063 Iustin Pop
3411 a8083063 Iustin Pop
    if self.op.start:
3412 a8083063 Iustin Pop
      self.instance_status = 'up'
3413 a8083063 Iustin Pop
    else:
3414 a8083063 Iustin Pop
      self.instance_status = 'down'
3415 a8083063 Iustin Pop
3416 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3417 a8083063 Iustin Pop
    """Create and add the instance to the cluster.
3418 a8083063 Iustin Pop

3419 a8083063 Iustin Pop
    """
3420 a8083063 Iustin Pop
    instance = self.op.instance_name
3421 a8083063 Iustin Pop
    pnode_name = self.pnode.name
3422 a8083063 Iustin Pop
3423 1862d460 Alexander Schreiber
    if self.op.mac == "auto":
3424 ba4b62cf Iustin Pop
      mac_address = self.cfg.GenerateMAC()
3425 1862d460 Alexander Schreiber
    else:
3426 ba4b62cf Iustin Pop
      mac_address = self.op.mac
3427 1862d460 Alexander Schreiber
3428 1862d460 Alexander Schreiber
    nic = objects.NIC(bridge=self.op.bridge, mac=mac_address)
3429 a8083063 Iustin Pop
    if self.inst_ip is not None:
3430 a8083063 Iustin Pop
      nic.ip = self.inst_ip
3431 a8083063 Iustin Pop
3432 2a6469d5 Alexander Schreiber
    ht_kind = self.sstore.GetHypervisorType()
3433 2a6469d5 Alexander Schreiber
    if ht_kind in constants.HTS_REQ_PORT:
3434 2a6469d5 Alexander Schreiber
      network_port = self.cfg.AllocatePort()
3435 2a6469d5 Alexander Schreiber
    else:
3436 2a6469d5 Alexander Schreiber
      network_port = None
3437 58acb49d Alexander Schreiber
3438 2c313123 Manuel Franceschini
    # this is needed because os.path.join does not accept None arguments
3439 2c313123 Manuel Franceschini
    if self.op.file_storage_dir is None:
3440 2c313123 Manuel Franceschini
      string_file_storage_dir = ""
3441 2c313123 Manuel Franceschini
    else:
3442 2c313123 Manuel Franceschini
      string_file_storage_dir = self.op.file_storage_dir
3443 2c313123 Manuel Franceschini
3444 0f1a06e3 Manuel Franceschini
    # build the full file storage dir path
3445 0f1a06e3 Manuel Franceschini
    file_storage_dir = os.path.normpath(os.path.join(
3446 0f1a06e3 Manuel Franceschini
                                        self.sstore.GetFileStorageDir(),
3447 2c313123 Manuel Franceschini
                                        string_file_storage_dir, instance))
3448 0f1a06e3 Manuel Franceschini
3449 0f1a06e3 Manuel Franceschini
3450 923b1523 Iustin Pop
    disks = _GenerateDiskTemplate(self.cfg,
3451 a8083063 Iustin Pop
                                  self.op.disk_template,
3452 a8083063 Iustin Pop
                                  instance, pnode_name,
3453 a8083063 Iustin Pop
                                  self.secondaries, self.op.disk_size,
3454 0f1a06e3 Manuel Franceschini
                                  self.op.swap_size,
3455 0f1a06e3 Manuel Franceschini
                                  file_storage_dir,
3456 0f1a06e3 Manuel Franceschini
                                  self.op.file_driver)
3457 a8083063 Iustin Pop
3458 a8083063 Iustin Pop
    iobj = objects.Instance(name=instance, os=self.op.os_type,
3459 a8083063 Iustin Pop
                            primary_node=pnode_name,
3460 a8083063 Iustin Pop
                            memory=self.op.mem_size,
3461 a8083063 Iustin Pop
                            vcpus=self.op.vcpus,
3462 a8083063 Iustin Pop
                            nics=[nic], disks=disks,
3463 a8083063 Iustin Pop
                            disk_template=self.op.disk_template,
3464 a8083063 Iustin Pop
                            status=self.instance_status,
3465 58acb49d Alexander Schreiber
                            network_port=network_port,
3466 3b6d8c9b Iustin Pop
                            kernel_path=self.op.kernel_path,
3467 3b6d8c9b Iustin Pop
                            initrd_path=self.op.initrd_path,
3468 25c5878d Alexander Schreiber
                            hvm_boot_order=self.op.hvm_boot_order,
3469 a8083063 Iustin Pop
                            )
3470 a8083063 Iustin Pop
3471 a8083063 Iustin Pop
    feedback_fn("* creating instance disks...")
3472 a8083063 Iustin Pop
    if not _CreateDisks(self.cfg, iobj):
3473 a8083063 Iustin Pop
      _RemoveDisks(iobj, self.cfg)
3474 3ecf6786 Iustin Pop
      raise errors.OpExecError("Device creation failed, reverting...")
3475 a8083063 Iustin Pop
3476 a8083063 Iustin Pop
    feedback_fn("adding instance %s to cluster config" % instance)
3477 a8083063 Iustin Pop
3478 a8083063 Iustin Pop
    self.cfg.AddInstance(iobj)
3479 a8083063 Iustin Pop
3480 a8083063 Iustin Pop
    if self.op.wait_for_sync:
3481 5bfac263 Iustin Pop
      disk_abort = not _WaitForSync(self.cfg, iobj, self.proc)
3482 a1f445d3 Iustin Pop
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
3483 a8083063 Iustin Pop
      # make sure the disks are not degraded (still sync-ing is ok)
3484 a8083063 Iustin Pop
      time.sleep(15)
3485 a8083063 Iustin Pop
      feedback_fn("* checking mirrors status")
3486 5bfac263 Iustin Pop
      disk_abort = not _WaitForSync(self.cfg, iobj, self.proc, oneshot=True)
3487 a8083063 Iustin Pop
    else:
3488 a8083063 Iustin Pop
      disk_abort = False
3489 a8083063 Iustin Pop
3490 a8083063 Iustin Pop
    if disk_abort:
3491 a8083063 Iustin Pop
      _RemoveDisks(iobj, self.cfg)
3492 a8083063 Iustin Pop
      self.cfg.RemoveInstance(iobj.name)
3493 3ecf6786 Iustin Pop
      raise errors.OpExecError("There are some degraded disks for"
3494 3ecf6786 Iustin Pop
                               " this instance")
3495 a8083063 Iustin Pop
3496 a8083063 Iustin Pop
    feedback_fn("creating os for instance %s on node %s" %
3497 a8083063 Iustin Pop
                (instance, pnode_name))
3498 a8083063 Iustin Pop
3499 a8083063 Iustin Pop
    if iobj.disk_template != constants.DT_DISKLESS:
3500 a8083063 Iustin Pop
      if self.op.mode == constants.INSTANCE_CREATE:
3501 a8083063 Iustin Pop
        feedback_fn("* running the instance OS create scripts...")
3502 a8083063 Iustin Pop
        if not rpc.call_instance_os_add(pnode_name, iobj, "sda", "sdb"):
3503 3ecf6786 Iustin Pop
          raise errors.OpExecError("could not add os for instance %s"
3504 3ecf6786 Iustin Pop
                                   " on node %s" %
3505 3ecf6786 Iustin Pop
                                   (instance, pnode_name))
3506 a8083063 Iustin Pop
3507 a8083063 Iustin Pop
      elif self.op.mode == constants.INSTANCE_IMPORT:
3508 a8083063 Iustin Pop
        feedback_fn("* running the instance OS import scripts...")
3509 a8083063 Iustin Pop
        src_node = self.op.src_node
3510 a8083063 Iustin Pop
        src_image = self.src_image
3511 a8083063 Iustin Pop
        if not rpc.call_instance_os_import(pnode_name, iobj, "sda", "sdb",
3512 a8083063 Iustin Pop
                                                src_node, src_image):
3513 3ecf6786 Iustin Pop
          raise errors.OpExecError("Could not import os for instance"
3514 3ecf6786 Iustin Pop
                                   " %s on node %s" %
3515 3ecf6786 Iustin Pop
                                   (instance, pnode_name))
3516 a8083063 Iustin Pop
      else:
3517 a8083063 Iustin Pop
        # also checked in the prereq part
3518 3ecf6786 Iustin Pop
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
3519 3ecf6786 Iustin Pop
                                     % self.op.mode)
3520 a8083063 Iustin Pop
3521 a8083063 Iustin Pop
    if self.op.start:
3522 a8083063 Iustin Pop
      logger.Info("starting instance %s on node %s" % (instance, pnode_name))
3523 a8083063 Iustin Pop
      feedback_fn("* starting instance...")
3524 a8083063 Iustin Pop
      if not rpc.call_instance_start(pnode_name, iobj, None):
3525 3ecf6786 Iustin Pop
        raise errors.OpExecError("Could not start instance")
3526 a8083063 Iustin Pop
3527 a8083063 Iustin Pop
3528 a8083063 Iustin Pop
class LUConnectConsole(NoHooksLU):
3529 a8083063 Iustin Pop
  """Connect to an instance's console.
3530 a8083063 Iustin Pop

3531 a8083063 Iustin Pop
  This is somewhat special in that it returns the command line that
3532 a8083063 Iustin Pop
  you need to run on the master node in order to connect to the
3533 a8083063 Iustin Pop
  console.
3534 a8083063 Iustin Pop

3535 a8083063 Iustin Pop
  """
3536 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
3537 a8083063 Iustin Pop
3538 a8083063 Iustin Pop
  def CheckPrereq(self):
3539 a8083063 Iustin Pop
    """Check prerequisites.
3540 a8083063 Iustin Pop

3541 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
3542 a8083063 Iustin Pop

3543 a8083063 Iustin Pop
    """
3544 a8083063 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
3545 a8083063 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
3546 a8083063 Iustin Pop
    if instance is None:
3547 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
3548 3ecf6786 Iustin Pop
                                 self.op.instance_name)
3549 a8083063 Iustin Pop
    self.instance = instance
3550 a8083063 Iustin Pop
3551 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
3552 a8083063 Iustin Pop
    """Connect to the console of an instance
3553 a8083063 Iustin Pop

3554 a8083063 Iustin Pop
    """
3555 a8083063 Iustin Pop
    instance = self.instance
3556 a8083063 Iustin Pop
    node = instance.primary_node
3557 a8083063 Iustin Pop
3558 a8083063 Iustin Pop
    node_insts = rpc.call_instance_list([node])[node]
3559 a8083063 Iustin Pop
    if node_insts is False:
3560 3ecf6786 Iustin Pop
      raise errors.OpExecError("Can't connect to node %s." % node)
3561 a8083063 Iustin Pop
3562 a8083063 Iustin Pop
    if instance.name not in node_insts:
3563 3ecf6786 Iustin Pop
      raise errors.OpExecError("Instance %s is not running." % instance.name)
3564 a8083063 Iustin Pop
3565 a8083063 Iustin Pop
    logger.Debug("connecting to console of %s on %s" % (instance.name, node))
3566 a8083063 Iustin Pop
3567 a8083063 Iustin Pop
    hyper = hypervisor.GetHypervisor()
3568 30989e69 Alexander Schreiber
    console_cmd = hyper.GetShellCommandForConsole(instance)
3569 b047857b Michael Hanselmann
3570 82122173 Iustin Pop
    # build ssh cmdline
3571 0a80a26f Michael Hanselmann
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
3572 a8083063 Iustin Pop
3573 a8083063 Iustin Pop
3574 a8083063 Iustin Pop
class LUReplaceDisks(LogicalUnit):
3575 a8083063 Iustin Pop
  """Replace the disks of an instance.
3576 a8083063 Iustin Pop

3577 a8083063 Iustin Pop
  """
3578 a8083063 Iustin Pop
  HPATH = "mirrors-replace"
3579 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
3580 a9e0c397 Iustin Pop
  _OP_REQP = ["instance_name", "mode", "disks"]
3581 a8083063 Iustin Pop
3582 a8083063 Iustin Pop
  def BuildHooksEnv(self):
3583 a8083063 Iustin Pop
    """Build hooks env.
3584 a8083063 Iustin Pop

3585 a8083063 Iustin Pop
    This runs on the master, the primary and all the secondaries.
3586 a8083063 Iustin Pop

3587 a8083063 Iustin Pop
    """
3588 a8083063 Iustin Pop
    env = {
3589 a9e0c397 Iustin Pop
      "MODE": self.op.mode,
3590 a8083063 Iustin Pop
      "NEW_SECONDARY": self.op.remote_node,
3591 a8083063 Iustin Pop
      "OLD_SECONDARY": self.instance.secondary_nodes[0],
3592 a8083063 Iustin Pop
      }
3593 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnvByObject(self.instance))
3594 0834c866 Iustin Pop
    nl = [
3595 0834c866 Iustin Pop
      self.sstore.GetMasterNode(),
3596 0834c866 Iustin Pop
      self.instance.primary_node,
3597 0834c866 Iustin Pop
      ]
3598 0834c866 Iustin Pop
    if self.op.remote_node is not None:
3599 0834c866 Iustin Pop
      nl.append(self.op.remote_node)
3600 a8083063 Iustin Pop
    return env, nl, nl
3601 a8083063 Iustin Pop
3602 a8083063 Iustin Pop
  def CheckPrereq(self):
3603 a8083063 Iustin Pop
    """Check prerequisites.
3604 a8083063 Iustin Pop

3605 a8083063 Iustin Pop
    This checks that the instance is in the cluster.
3606 a8083063 Iustin Pop

3607 a8083063 Iustin Pop
    """
3608 a8083063 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
3609 a8083063 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
3610 a8083063 Iustin Pop
    if instance is None:
3611 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not known" %
3612 3ecf6786 Iustin Pop
                                 self.op.instance_name)
3613 a8083063 Iustin Pop
    self.instance = instance
3614 7df43a76 Iustin Pop
    self.op.instance_name = instance.name
3615 a8083063 Iustin Pop
3616 a9e0c397 Iustin Pop
    if instance.disk_template not in constants.DTS_NET_MIRROR:
3617 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance's disk layout is not"
3618 a9e0c397 Iustin Pop
                                 " network mirrored.")
3619 a8083063 Iustin Pop
3620 a8083063 Iustin Pop
    if len(instance.secondary_nodes) != 1:
3621 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("The instance has a strange layout,"
3622 3ecf6786 Iustin Pop
                                 " expected one secondary but found %d" %
3623 3ecf6786 Iustin Pop
                                 len(instance.secondary_nodes))
3624 a8083063 Iustin Pop
3625 a9e0c397 Iustin Pop
    self.sec_node = instance.secondary_nodes[0]
3626 a9e0c397 Iustin Pop
3627 a8083063 Iustin Pop
    remote_node = getattr(self.op, "remote_node", None)
3628 a9e0c397 Iustin Pop
    if remote_node is not None:
3629 a8083063 Iustin Pop
      remote_node = self.cfg.ExpandNodeName(remote_node)
3630 a8083063 Iustin Pop
      if remote_node is None:
3631 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Node '%s' not known" %
3632 3ecf6786 Iustin Pop
                                   self.op.remote_node)
3633 a9e0c397 Iustin Pop
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
3634 a9e0c397 Iustin Pop
    else:
3635 a9e0c397 Iustin Pop
      self.remote_node_info = None
3636 a8083063 Iustin Pop
    if remote_node == instance.primary_node:
3637 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("The specified node is the primary node of"
3638 3ecf6786 Iustin Pop
                                 " the instance.")
3639 a9e0c397 Iustin Pop
    elif remote_node == self.sec_node:
3640 0834c866 Iustin Pop
      if self.op.mode == constants.REPLACE_DISK_SEC:
3641 0834c866 Iustin Pop
        # this is for DRBD8, where we can't execute the same mode of
3642 0834c866 Iustin Pop
        # replacement as for drbd7 (no different port allocated)
3643 0834c866 Iustin Pop
        raise errors.OpPrereqError("Same secondary given, cannot execute"
3644 0834c866 Iustin Pop
                                   " replacement")
3645 a9e0c397 Iustin Pop
      # the user gave the current secondary, switch to
3646 0834c866 Iustin Pop
      # 'no-replace-secondary' mode for drbd7
3647 a9e0c397 Iustin Pop
      remote_node = None
3648 a9e0c397 Iustin Pop
    if (instance.disk_template == constants.DT_REMOTE_RAID1 and
3649 a9e0c397 Iustin Pop
        self.op.mode != constants.REPLACE_DISK_ALL):
3650 a9e0c397 Iustin Pop
      raise errors.OpPrereqError("Template 'remote_raid1' only allows all"
3651 a9e0c397 Iustin Pop
                                 " disks replacement, not individual ones")
3652 a9e0c397 Iustin Pop
    if instance.disk_template == constants.DT_DRBD8:
3653 7df43a76 Iustin Pop
      if (self.op.mode == constants.REPLACE_DISK_ALL and
3654 7df43a76 Iustin Pop
          remote_node is not None):
3655 7df43a76 Iustin Pop
        # switch to replace secondary mode
3656 7df43a76 Iustin Pop
        self.op.mode = constants.REPLACE_DISK_SEC
3657 7df43a76 Iustin Pop
3658 a9e0c397 Iustin Pop
      if self.op.mode == constants.REPLACE_DISK_ALL:
3659 12c3449a Michael Hanselmann
        raise errors.OpPrereqError("Template 'drbd' only allows primary or"
3660 a9e0c397 Iustin Pop
                                   " secondary disk replacement, not"
3661 a9e0c397 Iustin Pop
                                   " both at once")
3662 a9e0c397 Iustin Pop
      elif self.op.mode == constants.REPLACE_DISK_PRI:
3663 a9e0c397 Iustin Pop
        if remote_node is not None:
3664 12c3449a Michael Hanselmann
          raise errors.OpPrereqError("Template 'drbd' does not allow changing"
3665 a9e0c397 Iustin Pop
                                     " the secondary while doing a primary"
3666 a9e0c397 Iustin Pop
                                     " node disk replacement")
3667 a9e0c397 Iustin Pop
        self.tgt_node = instance.primary_node
3668 cff90b79 Iustin Pop
        self.oth_node = instance.secondary_nodes[0]
3669 a9e0c397 Iustin Pop
      elif self.op.mode == constants.REPLACE_DISK_SEC:
3670 a9e0c397 Iustin Pop
        self.new_node = remote_node # this can be None, in which case
3671 a9e0c397 Iustin Pop
                                    # we don't change the secondary
3672 a9e0c397 Iustin Pop
        self.tgt_node = instance.secondary_nodes[0]
3673 cff90b79 Iustin Pop
        self.oth_node = instance.primary_node
3674 a9e0c397 Iustin Pop
      else:
3675 a9e0c397 Iustin Pop
        raise errors.ProgrammerError("Unhandled disk replace mode")
3676 a9e0c397 Iustin Pop
3677 a9e0c397 Iustin Pop
    for name in self.op.disks:
3678 a9e0c397 Iustin Pop
      if instance.FindDisk(name) is None:
3679 a9e0c397 Iustin Pop
        raise errors.OpPrereqError("Disk '%s' not found for instance '%s'" %
3680 a9e0c397 Iustin Pop
                                   (name, instance.name))
3681 a8083063 Iustin Pop
    self.op.remote_node = remote_node
3682 a8083063 Iustin Pop
3683 a9e0c397 Iustin Pop
  def _ExecRR1(self, feedback_fn):
3684 a8083063 Iustin Pop
    """Replace the disks of an instance.
3685 a8083063 Iustin Pop

3686 a8083063 Iustin Pop
    """
3687 a8083063 Iustin Pop
    instance = self.instance
3688 a8083063 Iustin Pop
    iv_names = {}
3689 a8083063 Iustin Pop
    # start of work
3690 a9e0c397 Iustin Pop
    if self.op.remote_node is None:
3691 a9e0c397 Iustin Pop
      remote_node = self.sec_node
3692 a9e0c397 Iustin Pop
    else:
3693 a9e0c397 Iustin Pop
      remote_node = self.op.remote_node
3694 a8083063 Iustin Pop
    cfg = self.cfg
3695 a8083063 Iustin Pop
    for dev in instance.disks:
3696 a8083063 Iustin Pop
      size = dev.size
3697 923b1523 Iustin Pop
      lv_names = [".%s_%s" % (dev.iv_name, suf) for suf in ["data", "meta"]]
3698 923b1523 Iustin Pop
      names = _GenerateUniqueNames(cfg, lv_names)
3699 923b1523 Iustin Pop
      new_drbd = _GenerateMDDRBDBranch(cfg, instance.primary_node,
3700 923b1523 Iustin Pop
                                       remote_node, size, names)
3701 a8083063 Iustin Pop
      iv_names[dev.iv_name] = (dev, dev.children[0], new_drbd)
3702 a8083063 Iustin Pop
      logger.Info("adding new mirror component on secondary for %s" %
3703 a8083063 Iustin Pop
                  dev.iv_name)
3704 a8083063 Iustin Pop
      #HARDCODE
3705 3f78eef2 Iustin Pop
      if not _CreateBlockDevOnSecondary(cfg, remote_node, instance,
3706 3f78eef2 Iustin Pop
                                        new_drbd, False,
3707 a0c3fea1 Michael Hanselmann
                                        _GetInstanceInfoText(instance)):
3708 f4bc1f2c Michael Hanselmann
        raise errors.OpExecError("Failed to create new component on secondary"
3709 f4bc1f2c Michael Hanselmann
                                 " node %s. Full abort, cleanup manually!" %
3710 3ecf6786 Iustin Pop
                                 remote_node)
3711 a8083063 Iustin Pop
3712 a8083063 Iustin Pop
      logger.Info("adding new mirror component on primary")
3713 a8083063 Iustin Pop
      #HARDCODE
3714 3f78eef2 Iustin Pop
      if not _CreateBlockDevOnPrimary(cfg, instance.primary_node,
3715 3f78eef2 Iustin Pop
                                      instance, new_drbd,
3716 a0c3fea1 Michael Hanselmann
                                      _GetInstanceInfoText(instance)):
3717 a8083063 Iustin Pop
        # remove secondary dev
3718 a8083063 Iustin Pop
        cfg.SetDiskID(new_drbd, remote_node)
3719 a8083063 Iustin Pop
        rpc.call_blockdev_remove(remote_node, new_drbd)
3720 f4bc1f2c Michael Hanselmann
        raise errors.OpExecError("Failed to create volume on primary!"
3721 f4bc1f2c Michael Hanselmann
                                 " Full abort, cleanup manually!!")
3722 a8083063 Iustin Pop
3723 a8083063 Iustin Pop
      # the device exists now
3724 a8083063 Iustin Pop
      # call the primary node to add the mirror to md
3725 a8083063 Iustin Pop
      logger.Info("adding new mirror component to md")
3726 153d9724 Iustin Pop
      if not rpc.call_blockdev_addchildren(instance.primary_node, dev,
3727 153d9724 Iustin Pop
                                           [new_drbd]):
3728 a8083063 Iustin Pop
        logger.Error("Can't add mirror compoment to md!")
3729 a8083063 Iustin Pop
        cfg.SetDiskID(new_drbd, remote_node)
3730 a8083063 Iustin Pop
        if not rpc.call_blockdev_remove(remote_node, new_drbd):
3731 a8083063 Iustin Pop
          logger.Error("Can't rollback on secondary")
3732 a8083063 Iustin Pop
        cfg.SetDiskID(new_drbd, instance.primary_node)
3733 a8083063 Iustin Pop
        if not rpc.call_blockdev_remove(instance.primary_node, new_drbd):
3734 a8083063 Iustin Pop
          logger.Error("Can't rollback on primary")
3735 3ecf6786 Iustin Pop
        raise errors.OpExecError("Full abort, cleanup manually!!")
3736 a8083063 Iustin Pop
3737 a8083063 Iustin Pop
      dev.children.append(new_drbd)
3738 a8083063 Iustin Pop
      cfg.AddInstance(instance)
3739 a8083063 Iustin Pop
3740 a8083063 Iustin Pop
    # this can fail as the old devices are degraded and _WaitForSync
3741 a8083063 Iustin Pop
    # does a combined result over all disks, so we don't check its
3742 a8083063 Iustin Pop
    # return value
3743 5bfac263 Iustin Pop
    _WaitForSync(cfg, instance, self.proc, unlock=True)
3744 a8083063 Iustin Pop
3745 a8083063 Iustin Pop
    # so check manually all the devices
3746 a8083063 Iustin Pop
    for name in iv_names:
3747 a8083063 Iustin Pop
      dev, child, new_drbd = iv_names[name]
3748 a8083063 Iustin Pop
      cfg.SetDiskID(dev, instance.primary_node)
3749 a8083063 Iustin Pop
      is_degr = rpc.call_blockdev_find(instance.primary_node, dev)[5]
3750 a8083063 Iustin Pop
      if is_degr:
3751 3ecf6786 Iustin Pop
        raise errors.OpExecError("MD device %s is degraded!" % name)
3752 a8083063 Iustin Pop
      cfg.SetDiskID(new_drbd, instance.primary_node)
3753 a8083063 Iustin Pop
      is_degr = rpc.call_blockdev_find(instance.primary_node, new_drbd)[5]
3754 a8083063 Iustin Pop
      if is_degr:
3755 3ecf6786 Iustin Pop
        raise errors.OpExecError("New drbd device %s is degraded!" % name)
3756 a8083063 Iustin Pop
3757 a8083063 Iustin Pop
    for name in iv_names:
3758 a8083063 Iustin Pop
      dev, child, new_drbd = iv_names[name]
3759 a8083063 Iustin Pop
      logger.Info("remove mirror %s component" % name)
3760 a8083063 Iustin Pop
      cfg.SetDiskID(dev, instance.primary_node)
3761 153d9724 Iustin Pop
      if not rpc.call_blockdev_removechildren(instance.primary_node,
3762 153d9724 Iustin Pop
                                              dev, [child]):
3763 a8083063 Iustin Pop
        logger.Error("Can't remove child from mirror, aborting"
3764 a8083063 Iustin Pop
                     " *this device cleanup*.\nYou need to cleanup manually!!")
3765 a8083063 Iustin Pop
        continue
3766 a8083063 Iustin Pop
3767 a8083063 Iustin Pop
      for node in child.logical_id[:2]:
3768 a8083063 Iustin Pop
        logger.Info("remove child device on %s" % node)
3769 a8083063 Iustin Pop
        cfg.SetDiskID(child, node)
3770 a8083063 Iustin Pop
        if not rpc.call_blockdev_remove(node, child):
3771 a8083063 Iustin Pop
          logger.Error("Warning: failed to remove device from node %s,"
3772 a8083063 Iustin Pop
                       " continuing operation." % node)
3773 a8083063 Iustin Pop
3774 a8083063 Iustin Pop
      dev.children.remove(child)
3775 a8083063 Iustin Pop
3776 a8083063 Iustin Pop
      cfg.AddInstance(instance)
3777 a8083063 Iustin Pop
3778 a9e0c397 Iustin Pop
  def _ExecD8DiskOnly(self, feedback_fn):
3779 a9e0c397 Iustin Pop
    """Replace a disk on the primary or secondary for dbrd8.
3780 a9e0c397 Iustin Pop

3781 a9e0c397 Iustin Pop
    The algorithm for replace is quite complicated:
3782 a9e0c397 Iustin Pop
      - for each disk to be replaced:
3783 a9e0c397 Iustin Pop
        - create new LVs on the target node with unique names
3784 a9e0c397 Iustin Pop
        - detach old LVs from the drbd device
3785 a9e0c397 Iustin Pop
        - rename old LVs to name_replaced.<time_t>
3786 a9e0c397 Iustin Pop
        - rename new LVs to old LVs
3787 a9e0c397 Iustin Pop
        - attach the new LVs (with the old names now) to the drbd device
3788 a9e0c397 Iustin Pop
      - wait for sync across all devices
3789 a9e0c397 Iustin Pop
      - for each modified disk:
3790 a9e0c397 Iustin Pop
        - remove old LVs (which have the name name_replaces.<time_t>)
3791 a9e0c397 Iustin Pop

3792 a9e0c397 Iustin Pop
    Failures are not very well handled.
3793 cff90b79 Iustin Pop

3794 a9e0c397 Iustin Pop
    """
3795 cff90b79 Iustin Pop
    steps_total = 6
3796 5bfac263 Iustin Pop
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
3797 a9e0c397 Iustin Pop
    instance = self.instance
3798 a9e0c397 Iustin Pop
    iv_names = {}
3799 a9e0c397 Iustin Pop
    vgname = self.cfg.GetVGName()
3800 a9e0c397 Iustin Pop
    # start of work
3801 a9e0c397 Iustin Pop
    cfg = self.cfg
3802 a9e0c397 Iustin Pop
    tgt_node = self.tgt_node
3803 cff90b79 Iustin Pop
    oth_node = self.oth_node
3804 cff90b79 Iustin Pop
3805 cff90b79 Iustin Pop
    # Step: check device activation
3806 5bfac263 Iustin Pop
    self.proc.LogStep(1, steps_total, "check device existence")
3807 cff90b79 Iustin Pop
    info("checking volume groups")
3808 cff90b79 Iustin Pop
    my_vg = cfg.GetVGName()
3809 cff90b79 Iustin Pop
    results = rpc.call_vg_list([oth_node, tgt_node])
3810 cff90b79 Iustin Pop
    if not results:
3811 cff90b79 Iustin Pop
      raise errors.OpExecError("Can't list volume groups on the nodes")
3812 cff90b79 Iustin Pop
    for node in oth_node, tgt_node:
3813 cff90b79 Iustin Pop
      res = results.get(node, False)
3814 cff90b79 Iustin Pop
      if not res or my_vg not in res:
3815 cff90b79 Iustin Pop
        raise errors.OpExecError("Volume group '%s' not found on %s" %
3816 cff90b79 Iustin Pop
                                 (my_vg, node))
3817 cff90b79 Iustin Pop
    for dev in instance.disks:
3818 cff90b79 Iustin Pop
      if not dev.iv_name in self.op.disks:
3819 cff90b79 Iustin Pop
        continue
3820 cff90b79 Iustin Pop
      for node in tgt_node, oth_node:
3821 cff90b79 Iustin Pop
        info("checking %s on %s" % (dev.iv_name, node))
3822 cff90b79 Iustin Pop
        cfg.SetDiskID(dev, node)
3823 cff90b79 Iustin Pop
        if not rpc.call_blockdev_find(node, dev):
3824 cff90b79 Iustin Pop
          raise errors.OpExecError("Can't find device %s on node %s" %
3825 cff90b79 Iustin Pop
                                   (dev.iv_name, node))
3826 cff90b79 Iustin Pop
3827 cff90b79 Iustin Pop
    # Step: check other node consistency
3828 5bfac263 Iustin Pop
    self.proc.LogStep(2, steps_total, "check peer consistency")
3829 cff90b79 Iustin Pop
    for dev in instance.disks:
3830 cff90b79 Iustin Pop
      if not dev.iv_name in self.op.disks:
3831 cff90b79 Iustin Pop
        continue
3832 cff90b79 Iustin Pop
      info("checking %s consistency on %s" % (dev.iv_name, oth_node))
3833 cff90b79 Iustin Pop
      if not _CheckDiskConsistency(self.cfg, dev, oth_node,
3834 cff90b79 Iustin Pop
                                   oth_node==instance.primary_node):
3835 cff90b79 Iustin Pop
        raise errors.OpExecError("Peer node (%s) has degraded storage, unsafe"
3836 cff90b79 Iustin Pop
                                 " to replace disks on this node (%s)" %
3837 cff90b79 Iustin Pop
                                 (oth_node, tgt_node))
3838 cff90b79 Iustin Pop
3839 cff90b79 Iustin Pop
    # Step: create new storage
3840 5bfac263 Iustin Pop
    self.proc.LogStep(3, steps_total, "allocate new storage")
3841 a9e0c397 Iustin Pop
    for dev in instance.disks:
3842 a9e0c397 Iustin Pop
      if not dev.iv_name in self.op.disks:
3843 a9e0c397 Iustin Pop
        continue
3844 a9e0c397 Iustin Pop
      size = dev.size
3845 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, tgt_node)
3846 a9e0c397 Iustin Pop
      lv_names = [".%s_%s" % (dev.iv_name, suf) for suf in ["data", "meta"]]
3847 a9e0c397 Iustin Pop
      names = _GenerateUniqueNames(cfg, lv_names)
3848 a9e0c397 Iustin Pop
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=size,
3849 a9e0c397 Iustin Pop
                             logical_id=(vgname, names[0]))
3850 a9e0c397 Iustin Pop
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
3851 a9e0c397 Iustin Pop
                             logical_id=(vgname, names[1]))
3852 a9e0c397 Iustin Pop
      new_lvs = [lv_data, lv_meta]
3853 a9e0c397 Iustin Pop
      old_lvs = dev.children
3854 a9e0c397 Iustin Pop
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
3855 cff90b79 Iustin Pop
      info("creating new local storage on %s for %s" %
3856 cff90b79 Iustin Pop
           (tgt_node, dev.iv_name))
3857 a9e0c397 Iustin Pop
      # since we *always* want to create this LV, we use the
3858 a9e0c397 Iustin Pop
      # _Create...OnPrimary (which forces the creation), even if we
3859 a9e0c397 Iustin Pop
      # are talking about the secondary node
3860 a9e0c397 Iustin Pop
      for new_lv in new_lvs:
3861 3f78eef2 Iustin Pop
        if not _CreateBlockDevOnPrimary(cfg, tgt_node, instance, new_lv,
3862 a9e0c397 Iustin Pop
                                        _GetInstanceInfoText(instance)):
3863 a9e0c397 Iustin Pop
          raise errors.OpExecError("Failed to create new LV named '%s' on"
3864 a9e0c397 Iustin Pop
                                   " node '%s'" %
3865 a9e0c397 Iustin Pop
                                   (new_lv.logical_id[1], tgt_node))
3866 a9e0c397 Iustin Pop
3867 cff90b79 Iustin Pop
    # Step: for each lv, detach+rename*2+attach
3868 5bfac263 Iustin Pop
    self.proc.LogStep(4, steps_total, "change drbd configuration")
3869 cff90b79 Iustin Pop
    for dev, old_lvs, new_lvs in iv_names.itervalues():
3870 cff90b79 Iustin Pop
      info("detaching %s drbd from local storage" % dev.iv_name)
3871 a9e0c397 Iustin Pop
      if not rpc.call_blockdev_removechildren(tgt_node, dev, old_lvs):
3872 a9e0c397 Iustin Pop
        raise errors.OpExecError("Can't detach drbd from local storage on node"
3873 a9e0c397 Iustin Pop
                                 " %s for device %s" % (tgt_node, dev.iv_name))
3874 cff90b79 Iustin Pop
      #dev.children = []
3875 cff90b79 Iustin Pop
      #cfg.Update(instance)
3876 a9e0c397 Iustin Pop
3877 a9e0c397 Iustin Pop
      # ok, we created the new LVs, so now we know we have the needed
3878 a9e0c397 Iustin Pop
      # storage; as such, we proceed on the target node to rename
3879 a9e0c397 Iustin Pop
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
3880 c99a3cc0 Manuel Franceschini
      # using the assumption that logical_id == physical_id (which in
3881 a9e0c397 Iustin Pop
      # turn is the unique_id on that node)
3882 cff90b79 Iustin Pop
3883 cff90b79 Iustin Pop
      # FIXME(iustin): use a better name for the replaced LVs
3884 a9e0c397 Iustin Pop
      temp_suffix = int(time.time())
3885 a9e0c397 Iustin Pop
      ren_fn = lambda d, suff: (d.physical_id[0],
3886 a9e0c397 Iustin Pop
                                d.physical_id[1] + "_replaced-%s" % suff)
3887 cff90b79 Iustin Pop
      # build the rename list based on what LVs exist on the node
3888 cff90b79 Iustin Pop
      rlist = []
3889 cff90b79 Iustin Pop
      for to_ren in old_lvs:
3890 cff90b79 Iustin Pop
        find_res = rpc.call_blockdev_find(tgt_node, to_ren)
3891 cff90b79 Iustin Pop
        if find_res is not None: # device exists
3892 cff90b79 Iustin Pop
          rlist.append((to_ren, ren_fn(to_ren, temp_suffix)))
3893 cff90b79 Iustin Pop
3894 cff90b79 Iustin Pop
      info("renaming the old LVs on the target node")
3895 a9e0c397 Iustin Pop
      if not rpc.call_blockdev_rename(tgt_node, rlist):
3896 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't rename old LVs on node %s" % tgt_node)
3897 a9e0c397 Iustin Pop
      # now we rename the new LVs to the old LVs
3898 cff90b79 Iustin Pop
      info("renaming the new LVs on the target node")
3899 a9e0c397 Iustin Pop
      rlist = [(new, old.physical_id) for old, new in zip(old_lvs, new_lvs)]
3900 a9e0c397 Iustin Pop
      if not rpc.call_blockdev_rename(tgt_node, rlist):
3901 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't rename new LVs on node %s" % tgt_node)
3902 cff90b79 Iustin Pop
3903 cff90b79 Iustin Pop
      for old, new in zip(old_lvs, new_lvs):
3904 cff90b79 Iustin Pop
        new.logical_id = old.logical_id
3905 cff90b79 Iustin Pop
        cfg.SetDiskID(new, tgt_node)
3906 a9e0c397 Iustin Pop
3907 cff90b79 Iustin Pop
      for disk in old_lvs:
3908 cff90b79 Iustin Pop
        disk.logical_id = ren_fn(disk, temp_suffix)
3909 cff90b79 Iustin Pop
        cfg.SetDiskID(disk, tgt_node)
3910 a9e0c397 Iustin Pop
3911 a9e0c397 Iustin Pop
      # now that the new lvs have the old name, we can add them to the device
3912 cff90b79 Iustin Pop
      info("adding new mirror component on %s" % tgt_node)
3913 a9e0c397 Iustin Pop
      if not rpc.call_blockdev_addchildren(tgt_node, dev, new_lvs):
3914 a9e0c397 Iustin Pop
        for new_lv in new_lvs:
3915 a9e0c397 Iustin Pop
          if not rpc.call_blockdev_remove(tgt_node, new_lv):
3916 79caa9ed Guido Trotter
            warning("Can't rollback device %s", hint="manually cleanup unused"
3917 cff90b79 Iustin Pop
                    " logical volumes")
3918 cff90b79 Iustin Pop
        raise errors.OpExecError("Can't add local storage to drbd")
3919 a9e0c397 Iustin Pop
3920 a9e0c397 Iustin Pop
      dev.children = new_lvs
3921 a9e0c397 Iustin Pop
      cfg.Update(instance)
3922 a9e0c397 Iustin Pop
3923 cff90b79 Iustin Pop
    # Step: wait for sync
3924 a9e0c397 Iustin Pop
3925 a9e0c397 Iustin Pop
    # this can fail as the old devices are degraded and _WaitForSync
3926 a9e0c397 Iustin Pop
    # does a combined result over all disks, so we don't check its
3927 a9e0c397 Iustin Pop
    # return value
3928 5bfac263 Iustin Pop
    self.proc.LogStep(5, steps_total, "sync devices")
3929 5bfac263 Iustin Pop
    _WaitForSync(cfg, instance, self.proc, unlock=True)
3930 a9e0c397 Iustin Pop
3931 a9e0c397 Iustin Pop
    # so check manually all the devices
3932 a9e0c397 Iustin Pop
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
3933 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, instance.primary_node)
3934 a9e0c397 Iustin Pop
      is_degr = rpc.call_blockdev_find(instance.primary_node, dev)[5]
3935 a9e0c397 Iustin Pop
      if is_degr:
3936 a9e0c397 Iustin Pop
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
3937 a9e0c397 Iustin Pop
3938 cff90b79 Iustin Pop
    # Step: remove old storage
3939 5bfac263 Iustin Pop
    self.proc.LogStep(6, steps_total, "removing old storage")
3940 a9e0c397 Iustin Pop
    for name, (dev, old_lvs, new_lvs) in iv_names.iteritems():
3941 cff90b79 Iustin Pop
      info("remove logical volumes for %s" % name)
3942 a9e0c397 Iustin Pop
      for lv in old_lvs:
3943 a9e0c397 Iustin Pop
        cfg.SetDiskID(lv, tgt_node)
3944 a9e0c397 Iustin Pop
        if not rpc.call_blockdev_remove(tgt_node, lv):
3945 79caa9ed Guido Trotter
          warning("Can't remove old LV", hint="manually remove unused LVs")
3946 a9e0c397 Iustin Pop
          continue
3947 a9e0c397 Iustin Pop
3948 a9e0c397 Iustin Pop
  def _ExecD8Secondary(self, feedback_fn):
3949 a9e0c397 Iustin Pop
    """Replace the secondary node for drbd8.
3950 a9e0c397 Iustin Pop

3951 a9e0c397 Iustin Pop
    The algorithm for replace is quite complicated:
3952 a9e0c397 Iustin Pop
      - for all disks of the instance:
3953 a9e0c397 Iustin Pop
        - create new LVs on the new node with same names
3954 a9e0c397 Iustin Pop
        - shutdown the drbd device on the old secondary
3955 a9e0c397 Iustin Pop
        - disconnect the drbd network on the primary
3956 a9e0c397 Iustin Pop
        - create the drbd device on the new secondary
3957 a9e0c397 Iustin Pop
        - network attach the drbd on the primary, using an artifice:
3958 a9e0c397 Iustin Pop
          the drbd code for Attach() will connect to the network if it
3959 a9e0c397 Iustin Pop
          finds a device which is connected to the good local disks but
3960 a9e0c397 Iustin Pop
          not network enabled
3961 a9e0c397 Iustin Pop
      - wait for sync across all devices
3962 a9e0c397 Iustin Pop
      - remove all disks from the old secondary
3963 a9e0c397 Iustin Pop

3964 a9e0c397 Iustin Pop
    Failures are not very well handled.
3965 0834c866 Iustin Pop

3966 a9e0c397 Iustin Pop
    """
3967 0834c866 Iustin Pop
    steps_total = 6
3968 5bfac263 Iustin Pop
    warning, info = (self.proc.LogWarning, self.proc.LogInfo)
3969 a9e0c397 Iustin Pop
    instance = self.instance
3970 a9e0c397 Iustin Pop
    iv_names = {}
3971 a9e0c397 Iustin Pop
    vgname = self.cfg.GetVGName()
3972 a9e0c397 Iustin Pop
    # start of work
3973 a9e0c397 Iustin Pop
    cfg = self.cfg
3974 a9e0c397 Iustin Pop
    old_node = self.tgt_node
3975 a9e0c397 Iustin Pop
    new_node = self.new_node
3976 a9e0c397 Iustin Pop
    pri_node = instance.primary_node
3977 0834c866 Iustin Pop
3978 0834c866 Iustin Pop
    # Step: check device activation
3979 5bfac263 Iustin Pop
    self.proc.LogStep(1, steps_total, "check device existence")
3980 0834c866 Iustin Pop
    info("checking volume groups")
3981 0834c866 Iustin Pop
    my_vg = cfg.GetVGName()
3982 0834c866 Iustin Pop
    results = rpc.call_vg_list([pri_node, new_node])
3983 0834c866 Iustin Pop
    if not results:
3984 0834c866 Iustin Pop
      raise errors.OpExecError("Can't list volume groups on the nodes")
3985 0834c866 Iustin Pop
    for node in pri_node, new_node:
3986 0834c866 Iustin Pop
      res = results.get(node, False)
3987 0834c866 Iustin Pop
      if not res or my_vg not in res:
3988 0834c866 Iustin Pop
        raise errors.OpExecError("Volume group '%s' not found on %s" %
3989 0834c866 Iustin Pop
                                 (my_vg, node))
3990 0834c866 Iustin Pop
    for dev in instance.disks:
3991 0834c866 Iustin Pop
      if not dev.iv_name in self.op.disks:
3992 0834c866 Iustin Pop
        continue
3993 0834c866 Iustin Pop
      info("checking %s on %s" % (dev.iv_name, pri_node))
3994 0834c866 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
3995 0834c866 Iustin Pop
      if not rpc.call_blockdev_find(pri_node, dev):
3996 0834c866 Iustin Pop
        raise errors.OpExecError("Can't find device %s on node %s" %
3997 0834c866 Iustin Pop
                                 (dev.iv_name, pri_node))
3998 0834c866 Iustin Pop
3999 0834c866 Iustin Pop
    # Step: check other node consistency
4000 5bfac263 Iustin Pop
    self.proc.LogStep(2, steps_total, "check peer consistency")
4001 0834c866 Iustin Pop
    for dev in instance.disks:
4002 0834c866 Iustin Pop
      if not dev.iv_name in self.op.disks:
4003 0834c866 Iustin Pop
        continue
4004 0834c866 Iustin Pop
      info("checking %s consistency on %s" % (dev.iv_name, pri_node))
4005 0834c866 Iustin Pop
      if not _CheckDiskConsistency(self.cfg, dev, pri_node, True, ldisk=True):
4006 0834c866 Iustin Pop
        raise errors.OpExecError("Primary node (%s) has degraded storage,"
4007 0834c866 Iustin Pop
                                 " unsafe to replace the secondary" %
4008 0834c866 Iustin Pop
                                 pri_node)
4009 0834c866 Iustin Pop
4010 0834c866 Iustin Pop
    # Step: create new storage
4011 5bfac263 Iustin Pop
    self.proc.LogStep(3, steps_total, "allocate new storage")
4012 a9e0c397 Iustin Pop
    for dev in instance.disks:
4013 a9e0c397 Iustin Pop
      size = dev.size
4014 0834c866 Iustin Pop
      info("adding new local storage on %s for %s" % (new_node, dev.iv_name))
4015 a9e0c397 Iustin Pop
      # since we *always* want to create this LV, we use the
4016 a9e0c397 Iustin Pop
      # _Create...OnPrimary (which forces the creation), even if we
4017 a9e0c397 Iustin Pop
      # are talking about the secondary node
4018 a9e0c397 Iustin Pop
      for new_lv in dev.children:
4019 3f78eef2 Iustin Pop
        if not _CreateBlockDevOnPrimary(cfg, new_node, instance, new_lv,
4020 a9e0c397 Iustin Pop
                                        _GetInstanceInfoText(instance)):
4021 a9e0c397 Iustin Pop
          raise errors.OpExecError("Failed to create new LV named '%s' on"
4022 a9e0c397 Iustin Pop
                                   " node '%s'" %
4023 a9e0c397 Iustin Pop
                                   (new_lv.logical_id[1], new_node))
4024 a9e0c397 Iustin Pop
4025 0834c866 Iustin Pop
      iv_names[dev.iv_name] = (dev, dev.children)
4026 0834c866 Iustin Pop
4027 5bfac263 Iustin Pop
    self.proc.LogStep(4, steps_total, "changing drbd configuration")
4028 0834c866 Iustin Pop
    for dev in instance.disks:
4029 0834c866 Iustin Pop
      size = dev.size
4030 0834c866 Iustin Pop
      info("activating a new drbd on %s for %s" % (new_node, dev.iv_name))
4031 a9e0c397 Iustin Pop
      # create new devices on new_node
4032 a9e0c397 Iustin Pop
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
4033 a9e0c397 Iustin Pop
                              logical_id=(pri_node, new_node,
4034 a9e0c397 Iustin Pop
                                          dev.logical_id[2]),
4035 a9e0c397 Iustin Pop
                              children=dev.children)
4036 3f78eef2 Iustin Pop
      if not _CreateBlockDevOnSecondary(cfg, new_node, instance,
4037 3f78eef2 Iustin Pop
                                        new_drbd, False,
4038 a9e0c397 Iustin Pop
                                      _GetInstanceInfoText(instance)):
4039 a9e0c397 Iustin Pop
        raise errors.OpExecError("Failed to create new DRBD on"
4040 a9e0c397 Iustin Pop
                                 " node '%s'" % new_node)
4041 a9e0c397 Iustin Pop
4042 0834c866 Iustin Pop
    for dev in instance.disks:
4043 a9e0c397 Iustin Pop
      # we have new devices, shutdown the drbd on the old secondary
4044 0834c866 Iustin Pop
      info("shutting down drbd for %s on old node" % dev.iv_name)
4045 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, old_node)
4046 a9e0c397 Iustin Pop
      if not rpc.call_blockdev_shutdown(old_node, dev):
4047 0834c866 Iustin Pop
        warning("Failed to shutdown drbd for %s on old node" % dev.iv_name,
4048 79caa9ed Guido Trotter
                hint="Please cleanup this device manually as soon as possible")
4049 a9e0c397 Iustin Pop
4050 642445d9 Iustin Pop
    info("detaching primary drbds from the network (=> standalone)")
4051 642445d9 Iustin Pop
    done = 0
4052 642445d9 Iustin Pop
    for dev in instance.disks:
4053 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4054 642445d9 Iustin Pop
      # set the physical (unique in bdev terms) id to None, meaning
4055 642445d9 Iustin Pop
      # detach from network
4056 642445d9 Iustin Pop
      dev.physical_id = (None,) * len(dev.physical_id)
4057 642445d9 Iustin Pop
      # and 'find' the device, which will 'fix' it to match the
4058 642445d9 Iustin Pop
      # standalone state
4059 642445d9 Iustin Pop
      if rpc.call_blockdev_find(pri_node, dev):
4060 642445d9 Iustin Pop
        done += 1
4061 642445d9 Iustin Pop
      else:
4062 642445d9 Iustin Pop
        warning("Failed to detach drbd %s from network, unusual case" %
4063 642445d9 Iustin Pop
                dev.iv_name)
4064 642445d9 Iustin Pop
4065 642445d9 Iustin Pop
    if not done:
4066 642445d9 Iustin Pop
      # no detaches succeeded (very unlikely)
4067 642445d9 Iustin Pop
      raise errors.OpExecError("Can't detach at least one DRBD from old node")
4068 642445d9 Iustin Pop
4069 642445d9 Iustin Pop
    # if we managed to detach at least one, we update all the disks of
4070 642445d9 Iustin Pop
    # the instance to point to the new secondary
4071 642445d9 Iustin Pop
    info("updating instance configuration")
4072 642445d9 Iustin Pop
    for dev in instance.disks:
4073 642445d9 Iustin Pop
      dev.logical_id = (pri_node, new_node) + dev.logical_id[2:]
4074 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4075 642445d9 Iustin Pop
    cfg.Update(instance)
4076 a9e0c397 Iustin Pop
4077 642445d9 Iustin Pop
    # and now perform the drbd attach
4078 642445d9 Iustin Pop
    info("attaching primary drbds to new secondary (standalone => connected)")
4079 642445d9 Iustin Pop
    failures = []
4080 642445d9 Iustin Pop
    for dev in instance.disks:
4081 642445d9 Iustin Pop
      info("attaching primary drbd for %s to new secondary node" % dev.iv_name)
4082 642445d9 Iustin Pop
      # since the attach is smart, it's enough to 'find' the device,
4083 642445d9 Iustin Pop
      # it will automatically activate the network, if the physical_id
4084 642445d9 Iustin Pop
      # is correct
4085 642445d9 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4086 642445d9 Iustin Pop
      if not rpc.call_blockdev_find(pri_node, dev):
4087 642445d9 Iustin Pop
        warning("can't attach drbd %s to new secondary!" % dev.iv_name,
4088 642445d9 Iustin Pop
                "please do a gnt-instance info to see the status of disks")
4089 a9e0c397 Iustin Pop
4090 a9e0c397 Iustin Pop
    # this can fail as the old devices are degraded and _WaitForSync
4091 a9e0c397 Iustin Pop
    # does a combined result over all disks, so we don't check its
4092 a9e0c397 Iustin Pop
    # return value
4093 5bfac263 Iustin Pop
    self.proc.LogStep(5, steps_total, "sync devices")
4094 5bfac263 Iustin Pop
    _WaitForSync(cfg, instance, self.proc, unlock=True)
4095 a9e0c397 Iustin Pop
4096 a9e0c397 Iustin Pop
    # so check manually all the devices
4097 a9e0c397 Iustin Pop
    for name, (dev, old_lvs) in iv_names.iteritems():
4098 a9e0c397 Iustin Pop
      cfg.SetDiskID(dev, pri_node)
4099 a9e0c397 Iustin Pop
      is_degr = rpc.call_blockdev_find(pri_node, dev)[5]
4100 a9e0c397 Iustin Pop
      if is_degr:
4101 a9e0c397 Iustin Pop
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
4102 a9e0c397 Iustin Pop
4103 5bfac263 Iustin Pop
    self.proc.LogStep(6, steps_total, "removing old storage")
4104 a9e0c397 Iustin Pop
    for name, (dev, old_lvs) in iv_names.iteritems():
4105 0834c866 Iustin Pop
      info("remove logical volumes for %s" % name)
4106 a9e0c397 Iustin Pop
      for lv in old_lvs:
4107 a9e0c397 Iustin Pop
        cfg.SetDiskID(lv, old_node)
4108 a9e0c397 Iustin Pop
        if not rpc.call_blockdev_remove(old_node, lv):
4109 0834c866 Iustin Pop
          warning("Can't remove LV on old secondary",
4110 79caa9ed Guido Trotter
                  hint="Cleanup stale volumes by hand")
4111 a9e0c397 Iustin Pop
4112 a9e0c397 Iustin Pop
  def Exec(self, feedback_fn):
4113 a9e0c397 Iustin Pop
    """Execute disk replacement.
4114 a9e0c397 Iustin Pop

4115 a9e0c397 Iustin Pop
    This dispatches the disk replacement to the appropriate handler.
4116 a9e0c397 Iustin Pop

4117 a9e0c397 Iustin Pop
    """
4118 a9e0c397 Iustin Pop
    instance = self.instance
4119 a9e0c397 Iustin Pop
    if instance.disk_template == constants.DT_REMOTE_RAID1:
4120 a9e0c397 Iustin Pop
      fn = self._ExecRR1
4121 a9e0c397 Iustin Pop
    elif instance.disk_template == constants.DT_DRBD8:
4122 a9e0c397 Iustin Pop
      if self.op.remote_node is None:
4123 a9e0c397 Iustin Pop
        fn = self._ExecD8DiskOnly
4124 a9e0c397 Iustin Pop
      else:
4125 a9e0c397 Iustin Pop
        fn = self._ExecD8Secondary
4126 a9e0c397 Iustin Pop
    else:
4127 a9e0c397 Iustin Pop
      raise errors.ProgrammerError("Unhandled disk replacement case")
4128 a9e0c397 Iustin Pop
    return fn(feedback_fn)
4129 a9e0c397 Iustin Pop
4130 a8083063 Iustin Pop
4131 a8083063 Iustin Pop
class LUQueryInstanceData(NoHooksLU):
4132 a8083063 Iustin Pop
  """Query runtime instance data.
4133 a8083063 Iustin Pop

4134 a8083063 Iustin Pop
  """
4135 a8083063 Iustin Pop
  _OP_REQP = ["instances"]
4136 a8083063 Iustin Pop
4137 a8083063 Iustin Pop
  def CheckPrereq(self):
4138 a8083063 Iustin Pop
    """Check prerequisites.
4139 a8083063 Iustin Pop

4140 a8083063 Iustin Pop
    This only checks the optional instance list against the existing names.
4141 a8083063 Iustin Pop

4142 a8083063 Iustin Pop
    """
4143 a8083063 Iustin Pop
    if not isinstance(self.op.instances, list):
4144 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Invalid argument type 'instances'")
4145 a8083063 Iustin Pop
    if self.op.instances:
4146 a8083063 Iustin Pop
      self.wanted_instances = []
4147 a8083063 Iustin Pop
      names = self.op.instances
4148 a8083063 Iustin Pop
      for name in names:
4149 a8083063 Iustin Pop
        instance = self.cfg.GetInstanceInfo(self.cfg.ExpandInstanceName(name))
4150 a8083063 Iustin Pop
        if instance is None:
4151 3ecf6786 Iustin Pop
          raise errors.OpPrereqError("No such instance name '%s'" % name)
4152 515207af Guido Trotter
        self.wanted_instances.append(instance)
4153 a8083063 Iustin Pop
    else:
4154 a8083063 Iustin Pop
      self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
4155 a8083063 Iustin Pop
                               in self.cfg.GetInstanceList()]
4156 a8083063 Iustin Pop
    return
4157 a8083063 Iustin Pop
4158 a8083063 Iustin Pop
4159 a8083063 Iustin Pop
  def _ComputeDiskStatus(self, instance, snode, dev):
4160 a8083063 Iustin Pop
    """Compute block device status.
4161 a8083063 Iustin Pop

4162 a8083063 Iustin Pop
    """
4163 a8083063 Iustin Pop
    self.cfg.SetDiskID(dev, instance.primary_node)
4164 a8083063 Iustin Pop
    dev_pstatus = rpc.call_blockdev_find(instance.primary_node, dev)
4165 a1f445d3 Iustin Pop
    if dev.dev_type in constants.LDS_DRBD:
4166 a8083063 Iustin Pop
      # we change the snode then (otherwise we use the one passed in)
4167 a8083063 Iustin Pop
      if dev.logical_id[0] == instance.primary_node:
4168 a8083063 Iustin Pop
        snode = dev.logical_id[1]
4169 a8083063 Iustin Pop
      else:
4170 a8083063 Iustin Pop
        snode = dev.logical_id[0]
4171 a8083063 Iustin Pop
4172 a8083063 Iustin Pop
    if snode:
4173 a8083063 Iustin Pop
      self.cfg.SetDiskID(dev, snode)
4174 a8083063 Iustin Pop
      dev_sstatus = rpc.call_blockdev_find(snode, dev)
4175 a8083063 Iustin Pop
    else:
4176 a8083063 Iustin Pop
      dev_sstatus = None
4177 a8083063 Iustin Pop
4178 a8083063 Iustin Pop
    if dev.children:
4179 a8083063 Iustin Pop
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
4180 a8083063 Iustin Pop
                      for child in dev.children]
4181 a8083063 Iustin Pop
    else:
4182 a8083063 Iustin Pop
      dev_children = []
4183 a8083063 Iustin Pop
4184 a8083063 Iustin Pop
    data = {
4185 a8083063 Iustin Pop
      "iv_name": dev.iv_name,
4186 a8083063 Iustin Pop
      "dev_type": dev.dev_type,
4187 a8083063 Iustin Pop
      "logical_id": dev.logical_id,
4188 a8083063 Iustin Pop
      "physical_id": dev.physical_id,
4189 a8083063 Iustin Pop
      "pstatus": dev_pstatus,
4190 a8083063 Iustin Pop
      "sstatus": dev_sstatus,
4191 a8083063 Iustin Pop
      "children": dev_children,
4192 a8083063 Iustin Pop
      }
4193 a8083063 Iustin Pop
4194 a8083063 Iustin Pop
    return data
4195 a8083063 Iustin Pop
4196 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4197 a8083063 Iustin Pop
    """Gather and return data"""
4198 a8083063 Iustin Pop
    result = {}
4199 a8083063 Iustin Pop
    for instance in self.wanted_instances:
4200 a8083063 Iustin Pop
      remote_info = rpc.call_instance_info(instance.primary_node,
4201 a8083063 Iustin Pop
                                                instance.name)
4202 a8083063 Iustin Pop
      if remote_info and "state" in remote_info:
4203 a8083063 Iustin Pop
        remote_state = "up"
4204 a8083063 Iustin Pop
      else:
4205 a8083063 Iustin Pop
        remote_state = "down"
4206 a8083063 Iustin Pop
      if instance.status == "down":
4207 a8083063 Iustin Pop
        config_state = "down"
4208 a8083063 Iustin Pop
      else:
4209 a8083063 Iustin Pop
        config_state = "up"
4210 a8083063 Iustin Pop
4211 a8083063 Iustin Pop
      disks = [self._ComputeDiskStatus(instance, None, device)
4212 a8083063 Iustin Pop
               for device in instance.disks]
4213 a8083063 Iustin Pop
4214 a8083063 Iustin Pop
      idict = {
4215 a8083063 Iustin Pop
        "name": instance.name,
4216 a8083063 Iustin Pop
        "config_state": config_state,
4217 a8083063 Iustin Pop
        "run_state": remote_state,
4218 a8083063 Iustin Pop
        "pnode": instance.primary_node,
4219 a8083063 Iustin Pop
        "snodes": instance.secondary_nodes,
4220 a8083063 Iustin Pop
        "os": instance.os,
4221 a8083063 Iustin Pop
        "memory": instance.memory,
4222 a8083063 Iustin Pop
        "nics": [(nic.mac, nic.ip, nic.bridge) for nic in instance.nics],
4223 a8083063 Iustin Pop
        "disks": disks,
4224 58acb49d Alexander Schreiber
        "network_port": instance.network_port,
4225 f55ff7ec Iustin Pop
        "vcpus": instance.vcpus,
4226 71aa8f73 Iustin Pop
        "kernel_path": instance.kernel_path,
4227 71aa8f73 Iustin Pop
        "initrd_path": instance.initrd_path,
4228 8ae6bb54 Iustin Pop
        "hvm_boot_order": instance.hvm_boot_order,
4229 a8083063 Iustin Pop
        }
4230 a8083063 Iustin Pop
4231 a8083063 Iustin Pop
      result[instance.name] = idict
4232 a8083063 Iustin Pop
4233 a8083063 Iustin Pop
    return result
4234 a8083063 Iustin Pop
4235 a8083063 Iustin Pop
4236 7767bbf5 Manuel Franceschini
class LUSetInstanceParams(LogicalUnit):
4237 a8083063 Iustin Pop
  """Modifies an instances's parameters.
4238 a8083063 Iustin Pop

4239 a8083063 Iustin Pop
  """
4240 a8083063 Iustin Pop
  HPATH = "instance-modify"
4241 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4242 a8083063 Iustin Pop
  _OP_REQP = ["instance_name"]
4243 a8083063 Iustin Pop
4244 a8083063 Iustin Pop
  def BuildHooksEnv(self):
4245 a8083063 Iustin Pop
    """Build hooks env.
4246 a8083063 Iustin Pop

4247 a8083063 Iustin Pop
    This runs on the master, primary and secondaries.
4248 a8083063 Iustin Pop

4249 a8083063 Iustin Pop
    """
4250 396e1b78 Michael Hanselmann
    args = dict()
4251 a8083063 Iustin Pop
    if self.mem:
4252 396e1b78 Michael Hanselmann
      args['memory'] = self.mem
4253 a8083063 Iustin Pop
    if self.vcpus:
4254 396e1b78 Michael Hanselmann
      args['vcpus'] = self.vcpus
4255 ef756965 Iustin Pop
    if self.do_ip or self.do_bridge or self.mac:
4256 396e1b78 Michael Hanselmann
      if self.do_ip:
4257 396e1b78 Michael Hanselmann
        ip = self.ip
4258 396e1b78 Michael Hanselmann
      else:
4259 396e1b78 Michael Hanselmann
        ip = self.instance.nics[0].ip
4260 396e1b78 Michael Hanselmann
      if self.bridge:
4261 396e1b78 Michael Hanselmann
        bridge = self.bridge
4262 396e1b78 Michael Hanselmann
      else:
4263 396e1b78 Michael Hanselmann
        bridge = self.instance.nics[0].bridge
4264 ef756965 Iustin Pop
      if self.mac:
4265 ef756965 Iustin Pop
        mac = self.mac
4266 ef756965 Iustin Pop
      else:
4267 ef756965 Iustin Pop
        mac = self.instance.nics[0].mac
4268 ef756965 Iustin Pop
      args['nics'] = [(ip, bridge, mac)]
4269 396e1b78 Michael Hanselmann
    env = _BuildInstanceHookEnvByObject(self.instance, override=args)
4270 880478f8 Iustin Pop
    nl = [self.sstore.GetMasterNode(),
4271 a8083063 Iustin Pop
          self.instance.primary_node] + list(self.instance.secondary_nodes)
4272 a8083063 Iustin Pop
    return env, nl, nl
4273 a8083063 Iustin Pop
4274 a8083063 Iustin Pop
  def CheckPrereq(self):
4275 a8083063 Iustin Pop
    """Check prerequisites.
4276 a8083063 Iustin Pop

4277 a8083063 Iustin Pop
    This only checks the instance list against the existing names.
4278 a8083063 Iustin Pop

4279 a8083063 Iustin Pop
    """
4280 a8083063 Iustin Pop
    self.mem = getattr(self.op, "mem", None)
4281 a8083063 Iustin Pop
    self.vcpus = getattr(self.op, "vcpus", None)
4282 a8083063 Iustin Pop
    self.ip = getattr(self.op, "ip", None)
4283 1862d460 Alexander Schreiber
    self.mac = getattr(self.op, "mac", None)
4284 a8083063 Iustin Pop
    self.bridge = getattr(self.op, "bridge", None)
4285 973d7867 Iustin Pop
    self.kernel_path = getattr(self.op, "kernel_path", None)
4286 973d7867 Iustin Pop
    self.initrd_path = getattr(self.op, "initrd_path", None)
4287 25c5878d Alexander Schreiber
    self.hvm_boot_order = getattr(self.op, "hvm_boot_order", None)
4288 7767bbf5 Manuel Franceschini
    all_params = [self.mem, self.vcpus, self.ip, self.bridge, self.mac,
4289 7767bbf5 Manuel Franceschini
                  self.kernel_path, self.initrd_path, self.hvm_boot_order]
4290 7767bbf5 Manuel Franceschini
    if all_params.count(None) == len(all_params):
4291 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("No changes submitted")
4292 a8083063 Iustin Pop
    if self.mem is not None:
4293 a8083063 Iustin Pop
      try:
4294 a8083063 Iustin Pop
        self.mem = int(self.mem)
4295 a8083063 Iustin Pop
      except ValueError, err:
4296 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid memory size: %s" % str(err))
4297 a8083063 Iustin Pop
    if self.vcpus is not None:
4298 a8083063 Iustin Pop
      try:
4299 a8083063 Iustin Pop
        self.vcpus = int(self.vcpus)
4300 a8083063 Iustin Pop
      except ValueError, err:
4301 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid vcpus number: %s" % str(err))
4302 a8083063 Iustin Pop
    if self.ip is not None:
4303 a8083063 Iustin Pop
      self.do_ip = True
4304 a8083063 Iustin Pop
      if self.ip.lower() == "none":
4305 a8083063 Iustin Pop
        self.ip = None
4306 a8083063 Iustin Pop
      else:
4307 a8083063 Iustin Pop
        if not utils.IsValidIP(self.ip):
4308 3ecf6786 Iustin Pop
          raise errors.OpPrereqError("Invalid IP address '%s'." % self.ip)
4309 a8083063 Iustin Pop
    else:
4310 a8083063 Iustin Pop
      self.do_ip = False
4311 ecb215b5 Michael Hanselmann
    self.do_bridge = (self.bridge is not None)
4312 1862d460 Alexander Schreiber
    if self.mac is not None:
4313 1862d460 Alexander Schreiber
      if self.cfg.IsMacInUse(self.mac):
4314 1862d460 Alexander Schreiber
        raise errors.OpPrereqError('MAC address %s already in use in cluster' %
4315 1862d460 Alexander Schreiber
                                   self.mac)
4316 1862d460 Alexander Schreiber
      if not utils.IsValidMac(self.mac):
4317 1862d460 Alexander Schreiber
        raise errors.OpPrereqError('Invalid MAC address %s' % self.mac)
4318 a8083063 Iustin Pop
4319 973d7867 Iustin Pop
    if self.kernel_path is not None:
4320 973d7867 Iustin Pop
      self.do_kernel_path = True
4321 973d7867 Iustin Pop
      if self.kernel_path == constants.VALUE_NONE:
4322 973d7867 Iustin Pop
        raise errors.OpPrereqError("Can't set instance to no kernel")
4323 973d7867 Iustin Pop
4324 973d7867 Iustin Pop
      if self.kernel_path != constants.VALUE_DEFAULT:
4325 973d7867 Iustin Pop
        if not os.path.isabs(self.kernel_path):
4326 ba4b62cf Iustin Pop
          raise errors.OpPrereqError("The kernel path must be an absolute"
4327 973d7867 Iustin Pop
                                    " filename")
4328 8cafeb26 Iustin Pop
    else:
4329 8cafeb26 Iustin Pop
      self.do_kernel_path = False
4330 973d7867 Iustin Pop
4331 973d7867 Iustin Pop
    if self.initrd_path is not None:
4332 973d7867 Iustin Pop
      self.do_initrd_path = True
4333 973d7867 Iustin Pop
      if self.initrd_path not in (constants.VALUE_NONE,
4334 973d7867 Iustin Pop
                                  constants.VALUE_DEFAULT):
4335 2bc22872 Iustin Pop
        if not os.path.isabs(self.initrd_path):
4336 ba4b62cf Iustin Pop
          raise errors.OpPrereqError("The initrd path must be an absolute"
4337 973d7867 Iustin Pop
                                    " filename")
4338 8cafeb26 Iustin Pop
    else:
4339 8cafeb26 Iustin Pop
      self.do_initrd_path = False
4340 973d7867 Iustin Pop
4341 25c5878d Alexander Schreiber
    # boot order verification
4342 25c5878d Alexander Schreiber
    if self.hvm_boot_order is not None:
4343 25c5878d Alexander Schreiber
      if self.hvm_boot_order != constants.VALUE_DEFAULT:
4344 25c5878d Alexander Schreiber
        if len(self.hvm_boot_order.strip("acdn")) != 0:
4345 25c5878d Alexander Schreiber
          raise errors.OpPrereqError("invalid boot order specified,"
4346 25c5878d Alexander Schreiber
                                     " must be one or more of [acdn]"
4347 25c5878d Alexander Schreiber
                                     " or 'default'")
4348 25c5878d Alexander Schreiber
4349 a8083063 Iustin Pop
    instance = self.cfg.GetInstanceInfo(
4350 a8083063 Iustin Pop
      self.cfg.ExpandInstanceName(self.op.instance_name))
4351 a8083063 Iustin Pop
    if instance is None:
4352 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("No such instance name '%s'" %
4353 3ecf6786 Iustin Pop
                                 self.op.instance_name)
4354 a8083063 Iustin Pop
    self.op.instance_name = instance.name
4355 a8083063 Iustin Pop
    self.instance = instance
4356 a8083063 Iustin Pop
    return
4357 a8083063 Iustin Pop
4358 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4359 a8083063 Iustin Pop
    """Modifies an instance.
4360 a8083063 Iustin Pop

4361 a8083063 Iustin Pop
    All parameters take effect only at the next restart of the instance.
4362 a8083063 Iustin Pop
    """
4363 a8083063 Iustin Pop
    result = []
4364 a8083063 Iustin Pop
    instance = self.instance
4365 a8083063 Iustin Pop
    if self.mem:
4366 a8083063 Iustin Pop
      instance.memory = self.mem
4367 a8083063 Iustin Pop
      result.append(("mem", self.mem))
4368 a8083063 Iustin Pop
    if self.vcpus:
4369 a8083063 Iustin Pop
      instance.vcpus = self.vcpus
4370 a8083063 Iustin Pop
      result.append(("vcpus",  self.vcpus))
4371 a8083063 Iustin Pop
    if self.do_ip:
4372 a8083063 Iustin Pop
      instance.nics[0].ip = self.ip
4373 a8083063 Iustin Pop
      result.append(("ip", self.ip))
4374 a8083063 Iustin Pop
    if self.bridge:
4375 a8083063 Iustin Pop
      instance.nics[0].bridge = self.bridge
4376 a8083063 Iustin Pop
      result.append(("bridge", self.bridge))
4377 1862d460 Alexander Schreiber
    if self.mac:
4378 1862d460 Alexander Schreiber
      instance.nics[0].mac = self.mac
4379 1862d460 Alexander Schreiber
      result.append(("mac", self.mac))
4380 973d7867 Iustin Pop
    if self.do_kernel_path:
4381 973d7867 Iustin Pop
      instance.kernel_path = self.kernel_path
4382 973d7867 Iustin Pop
      result.append(("kernel_path", self.kernel_path))
4383 973d7867 Iustin Pop
    if self.do_initrd_path:
4384 973d7867 Iustin Pop
      instance.initrd_path = self.initrd_path
4385 973d7867 Iustin Pop
      result.append(("initrd_path", self.initrd_path))
4386 25c5878d Alexander Schreiber
    if self.hvm_boot_order:
4387 25c5878d Alexander Schreiber
      if self.hvm_boot_order == constants.VALUE_DEFAULT:
4388 25c5878d Alexander Schreiber
        instance.hvm_boot_order = None
4389 25c5878d Alexander Schreiber
      else:
4390 25c5878d Alexander Schreiber
        instance.hvm_boot_order = self.hvm_boot_order
4391 25c5878d Alexander Schreiber
      result.append(("hvm_boot_order", self.hvm_boot_order))
4392 a8083063 Iustin Pop
4393 a8083063 Iustin Pop
    self.cfg.AddInstance(instance)
4394 a8083063 Iustin Pop
4395 a8083063 Iustin Pop
    return result
4396 a8083063 Iustin Pop
4397 a8083063 Iustin Pop
4398 a8083063 Iustin Pop
class LUQueryExports(NoHooksLU):
4399 a8083063 Iustin Pop
  """Query the exports list
4400 a8083063 Iustin Pop

4401 a8083063 Iustin Pop
  """
4402 a8083063 Iustin Pop
  _OP_REQP = []
4403 a8083063 Iustin Pop
4404 a8083063 Iustin Pop
  def CheckPrereq(self):
4405 a8083063 Iustin Pop
    """Check that the nodelist contains only existing nodes.
4406 a8083063 Iustin Pop

4407 a8083063 Iustin Pop
    """
4408 dcb93971 Michael Hanselmann
    self.nodes = _GetWantedNodes(self, getattr(self.op, "nodes", None))
4409 a8083063 Iustin Pop
4410 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4411 a8083063 Iustin Pop
    """Compute the list of all the exported system images.
4412 a8083063 Iustin Pop

4413 a8083063 Iustin Pop
    Returns:
4414 a8083063 Iustin Pop
      a dictionary with the structure node->(export-list)
4415 a8083063 Iustin Pop
      where export-list is a list of the instances exported on
4416 a8083063 Iustin Pop
      that node.
4417 a8083063 Iustin Pop

4418 a8083063 Iustin Pop
    """
4419 a7ba5e53 Iustin Pop
    return rpc.call_export_list(self.nodes)
4420 a8083063 Iustin Pop
4421 a8083063 Iustin Pop
4422 a8083063 Iustin Pop
class LUExportInstance(LogicalUnit):
4423 a8083063 Iustin Pop
  """Export an instance to an image in the cluster.
4424 a8083063 Iustin Pop

4425 a8083063 Iustin Pop
  """
4426 a8083063 Iustin Pop
  HPATH = "instance-export"
4427 a8083063 Iustin Pop
  HTYPE = constants.HTYPE_INSTANCE
4428 a8083063 Iustin Pop
  _OP_REQP = ["instance_name", "target_node", "shutdown"]
4429 a8083063 Iustin Pop
4430 a8083063 Iustin Pop
  def BuildHooksEnv(self):
4431 a8083063 Iustin Pop
    """Build hooks env.
4432 a8083063 Iustin Pop

4433 a8083063 Iustin Pop
    This will run on the master, primary node and target node.
4434 a8083063 Iustin Pop

4435 a8083063 Iustin Pop
    """
4436 a8083063 Iustin Pop
    env = {
4437 a8083063 Iustin Pop
      "EXPORT_NODE": self.op.target_node,
4438 a8083063 Iustin Pop
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
4439 a8083063 Iustin Pop
      }
4440 396e1b78 Michael Hanselmann
    env.update(_BuildInstanceHookEnvByObject(self.instance))
4441 880478f8 Iustin Pop
    nl = [self.sstore.GetMasterNode(), self.instance.primary_node,
4442 a8083063 Iustin Pop
          self.op.target_node]
4443 a8083063 Iustin Pop
    return env, nl, nl
4444 a8083063 Iustin Pop
4445 a8083063 Iustin Pop
  def CheckPrereq(self):
4446 a8083063 Iustin Pop
    """Check prerequisites.
4447 a8083063 Iustin Pop

4448 a8083063 Iustin Pop
    This checks that the instance name is a valid one.
4449 a8083063 Iustin Pop

4450 a8083063 Iustin Pop
    """
4451 a8083063 Iustin Pop
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
4452 a8083063 Iustin Pop
    self.instance = self.cfg.GetInstanceInfo(instance_name)
4453 a8083063 Iustin Pop
    if self.instance is None:
4454 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Instance '%s' not found" %
4455 3ecf6786 Iustin Pop
                                 self.op.instance_name)
4456 a8083063 Iustin Pop
4457 a8083063 Iustin Pop
    # node verification
4458 a8083063 Iustin Pop
    dst_node_short = self.cfg.ExpandNodeName(self.op.target_node)
4459 a8083063 Iustin Pop
    self.dst_node = self.cfg.GetNodeInfo(dst_node_short)
4460 a8083063 Iustin Pop
4461 a8083063 Iustin Pop
    if self.dst_node is None:
4462 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Destination node '%s' is unknown." %
4463 3ecf6786 Iustin Pop
                                 self.op.target_node)
4464 a8083063 Iustin Pop
    self.op.target_node = self.dst_node.name
4465 a8083063 Iustin Pop
4466 a8083063 Iustin Pop
  def Exec(self, feedback_fn):
4467 a8083063 Iustin Pop
    """Export an instance to an image in the cluster.
4468 a8083063 Iustin Pop

4469 a8083063 Iustin Pop
    """
4470 a8083063 Iustin Pop
    instance = self.instance
4471 a8083063 Iustin Pop
    dst_node = self.dst_node
4472 a8083063 Iustin Pop
    src_node = instance.primary_node
4473 a8083063 Iustin Pop
    if self.op.shutdown:
4474 fb300fb7 Guido Trotter
      # shutdown the instance, but not the disks
4475 fb300fb7 Guido Trotter
      if not rpc.call_instance_shutdown(src_node, instance):
4476 fb300fb7 Guido Trotter
         raise errors.OpExecError("Could not shutdown instance %s on node %s" %
4477 b62ddbe5 Guido Trotter
                                 (instance.name, src_node))
4478 a8083063 Iustin Pop
4479 a8083063 Iustin Pop
    vgname = self.cfg.GetVGName()
4480 a8083063 Iustin Pop
4481 a8083063 Iustin Pop
    snap_disks = []
4482 a8083063 Iustin Pop
4483 a8083063 Iustin Pop
    try:
4484 a8083063 Iustin Pop
      for disk in instance.disks:
4485 a8083063 Iustin Pop
        if disk.iv_name == "sda":
4486 a8083063 Iustin Pop
          # new_dev_name will be a snapshot of an lvm leaf of the one we passed
4487 a8083063 Iustin Pop
          new_dev_name = rpc.call_blockdev_snapshot(src_node, disk)
4488 a8083063 Iustin Pop
4489 a8083063 Iustin Pop
          if not new_dev_name:
4490 a8083063 Iustin Pop
            logger.Error("could not snapshot block device %s on node %s" %
4491 a8083063 Iustin Pop
                         (disk.logical_id[1], src_node))
4492 a8083063 Iustin Pop
          else:
4493 fe96220b Iustin Pop
            new_dev = objects.Disk(dev_type=constants.LD_LV, size=disk.size,
4494 a8083063 Iustin Pop
                                      logical_id=(vgname, new_dev_name),
4495 a8083063 Iustin Pop
                                      physical_id=(vgname, new_dev_name),
4496 a8083063 Iustin Pop
                                      iv_name=disk.iv_name)
4497 a8083063 Iustin Pop
            snap_disks.append(new_dev)
4498 a8083063 Iustin Pop
4499 a8083063 Iustin Pop
    finally:
4500 fb300fb7 Guido Trotter
      if self.op.shutdown and instance.status == "up":
4501 fb300fb7 Guido Trotter
        if not rpc.call_instance_start(src_node, instance, None):
4502 fb300fb7 Guido Trotter
          _ShutdownInstanceDisks(instance, self.cfg)
4503 fb300fb7 Guido Trotter
          raise errors.OpExecError("Could not start instance")
4504 a8083063 Iustin Pop
4505 a8083063 Iustin Pop
    # TODO: check for size
4506 a8083063 Iustin Pop
4507 a8083063 Iustin Pop
    for dev in snap_disks:
4508 16687b98 Manuel Franceschini
      if not rpc.call_snapshot_export(src_node, dev, dst_node.name, instance):
4509 16687b98 Manuel Franceschini
        logger.Error("could not export block device %s from node %s to node %s"
4510 16687b98 Manuel Franceschini
                     % (dev.logical_id[1], src_node, dst_node.name))
4511 a8083063 Iustin Pop
      if not rpc.call_blockdev_remove(src_node, dev):
4512 16687b98 Manuel Franceschini
        logger.Error("could not remove snapshot block device %s from node %s" %
4513 16687b98 Manuel Franceschini
                     (dev.logical_id[1], src_node))
4514 a8083063 Iustin Pop
4515 a8083063 Iustin Pop
    if not rpc.call_finalize_export(dst_node.name, instance, snap_disks):
4516 a8083063 Iustin Pop
      logger.Error("could not finalize export for instance %s on node %s" %
4517 a8083063 Iustin Pop
                   (instance.name, dst_node.name))
4518 a8083063 Iustin Pop
4519 a8083063 Iustin Pop
    nodelist = self.cfg.GetNodeList()
4520 a8083063 Iustin Pop
    nodelist.remove(dst_node.name)
4521 a8083063 Iustin Pop
4522 a8083063 Iustin Pop
    # on one-node clusters nodelist will be empty after the removal
4523 a8083063 Iustin Pop
    # if we proceed the backup would be removed because OpQueryExports
4524 a8083063 Iustin Pop
    # substitutes an empty list with the full cluster node list.
4525 a8083063 Iustin Pop
    if nodelist:
4526 a8083063 Iustin Pop
      op = opcodes.OpQueryExports(nodes=nodelist)
4527 5bfac263 Iustin Pop
      exportlist = self.proc.ChainOpCode(op)
4528 a8083063 Iustin Pop
      for node in exportlist:
4529 a8083063 Iustin Pop
        if instance.name in exportlist[node]:
4530 a8083063 Iustin Pop
          if not rpc.call_export_remove(node, instance.name):
4531 a8083063 Iustin Pop
            logger.Error("could not remove older export for instance %s"
4532 a8083063 Iustin Pop
                         " on node %s" % (instance.name, node))
4533 5c947f38 Iustin Pop
4534 5c947f38 Iustin Pop
4535 5c947f38 Iustin Pop
class TagsLU(NoHooksLU):
4536 5c947f38 Iustin Pop
  """Generic tags LU.
4537 5c947f38 Iustin Pop

4538 5c947f38 Iustin Pop
  This is an abstract class which is the parent of all the other tags LUs.
4539 5c947f38 Iustin Pop

4540 5c947f38 Iustin Pop
  """
4541 5c947f38 Iustin Pop
  def CheckPrereq(self):
4542 5c947f38 Iustin Pop
    """Check prerequisites.
4543 5c947f38 Iustin Pop

4544 5c947f38 Iustin Pop
    """
4545 5c947f38 Iustin Pop
    if self.op.kind == constants.TAG_CLUSTER:
4546 5c947f38 Iustin Pop
      self.target = self.cfg.GetClusterInfo()
4547 5c947f38 Iustin Pop
    elif self.op.kind == constants.TAG_NODE:
4548 5c947f38 Iustin Pop
      name = self.cfg.ExpandNodeName(self.op.name)
4549 5c947f38 Iustin Pop
      if name is None:
4550 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid node name (%s)" %
4551 3ecf6786 Iustin Pop
                                   (self.op.name,))
4552 5c947f38 Iustin Pop
      self.op.name = name
4553 5c947f38 Iustin Pop
      self.target = self.cfg.GetNodeInfo(name)
4554 5c947f38 Iustin Pop
    elif self.op.kind == constants.TAG_INSTANCE:
4555 8f684e16 Iustin Pop
      name = self.cfg.ExpandInstanceName(self.op.name)
4556 5c947f38 Iustin Pop
      if name is None:
4557 3ecf6786 Iustin Pop
        raise errors.OpPrereqError("Invalid instance name (%s)" %
4558 3ecf6786 Iustin Pop
                                   (self.op.name,))
4559 5c947f38 Iustin Pop
      self.op.name = name
4560 5c947f38 Iustin Pop
      self.target = self.cfg.GetInstanceInfo(name)
4561 5c947f38 Iustin Pop
    else:
4562 3ecf6786 Iustin Pop
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
4563 3ecf6786 Iustin Pop
                                 str(self.op.kind))
4564 5c947f38 Iustin Pop
4565 5c947f38 Iustin Pop
4566 5c947f38 Iustin Pop
class LUGetTags(TagsLU):
4567 5c947f38 Iustin Pop
  """Returns the tags of a given object.
4568 5c947f38 Iustin Pop

4569 5c947f38 Iustin Pop
  """
4570 5c947f38 Iustin Pop
  _OP_REQP = ["kind", "name"]
4571 5c947f38 Iustin Pop
4572 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
4573 5c947f38 Iustin Pop
    """Returns the tag list.
4574 5c947f38 Iustin Pop

4575 5c947f38 Iustin Pop
    """
4576 5c947f38 Iustin Pop
    return self.target.GetTags()
4577 5c947f38 Iustin Pop
4578 5c947f38 Iustin Pop
4579 73415719 Iustin Pop
class LUSearchTags(NoHooksLU):
4580 73415719 Iustin Pop
  """Searches the tags for a given pattern.
4581 73415719 Iustin Pop

4582 73415719 Iustin Pop
  """
4583 73415719 Iustin Pop
  _OP_REQP = ["pattern"]
4584 73415719 Iustin Pop
4585 73415719 Iustin Pop
  def CheckPrereq(self):
4586 73415719 Iustin Pop
    """Check prerequisites.
4587 73415719 Iustin Pop

4588 73415719 Iustin Pop
    This checks the pattern passed for validity by compiling it.
4589 73415719 Iustin Pop

4590 73415719 Iustin Pop
    """
4591 73415719 Iustin Pop
    try:
4592 73415719 Iustin Pop
      self.re = re.compile(self.op.pattern)
4593 73415719 Iustin Pop
    except re.error, err:
4594 73415719 Iustin Pop
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
4595 73415719 Iustin Pop
                                 (self.op.pattern, err))
4596 73415719 Iustin Pop
4597 73415719 Iustin Pop
  def Exec(self, feedback_fn):
4598 73415719 Iustin Pop
    """Returns the tag list.
4599 73415719 Iustin Pop

4600 73415719 Iustin Pop
    """
4601 73415719 Iustin Pop
    cfg = self.cfg
4602 73415719 Iustin Pop
    tgts = [("/cluster", cfg.GetClusterInfo())]
4603 73415719 Iustin Pop
    ilist = [cfg.GetInstanceInfo(name) for name in cfg.GetInstanceList()]
4604 73415719 Iustin Pop
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
4605 73415719 Iustin Pop
    nlist = [cfg.GetNodeInfo(name) for name in cfg.GetNodeList()]
4606 73415719 Iustin Pop
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
4607 73415719 Iustin Pop
    results = []
4608 73415719 Iustin Pop
    for path, target in tgts:
4609 73415719 Iustin Pop
      for tag in target.GetTags():
4610 73415719 Iustin Pop
        if self.re.search(tag):
4611 73415719 Iustin Pop
          results.append((path, tag))
4612 73415719 Iustin Pop
    return results
4613 73415719 Iustin Pop
4614 73415719 Iustin Pop
4615 f27302fa Iustin Pop
class LUAddTags(TagsLU):
4616 5c947f38 Iustin Pop
  """Sets a tag on a given object.
4617 5c947f38 Iustin Pop

4618 5c947f38 Iustin Pop
  """
4619 f27302fa Iustin Pop
  _OP_REQP = ["kind", "name", "tags"]
4620 5c947f38 Iustin Pop
4621 5c947f38 Iustin Pop
  def CheckPrereq(self):
4622 5c947f38 Iustin Pop
    """Check prerequisites.
4623 5c947f38 Iustin Pop

4624 5c947f38 Iustin Pop
    This checks the type and length of the tag name and value.
4625 5c947f38 Iustin Pop

4626 5c947f38 Iustin Pop
    """
4627 5c947f38 Iustin Pop
    TagsLU.CheckPrereq(self)
4628 f27302fa Iustin Pop
    for tag in self.op.tags:
4629 f27302fa Iustin Pop
      objects.TaggableObject.ValidateTag(tag)
4630 5c947f38 Iustin Pop
4631 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
4632 5c947f38 Iustin Pop
    """Sets the tag.
4633 5c947f38 Iustin Pop

4634 5c947f38 Iustin Pop
    """
4635 5c947f38 Iustin Pop
    try:
4636 f27302fa Iustin Pop
      for tag in self.op.tags:
4637 f27302fa Iustin Pop
        self.target.AddTag(tag)
4638 5c947f38 Iustin Pop
    except errors.TagError, err:
4639 3ecf6786 Iustin Pop
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
4640 5c947f38 Iustin Pop
    try:
4641 5c947f38 Iustin Pop
      self.cfg.Update(self.target)
4642 5c947f38 Iustin Pop
    except errors.ConfigurationError:
4643 3ecf6786 Iustin Pop
      raise errors.OpRetryError("There has been a modification to the"
4644 3ecf6786 Iustin Pop
                                " config file and the operation has been"
4645 3ecf6786 Iustin Pop
                                " aborted. Please retry.")
4646 5c947f38 Iustin Pop
4647 5c947f38 Iustin Pop
4648 f27302fa Iustin Pop
class LUDelTags(TagsLU):
4649 f27302fa Iustin Pop
  """Delete a list of tags from a given object.
4650 5c947f38 Iustin Pop

4651 5c947f38 Iustin Pop
  """
4652 f27302fa Iustin Pop
  _OP_REQP = ["kind", "name", "tags"]
4653 5c947f38 Iustin Pop
4654 5c947f38 Iustin Pop
  def CheckPrereq(self):
4655 5c947f38 Iustin Pop
    """Check prerequisites.
4656 5c947f38 Iustin Pop

4657 5c947f38 Iustin Pop
    This checks that we have the given tag.
4658 5c947f38 Iustin Pop

4659 5c947f38 Iustin Pop
    """
4660 5c947f38 Iustin Pop
    TagsLU.CheckPrereq(self)
4661 f27302fa Iustin Pop
    for tag in self.op.tags:
4662 f27302fa Iustin Pop
      objects.TaggableObject.ValidateTag(tag)
4663 f27302fa Iustin Pop
    del_tags = frozenset(self.op.tags)
4664 f27302fa Iustin Pop
    cur_tags = self.target.GetTags()
4665 f27302fa Iustin Pop
    if not del_tags <= cur_tags:
4666 f27302fa Iustin Pop
      diff_tags = del_tags - cur_tags
4667 f27302fa Iustin Pop
      diff_names = ["'%s'" % tag for tag in diff_tags]
4668 f27302fa Iustin Pop
      diff_names.sort()
4669 f27302fa Iustin Pop
      raise errors.OpPrereqError("Tag(s) %s not found" %
4670 f27302fa Iustin Pop
                                 (",".join(diff_names)))
4671 5c947f38 Iustin Pop
4672 5c947f38 Iustin Pop
  def Exec(self, feedback_fn):
4673 5c947f38 Iustin Pop
    """Remove the tag from the object.
4674 5c947f38 Iustin Pop

4675 5c947f38 Iustin Pop
    """
4676 f27302fa Iustin Pop
    for tag in self.op.tags:
4677 f27302fa Iustin Pop
      self.target.RemoveTag(tag)
4678 5c947f38 Iustin Pop
    try:
4679 5c947f38 Iustin Pop
      self.cfg.Update(self.target)
4680 5c947f38 Iustin Pop
    except errors.ConfigurationError:
4681 3ecf6786 Iustin Pop
      raise errors.OpRetryError("There has been a modification to the"
4682 3ecf6786 Iustin Pop
                                " config file and the operation has been"
4683 3ecf6786 Iustin Pop
                                " aborted. Please retry.")
4684 06009e27 Iustin Pop
4685 06009e27 Iustin Pop
class LUTestDelay(NoHooksLU):
4686 06009e27 Iustin Pop
  """Sleep for a specified amount of time.
4687 06009e27 Iustin Pop

4688 06009e27 Iustin Pop
  This LU sleeps on the master and/or nodes for a specified amoutn of
4689 06009e27 Iustin Pop
  time.
4690 06009e27 Iustin Pop

4691 06009e27 Iustin Pop
  """
4692 06009e27 Iustin Pop
  _OP_REQP = ["duration", "on_master", "on_nodes"]
4693 06009e27 Iustin Pop
4694 06009e27 Iustin Pop
  def CheckPrereq(self):
4695 06009e27 Iustin Pop
    """Check prerequisites.
4696 06009e27 Iustin Pop

4697 06009e27 Iustin Pop
    This checks that we have a good list of nodes and/or the duration
4698 06009e27 Iustin Pop
    is valid.
4699 06009e27 Iustin Pop

4700 06009e27 Iustin Pop
    """
4701 06009e27 Iustin Pop
4702 06009e27 Iustin Pop
    if self.op.on_nodes:
4703 06009e27 Iustin Pop
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
4704 06009e27 Iustin Pop
4705 06009e27 Iustin Pop
  def Exec(self, feedback_fn):
4706 06009e27 Iustin Pop
    """Do the actual sleep.
4707 06009e27 Iustin Pop

4708 06009e27 Iustin Pop
    """
4709 06009e27 Iustin Pop
    if self.op.on_master:
4710 06009e27 Iustin Pop
      if not utils.TestDelay(self.op.duration):
4711 06009e27 Iustin Pop
        raise errors.OpExecError("Error during master delay test")
4712 06009e27 Iustin Pop
    if self.op.on_nodes:
4713 06009e27 Iustin Pop
      result = rpc.call_test_delay(self.op.on_nodes, self.op.duration)
4714 06009e27 Iustin Pop
      if not result:
4715 06009e27 Iustin Pop
        raise errors.OpExecError("Complete failure from rpc call")
4716 06009e27 Iustin Pop
      for node, node_result in result.items():
4717 06009e27 Iustin Pop
        if not node_result:
4718 06009e27 Iustin Pop
          raise errors.OpExecError("Failure during rpc call to node %s,"
4719 06009e27 Iustin Pop
                                   " result: %s" % (node, node_result))
4720 d61df03e Iustin Pop
4721 d61df03e Iustin Pop
4722 298fe380 Iustin Pop
def _IAllocatorGetClusterData(cfg, sstore):
4723 d61df03e Iustin Pop
  """Compute the generic allocator input data.
4724 d61df03e Iustin Pop

4725 d61df03e Iustin Pop
  This is the data that is independent of the actual operation.
4726 d61df03e Iustin Pop

4727 d61df03e Iustin Pop
  """
4728 d61df03e Iustin Pop
  # cluster data
4729 d61df03e Iustin Pop
  data = {
4730 d61df03e Iustin Pop
    "version": 1,
4731 d61df03e Iustin Pop
    "cluster_name": sstore.GetClusterName(),
4732 d61df03e Iustin Pop
    "cluster_tags": list(cfg.GetClusterInfo().GetTags()),
4733 d61df03e Iustin Pop
    # we don't have job IDs
4734 d61df03e Iustin Pop
    }
4735 d61df03e Iustin Pop
4736 d61df03e Iustin Pop
  # node data
4737 d61df03e Iustin Pop
  node_results = {}
4738 d61df03e Iustin Pop
  node_list = cfg.GetNodeList()
4739 d61df03e Iustin Pop
  node_data = rpc.call_node_info(node_list, cfg.GetVGName())
4740 d61df03e Iustin Pop
  for nname in node_list:
4741 d61df03e Iustin Pop
    ninfo = cfg.GetNodeInfo(nname)
4742 d61df03e Iustin Pop
    if nname not in node_data or not isinstance(node_data[nname], dict):
4743 d61df03e Iustin Pop
      raise errors.OpExecError("Can't get data for node %s" % nname)
4744 d61df03e Iustin Pop
    remote_info = node_data[nname]
4745 d61df03e Iustin Pop
    for attr in ['memory_total', 'memory_free',
4746 d61df03e Iustin Pop
                 'vg_size', 'vg_free']:
4747 d61df03e Iustin Pop
      if attr not in remote_info:
4748 d61df03e Iustin Pop
        raise errors.OpExecError("Node '%s' didn't return attribute '%s'" %
4749 d61df03e Iustin Pop
                                 (nname, attr))
4750 d61df03e Iustin Pop
      try:
4751 d61df03e Iustin Pop
        int(remote_info[attr])
4752 d61df03e Iustin Pop
      except ValueError, err:
4753 d61df03e Iustin Pop
        raise errors.OpExecError("Node '%s' returned invalid value for '%s':"
4754 d61df03e Iustin Pop
                                 " %s" % (nname, attr, str(err)))
4755 d61df03e Iustin Pop
    pnr = {
4756 d61df03e Iustin Pop
      "tags": list(ninfo.GetTags()),
4757 d61df03e Iustin Pop
      "total_memory": utils.TryConvert(int, remote_info['memory_total']),
4758 d61df03e Iustin Pop
      "free_memory": utils.TryConvert(int, remote_info['memory_free']),
4759 d61df03e Iustin Pop
      "total_disk": utils.TryConvert(int, remote_info['vg_size']),
4760 d61df03e Iustin Pop
      "free_disk": utils.TryConvert(int, remote_info['vg_free']),
4761 d61df03e Iustin Pop
      "primary_ip": ninfo.primary_ip,
4762 d61df03e Iustin Pop
      "secondary_ip": ninfo.secondary_ip,
4763 d61df03e Iustin Pop
      }
4764 d61df03e Iustin Pop
    node_results[nname] = pnr
4765 d61df03e Iustin Pop
  data["nodes"] = node_results
4766 d61df03e Iustin Pop
4767 d61df03e Iustin Pop
  # instance data
4768 d61df03e Iustin Pop
  instance_data = {}
4769 d61df03e Iustin Pop
  i_list = cfg.GetInstanceList()
4770 d61df03e Iustin Pop
  for iname in i_list:
4771 d61df03e Iustin Pop
    iinfo = cfg.GetInstanceInfo(iname)
4772 d61df03e Iustin Pop
    nic_data = [{"mac": n.mac, "ip": n.ip, "bridge": n.bridge}
4773 d61df03e Iustin Pop
                for n in iinfo.nics]
4774 d61df03e Iustin Pop
    pir = {
4775 d61df03e Iustin Pop
      "tags": list(iinfo.GetTags()),
4776 d61df03e Iustin Pop
      "should_run": iinfo.status == "up",
4777 d61df03e Iustin Pop
      "vcpus": iinfo.vcpus,
4778 d61df03e Iustin Pop
      "memory": iinfo.memory,
4779 d61df03e Iustin Pop
      "os": iinfo.os,
4780 d61df03e Iustin Pop
      "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
4781 d61df03e Iustin Pop
      "nics": nic_data,
4782 d61df03e Iustin Pop
      "disks": [{"size": dsk.size, "mode": "w"} for dsk in iinfo.disks],
4783 d61df03e Iustin Pop
      "disk_template": iinfo.disk_template,
4784 d61df03e Iustin Pop
      }
4785 d61df03e Iustin Pop
    instance_data[iname] = pir
4786 d61df03e Iustin Pop
4787 d61df03e Iustin Pop
  data["instances"] = instance_data
4788 d61df03e Iustin Pop
4789 d61df03e Iustin Pop
  return data
4790 d61df03e Iustin Pop
4791 d61df03e Iustin Pop
4792 298fe380 Iustin Pop
def _IAllocatorAddNewInstance(data, op):
4793 d61df03e Iustin Pop
  """Add new instance data to allocator structure.
4794 d61df03e Iustin Pop

4795 d61df03e Iustin Pop
  This in combination with _AllocatorGetClusterData will create the
4796 d61df03e Iustin Pop
  correct structure needed as input for the allocator.
4797 d61df03e Iustin Pop

4798 d61df03e Iustin Pop
  The checks for the completeness of the opcode must have already been
4799 d61df03e Iustin Pop
  done.
4800 d61df03e Iustin Pop

4801 d61df03e Iustin Pop
  """
4802 298fe380 Iustin Pop
  if len(op.disks) != 2:
4803 298fe380 Iustin Pop
    raise errors.OpExecError("Only two-disk configurations supported")
4804 298fe380 Iustin Pop
4805 298fe380 Iustin Pop
  disk_space = _ComputeDiskSize(op.disk_template,
4806 298fe380 Iustin Pop
                                op.disks[0]["size"], op.disks[1]["size"])
4807 298fe380 Iustin Pop
4808 d61df03e Iustin Pop
  request = {
4809 d61df03e Iustin Pop
    "type": "allocate",
4810 d61df03e Iustin Pop
    "name": op.name,
4811 d61df03e Iustin Pop
    "disk_template": op.disk_template,
4812 d61df03e Iustin Pop
    "tags": op.tags,
4813 d61df03e Iustin Pop
    "os": op.os,
4814 d61df03e Iustin Pop
    "vcpus": op.vcpus,
4815 d61df03e Iustin Pop
    "memory": op.mem_size,
4816 d61df03e Iustin Pop
    "disks": op.disks,
4817 298fe380 Iustin Pop
    "disk_space_total": disk_space,
4818 d61df03e Iustin Pop
    "nics": op.nics,
4819 d61df03e Iustin Pop
    }
4820 d61df03e Iustin Pop
  data["request"] = request
4821 d61df03e Iustin Pop
4822 d61df03e Iustin Pop
4823 298fe380 Iustin Pop
def _IAllocatorAddRelocateInstance(data, op):
4824 d61df03e Iustin Pop
  """Add relocate instance data to allocator structure.
4825 d61df03e Iustin Pop

4826 298fe380 Iustin Pop
  This in combination with _IAllocatorGetClusterData will create the
4827 d61df03e Iustin Pop
  correct structure needed as input for the allocator.
4828 d61df03e Iustin Pop

4829 d61df03e Iustin Pop
  The checks for the completeness of the opcode must have already been
4830 d61df03e Iustin Pop
  done.
4831 d61df03e Iustin Pop

4832 d61df03e Iustin Pop
  """
4833 d61df03e Iustin Pop
  request = {
4834 d61df03e Iustin Pop
    "type": "replace_secondary",
4835 d61df03e Iustin Pop
    "name": op.name,
4836 d61df03e Iustin Pop
    }
4837 d61df03e Iustin Pop
  data["request"] = request
4838 d61df03e Iustin Pop
4839 d61df03e Iustin Pop
4840 298fe380 Iustin Pop
def _IAllocatorRun(name, data):
4841 298fe380 Iustin Pop
  """Run an instance allocator and return the results.
4842 298fe380 Iustin Pop

4843 298fe380 Iustin Pop
  """
4844 298fe380 Iustin Pop
  alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4845 298fe380 Iustin Pop
                                os.path.isfile)
4846 298fe380 Iustin Pop
  if alloc_script is None:
4847 538475ca Iustin Pop
    raise errors.OpExecError("Can't find allocator '%s'" % name)
4848 298fe380 Iustin Pop
4849 298fe380 Iustin Pop
  fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4850 298fe380 Iustin Pop
  try:
4851 298fe380 Iustin Pop
    os.write(fd, data)
4852 298fe380 Iustin Pop
    os.close(fd)
4853 298fe380 Iustin Pop
    result = utils.RunCmd([alloc_script, fin_name])
4854 298fe380 Iustin Pop
    if result.failed:
4855 298fe380 Iustin Pop
      raise errors.OpExecError("Instance allocator call failed: %s,"
4856 298fe380 Iustin Pop
                               " output: %s" %
4857 298fe380 Iustin Pop
                               (result.fail_reason, result.stdout))
4858 298fe380 Iustin Pop
  finally:
4859 298fe380 Iustin Pop
    os.unlink(fin_name)
4860 298fe380 Iustin Pop
  return result.stdout
4861 298fe380 Iustin Pop
4862 298fe380 Iustin Pop
4863 538475ca Iustin Pop
def _IAllocatorValidateResult(data):
4864 538475ca Iustin Pop
  """Process the allocator results.
4865 538475ca Iustin Pop

4866 538475ca Iustin Pop
  """
4867 538475ca Iustin Pop
  try:
4868 8d14b30d Iustin Pop
    rdict = serializer.Load(data)
4869 538475ca Iustin Pop
  except Exception, err:
4870 538475ca Iustin Pop
    raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
4871 538475ca Iustin Pop
4872 538475ca Iustin Pop
  if not isinstance(rdict, dict):
4873 538475ca Iustin Pop
    raise errors.OpExecError("Can't parse iallocator results: not a dict")
4874 538475ca Iustin Pop
4875 538475ca Iustin Pop
  for key in "success", "info", "nodes":
4876 538475ca Iustin Pop
    if key not in rdict:
4877 538475ca Iustin Pop
      raise errors.OpExecError("Can't parse iallocator results:"
4878 538475ca Iustin Pop
                               " missing key '%s'" % key)
4879 538475ca Iustin Pop
4880 538475ca Iustin Pop
  if not isinstance(rdict["nodes"], list):
4881 538475ca Iustin Pop
    raise errors.OpExecError("Can't parse iallocator results: 'nodes' key"
4882 538475ca Iustin Pop
                             " is not a list")
4883 538475ca Iustin Pop
  return rdict
4884 538475ca Iustin Pop
4885 538475ca Iustin Pop
4886 d61df03e Iustin Pop
class LUTestAllocator(NoHooksLU):
4887 d61df03e Iustin Pop
  """Run allocator tests.
4888 d61df03e Iustin Pop

4889 d61df03e Iustin Pop
  This LU runs the allocator tests
4890 d61df03e Iustin Pop

4891 d61df03e Iustin Pop
  """
4892 d61df03e Iustin Pop
  _OP_REQP = ["direction", "mode", "name"]
4893 d61df03e Iustin Pop
4894 d61df03e Iustin Pop
  def CheckPrereq(self):
4895 d61df03e Iustin Pop
    """Check prerequisites.
4896 d61df03e Iustin Pop

4897 d61df03e Iustin Pop
    This checks the opcode parameters depending on the director and mode test.
4898 d61df03e Iustin Pop

4899 d61df03e Iustin Pop
    """
4900 298fe380 Iustin Pop
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
4901 d61df03e Iustin Pop
      for attr in ["name", "mem_size", "disks", "disk_template",
4902 d61df03e Iustin Pop
                   "os", "tags", "nics", "vcpus"]:
4903 d61df03e Iustin Pop
        if not hasattr(self.op, attr):
4904 d61df03e Iustin Pop
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
4905 d61df03e Iustin Pop
                                     attr)
4906 d61df03e Iustin Pop
      iname = self.cfg.ExpandInstanceName(self.op.name)
4907 d61df03e Iustin Pop
      if iname is not None:
4908 d61df03e Iustin Pop
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
4909 d61df03e Iustin Pop
                                   iname)
4910 d61df03e Iustin Pop
      if not isinstance(self.op.nics, list):
4911 d61df03e Iustin Pop
        raise errors.OpPrereqError("Invalid parameter 'nics'")
4912 d61df03e Iustin Pop
      for row in self.op.nics:
4913 d61df03e Iustin Pop
        if (not isinstance(row, dict) or
4914 d61df03e Iustin Pop
            "mac" not in row or
4915 d61df03e Iustin Pop
            "ip" not in row or
4916 d61df03e Iustin Pop
            "bridge" not in row):
4917 d61df03e Iustin Pop
          raise errors.OpPrereqError("Invalid contents of the"
4918 d61df03e Iustin Pop
                                     " 'nics' parameter")
4919 d61df03e Iustin Pop
      if not isinstance(self.op.disks, list):
4920 d61df03e Iustin Pop
        raise errors.OpPrereqError("Invalid parameter 'disks'")
4921 298fe380 Iustin Pop
      if len(self.op.disks) != 2:
4922 298fe380 Iustin Pop
        raise errors.OpPrereqError("Only two-disk configurations supported")
4923 d61df03e Iustin Pop
      for row in self.op.disks:
4924 d61df03e Iustin Pop
        if (not isinstance(row, dict) or
4925 d61df03e Iustin Pop
            "size" not in row or
4926 d61df03e Iustin Pop
            not isinstance(row["size"], int) or
4927 d61df03e Iustin Pop
            "mode" not in row or
4928 d61df03e Iustin Pop
            row["mode"] not in ['r', 'w']):
4929 d61df03e Iustin Pop
          raise errors.OpPrereqError("Invalid contents of the"
4930 d61df03e Iustin Pop
                                     " 'disks' parameter")
4931 298fe380 Iustin Pop
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
4932 d61df03e Iustin Pop
      if not hasattr(self.op, "name"):
4933 d61df03e Iustin Pop
        raise errors.OpPrereqError("Missing attribute 'name' on opcode input")
4934 d61df03e Iustin Pop
      fname = self.cfg.ExpandInstanceName(self.op.name)
4935 d61df03e Iustin Pop
      if fname is None:
4936 d61df03e Iustin Pop
        raise errors.OpPrereqError("Instance '%s' not found for relocation" %
4937 d61df03e Iustin Pop
                                   self.op.name)
4938 d61df03e Iustin Pop
      self.op.name = fname
4939 d61df03e Iustin Pop
    else:
4940 d61df03e Iustin Pop
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
4941 d61df03e Iustin Pop
                                 self.op.mode)
4942 d61df03e Iustin Pop
4943 298fe380 Iustin Pop
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
4944 298fe380 Iustin Pop
      if not hasattr(self.op, "allocator") or self.op.allocator is None:
4945 d61df03e Iustin Pop
        raise errors.OpPrereqError("Missing allocator name")
4946 298fe380 Iustin Pop
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
4947 d61df03e Iustin Pop
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
4948 d61df03e Iustin Pop
                                 self.op.direction)
4949 d61df03e Iustin Pop
4950 d61df03e Iustin Pop
  def Exec(self, feedback_fn):
4951 d61df03e Iustin Pop
    """Run the allocator test.
4952 d61df03e Iustin Pop

4953 d61df03e Iustin Pop
    """
4954 298fe380 Iustin Pop
    data = _IAllocatorGetClusterData(self.cfg, self.sstore)
4955 298fe380 Iustin Pop
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
4956 298fe380 Iustin Pop
      _IAllocatorAddNewInstance(data, self.op)
4957 d61df03e Iustin Pop
    else:
4958 298fe380 Iustin Pop
      _IAllocatorAddRelocateInstance(data, self.op)
4959 d61df03e Iustin Pop
4960 8d14b30d Iustin Pop
    text = serializer.Dump(data)
4961 298fe380 Iustin Pop
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
4962 298fe380 Iustin Pop
      result = text
4963 298fe380 Iustin Pop
    else:
4964 298fe380 Iustin Pop
      result = _IAllocatorRun(self.op.allocator, text)
4965 298fe380 Iustin Pop
    return result