Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_xen.py @ ce9283c1

History | View | Annotate | Download (31.9 kB)

1 65a6f9b7 Michael Hanselmann
#
2 65a6f9b7 Michael Hanselmann
#
3 65a6f9b7 Michael Hanselmann
4 1a63f285 Iustin Pop
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Google Inc.
5 65a6f9b7 Michael Hanselmann
#
6 65a6f9b7 Michael Hanselmann
# This program is free software; you can redistribute it and/or modify
7 65a6f9b7 Michael Hanselmann
# it under the terms of the GNU General Public License as published by
8 65a6f9b7 Michael Hanselmann
# the Free Software Foundation; either version 2 of the License, or
9 65a6f9b7 Michael Hanselmann
# (at your option) any later version.
10 65a6f9b7 Michael Hanselmann
#
11 65a6f9b7 Michael Hanselmann
# This program is distributed in the hope that it will be useful, but
12 65a6f9b7 Michael Hanselmann
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 65a6f9b7 Michael Hanselmann
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 65a6f9b7 Michael Hanselmann
# General Public License for more details.
15 65a6f9b7 Michael Hanselmann
#
16 65a6f9b7 Michael Hanselmann
# You should have received a copy of the GNU General Public License
17 65a6f9b7 Michael Hanselmann
# along with this program; if not, write to the Free Software
18 65a6f9b7 Michael Hanselmann
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 65a6f9b7 Michael Hanselmann
# 02110-1301, USA.
20 65a6f9b7 Michael Hanselmann
21 65a6f9b7 Michael Hanselmann
22 65a6f9b7 Michael Hanselmann
"""Xen hypervisors
23 65a6f9b7 Michael Hanselmann

24 65a6f9b7 Michael Hanselmann
"""
25 65a6f9b7 Michael Hanselmann
26 b48909c8 Iustin Pop
import logging
27 d0bb3f24 Michael Hanselmann
import string # pylint: disable=W0402
28 65a6f9b7 Michael Hanselmann
from cStringIO import StringIO
29 65a6f9b7 Michael Hanselmann
30 65a6f9b7 Michael Hanselmann
from ganeti import constants
31 65a6f9b7 Michael Hanselmann
from ganeti import errors
32 65a6f9b7 Michael Hanselmann
from ganeti import utils
33 a2d32034 Michael Hanselmann
from ganeti.hypervisor import hv_base
34 a744b676 Manuel Franceschini
from ganeti import netutils
35 55cc0a44 Michael Hanselmann
from ganeti import objects
36 9d9bded1 Michael Hanselmann
from ganeti import pathutils
37 053c356a Guido Trotter
from ganeti import ssconf
38 65a6f9b7 Michael Hanselmann
39 65a6f9b7 Michael Hanselmann
40 a8e8c0c6 Michael Hanselmann
XEND_CONFIG_FILE = utils.PathJoin(pathutils.XEN_CONFIG_DIR, "xend-config.sxp")
41 a8e8c0c6 Michael Hanselmann
XL_CONFIG_FILE = utils.PathJoin(pathutils.XEN_CONFIG_DIR, "xen/xl.conf")
42 a8e8c0c6 Michael Hanselmann
VIF_BRIDGE_SCRIPT = utils.PathJoin(pathutils.XEN_CONFIG_DIR,
43 a8e8c0c6 Michael Hanselmann
                                   "scripts/vif-bridge")
44 18bf85b1 Michael Hanselmann
_DOM0_NAME = "Domain-0"
45 d0bb3f24 Michael Hanselmann
_DISK_LETTERS = string.ascii_lowercase
46 d0bb3f24 Michael Hanselmann
47 d0bb3f24 Michael Hanselmann
_FILE_DRIVER_MAP = {
48 d0bb3f24 Michael Hanselmann
  constants.FD_LOOP: "file",
49 d0bb3f24 Michael Hanselmann
  constants.FD_BLKTAP: "tap:aio",
50 d0bb3f24 Michael Hanselmann
  }
51 22d568c2 Guido Trotter
52 22d568c2 Guido Trotter
53 347fa0f1 Michael Hanselmann
def _CreateConfigCpus(cpu_mask):
54 347fa0f1 Michael Hanselmann
  """Create a CPU config string for Xen's config file.
55 347fa0f1 Michael Hanselmann

56 347fa0f1 Michael Hanselmann
  """
57 347fa0f1 Michael Hanselmann
  # Convert the string CPU mask to a list of list of int's
58 347fa0f1 Michael Hanselmann
  cpu_list = utils.ParseMultiCpuMask(cpu_mask)
59 347fa0f1 Michael Hanselmann
60 347fa0f1 Michael Hanselmann
  if len(cpu_list) == 1:
61 347fa0f1 Michael Hanselmann
    all_cpu_mapping = cpu_list[0]
62 347fa0f1 Michael Hanselmann
    if all_cpu_mapping == constants.CPU_PINNING_OFF:
63 347fa0f1 Michael Hanselmann
      # If CPU pinning has 1 entry that's "all", then remove the
64 347fa0f1 Michael Hanselmann
      # parameter from the config file
65 347fa0f1 Michael Hanselmann
      return None
66 347fa0f1 Michael Hanselmann
    else:
67 347fa0f1 Michael Hanselmann
      # If CPU pinning has one non-all entry, mapping all vCPUS (the entire
68 347fa0f1 Michael Hanselmann
      # VM) to one physical CPU, using format 'cpu = "C"'
69 347fa0f1 Michael Hanselmann
      return "cpu = \"%s\"" % ",".join(map(str, all_cpu_mapping))
70 347fa0f1 Michael Hanselmann
  else:
71 347fa0f1 Michael Hanselmann
72 347fa0f1 Michael Hanselmann
    def _GetCPUMap(vcpu):
73 347fa0f1 Michael Hanselmann
      if vcpu[0] == constants.CPU_PINNING_ALL_VAL:
74 347fa0f1 Michael Hanselmann
        cpu_map = constants.CPU_PINNING_ALL_XEN
75 347fa0f1 Michael Hanselmann
      else:
76 347fa0f1 Michael Hanselmann
        cpu_map = ",".join(map(str, vcpu))
77 347fa0f1 Michael Hanselmann
      return "\"%s\"" % cpu_map
78 347fa0f1 Michael Hanselmann
79 347fa0f1 Michael Hanselmann
    # build the result string in format 'cpus = [ "c", "c", "c" ]',
80 347fa0f1 Michael Hanselmann
    # where each c is a physical CPU number, a range, a list, or any
81 347fa0f1 Michael Hanselmann
    # combination
82 347fa0f1 Michael Hanselmann
    return "cpus = [ %s ]" % ", ".join(map(_GetCPUMap, cpu_list))
83 347fa0f1 Michael Hanselmann
84 347fa0f1 Michael Hanselmann
85 b255379d Michael Hanselmann
def _RunXmList(fn, xmllist_errors):
86 b255379d Michael Hanselmann
  """Helper function for L{_GetXmList} to run "xm list".
87 b255379d Michael Hanselmann

88 b255379d Michael Hanselmann
  @type fn: callable
89 b255379d Michael Hanselmann
  @param fn: Function returning result of running C{xm list}
90 b255379d Michael Hanselmann
  @type xmllist_errors: list
91 b255379d Michael Hanselmann
  @param xmllist_errors: Error list
92 b255379d Michael Hanselmann
  @rtype: list
93 b255379d Michael Hanselmann

94 b255379d Michael Hanselmann
  """
95 b255379d Michael Hanselmann
  result = fn()
96 b255379d Michael Hanselmann
  if result.failed:
97 b255379d Michael Hanselmann
    logging.error("xm list failed (%s): %s", result.fail_reason,
98 b255379d Michael Hanselmann
                  result.output)
99 b255379d Michael Hanselmann
    xmllist_errors.append(result)
100 b255379d Michael Hanselmann
    raise utils.RetryAgain()
101 b255379d Michael Hanselmann
102 b255379d Michael Hanselmann
  # skip over the heading
103 b255379d Michael Hanselmann
  return result.stdout.splitlines()
104 b255379d Michael Hanselmann
105 b255379d Michael Hanselmann
106 b255379d Michael Hanselmann
def _ParseXmList(lines, include_node):
107 b255379d Michael Hanselmann
  """Parses the output of C{xm list}.
108 b255379d Michael Hanselmann

109 b255379d Michael Hanselmann
  @type lines: list
110 b255379d Michael Hanselmann
  @param lines: Output lines of C{xm list}
111 b255379d Michael Hanselmann
  @type include_node: boolean
112 b255379d Michael Hanselmann
  @param include_node: If True, return information for Dom0
113 b255379d Michael Hanselmann
  @return: list of tuple containing (name, id, memory, vcpus, state, time
114 b255379d Michael Hanselmann
    spent)
115 b255379d Michael Hanselmann

116 b255379d Michael Hanselmann
  """
117 b255379d Michael Hanselmann
  result = []
118 b255379d Michael Hanselmann
119 b255379d Michael Hanselmann
  # Iterate through all lines while ignoring header
120 b255379d Michael Hanselmann
  for line in lines[1:]:
121 b255379d Michael Hanselmann
    # The format of lines is:
122 b255379d Michael Hanselmann
    # Name      ID Mem(MiB) VCPUs State  Time(s)
123 b255379d Michael Hanselmann
    # Domain-0   0  3418     4 r-----    266.2
124 b255379d Michael Hanselmann
    data = line.split()
125 b255379d Michael Hanselmann
    if len(data) != 6:
126 b255379d Michael Hanselmann
      raise errors.HypervisorError("Can't parse output of xm list,"
127 b255379d Michael Hanselmann
                                   " line: %s" % line)
128 b255379d Michael Hanselmann
    try:
129 b255379d Michael Hanselmann
      data[1] = int(data[1])
130 b255379d Michael Hanselmann
      data[2] = int(data[2])
131 b255379d Michael Hanselmann
      data[3] = int(data[3])
132 b255379d Michael Hanselmann
      data[5] = float(data[5])
133 b255379d Michael Hanselmann
    except (TypeError, ValueError), err:
134 b255379d Michael Hanselmann
      raise errors.HypervisorError("Can't parse output of xm list,"
135 b255379d Michael Hanselmann
                                   " line: %s, error: %s" % (line, err))
136 b255379d Michael Hanselmann
137 b255379d Michael Hanselmann
    # skip the Domain-0 (optional)
138 b255379d Michael Hanselmann
    if include_node or data[0] != _DOM0_NAME:
139 b255379d Michael Hanselmann
      result.append(data)
140 b255379d Michael Hanselmann
141 b255379d Michael Hanselmann
  return result
142 b255379d Michael Hanselmann
143 b255379d Michael Hanselmann
144 b255379d Michael Hanselmann
def _GetXmList(fn, include_node, _timeout=5):
145 b255379d Michael Hanselmann
  """Return the list of running instances.
146 b255379d Michael Hanselmann

147 b255379d Michael Hanselmann
  See L{_RunXmList} and L{_ParseXmList} for parameter details.
148 b255379d Michael Hanselmann

149 b255379d Michael Hanselmann
  """
150 b255379d Michael Hanselmann
  xmllist_errors = []
151 b255379d Michael Hanselmann
  try:
152 b255379d Michael Hanselmann
    lines = utils.Retry(_RunXmList, (0.3, 1.5, 1.0), _timeout,
153 b255379d Michael Hanselmann
                        args=(fn, xmllist_errors))
154 b255379d Michael Hanselmann
  except utils.RetryTimeout:
155 b255379d Michael Hanselmann
    if xmllist_errors:
156 b255379d Michael Hanselmann
      xmlist_result = xmllist_errors.pop()
157 b255379d Michael Hanselmann
158 b255379d Michael Hanselmann
      errmsg = ("xm list failed, timeout exceeded (%s): %s" %
159 b255379d Michael Hanselmann
                (xmlist_result.fail_reason, xmlist_result.output))
160 b255379d Michael Hanselmann
    else:
161 b255379d Michael Hanselmann
      errmsg = "xm list failed"
162 b255379d Michael Hanselmann
163 b255379d Michael Hanselmann
    raise errors.HypervisorError(errmsg)
164 b255379d Michael Hanselmann
165 b255379d Michael Hanselmann
  return _ParseXmList(lines, include_node)
166 b255379d Michael Hanselmann
167 b255379d Michael Hanselmann
168 06c9a520 Michael Hanselmann
def _ParseNodeInfo(info):
169 06c9a520 Michael Hanselmann
  """Return information about the node.
170 06c9a520 Michael Hanselmann

171 06c9a520 Michael Hanselmann
  @return: a dict with the following keys (memory values in MiB):
172 06c9a520 Michael Hanselmann
        - memory_total: the total memory size on the node
173 06c9a520 Michael Hanselmann
        - memory_free: the available memory on the node for instances
174 06c9a520 Michael Hanselmann
        - nr_cpus: total number of CPUs
175 06c9a520 Michael Hanselmann
        - nr_nodes: in a NUMA system, the number of domains
176 06c9a520 Michael Hanselmann
        - nr_sockets: the number of physical CPU sockets in the node
177 06c9a520 Michael Hanselmann
        - hv_version: the hypervisor version in the form (major, minor)
178 06c9a520 Michael Hanselmann

179 06c9a520 Michael Hanselmann
  """
180 06c9a520 Michael Hanselmann
  result = {}
181 06c9a520 Michael Hanselmann
  cores_per_socket = threads_per_core = nr_cpus = None
182 06c9a520 Michael Hanselmann
  xen_major, xen_minor = None, None
183 06c9a520 Michael Hanselmann
  memory_total = None
184 06c9a520 Michael Hanselmann
  memory_free = None
185 06c9a520 Michael Hanselmann
186 06c9a520 Michael Hanselmann
  for line in info.splitlines():
187 06c9a520 Michael Hanselmann
    fields = line.split(":", 1)
188 06c9a520 Michael Hanselmann
189 06c9a520 Michael Hanselmann
    if len(fields) < 2:
190 06c9a520 Michael Hanselmann
      continue
191 06c9a520 Michael Hanselmann
192 06c9a520 Michael Hanselmann
    (key, val) = map(lambda s: s.strip(), fields)
193 06c9a520 Michael Hanselmann
194 06c9a520 Michael Hanselmann
    # Note: in Xen 3, memory has changed to total_memory
195 06c9a520 Michael Hanselmann
    if key in ("memory", "total_memory"):
196 06c9a520 Michael Hanselmann
      memory_total = int(val)
197 06c9a520 Michael Hanselmann
    elif key == "free_memory":
198 06c9a520 Michael Hanselmann
      memory_free = int(val)
199 06c9a520 Michael Hanselmann
    elif key == "nr_cpus":
200 06c9a520 Michael Hanselmann
      nr_cpus = result["cpu_total"] = int(val)
201 06c9a520 Michael Hanselmann
    elif key == "nr_nodes":
202 06c9a520 Michael Hanselmann
      result["cpu_nodes"] = int(val)
203 06c9a520 Michael Hanselmann
    elif key == "cores_per_socket":
204 06c9a520 Michael Hanselmann
      cores_per_socket = int(val)
205 06c9a520 Michael Hanselmann
    elif key == "threads_per_core":
206 06c9a520 Michael Hanselmann
      threads_per_core = int(val)
207 06c9a520 Michael Hanselmann
    elif key == "xen_major":
208 06c9a520 Michael Hanselmann
      xen_major = int(val)
209 06c9a520 Michael Hanselmann
    elif key == "xen_minor":
210 06c9a520 Michael Hanselmann
      xen_minor = int(val)
211 06c9a520 Michael Hanselmann
212 06c9a520 Michael Hanselmann
  if None not in [cores_per_socket, threads_per_core, nr_cpus]:
213 06c9a520 Michael Hanselmann
    result["cpu_sockets"] = nr_cpus / (cores_per_socket * threads_per_core)
214 06c9a520 Michael Hanselmann
215 06c9a520 Michael Hanselmann
  if memory_free is not None:
216 06c9a520 Michael Hanselmann
    result["memory_free"] = memory_free
217 06c9a520 Michael Hanselmann
218 06c9a520 Michael Hanselmann
  if memory_total is not None:
219 06c9a520 Michael Hanselmann
    result["memory_total"] = memory_total
220 06c9a520 Michael Hanselmann
221 06c9a520 Michael Hanselmann
  if not (xen_major is None or xen_minor is None):
222 06c9a520 Michael Hanselmann
    result[constants.HV_NODEINFO_KEY_VERSION] = (xen_major, xen_minor)
223 06c9a520 Michael Hanselmann
224 06c9a520 Michael Hanselmann
  return result
225 06c9a520 Michael Hanselmann
226 06c9a520 Michael Hanselmann
227 06c9a520 Michael Hanselmann
def _MergeInstanceInfo(info, fn):
228 06c9a520 Michael Hanselmann
  """Updates node information from L{_ParseNodeInfo} with instance info.
229 06c9a520 Michael Hanselmann

230 06c9a520 Michael Hanselmann
  @type info: dict
231 06c9a520 Michael Hanselmann
  @param info: Result from L{_ParseNodeInfo}
232 06c9a520 Michael Hanselmann
  @type fn: callable
233 06c9a520 Michael Hanselmann
  @param fn: Function returning result of running C{xm list}
234 06c9a520 Michael Hanselmann
  @rtype: dict
235 06c9a520 Michael Hanselmann

236 06c9a520 Michael Hanselmann
  """
237 06c9a520 Michael Hanselmann
  total_instmem = 0
238 06c9a520 Michael Hanselmann
239 06c9a520 Michael Hanselmann
  for (name, _, mem, vcpus, _, _) in fn(True):
240 06c9a520 Michael Hanselmann
    if name == _DOM0_NAME:
241 06c9a520 Michael Hanselmann
      info["memory_dom0"] = mem
242 06c9a520 Michael Hanselmann
      info["dom0_cpus"] = vcpus
243 06c9a520 Michael Hanselmann
244 06c9a520 Michael Hanselmann
    # Include Dom0 in total memory usage
245 06c9a520 Michael Hanselmann
    total_instmem += mem
246 06c9a520 Michael Hanselmann
247 06c9a520 Michael Hanselmann
  memory_free = info.get("memory_free")
248 06c9a520 Michael Hanselmann
  memory_total = info.get("memory_total")
249 06c9a520 Michael Hanselmann
250 06c9a520 Michael Hanselmann
  # Calculate memory used by hypervisor
251 06c9a520 Michael Hanselmann
  if None not in [memory_total, memory_free, total_instmem]:
252 06c9a520 Michael Hanselmann
    info["memory_hv"] = memory_total - memory_free - total_instmem
253 06c9a520 Michael Hanselmann
254 06c9a520 Michael Hanselmann
  return info
255 06c9a520 Michael Hanselmann
256 06c9a520 Michael Hanselmann
257 06c9a520 Michael Hanselmann
def _GetNodeInfo(info, fn):
258 06c9a520 Michael Hanselmann
  """Combines L{_MergeInstanceInfo} and L{_ParseNodeInfo}.
259 06c9a520 Michael Hanselmann

260 06c9a520 Michael Hanselmann
  """
261 06c9a520 Michael Hanselmann
  return _MergeInstanceInfo(_ParseNodeInfo(info), fn)
262 06c9a520 Michael Hanselmann
263 06c9a520 Michael Hanselmann
264 d0bb3f24 Michael Hanselmann
def _GetConfigFileDiskData(block_devices, blockdev_prefix,
265 d0bb3f24 Michael Hanselmann
                           _letters=_DISK_LETTERS):
266 d0bb3f24 Michael Hanselmann
  """Get disk directives for Xen config file.
267 d0bb3f24 Michael Hanselmann

268 d0bb3f24 Michael Hanselmann
  This method builds the xen config disk directive according to the
269 d0bb3f24 Michael Hanselmann
  given disk_template and block_devices.
270 d0bb3f24 Michael Hanselmann

271 d0bb3f24 Michael Hanselmann
  @param block_devices: list of tuples (cfdev, rldev):
272 d0bb3f24 Michael Hanselmann
      - cfdev: dict containing ganeti config disk part
273 ce9283c1 Thomas Thrainer
      - rldev: ganeti.block.bdev.BlockDev object
274 d0bb3f24 Michael Hanselmann
  @param blockdev_prefix: a string containing blockdevice prefix,
275 d0bb3f24 Michael Hanselmann
                          e.g. "sd" for /dev/sda
276 d0bb3f24 Michael Hanselmann

277 d0bb3f24 Michael Hanselmann
  @return: string containing disk directive for xen instance config file
278 d0bb3f24 Michael Hanselmann

279 d0bb3f24 Michael Hanselmann
  """
280 d0bb3f24 Michael Hanselmann
  if len(block_devices) > len(_letters):
281 d0bb3f24 Michael Hanselmann
    raise errors.HypervisorError("Too many disks")
282 d0bb3f24 Michael Hanselmann
283 d0bb3f24 Michael Hanselmann
  disk_data = []
284 d0bb3f24 Michael Hanselmann
285 d0bb3f24 Michael Hanselmann
  for sd_suffix, (cfdev, dev_path) in zip(_letters, block_devices):
286 d0bb3f24 Michael Hanselmann
    sd_name = blockdev_prefix + sd_suffix
287 d0bb3f24 Michael Hanselmann
288 d0bb3f24 Michael Hanselmann
    if cfdev.mode == constants.DISK_RDWR:
289 d0bb3f24 Michael Hanselmann
      mode = "w"
290 d0bb3f24 Michael Hanselmann
    else:
291 d0bb3f24 Michael Hanselmann
      mode = "r"
292 d0bb3f24 Michael Hanselmann
293 d0bb3f24 Michael Hanselmann
    if cfdev.dev_type == constants.LD_FILE:
294 d0bb3f24 Michael Hanselmann
      driver = _FILE_DRIVER_MAP[cfdev.physical_id[0]]
295 d0bb3f24 Michael Hanselmann
    else:
296 d0bb3f24 Michael Hanselmann
      driver = "phy"
297 d0bb3f24 Michael Hanselmann
298 d0bb3f24 Michael Hanselmann
    disk_data.append("'%s:%s,%s,%s'" % (driver, dev_path, sd_name, mode))
299 d0bb3f24 Michael Hanselmann
300 d0bb3f24 Michael Hanselmann
  return disk_data
301 d0bb3f24 Michael Hanselmann
302 d0bb3f24 Michael Hanselmann
303 a2d32034 Michael Hanselmann
class XenHypervisor(hv_base.BaseHypervisor):
304 65a6f9b7 Michael Hanselmann
  """Xen generic hypervisor interface
305 65a6f9b7 Michael Hanselmann

306 65a6f9b7 Michael Hanselmann
  This is the Xen base class used for both Xen PVM and HVM. It contains
307 65a6f9b7 Michael Hanselmann
  all the functionality that is identical for both.
308 65a6f9b7 Michael Hanselmann

309 65a6f9b7 Michael Hanselmann
  """
310 d271c6fd Iustin Pop
  CAN_MIGRATE = True
311 7dd106d3 Iustin Pop
  REBOOT_RETRY_COUNT = 60
312 7dd106d3 Iustin Pop
  REBOOT_RETRY_INTERVAL = 10
313 65a6f9b7 Michael Hanselmann
314 3680f662 Guido Trotter
  ANCILLARY_FILES = [
315 22d568c2 Guido Trotter
    XEND_CONFIG_FILE,
316 22d568c2 Guido Trotter
    XL_CONFIG_FILE,
317 22d568c2 Guido Trotter
    VIF_BRIDGE_SCRIPT,
318 3680f662 Guido Trotter
    ]
319 69ab2e12 Guido Trotter
  ANCILLARY_FILES_OPT = [
320 69ab2e12 Guido Trotter
    XL_CONFIG_FILE,
321 3680f662 Guido Trotter
    ]
322 3680f662 Guido Trotter
323 3d942d8b Michael Hanselmann
  def __init__(self, _cfgdir=None, _run_cmd_fn=None, _cmd=None):
324 0a903309 Michael Hanselmann
    hv_base.BaseHypervisor.__init__(self)
325 0a903309 Michael Hanselmann
326 0a903309 Michael Hanselmann
    if _cfgdir is None:
327 0a903309 Michael Hanselmann
      self._cfgdir = pathutils.XEN_CONFIG_DIR
328 0a903309 Michael Hanselmann
    else:
329 0a903309 Michael Hanselmann
      self._cfgdir = _cfgdir
330 0a903309 Michael Hanselmann
331 3d942d8b Michael Hanselmann
    if _run_cmd_fn is None:
332 3d942d8b Michael Hanselmann
      self._run_cmd_fn = utils.RunCmd
333 3d942d8b Michael Hanselmann
    else:
334 3d942d8b Michael Hanselmann
      self._run_cmd_fn = _run_cmd_fn
335 3d942d8b Michael Hanselmann
336 3d942d8b Michael Hanselmann
    self._cmd = _cmd
337 3d942d8b Michael Hanselmann
338 3d942d8b Michael Hanselmann
  def _GetCommand(self):
339 d8784f7d Michael Hanselmann
    """Returns Xen command to use.
340 d8784f7d Michael Hanselmann

341 d8784f7d Michael Hanselmann
    """
342 3d942d8b Michael Hanselmann
    if self._cmd is None:
343 3d942d8b Michael Hanselmann
      # TODO: Make command a hypervisor parameter
344 3d942d8b Michael Hanselmann
      cmd = constants.XEN_CMD
345 3d942d8b Michael Hanselmann
    else:
346 3d942d8b Michael Hanselmann
      cmd = self._cmd
347 3d942d8b Michael Hanselmann
348 3d942d8b Michael Hanselmann
    if cmd not in constants.KNOWN_XEN_COMMANDS:
349 3d942d8b Michael Hanselmann
      raise errors.ProgrammerError("Unknown Xen command '%s'" % cmd)
350 3d942d8b Michael Hanselmann
351 3d942d8b Michael Hanselmann
    return cmd
352 3d942d8b Michael Hanselmann
353 3d942d8b Michael Hanselmann
  def _RunXen(self, args):
354 81124130 Michael Hanselmann
    """Wrapper around L{utils.process.RunCmd} to run Xen command.
355 3d942d8b Michael Hanselmann

356 81124130 Michael Hanselmann
    @see: L{utils.process.RunCmd}
357 3d942d8b Michael Hanselmann

358 3d942d8b Michael Hanselmann
    """
359 3d942d8b Michael Hanselmann
    cmd = [self._GetCommand()]
360 3d942d8b Michael Hanselmann
    cmd.extend(args)
361 3d942d8b Michael Hanselmann
362 3d942d8b Michael Hanselmann
    return self._run_cmd_fn(cmd)
363 3d942d8b Michael Hanselmann
364 0a903309 Michael Hanselmann
  def _ConfigFileName(self, instance_name):
365 c2be2532 Guido Trotter
    """Get the config file name for an instance.
366 c2be2532 Guido Trotter

367 c2be2532 Guido Trotter
    @param instance_name: instance name
368 c2be2532 Guido Trotter
    @type instance_name: str
369 c2be2532 Guido Trotter
    @return: fully qualified path to instance config file
370 c2be2532 Guido Trotter
    @rtype: str
371 c2be2532 Guido Trotter

372 c2be2532 Guido Trotter
    """
373 0a903309 Michael Hanselmann
    return utils.PathJoin(self._cfgdir, instance_name)
374 c2be2532 Guido Trotter
375 5661b908 Iustin Pop
  @classmethod
376 c3d839f5 Michael Hanselmann
  def _GetConfig(cls, instance, startup_memory, block_devices):
377 c3d839f5 Michael Hanselmann
    """Build Xen configuration for an instance.
378 65a6f9b7 Michael Hanselmann

379 65a6f9b7 Michael Hanselmann
    """
380 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
381 65a6f9b7 Michael Hanselmann
382 c3d839f5 Michael Hanselmann
  def _WriteConfigFile(self, instance_name, data):
383 4390ccff Guido Trotter
    """Write the Xen config file for the instance.
384 4390ccff Guido Trotter

385 4390ccff Guido Trotter
    This version of the function just writes the config file from static data.
386 4390ccff Guido Trotter

387 4390ccff Guido Trotter
    """
388 1a63f285 Iustin Pop
    # just in case it exists
389 0a903309 Michael Hanselmann
    utils.RemoveFile(utils.PathJoin(self._cfgdir, "auto", instance_name))
390 a8e8c0c6 Michael Hanselmann
391 0a903309 Michael Hanselmann
    cfg_file = self._ConfigFileName(instance_name)
392 1a63f285 Iustin Pop
    try:
393 1a63f285 Iustin Pop
      utils.WriteFile(cfg_file, data=data)
394 1a63f285 Iustin Pop
    except EnvironmentError, err:
395 1a63f285 Iustin Pop
      raise errors.HypervisorError("Cannot write Xen instance configuration"
396 1a63f285 Iustin Pop
                                   " file %s: %s" % (cfg_file, err))
397 4390ccff Guido Trotter
398 0a903309 Michael Hanselmann
  def _ReadConfigFile(self, instance_name):
399 4390ccff Guido Trotter
    """Returns the contents of the instance config file.
400 4390ccff Guido Trotter

401 4390ccff Guido Trotter
    """
402 0a903309 Michael Hanselmann
    filename = self._ConfigFileName(instance_name)
403 76c364d9 Michael Hanselmann
404 4390ccff Guido Trotter
    try:
405 76c364d9 Michael Hanselmann
      file_content = utils.ReadFile(filename)
406 4390ccff Guido Trotter
    except EnvironmentError, err:
407 4390ccff Guido Trotter
      raise errors.HypervisorError("Failed to load Xen config file: %s" % err)
408 76c364d9 Michael Hanselmann
409 4390ccff Guido Trotter
    return file_content
410 4390ccff Guido Trotter
411 0a903309 Michael Hanselmann
  def _RemoveConfigFile(self, instance_name):
412 65a6f9b7 Michael Hanselmann
    """Remove the xen configuration file.
413 65a6f9b7 Michael Hanselmann

414 65a6f9b7 Michael Hanselmann
    """
415 0a903309 Michael Hanselmann
    utils.RemoveFile(self._ConfigFileName(instance_name))
416 65a6f9b7 Michael Hanselmann
417 3d942d8b Michael Hanselmann
  def _GetXmList(self, include_node):
418 b255379d Michael Hanselmann
    """Wrapper around module level L{_GetXmList}.
419 06b78e8b Michael Hanselmann

420 06b78e8b Michael Hanselmann
    """
421 3d942d8b Michael Hanselmann
    return _GetXmList(lambda: self._RunXen(["list"]), include_node)
422 65a6f9b7 Michael Hanselmann
423 65a6f9b7 Michael Hanselmann
  def ListInstances(self):
424 65a6f9b7 Michael Hanselmann
    """Get the list of running instances.
425 65a6f9b7 Michael Hanselmann

426 65a6f9b7 Michael Hanselmann
    """
427 b255379d Michael Hanselmann
    xm_list = self._GetXmList(False)
428 65a6f9b7 Michael Hanselmann
    names = [info[0] for info in xm_list]
429 65a6f9b7 Michael Hanselmann
    return names
430 65a6f9b7 Michael Hanselmann
431 65a6f9b7 Michael Hanselmann
  def GetInstanceInfo(self, instance_name):
432 65a6f9b7 Michael Hanselmann
    """Get instance properties.
433 65a6f9b7 Michael Hanselmann

434 c41eea6e Iustin Pop
    @param instance_name: the instance name
435 c41eea6e Iustin Pop

436 c41eea6e Iustin Pop
    @return: tuple (name, id, memory, vcpus, stat, times)
437 65a6f9b7 Michael Hanselmann

438 65a6f9b7 Michael Hanselmann
    """
439 b255379d Michael Hanselmann
    xm_list = self._GetXmList(instance_name == _DOM0_NAME)
440 65a6f9b7 Michael Hanselmann
    result = None
441 65a6f9b7 Michael Hanselmann
    for data in xm_list:
442 65a6f9b7 Michael Hanselmann
      if data[0] == instance_name:
443 65a6f9b7 Michael Hanselmann
        result = data
444 65a6f9b7 Michael Hanselmann
        break
445 65a6f9b7 Michael Hanselmann
    return result
446 65a6f9b7 Michael Hanselmann
447 65a6f9b7 Michael Hanselmann
  def GetAllInstancesInfo(self):
448 65a6f9b7 Michael Hanselmann
    """Get properties of all instances.
449 65a6f9b7 Michael Hanselmann

450 c41eea6e Iustin Pop
    @return: list of tuples (name, id, memory, vcpus, stat, times)
451 c41eea6e Iustin Pop

452 65a6f9b7 Michael Hanselmann
    """
453 b255379d Michael Hanselmann
    xm_list = self._GetXmList(False)
454 65a6f9b7 Michael Hanselmann
    return xm_list
455 65a6f9b7 Michael Hanselmann
456 c3d839f5 Michael Hanselmann
  def _MakeConfigFile(self, instance, startup_memory, block_devices):
457 c3d839f5 Michael Hanselmann
    """Gather configuration details and write to disk.
458 c3d839f5 Michael Hanselmann

459 c3d839f5 Michael Hanselmann
    See L{_GetConfig} for arguments.
460 c3d839f5 Michael Hanselmann

461 c3d839f5 Michael Hanselmann
    """
462 c3d839f5 Michael Hanselmann
    buf = StringIO()
463 c3d839f5 Michael Hanselmann
    buf.write("# Automatically generated by Ganeti. Do not edit!\n")
464 c3d839f5 Michael Hanselmann
    buf.write("\n")
465 c3d839f5 Michael Hanselmann
    buf.write(self._GetConfig(instance, startup_memory, block_devices))
466 c3d839f5 Michael Hanselmann
    buf.write("\n")
467 c3d839f5 Michael Hanselmann
468 c3d839f5 Michael Hanselmann
    self._WriteConfigFile(instance.name, buf.getvalue())
469 c3d839f5 Michael Hanselmann
470 323f9095 Stephen Shirley
  def StartInstance(self, instance, block_devices, startup_paused):
471 c41eea6e Iustin Pop
    """Start an instance.
472 c41eea6e Iustin Pop

473 c41eea6e Iustin Pop
    """
474 61eb1a46 Guido Trotter
    startup_memory = self._InstanceStartupMemory(instance)
475 c3d839f5 Michael Hanselmann
476 c3d839f5 Michael Hanselmann
    self._MakeConfigFile(instance, startup_memory, block_devices)
477 c3d839f5 Michael Hanselmann
478 3d942d8b Michael Hanselmann
    cmd = ["create"]
479 323f9095 Stephen Shirley
    if startup_paused:
480 3d942d8b Michael Hanselmann
      cmd.append("-p")
481 3d942d8b Michael Hanselmann
    cmd.append(self._ConfigFileName(instance.name))
482 65a6f9b7 Michael Hanselmann
483 3d942d8b Michael Hanselmann
    result = self._RunXen(cmd)
484 65a6f9b7 Michael Hanselmann
    if result.failed:
485 65a6f9b7 Michael Hanselmann
      raise errors.HypervisorError("Failed to start instance %s: %s (%s)" %
486 65a6f9b7 Michael Hanselmann
                                   (instance.name, result.fail_reason,
487 65a6f9b7 Michael Hanselmann
                                    result.output))
488 65a6f9b7 Michael Hanselmann
489 bbcf7ad0 Iustin Pop
  def StopInstance(self, instance, force=False, retry=False, name=None):
490 c41eea6e Iustin Pop
    """Stop an instance.
491 c41eea6e Iustin Pop

492 c41eea6e Iustin Pop
    """
493 bbcf7ad0 Iustin Pop
    if name is None:
494 bbcf7ad0 Iustin Pop
      name = instance.name
495 4b8b172d Michael Hanselmann
496 31da5ab5 Michael Hanselmann
    return self._StopInstance(name, force)
497 31da5ab5 Michael Hanselmann
498 31da5ab5 Michael Hanselmann
  def _StopInstance(self, name, force):
499 31da5ab5 Michael Hanselmann
    """Stop an instance.
500 31da5ab5 Michael Hanselmann

501 31da5ab5 Michael Hanselmann
    """
502 65a6f9b7 Michael Hanselmann
    if force:
503 3d942d8b Michael Hanselmann
      action = "destroy"
504 65a6f9b7 Michael Hanselmann
    else:
505 3d942d8b Michael Hanselmann
      action = "shutdown"
506 65a6f9b7 Michael Hanselmann
507 3d942d8b Michael Hanselmann
    result = self._RunXen([action, name])
508 65a6f9b7 Michael Hanselmann
    if result.failed:
509 3213d3c8 Iustin Pop
      raise errors.HypervisorError("Failed to stop instance %s: %s, %s" %
510 bbcf7ad0 Iustin Pop
                                   (name, result.fail_reason, result.output))
511 65a6f9b7 Michael Hanselmann
512 4b8b172d Michael Hanselmann
    # Remove configuration file if stopping/starting instance was successful
513 4b8b172d Michael Hanselmann
    self._RemoveConfigFile(name)
514 4b8b172d Michael Hanselmann
515 65a6f9b7 Michael Hanselmann
  def RebootInstance(self, instance):
516 c41eea6e Iustin Pop
    """Reboot an instance.
517 c41eea6e Iustin Pop

518 c41eea6e Iustin Pop
    """
519 7dd106d3 Iustin Pop
    ini_info = self.GetInstanceInfo(instance.name)
520 65a6f9b7 Michael Hanselmann
521 e0561198 Iustin Pop
    if ini_info is None:
522 e0561198 Iustin Pop
      raise errors.HypervisorError("Failed to reboot instance %s,"
523 e0561198 Iustin Pop
                                   " not running" % instance.name)
524 e0561198 Iustin Pop
525 3d942d8b Michael Hanselmann
    result = self._RunXen(["reboot", instance.name])
526 65a6f9b7 Michael Hanselmann
    if result.failed:
527 3213d3c8 Iustin Pop
      raise errors.HypervisorError("Failed to reboot instance %s: %s, %s" %
528 3213d3c8 Iustin Pop
                                   (instance.name, result.fail_reason,
529 3213d3c8 Iustin Pop
                                    result.output))
530 06b78e8b Michael Hanselmann
531 06b78e8b Michael Hanselmann
    def _CheckInstance():
532 7dd106d3 Iustin Pop
      new_info = self.GetInstanceInfo(instance.name)
533 06b78e8b Michael Hanselmann
534 06b78e8b Michael Hanselmann
      # check if the domain ID has changed or the run time has decreased
535 e0561198 Iustin Pop
      if (new_info is not None and
536 e0561198 Iustin Pop
          (new_info[1] != ini_info[1] or new_info[5] < ini_info[5])):
537 06b78e8b Michael Hanselmann
        return
538 7dd106d3 Iustin Pop
539 06b78e8b Michael Hanselmann
      raise utils.RetryAgain()
540 06b78e8b Michael Hanselmann
541 06b78e8b Michael Hanselmann
    try:
542 06b78e8b Michael Hanselmann
      utils.Retry(_CheckInstance, self.REBOOT_RETRY_INTERVAL,
543 06b78e8b Michael Hanselmann
                  self.REBOOT_RETRY_INTERVAL * self.REBOOT_RETRY_COUNT)
544 06b78e8b Michael Hanselmann
    except utils.RetryTimeout:
545 7dd106d3 Iustin Pop
      raise errors.HypervisorError("Failed to reboot instance %s: instance"
546 7dd106d3 Iustin Pop
                                   " did not reboot in the expected interval" %
547 7dd106d3 Iustin Pop
                                   (instance.name, ))
548 65a6f9b7 Michael Hanselmann
549 2c7a0373 Guido Trotter
  def BalloonInstanceMemory(self, instance, mem):
550 2c7a0373 Guido Trotter
    """Balloon an instance memory to a certain value.
551 2c7a0373 Guido Trotter

552 2c7a0373 Guido Trotter
    @type instance: L{objects.Instance}
553 2c7a0373 Guido Trotter
    @param instance: instance to be accepted
554 2c7a0373 Guido Trotter
    @type mem: int
555 2c7a0373 Guido Trotter
    @param mem: actual memory size to use for instance runtime
556 2c7a0373 Guido Trotter

557 2c7a0373 Guido Trotter
    """
558 3d942d8b Michael Hanselmann
    result = self._RunXen(["mem-set", instance.name, mem])
559 2c7a0373 Guido Trotter
    if result.failed:
560 2c7a0373 Guido Trotter
      raise errors.HypervisorError("Failed to balloon instance %s: %s (%s)" %
561 2c7a0373 Guido Trotter
                                   (instance.name, result.fail_reason,
562 2c7a0373 Guido Trotter
                                    result.output))
563 3d942d8b Michael Hanselmann
564 3d942d8b Michael Hanselmann
    # Update configuration file
565 2c7a0373 Guido Trotter
    cmd = ["sed", "-ie", "s/^memory.*$/memory = %s/" % mem]
566 0a903309 Michael Hanselmann
    cmd.append(self._ConfigFileName(instance.name))
567 3d942d8b Michael Hanselmann
568 2c7a0373 Guido Trotter
    result = utils.RunCmd(cmd)
569 2c7a0373 Guido Trotter
    if result.failed:
570 2c7a0373 Guido Trotter
      raise errors.HypervisorError("Failed to update memory for %s: %s (%s)" %
571 2c7a0373 Guido Trotter
                                   (instance.name, result.fail_reason,
572 2c7a0373 Guido Trotter
                                    result.output))
573 2c7a0373 Guido Trotter
574 65a6f9b7 Michael Hanselmann
  def GetNodeInfo(self):
575 65a6f9b7 Michael Hanselmann
    """Return information about the node.
576 65a6f9b7 Michael Hanselmann

577 06c9a520 Michael Hanselmann
    @see: L{_GetNodeInfo} and L{_ParseNodeInfo}
578 65a6f9b7 Michael Hanselmann

579 65a6f9b7 Michael Hanselmann
    """
580 3d942d8b Michael Hanselmann
    result = self._RunXen(["info"])
581 65a6f9b7 Michael Hanselmann
    if result.failed:
582 b48909c8 Iustin Pop
      logging.error("Can't run 'xm info' (%s): %s", result.fail_reason,
583 b48909c8 Iustin Pop
                    result.output)
584 65a6f9b7 Michael Hanselmann
      return None
585 65a6f9b7 Michael Hanselmann
586 06c9a520 Michael Hanselmann
    return _GetNodeInfo(result.stdout, self._GetXmList)
587 65a6f9b7 Michael Hanselmann
588 637ce7f9 Guido Trotter
  @classmethod
589 55cc0a44 Michael Hanselmann
  def GetInstanceConsole(cls, instance, hvparams, beparams):
590 65a6f9b7 Michael Hanselmann
    """Return a command for connecting to the console of an instance.
591 65a6f9b7 Michael Hanselmann

592 65a6f9b7 Michael Hanselmann
    """
593 55cc0a44 Michael Hanselmann
    return objects.InstanceConsole(instance=instance.name,
594 55cc0a44 Michael Hanselmann
                                   kind=constants.CONS_SSH,
595 55cc0a44 Michael Hanselmann
                                   host=instance.primary_node,
596 052783ff Michael Hanselmann
                                   user=constants.SSH_CONSOLE_USER,
597 b9612abb Iustin Pop
                                   command=[pathutils.XEN_CONSOLE_WRAPPER,
598 1f5557ca Guido Trotter
                                            constants.XEN_CMD, instance.name])
599 65a6f9b7 Michael Hanselmann
600 65a6f9b7 Michael Hanselmann
  def Verify(self):
601 65a6f9b7 Michael Hanselmann
    """Verify the hypervisor.
602 65a6f9b7 Michael Hanselmann

603 65a6f9b7 Michael Hanselmann
    For Xen, this verifies that the xend process is running.
604 65a6f9b7 Michael Hanselmann

605 cd04dfd2 Michael Hanselmann
    @return: Problem description if something is wrong, C{None} otherwise
606 cd04dfd2 Michael Hanselmann

607 65a6f9b7 Michael Hanselmann
    """
608 3d942d8b Michael Hanselmann
    result = self._RunXen(["info"])
609 e3e66f02 Michael Hanselmann
    if result.failed:
610 3213d3c8 Iustin Pop
      return "'xm info' failed: %s, %s" % (result.fail_reason, result.output)
611 65a6f9b7 Michael Hanselmann
612 cd04dfd2 Michael Hanselmann
    return None
613 cd04dfd2 Michael Hanselmann
614 4390ccff Guido Trotter
  def MigrationInfo(self, instance):
615 4390ccff Guido Trotter
    """Get instance information to perform a migration.
616 4390ccff Guido Trotter

617 4390ccff Guido Trotter
    @type instance: L{objects.Instance}
618 4390ccff Guido Trotter
    @param instance: instance to be migrated
619 4390ccff Guido Trotter
    @rtype: string
620 4390ccff Guido Trotter
    @return: content of the xen config file
621 4390ccff Guido Trotter

622 4390ccff Guido Trotter
    """
623 4390ccff Guido Trotter
    return self._ReadConfigFile(instance.name)
624 4390ccff Guido Trotter
625 4390ccff Guido Trotter
  def AcceptInstance(self, instance, info, target):
626 4390ccff Guido Trotter
    """Prepare to accept an instance.
627 4390ccff Guido Trotter

628 4390ccff Guido Trotter
    @type instance: L{objects.Instance}
629 4390ccff Guido Trotter
    @param instance: instance to be accepted
630 4390ccff Guido Trotter
    @type info: string
631 4390ccff Guido Trotter
    @param info: content of the xen config file on the source node
632 4390ccff Guido Trotter
    @type target: string
633 4390ccff Guido Trotter
    @param target: target host (usually ip), on this node
634 4390ccff Guido Trotter

635 4390ccff Guido Trotter
    """
636 4390ccff Guido Trotter
    pass
637 4390ccff Guido Trotter
638 60af751d Andrea Spadaccini
  def FinalizeMigrationDst(self, instance, info, success):
639 4390ccff Guido Trotter
    """Finalize an instance migration.
640 4390ccff Guido Trotter

641 4390ccff Guido Trotter
    After a successful migration we write the xen config file.
642 4390ccff Guido Trotter
    We do nothing on a failure, as we did not change anything at accept time.
643 4390ccff Guido Trotter

644 4390ccff Guido Trotter
    @type instance: L{objects.Instance}
645 fea922fa Guido Trotter
    @param instance: instance whose migration is being finalized
646 4390ccff Guido Trotter
    @type info: string
647 4390ccff Guido Trotter
    @param info: content of the xen config file on the source node
648 4390ccff Guido Trotter
    @type success: boolean
649 4390ccff Guido Trotter
    @param success: whether the migration was a success or a failure
650 4390ccff Guido Trotter

651 4390ccff Guido Trotter
    """
652 4390ccff Guido Trotter
    if success:
653 c3d839f5 Michael Hanselmann
      self._WriteConfigFile(instance.name, info)
654 4390ccff Guido Trotter
655 6e7275c0 Iustin Pop
  def MigrateInstance(self, instance, target, live):
656 6e7275c0 Iustin Pop
    """Migrate an instance to a target node.
657 6e7275c0 Iustin Pop

658 6e7275c0 Iustin Pop
    The migration will not be attempted if the instance is not
659 6e7275c0 Iustin Pop
    currently running.
660 6e7275c0 Iustin Pop

661 58d38b02 Iustin Pop
    @type instance: L{objects.Instance}
662 58d38b02 Iustin Pop
    @param instance: the instance to be migrated
663 fdf7f055 Guido Trotter
    @type target: string
664 fdf7f055 Guido Trotter
    @param target: ip address of the target node
665 fdf7f055 Guido Trotter
    @type live: boolean
666 fdf7f055 Guido Trotter
    @param live: perform a live migration
667 fdf7f055 Guido Trotter

668 6e7275c0 Iustin Pop
    """
669 d8784f7d Michael Hanselmann
    port = instance.hvparams[constants.HV_MIGRATION_PORT]
670 d8784f7d Michael Hanselmann
671 d8784f7d Michael Hanselmann
    # TODO: Pass cluster name via RPC
672 d8784f7d Michael Hanselmann
    cluster_name = ssconf.SimpleStore().GetClusterName()
673 d8784f7d Michael Hanselmann
674 d8784f7d Michael Hanselmann
    return self._MigrateInstance(cluster_name, instance.name, target, port,
675 d8784f7d Michael Hanselmann
                                 live)
676 d8784f7d Michael Hanselmann
677 d8784f7d Michael Hanselmann
  def _MigrateInstance(self, cluster_name, instance_name, target, port, live,
678 d8784f7d Michael Hanselmann
                       _ping_fn=netutils.TcpPing):
679 d8784f7d Michael Hanselmann
    """Migrate an instance to a target node.
680 d8784f7d Michael Hanselmann

681 d8784f7d Michael Hanselmann
    @see: L{MigrateInstance} for details
682 d8784f7d Michael Hanselmann

683 d8784f7d Michael Hanselmann
    """
684 d8784f7d Michael Hanselmann
    if self.GetInstanceInfo(instance_name) is None:
685 6e7275c0 Iustin Pop
      raise errors.HypervisorError("Instance not running, cannot migrate")
686 50716be0 Iustin Pop
687 d8784f7d Michael Hanselmann
    cmd = self._GetCommand()
688 50716be0 Iustin Pop
689 d8784f7d Michael Hanselmann
    if (cmd == constants.XEN_CMD_XM and
690 d8784f7d Michael Hanselmann
        not _ping_fn(target, port, live_port_needed=True)):
691 50716be0 Iustin Pop
      raise errors.HypervisorError("Remote host %s not listening on port"
692 50716be0 Iustin Pop
                                   " %s, cannot migrate" % (target, port))
693 50716be0 Iustin Pop
694 3d942d8b Michael Hanselmann
    args = ["migrate"]
695 3d942d8b Michael Hanselmann
696 d8784f7d Michael Hanselmann
    if cmd == constants.XEN_CMD_XM:
697 0625d08f René Nussbaumer
      args.extend(["-p", "%d" % port])
698 0625d08f René Nussbaumer
      if live:
699 0625d08f René Nussbaumer
        args.append("-l")
700 3d942d8b Michael Hanselmann
701 d8784f7d Michael Hanselmann
    elif cmd == constants.XEN_CMD_XL:
702 d8784f7d Michael Hanselmann
      args.extend([
703 d8784f7d Michael Hanselmann
        "-s", constants.XL_SSH_CMD % cluster_name,
704 d8784f7d Michael Hanselmann
        "-C", self._ConfigFileName(instance_name),
705 d8784f7d Michael Hanselmann
        ])
706 3d942d8b Michael Hanselmann
707 0625d08f René Nussbaumer
    else:
708 d8784f7d Michael Hanselmann
      raise errors.HypervisorError("Unsupported Xen command: %s" % self._cmd)
709 0625d08f René Nussbaumer
710 d8784f7d Michael Hanselmann
    args.extend([instance_name, target])
711 3d942d8b Michael Hanselmann
712 3d942d8b Michael Hanselmann
    result = self._RunXen(args)
713 6e7275c0 Iustin Pop
    if result.failed:
714 6e7275c0 Iustin Pop
      raise errors.HypervisorError("Failed to migrate instance %s: %s" %
715 d8784f7d Michael Hanselmann
                                   (instance_name, result.output))
716 60af751d Andrea Spadaccini
717 60af751d Andrea Spadaccini
  def FinalizeMigrationSource(self, instance, success, live):
718 60af751d Andrea Spadaccini
    """Finalize the instance migration on the source node.
719 60af751d Andrea Spadaccini

720 60af751d Andrea Spadaccini
    @type instance: L{objects.Instance}
721 60af751d Andrea Spadaccini
    @param instance: the instance that was migrated
722 60af751d Andrea Spadaccini
    @type success: bool
723 60af751d Andrea Spadaccini
    @param success: whether the migration succeeded or not
724 60af751d Andrea Spadaccini
    @type live: bool
725 60af751d Andrea Spadaccini
    @param live: whether the user requested a live migration or not
726 60af751d Andrea Spadaccini

727 60af751d Andrea Spadaccini
    """
728 60af751d Andrea Spadaccini
    # pylint: disable=W0613
729 60af751d Andrea Spadaccini
    if success:
730 60af751d Andrea Spadaccini
      # remove old xen file after migration succeeded
731 60af751d Andrea Spadaccini
      try:
732 60af751d Andrea Spadaccini
        self._RemoveConfigFile(instance.name)
733 60af751d Andrea Spadaccini
      except EnvironmentError:
734 60af751d Andrea Spadaccini
        logging.exception("Failure while removing instance config file")
735 60af751d Andrea Spadaccini
736 60af751d Andrea Spadaccini
  def GetMigrationStatus(self, instance):
737 60af751d Andrea Spadaccini
    """Get the migration status
738 60af751d Andrea Spadaccini

739 60af751d Andrea Spadaccini
    As MigrateInstance for Xen is still blocking, if this method is called it
740 60af751d Andrea Spadaccini
    means that MigrateInstance has completed successfully. So we can safely
741 60af751d Andrea Spadaccini
    assume that the migration was successful and notify this fact to the client.
742 60af751d Andrea Spadaccini

743 60af751d Andrea Spadaccini
    @type instance: L{objects.Instance}
744 60af751d Andrea Spadaccini
    @param instance: the instance that is being migrated
745 60af751d Andrea Spadaccini
    @rtype: L{objects.MigrationStatus}
746 60af751d Andrea Spadaccini
    @return: the status of the current migration (one of
747 60af751d Andrea Spadaccini
             L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
748 60af751d Andrea Spadaccini
             progress info that can be retrieved from the hypervisor
749 60af751d Andrea Spadaccini

750 60af751d Andrea Spadaccini
    """
751 60af751d Andrea Spadaccini
    return objects.MigrationStatus(status=constants.HV_MIGRATION_COMPLETED)
752 6e7275c0 Iustin Pop
753 f5118ade Iustin Pop
  @classmethod
754 f5118ade Iustin Pop
  def PowercycleNode(cls):
755 f5118ade Iustin Pop
    """Xen-specific powercycle.
756 f5118ade Iustin Pop

757 f5118ade Iustin Pop
    This first does a Linux reboot (which triggers automatically a Xen
758 f5118ade Iustin Pop
    reboot), and if that fails it tries to do a Xen reboot. The reason
759 f5118ade Iustin Pop
    we don't try a Xen reboot first is that the xen reboot launches an
760 f5118ade Iustin Pop
    external command which connects to the Xen hypervisor, and that
761 f5118ade Iustin Pop
    won't work in case the root filesystem is broken and/or the xend
762 f5118ade Iustin Pop
    daemon is not working.
763 f5118ade Iustin Pop

764 f5118ade Iustin Pop
    """
765 f5118ade Iustin Pop
    try:
766 f5118ade Iustin Pop
      cls.LinuxPowercycle()
767 f5118ade Iustin Pop
    finally:
768 2876c2d6 Guido Trotter
      utils.RunCmd([constants.XEN_CMD, "debug", "R"])
769 f5118ade Iustin Pop
770 65a6f9b7 Michael Hanselmann
771 65a6f9b7 Michael Hanselmann
class XenPvmHypervisor(XenHypervisor):
772 65a6f9b7 Michael Hanselmann
  """Xen PVM hypervisor interface"""
773 65a6f9b7 Michael Hanselmann
774 205ab586 Iustin Pop
  PARAMETERS = {
775 2f2dbb4b Jun Futagawa
    constants.HV_USE_BOOTLOADER: hv_base.NO_CHECK,
776 2f2dbb4b Jun Futagawa
    constants.HV_BOOTLOADER_PATH: hv_base.OPT_FILE_CHECK,
777 2f2dbb4b Jun Futagawa
    constants.HV_BOOTLOADER_ARGS: hv_base.NO_CHECK,
778 205ab586 Iustin Pop
    constants.HV_KERNEL_PATH: hv_base.REQ_FILE_CHECK,
779 205ab586 Iustin Pop
    constants.HV_INITRD_PATH: hv_base.OPT_FILE_CHECK,
780 7adf7814 René Nussbaumer
    constants.HV_ROOT_PATH: hv_base.NO_CHECK,
781 205ab586 Iustin Pop
    constants.HV_KERNEL_ARGS: hv_base.NO_CHECK,
782 e2d14329 Andrea Spadaccini
    constants.HV_MIGRATION_PORT: hv_base.REQ_NET_PORT_CHECK,
783 783a6c0b Iustin Pop
    constants.HV_MIGRATION_MODE: hv_base.MIGRATION_MODE_CHECK,
784 525011bc Maciej Bliziński
    # TODO: Add a check for the blockdev prefix (matching [a-z:] or similar).
785 525011bc Maciej Bliziński
    constants.HV_BLOCKDEV_PREFIX: hv_base.NO_CHECK,
786 990ade2d Stephen Shirley
    constants.HV_REBOOT_BEHAVIOR:
787 c4708267 Tsachy Shacham
      hv_base.ParamInSet(True, constants.REBOOT_BEHAVIORS),
788 c4708267 Tsachy Shacham
    constants.HV_CPU_MASK: hv_base.OPT_MULTI_CPU_MASK_CHECK,
789 2c368f28 Guido Trotter
    constants.HV_CPU_CAP: hv_base.OPT_NONNEGATIVE_INT_CHECK,
790 8bd977e9 Sébastien Bocahu
    constants.HV_CPU_WEIGHT:
791 8bd977e9 Sébastien Bocahu
      (False, lambda x: 0 < x < 65536, "invalid weight", None, None),
792 205ab586 Iustin Pop
    }
793 f48148c3 Iustin Pop
794 c3d839f5 Michael Hanselmann
  def _GetConfig(self, instance, startup_memory, block_devices):
795 65a6f9b7 Michael Hanselmann
    """Write the Xen config file for the instance.
796 65a6f9b7 Michael Hanselmann

797 65a6f9b7 Michael Hanselmann
    """
798 a985b417 Iustin Pop
    hvp = instance.hvparams
799 65a6f9b7 Michael Hanselmann
    config = StringIO()
800 65a6f9b7 Michael Hanselmann
    config.write("# this is autogenerated by Ganeti, please do not edit\n#\n")
801 65a6f9b7 Michael Hanselmann
802 2f2dbb4b Jun Futagawa
    # if bootloader is True, use bootloader instead of kernel and ramdisk
803 2f2dbb4b Jun Futagawa
    # parameters.
804 2f2dbb4b Jun Futagawa
    if hvp[constants.HV_USE_BOOTLOADER]:
805 2f2dbb4b Jun Futagawa
      # bootloader handling
806 2f2dbb4b Jun Futagawa
      bootloader_path = hvp[constants.HV_BOOTLOADER_PATH]
807 2f2dbb4b Jun Futagawa
      if bootloader_path:
808 2f2dbb4b Jun Futagawa
        config.write("bootloader = '%s'\n" % bootloader_path)
809 2f2dbb4b Jun Futagawa
      else:
810 2f2dbb4b Jun Futagawa
        raise errors.HypervisorError("Bootloader enabled, but missing"
811 2f2dbb4b Jun Futagawa
                                     " bootloader path")
812 65a6f9b7 Michael Hanselmann
813 2f2dbb4b Jun Futagawa
      bootloader_args = hvp[constants.HV_BOOTLOADER_ARGS]
814 2f2dbb4b Jun Futagawa
      if bootloader_args:
815 2f2dbb4b Jun Futagawa
        config.write("bootargs = '%s'\n" % bootloader_args)
816 2f2dbb4b Jun Futagawa
    else:
817 2f2dbb4b Jun Futagawa
      # kernel handling
818 2f2dbb4b Jun Futagawa
      kpath = hvp[constants.HV_KERNEL_PATH]
819 2f2dbb4b Jun Futagawa
      config.write("kernel = '%s'\n" % kpath)
820 2f2dbb4b Jun Futagawa
821 2f2dbb4b Jun Futagawa
      # initrd handling
822 2f2dbb4b Jun Futagawa
      initrd_path = hvp[constants.HV_INITRD_PATH]
823 2f2dbb4b Jun Futagawa
      if initrd_path:
824 2f2dbb4b Jun Futagawa
        config.write("ramdisk = '%s'\n" % initrd_path)
825 65a6f9b7 Michael Hanselmann
826 65a6f9b7 Michael Hanselmann
    # rest of the settings
827 61eb1a46 Guido Trotter
    config.write("memory = %d\n" % startup_memory)
828 80121c83 Guido Trotter
    config.write("maxmem = %d\n" % instance.beparams[constants.BE_MAXMEM])
829 8b3fd458 Iustin Pop
    config.write("vcpus = %d\n" % instance.beparams[constants.BE_VCPUS])
830 347fa0f1 Michael Hanselmann
    cpu_pinning = _CreateConfigCpus(hvp[constants.HV_CPU_MASK])
831 c4708267 Tsachy Shacham
    if cpu_pinning:
832 c4708267 Tsachy Shacham
      config.write("%s\n" % cpu_pinning)
833 8bd977e9 Sébastien Bocahu
    cpu_cap = hvp[constants.HV_CPU_CAP]
834 8bd977e9 Sébastien Bocahu
    if cpu_cap:
835 8bd977e9 Sébastien Bocahu
      config.write("cpu_cap=%d\n" % cpu_cap)
836 8bd977e9 Sébastien Bocahu
    cpu_weight = hvp[constants.HV_CPU_WEIGHT]
837 8bd977e9 Sébastien Bocahu
    if cpu_weight:
838 8bd977e9 Sébastien Bocahu
      config.write("cpu_weight=%d\n" % cpu_weight)
839 c4708267 Tsachy Shacham
840 65a6f9b7 Michael Hanselmann
    config.write("name = '%s'\n" % instance.name)
841 65a6f9b7 Michael Hanselmann
842 65a6f9b7 Michael Hanselmann
    vif_data = []
843 65a6f9b7 Michael Hanselmann
    for nic in instance.nics:
844 503b97a9 Guido Trotter
      nic_str = "mac=%s" % (nic.mac)
845 65a6f9b7 Michael Hanselmann
      ip = getattr(nic, "ip", None)
846 65a6f9b7 Michael Hanselmann
      if ip is not None:
847 65a6f9b7 Michael Hanselmann
        nic_str += ", ip=%s" % ip
848 503b97a9 Guido Trotter
      if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
849 503b97a9 Guido Trotter
        nic_str += ", bridge=%s" % nic.nicparams[constants.NIC_LINK]
850 0183a697 Alessandro Cincaglini
      vif_data.append("'%s'" % nic_str)
851 65a6f9b7 Michael Hanselmann
852 d0bb3f24 Michael Hanselmann
    disk_data = \
853 d0bb3f24 Michael Hanselmann
      _GetConfigFileDiskData(block_devices, hvp[constants.HV_BLOCKDEV_PREFIX])
854 7ed85ffe Iustin Pop
855 65a6f9b7 Michael Hanselmann
    config.write("vif = [%s]\n" % ",".join(vif_data))
856 7ed85ffe Iustin Pop
    config.write("disk = [%s]\n" % ",".join(disk_data))
857 074ca009 Guido Trotter
858 7adf7814 René Nussbaumer
    if hvp[constants.HV_ROOT_PATH]:
859 7adf7814 René Nussbaumer
      config.write("root = '%s'\n" % hvp[constants.HV_ROOT_PATH])
860 65a6f9b7 Michael Hanselmann
    config.write("on_poweroff = 'destroy'\n")
861 990ade2d Stephen Shirley
    if hvp[constants.HV_REBOOT_BEHAVIOR] == constants.INSTANCE_REBOOT_ALLOWED:
862 990ade2d Stephen Shirley
      config.write("on_reboot = 'restart'\n")
863 990ade2d Stephen Shirley
    else:
864 990ade2d Stephen Shirley
      config.write("on_reboot = 'destroy'\n")
865 65a6f9b7 Michael Hanselmann
    config.write("on_crash = 'restart'\n")
866 07813a9e Iustin Pop
    config.write("extra = '%s'\n" % hvp[constants.HV_KERNEL_ARGS])
867 73cd67f4 Guido Trotter
868 c3d839f5 Michael Hanselmann
    return config.getvalue()
869 65a6f9b7 Michael Hanselmann
870 65a6f9b7 Michael Hanselmann
871 65a6f9b7 Michael Hanselmann
class XenHvmHypervisor(XenHypervisor):
872 65a6f9b7 Michael Hanselmann
  """Xen HVM hypervisor interface"""
873 65a6f9b7 Michael Hanselmann
874 69b99987 Michael Hanselmann
  ANCILLARY_FILES = XenHypervisor.ANCILLARY_FILES + [
875 9d9bded1 Michael Hanselmann
    pathutils.VNC_PASSWORD_FILE,
876 69b99987 Michael Hanselmann
    ]
877 69ab2e12 Guido Trotter
  ANCILLARY_FILES_OPT = XenHypervisor.ANCILLARY_FILES_OPT + [
878 9d9bded1 Michael Hanselmann
    pathutils.VNC_PASSWORD_FILE,
879 69ab2e12 Guido Trotter
    ]
880 3680f662 Guido Trotter
881 205ab586 Iustin Pop
  PARAMETERS = {
882 205ab586 Iustin Pop
    constants.HV_ACPI: hv_base.NO_CHECK,
883 016d04b3 Michael Hanselmann
    constants.HV_BOOT_ORDER: (True, ) +
884 016d04b3 Michael Hanselmann
      (lambda x: x and len(x.strip("acdn")) == 0,
885 016d04b3 Michael Hanselmann
       "Invalid boot order specified, must be one or more of [acdn]",
886 016d04b3 Michael Hanselmann
       None, None),
887 205ab586 Iustin Pop
    constants.HV_CDROM_IMAGE_PATH: hv_base.OPT_FILE_CHECK,
888 016d04b3 Michael Hanselmann
    constants.HV_DISK_TYPE:
889 016d04b3 Michael Hanselmann
      hv_base.ParamInSet(True, constants.HT_HVM_VALID_DISK_TYPES),
890 016d04b3 Michael Hanselmann
    constants.HV_NIC_TYPE:
891 016d04b3 Michael Hanselmann
      hv_base.ParamInSet(True, constants.HT_HVM_VALID_NIC_TYPES),
892 205ab586 Iustin Pop
    constants.HV_PAE: hv_base.NO_CHECK,
893 016d04b3 Michael Hanselmann
    constants.HV_VNC_BIND_ADDRESS:
894 8b312c1d Manuel Franceschini
      (False, netutils.IP4Address.IsValid,
895 016d04b3 Michael Hanselmann
       "VNC bind address is not a valid IP address", None, None),
896 205ab586 Iustin Pop
    constants.HV_KERNEL_PATH: hv_base.REQ_FILE_CHECK,
897 205ab586 Iustin Pop
    constants.HV_DEVICE_MODEL: hv_base.REQ_FILE_CHECK,
898 6e6bb8d5 Guido Trotter
    constants.HV_VNC_PASSWORD_FILE: hv_base.REQ_FILE_CHECK,
899 e2d14329 Andrea Spadaccini
    constants.HV_MIGRATION_PORT: hv_base.REQ_NET_PORT_CHECK,
900 783a6c0b Iustin Pop
    constants.HV_MIGRATION_MODE: hv_base.MIGRATION_MODE_CHECK,
901 6b970cef Jun Futagawa
    constants.HV_USE_LOCALTIME: hv_base.NO_CHECK,
902 e695efbf Iustin Pop
    # TODO: Add a check for the blockdev prefix (matching [a-z:] or similar).
903 e695efbf Iustin Pop
    constants.HV_BLOCKDEV_PREFIX: hv_base.NO_CHECK,
904 87f0aa48 Jack
    # Add PCI passthrough
905 3891c95e Bernardo Dal Seno
    constants.HV_PASSTHROUGH: hv_base.NO_CHECK,
906 990ade2d Stephen Shirley
    constants.HV_REBOOT_BEHAVIOR:
907 c4708267 Tsachy Shacham
      hv_base.ParamInSet(True, constants.REBOOT_BEHAVIORS),
908 c4708267 Tsachy Shacham
    constants.HV_CPU_MASK: hv_base.OPT_MULTI_CPU_MASK_CHECK,
909 8bd977e9 Sébastien Bocahu
    constants.HV_CPU_CAP: hv_base.NO_CHECK,
910 8bd977e9 Sébastien Bocahu
    constants.HV_CPU_WEIGHT:
911 8bd977e9 Sébastien Bocahu
      (False, lambda x: 0 < x < 65535, "invalid weight", None, None),
912 205ab586 Iustin Pop
    }
913 09ea8710 Iustin Pop
914 c3d839f5 Michael Hanselmann
  def _GetConfig(self, instance, startup_memory, block_devices):
915 65a6f9b7 Michael Hanselmann
    """Create a Xen 3.1 HVM config file.
916 65a6f9b7 Michael Hanselmann

917 65a6f9b7 Michael Hanselmann
    """
918 a985b417 Iustin Pop
    hvp = instance.hvparams
919 a985b417 Iustin Pop
920 65a6f9b7 Michael Hanselmann
    config = StringIO()
921 e2ee1cea Iustin Pop
922 e2ee1cea Iustin Pop
    # kernel handling
923 e2ee1cea Iustin Pop
    kpath = hvp[constants.HV_KERNEL_PATH]
924 e2ee1cea Iustin Pop
    config.write("kernel = '%s'\n" % kpath)
925 e2ee1cea Iustin Pop
926 65a6f9b7 Michael Hanselmann
    config.write("builder = 'hvm'\n")
927 61eb1a46 Guido Trotter
    config.write("memory = %d\n" % startup_memory)
928 80121c83 Guido Trotter
    config.write("maxmem = %d\n" % instance.beparams[constants.BE_MAXMEM])
929 8b3fd458 Iustin Pop
    config.write("vcpus = %d\n" % instance.beparams[constants.BE_VCPUS])
930 347fa0f1 Michael Hanselmann
    cpu_pinning = _CreateConfigCpus(hvp[constants.HV_CPU_MASK])
931 c4708267 Tsachy Shacham
    if cpu_pinning:
932 c4708267 Tsachy Shacham
      config.write("%s\n" % cpu_pinning)
933 8bd977e9 Sébastien Bocahu
    cpu_cap = hvp[constants.HV_CPU_CAP]
934 8bd977e9 Sébastien Bocahu
    if cpu_cap:
935 8bd977e9 Sébastien Bocahu
      config.write("cpu_cap=%d\n" % cpu_cap)
936 8bd977e9 Sébastien Bocahu
    cpu_weight = hvp[constants.HV_CPU_WEIGHT]
937 8bd977e9 Sébastien Bocahu
    if cpu_weight:
938 8bd977e9 Sébastien Bocahu
      config.write("cpu_weight=%d\n" % cpu_weight)
939 c4708267 Tsachy Shacham
940 65a6f9b7 Michael Hanselmann
    config.write("name = '%s'\n" % instance.name)
941 09ea8710 Iustin Pop
    if hvp[constants.HV_PAE]:
942 a21dda8b Iustin Pop
      config.write("pae = 1\n")
943 a21dda8b Iustin Pop
    else:
944 a21dda8b Iustin Pop
      config.write("pae = 0\n")
945 09ea8710 Iustin Pop
    if hvp[constants.HV_ACPI]:
946 a21dda8b Iustin Pop
      config.write("acpi = 1\n")
947 a21dda8b Iustin Pop
    else:
948 a21dda8b Iustin Pop
      config.write("acpi = 0\n")
949 65a6f9b7 Michael Hanselmann
    config.write("apic = 1\n")
950 09ea8710 Iustin Pop
    config.write("device_model = '%s'\n" % hvp[constants.HV_DEVICE_MODEL])
951 a985b417 Iustin Pop
    config.write("boot = '%s'\n" % hvp[constants.HV_BOOT_ORDER])
952 65a6f9b7 Michael Hanselmann
    config.write("sdl = 0\n")
953 97efde45 Guido Trotter
    config.write("usb = 1\n")
954 97efde45 Guido Trotter
    config.write("usbdevice = 'tablet'\n")
955 65a6f9b7 Michael Hanselmann
    config.write("vnc = 1\n")
956 a985b417 Iustin Pop
    if hvp[constants.HV_VNC_BIND_ADDRESS] is None:
957 d0c11cf7 Alexander Schreiber
      config.write("vnclisten = '%s'\n" % constants.VNC_DEFAULT_BIND_ADDRESS)
958 d0c11cf7 Alexander Schreiber
    else:
959 6b405598 Guido Trotter
      config.write("vnclisten = '%s'\n" % hvp[constants.HV_VNC_BIND_ADDRESS])
960 65a6f9b7 Michael Hanselmann
961 377d74c9 Guido Trotter
    if instance.network_port > constants.VNC_BASE_PORT:
962 377d74c9 Guido Trotter
      display = instance.network_port - constants.VNC_BASE_PORT
963 65a6f9b7 Michael Hanselmann
      config.write("vncdisplay = %s\n" % display)
964 65a6f9b7 Michael Hanselmann
      config.write("vncunused = 0\n")
965 65a6f9b7 Michael Hanselmann
    else:
966 65a6f9b7 Michael Hanselmann
      config.write("# vncdisplay = 1\n")
967 65a6f9b7 Michael Hanselmann
      config.write("vncunused = 1\n")
968 65a6f9b7 Michael Hanselmann
969 6e6bb8d5 Guido Trotter
    vnc_pwd_file = hvp[constants.HV_VNC_PASSWORD_FILE]
970 65a6f9b7 Michael Hanselmann
    try:
971 6e6bb8d5 Guido Trotter
      password = utils.ReadFile(vnc_pwd_file)
972 78f66a17 Guido Trotter
    except EnvironmentError, err:
973 78f66a17 Guido Trotter
      raise errors.HypervisorError("Failed to open VNC password file %s: %s" %
974 6e6bb8d5 Guido Trotter
                                   (vnc_pwd_file, err))
975 65a6f9b7 Michael Hanselmann
976 65a6f9b7 Michael Hanselmann
    config.write("vncpasswd = '%s'\n" % password.rstrip())
977 65a6f9b7 Michael Hanselmann
978 65a6f9b7 Michael Hanselmann
    config.write("serial = 'pty'\n")
979 6b970cef Jun Futagawa
    if hvp[constants.HV_USE_LOCALTIME]:
980 6b970cef Jun Futagawa
      config.write("localtime = 1\n")
981 65a6f9b7 Michael Hanselmann
982 65a6f9b7 Michael Hanselmann
    vif_data = []
983 a985b417 Iustin Pop
    nic_type = hvp[constants.HV_NIC_TYPE]
984 f48148c3 Iustin Pop
    if nic_type is None:
985 f48148c3 Iustin Pop
      # ensure old instances don't change
986 f48148c3 Iustin Pop
      nic_type_str = ", type=ioemu"
987 d08f6067 Guido Trotter
    elif nic_type == constants.HT_NIC_PARAVIRTUAL:
988 f48148c3 Iustin Pop
      nic_type_str = ", type=paravirtualized"
989 f48148c3 Iustin Pop
    else:
990 f48148c3 Iustin Pop
      nic_type_str = ", model=%s, type=ioemu" % nic_type
991 65a6f9b7 Michael Hanselmann
    for nic in instance.nics:
992 503b97a9 Guido Trotter
      nic_str = "mac=%s%s" % (nic.mac, nic_type_str)
993 65a6f9b7 Michael Hanselmann
      ip = getattr(nic, "ip", None)
994 65a6f9b7 Michael Hanselmann
      if ip is not None:
995 65a6f9b7 Michael Hanselmann
        nic_str += ", ip=%s" % ip
996 503b97a9 Guido Trotter
      if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
997 503b97a9 Guido Trotter
        nic_str += ", bridge=%s" % nic.nicparams[constants.NIC_LINK]
998 0183a697 Alessandro Cincaglini
      vif_data.append("'%s'" % nic_str)
999 65a6f9b7 Michael Hanselmann
1000 65a6f9b7 Michael Hanselmann
    config.write("vif = [%s]\n" % ",".join(vif_data))
1001 525011bc Maciej Bliziński
1002 d0bb3f24 Michael Hanselmann
    disk_data = \
1003 d0bb3f24 Michael Hanselmann
      _GetConfigFileDiskData(block_devices, hvp[constants.HV_BLOCKDEV_PREFIX])
1004 525011bc Maciej Bliziński
1005 a985b417 Iustin Pop
    iso_path = hvp[constants.HV_CDROM_IMAGE_PATH]
1006 f48148c3 Iustin Pop
    if iso_path:
1007 f48148c3 Iustin Pop
      iso = "'file:%s,hdc:cdrom,r'" % iso_path
1008 a21dda8b Iustin Pop
      disk_data.append(iso)
1009 a21dda8b Iustin Pop
1010 a21dda8b Iustin Pop
    config.write("disk = [%s]\n" % (",".join(disk_data)))
1011 87f0aa48 Jack
    # Add PCI passthrough
1012 87f0aa48 Jack
    pci_pass_arr = []
1013 87f0aa48 Jack
    pci_pass = hvp[constants.HV_PASSTHROUGH]
1014 87f0aa48 Jack
    if pci_pass:
1015 3891c95e Bernardo Dal Seno
      pci_pass_arr = pci_pass.split(";")
1016 3891c95e Bernardo Dal Seno
      config.write("pci = %s\n" % pci_pass_arr)
1017 65a6f9b7 Michael Hanselmann
    config.write("on_poweroff = 'destroy'\n")
1018 990ade2d Stephen Shirley
    if hvp[constants.HV_REBOOT_BEHAVIOR] == constants.INSTANCE_REBOOT_ALLOWED:
1019 990ade2d Stephen Shirley
      config.write("on_reboot = 'restart'\n")
1020 990ade2d Stephen Shirley
    else:
1021 990ade2d Stephen Shirley
      config.write("on_reboot = 'destroy'\n")
1022 65a6f9b7 Michael Hanselmann
    config.write("on_crash = 'restart'\n")
1023 73cd67f4 Guido Trotter
1024 c3d839f5 Michael Hanselmann
    return config.getvalue()