Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_xen.py @ 51a95d00

History | View | Annotate | Download (33.5 kB)

1
#
2
#
3

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

    
21

    
22
"""Xen hypervisors
23

24
"""
25

    
26
import logging
27
import string # pylint: disable=W0402
28
from cStringIO import StringIO
29

    
30
from ganeti import constants
31
from ganeti import errors
32
from ganeti import utils
33
from ganeti.hypervisor import hv_base
34
from ganeti import netutils
35
from ganeti import objects
36
from ganeti import pathutils
37
from ganeti import ssconf
38

    
39

    
40
XEND_CONFIG_FILE = utils.PathJoin(pathutils.XEN_CONFIG_DIR, "xend-config.sxp")
41
XL_CONFIG_FILE = utils.PathJoin(pathutils.XEN_CONFIG_DIR, "xen/xl.conf")
42
VIF_BRIDGE_SCRIPT = utils.PathJoin(pathutils.XEN_CONFIG_DIR,
43
                                   "scripts/vif-bridge")
44
_DOM0_NAME = "Domain-0"
45
_DISK_LETTERS = string.ascii_lowercase
46

    
47
_FILE_DRIVER_MAP = {
48
  constants.FD_LOOP: "file",
49
  constants.FD_BLKTAP: "tap:aio",
50
  }
51

    
52

    
53
def _CreateConfigCpus(cpu_mask):
54
  """Create a CPU config string for Xen's config file.
55

56
  """
57
  # Convert the string CPU mask to a list of list of int's
58
  cpu_list = utils.ParseMultiCpuMask(cpu_mask)
59

    
60
  if len(cpu_list) == 1:
61
    all_cpu_mapping = cpu_list[0]
62
    if all_cpu_mapping == constants.CPU_PINNING_OFF:
63
      # If CPU pinning has 1 entry that's "all", then remove the
64
      # parameter from the config file
65
      return None
66
    else:
67
      # If CPU pinning has one non-all entry, mapping all vCPUS (the entire
68
      # VM) to one physical CPU, using format 'cpu = "C"'
69
      return "cpu = \"%s\"" % ",".join(map(str, all_cpu_mapping))
70
  else:
71

    
72
    def _GetCPUMap(vcpu):
73
      if vcpu[0] == constants.CPU_PINNING_ALL_VAL:
74
        cpu_map = constants.CPU_PINNING_ALL_XEN
75
      else:
76
        cpu_map = ",".join(map(str, vcpu))
77
      return "\"%s\"" % cpu_map
78

    
79
    # build the result string in format 'cpus = [ "c", "c", "c" ]',
80
    # where each c is a physical CPU number, a range, a list, or any
81
    # combination
82
    return "cpus = [ %s ]" % ", ".join(map(_GetCPUMap, cpu_list))
83

    
84

    
85
def _RunXmList(fn, xmllist_errors):
86
  """Helper function for L{_GetXmList} to run "xm list".
87

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

94
  """
95
  result = fn()
96
  if result.failed:
97
    logging.error("xm list failed (%s): %s", result.fail_reason,
98
                  result.output)
99
    xmllist_errors.append(result)
100
    raise utils.RetryAgain()
101

    
102
  # skip over the heading
103
  return result.stdout.splitlines()
104

    
105

    
106
def _ParseXmList(lines, include_node):
107
  """Parses the output of C{xm list}.
108

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

116
  """
117
  result = []
118

    
119
  # Iterate through all lines while ignoring header
120
  for line in lines[1:]:
121
    # The format of lines is:
122
    # Name      ID Mem(MiB) VCPUs State  Time(s)
123
    # Domain-0   0  3418     4 r-----    266.2
124
    data = line.split()
125
    if len(data) != 6:
126
      raise errors.HypervisorError("Can't parse output of xm list,"
127
                                   " line: %s" % line)
128
    try:
129
      data[1] = int(data[1])
130
      data[2] = int(data[2])
131
      data[3] = int(data[3])
132
      data[5] = float(data[5])
133
    except (TypeError, ValueError), err:
134
      raise errors.HypervisorError("Can't parse output of xm list,"
135
                                   " line: %s, error: %s" % (line, err))
136

    
137
    # skip the Domain-0 (optional)
138
    if include_node or data[0] != _DOM0_NAME:
139
      result.append(data)
140

    
141
  return result
142

    
143

    
144
def _GetXmList(fn, include_node, _timeout=5):
145
  """Return the list of running instances.
146

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

149
  """
150
  xmllist_errors = []
151
  try:
152
    lines = utils.Retry(_RunXmList, (0.3, 1.5, 1.0), _timeout,
153
                        args=(fn, xmllist_errors))
154
  except utils.RetryTimeout:
155
    if xmllist_errors:
156
      xmlist_result = xmllist_errors.pop()
157

    
158
      errmsg = ("xm list failed, timeout exceeded (%s): %s" %
159
                (xmlist_result.fail_reason, xmlist_result.output))
160
    else:
161
      errmsg = "xm list failed"
162

    
163
    raise errors.HypervisorError(errmsg)
164

    
165
  return _ParseXmList(lines, include_node)
166

    
167

    
168
def _ParseNodeInfo(info):
169
  """Return information about the node.
170

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

179
  """
180
  result = {}
181
  cores_per_socket = threads_per_core = nr_cpus = None
182
  xen_major, xen_minor = None, None
183
  memory_total = None
184
  memory_free = None
185

    
186
  for line in info.splitlines():
187
    fields = line.split(":", 1)
188

    
189
    if len(fields) < 2:
190
      continue
191

    
192
    (key, val) = map(lambda s: s.strip(), fields)
193

    
194
    # Note: in Xen 3, memory has changed to total_memory
195
    if key in ("memory", "total_memory"):
196
      memory_total = int(val)
197
    elif key == "free_memory":
198
      memory_free = int(val)
199
    elif key == "nr_cpus":
200
      nr_cpus = result["cpu_total"] = int(val)
201
    elif key == "nr_nodes":
202
      result["cpu_nodes"] = int(val)
203
    elif key == "cores_per_socket":
204
      cores_per_socket = int(val)
205
    elif key == "threads_per_core":
206
      threads_per_core = int(val)
207
    elif key == "xen_major":
208
      xen_major = int(val)
209
    elif key == "xen_minor":
210
      xen_minor = int(val)
211

    
212
  if None not in [cores_per_socket, threads_per_core, nr_cpus]:
213
    result["cpu_sockets"] = nr_cpus / (cores_per_socket * threads_per_core)
214

    
215
  if memory_free is not None:
216
    result["memory_free"] = memory_free
217

    
218
  if memory_total is not None:
219
    result["memory_total"] = memory_total
220

    
221
  if not (xen_major is None or xen_minor is None):
222
    result[constants.HV_NODEINFO_KEY_VERSION] = (xen_major, xen_minor)
223

    
224
  return result
225

    
226

    
227
def _MergeInstanceInfo(info, fn):
228
  """Updates node information from L{_ParseNodeInfo} with instance info.
229

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

236
  """
237
  total_instmem = 0
238

    
239
  for (name, _, mem, vcpus, _, _) in fn(True):
240
    if name == _DOM0_NAME:
241
      info["memory_dom0"] = mem
242
      info["dom0_cpus"] = vcpus
243

    
244
    # Include Dom0 in total memory usage
245
    total_instmem += mem
246

    
247
  memory_free = info.get("memory_free")
248
  memory_total = info.get("memory_total")
249

    
250
  # Calculate memory used by hypervisor
251
  if None not in [memory_total, memory_free, total_instmem]:
252
    info["memory_hv"] = memory_total - memory_free - total_instmem
253

    
254
  return info
255

    
256

    
257
def _GetNodeInfo(info, fn):
258
  """Combines L{_MergeInstanceInfo} and L{_ParseNodeInfo}.
259

260
  """
261
  return _MergeInstanceInfo(_ParseNodeInfo(info), fn)
262

    
263

    
264
def _GetConfigFileDiskData(block_devices, blockdev_prefix,
265
                           _letters=_DISK_LETTERS):
266
  """Get disk directives for Xen config file.
267

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

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

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

279
  """
280
  if len(block_devices) > len(_letters):
281
    raise errors.HypervisorError("Too many disks")
282

    
283
  disk_data = []
284

    
285
  for sd_suffix, (cfdev, dev_path) in zip(_letters, block_devices):
286
    sd_name = blockdev_prefix + sd_suffix
287

    
288
    if cfdev.mode == constants.DISK_RDWR:
289
      mode = "w"
290
    else:
291
      mode = "r"
292

    
293
    if cfdev.dev_type == constants.LD_FILE:
294
      driver = _FILE_DRIVER_MAP[cfdev.physical_id[0]]
295
    else:
296
      driver = "phy"
297

    
298
    disk_data.append("'%s:%s,%s,%s'" % (driver, dev_path, sd_name, mode))
299

    
300
  return disk_data
301

    
302

    
303
class XenHypervisor(hv_base.BaseHypervisor):
304
  """Xen generic hypervisor interface
305

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

309
  """
310
  CAN_MIGRATE = True
311
  REBOOT_RETRY_COUNT = 60
312
  REBOOT_RETRY_INTERVAL = 10
313

    
314
  ANCILLARY_FILES = [
315
    XEND_CONFIG_FILE,
316
    XL_CONFIG_FILE,
317
    VIF_BRIDGE_SCRIPT,
318
    ]
319
  ANCILLARY_FILES_OPT = [
320
    XL_CONFIG_FILE,
321
    ]
322

    
323
  def __init__(self, _cfgdir=None, _run_cmd_fn=None, _cmd=None):
324
    hv_base.BaseHypervisor.__init__(self)
325

    
326
    if _cfgdir is None:
327
      self._cfgdir = pathutils.XEN_CONFIG_DIR
328
    else:
329
      self._cfgdir = _cfgdir
330

    
331
    if _run_cmd_fn is None:
332
      self._run_cmd_fn = utils.RunCmd
333
    else:
334
      self._run_cmd_fn = _run_cmd_fn
335

    
336
    self._cmd = _cmd
337

    
338
  def _GetCommand(self, hvparams=None):
339
    """Returns Xen command to use.
340

341
    @type hvparams: dict of strings
342
    @param hvparams: hypervisor parameters
343

344
    """
345
    if self._cmd is None:
346
      if hvparams is not None:
347
        cmd = hvparams[constants.HV_XEN_CMD]
348
      else:
349
        # TODO: Remove autoconf option once retrieving the command from
350
        # the hvparams is fully implemented.
351
        cmd = constants.XEN_CMD
352
    else:
353
      cmd = self._cmd
354

    
355
    if cmd not in constants.KNOWN_XEN_COMMANDS:
356
      raise errors.ProgrammerError("Unknown Xen command '%s'" % cmd)
357

    
358
    return cmd
359

    
360
  def _RunXen(self, args):
361
    """Wrapper around L{utils.process.RunCmd} to run Xen command.
362

363
    @see: L{utils.process.RunCmd}
364

365
    """
366
    cmd = [self._GetCommand()]
367
    cmd.extend(args)
368

    
369
    return self._run_cmd_fn(cmd)
370

    
371
  def _ConfigFileName(self, instance_name):
372
    """Get the config file name for an instance.
373

374
    @param instance_name: instance name
375
    @type instance_name: str
376
    @return: fully qualified path to instance config file
377
    @rtype: str
378

379
    """
380
    return utils.PathJoin(self._cfgdir, instance_name)
381

    
382
  @classmethod
383
  def _GetConfig(cls, instance, startup_memory, block_devices):
384
    """Build Xen configuration for an instance.
385

386
    """
387
    raise NotImplementedError
388

    
389
  def _WriteConfigFile(self, instance_name, data):
390
    """Write the Xen config file for the instance.
391

392
    This version of the function just writes the config file from static data.
393

394
    """
395
    # just in case it exists
396
    utils.RemoveFile(utils.PathJoin(self._cfgdir, "auto", instance_name))
397

    
398
    cfg_file = self._ConfigFileName(instance_name)
399
    try:
400
      utils.WriteFile(cfg_file, data=data)
401
    except EnvironmentError, err:
402
      raise errors.HypervisorError("Cannot write Xen instance configuration"
403
                                   " file %s: %s" % (cfg_file, err))
404

    
405
  def _ReadConfigFile(self, instance_name):
406
    """Returns the contents of the instance config file.
407

408
    """
409
    filename = self._ConfigFileName(instance_name)
410

    
411
    try:
412
      file_content = utils.ReadFile(filename)
413
    except EnvironmentError, err:
414
      raise errors.HypervisorError("Failed to load Xen config file: %s" % err)
415

    
416
    return file_content
417

    
418
  def _RemoveConfigFile(self, instance_name):
419
    """Remove the xen configuration file.
420

421
    """
422
    utils.RemoveFile(self._ConfigFileName(instance_name))
423

    
424
  def _StashConfigFile(self, instance_name):
425
    """Move the Xen config file to the log directory and return its new path.
426

427
    """
428
    old_filename = self._ConfigFileName(instance_name)
429
    base = ("%s-%s" %
430
            (instance_name, utils.TimestampForFilename()))
431
    new_filename = utils.PathJoin(pathutils.LOG_XEN_DIR, base)
432
    utils.RenameFile(old_filename, new_filename)
433
    return new_filename
434

    
435
  def _GetXmList(self, include_node):
436
    """Wrapper around module level L{_GetXmList}.
437

438
    """
439
    return _GetXmList(lambda: self._RunXen(["list"]), include_node)
440

    
441
  def ListInstances(self):
442
    """Get the list of running instances.
443

444
    """
445
    xm_list = self._GetXmList(False)
446
    names = [info[0] for info in xm_list]
447
    return names
448

    
449
  def GetInstanceInfo(self, instance_name):
450
    """Get instance properties.
451

452
    @param instance_name: the instance name
453

454
    @return: tuple (name, id, memory, vcpus, stat, times)
455

456
    """
457
    xm_list = self._GetXmList(instance_name == _DOM0_NAME)
458
    result = None
459
    for data in xm_list:
460
      if data[0] == instance_name:
461
        result = data
462
        break
463
    return result
464

    
465
  def GetAllInstancesInfo(self):
466
    """Get properties of all instances.
467

468
    @return: list of tuples (name, id, memory, vcpus, stat, times)
469

470
    """
471
    xm_list = self._GetXmList(False)
472
    return xm_list
473

    
474
  def _MakeConfigFile(self, instance, startup_memory, block_devices):
475
    """Gather configuration details and write to disk.
476

477
    See L{_GetConfig} for arguments.
478

479
    """
480
    buf = StringIO()
481
    buf.write("# Automatically generated by Ganeti. Do not edit!\n")
482
    buf.write("\n")
483
    buf.write(self._GetConfig(instance, startup_memory, block_devices))
484
    buf.write("\n")
485

    
486
    self._WriteConfigFile(instance.name, buf.getvalue())
487

    
488
  def StartInstance(self, instance, block_devices, startup_paused):
489
    """Start an instance.
490

491
    """
492
    startup_memory = self._InstanceStartupMemory(instance)
493

    
494
    self._MakeConfigFile(instance, startup_memory, block_devices)
495

    
496
    cmd = ["create"]
497
    if startup_paused:
498
      cmd.append("-p")
499
    cmd.append(self._ConfigFileName(instance.name))
500

    
501
    result = self._RunXen(cmd)
502
    if result.failed:
503
      # Move the Xen configuration file to the log directory to avoid
504
      # leaving a stale config file behind.
505
      stashed_config = self._StashConfigFile(instance.name)
506
      raise errors.HypervisorError("Failed to start instance %s: %s (%s). Moved"
507
                                   " config file to %s" %
508
                                   (instance.name, result.fail_reason,
509
                                    result.output, stashed_config))
510

    
511
  def StopInstance(self, instance, force=False, retry=False, name=None):
512
    """Stop an instance.
513

514
    """
515
    if name is None:
516
      name = instance.name
517

    
518
    return self._StopInstance(name, force)
519

    
520
  def _StopInstance(self, name, force):
521
    """Stop an instance.
522

523
    """
524
    if force:
525
      action = "destroy"
526
    else:
527
      action = "shutdown"
528

    
529
    result = self._RunXen([action, name])
530
    if result.failed:
531
      raise errors.HypervisorError("Failed to stop instance %s: %s, %s" %
532
                                   (name, result.fail_reason, result.output))
533

    
534
    # Remove configuration file if stopping/starting instance was successful
535
    self._RemoveConfigFile(name)
536

    
537
  def RebootInstance(self, instance):
538
    """Reboot an instance.
539

540
    """
541
    ini_info = self.GetInstanceInfo(instance.name)
542

    
543
    if ini_info is None:
544
      raise errors.HypervisorError("Failed to reboot instance %s,"
545
                                   " not running" % instance.name)
546

    
547
    result = self._RunXen(["reboot", instance.name])
548
    if result.failed:
549
      raise errors.HypervisorError("Failed to reboot instance %s: %s, %s" %
550
                                   (instance.name, result.fail_reason,
551
                                    result.output))
552

    
553
    def _CheckInstance():
554
      new_info = self.GetInstanceInfo(instance.name)
555

    
556
      # check if the domain ID has changed or the run time has decreased
557
      if (new_info is not None and
558
          (new_info[1] != ini_info[1] or new_info[5] < ini_info[5])):
559
        return
560

    
561
      raise utils.RetryAgain()
562

    
563
    try:
564
      utils.Retry(_CheckInstance, self.REBOOT_RETRY_INTERVAL,
565
                  self.REBOOT_RETRY_INTERVAL * self.REBOOT_RETRY_COUNT)
566
    except utils.RetryTimeout:
567
      raise errors.HypervisorError("Failed to reboot instance %s: instance"
568
                                   " did not reboot in the expected interval" %
569
                                   (instance.name, ))
570

    
571
  def BalloonInstanceMemory(self, instance, mem):
572
    """Balloon an instance memory to a certain value.
573

574
    @type instance: L{objects.Instance}
575
    @param instance: instance to be accepted
576
    @type mem: int
577
    @param mem: actual memory size to use for instance runtime
578

579
    """
580
    result = self._RunXen(["mem-set", instance.name, mem])
581
    if result.failed:
582
      raise errors.HypervisorError("Failed to balloon instance %s: %s (%s)" %
583
                                   (instance.name, result.fail_reason,
584
                                    result.output))
585

    
586
    # Update configuration file
587
    cmd = ["sed", "-ie", "s/^memory.*$/memory = %s/" % mem]
588
    cmd.append(self._ConfigFileName(instance.name))
589

    
590
    result = utils.RunCmd(cmd)
591
    if result.failed:
592
      raise errors.HypervisorError("Failed to update memory for %s: %s (%s)" %
593
                                   (instance.name, result.fail_reason,
594
                                    result.output))
595

    
596
  def GetNodeInfo(self):
597
    """Return information about the node.
598

599
    @see: L{_GetNodeInfo} and L{_ParseNodeInfo}
600

601
    """
602
    result = self._RunXen(["info"])
603
    if result.failed:
604
      logging.error("Can't run 'xm info' (%s): %s", result.fail_reason,
605
                    result.output)
606
      return None
607

    
608
    return _GetNodeInfo(result.stdout, self._GetXmList)
609

    
610
  @classmethod
611
  def GetInstanceConsole(cls, instance, hvparams, beparams):
612
    """Return a command for connecting to the console of an instance.
613

614
    """
615
    return objects.InstanceConsole(instance=instance.name,
616
                                   kind=constants.CONS_SSH,
617
                                   host=instance.primary_node,
618
                                   user=constants.SSH_CONSOLE_USER,
619
                                   command=[pathutils.XEN_CONSOLE_WRAPPER,
620
                                            constants.XEN_CMD, instance.name])
621

    
622
  def Verify(self):
623
    """Verify the hypervisor.
624

625
    For Xen, this verifies that the xend process is running.
626

627
    @return: Problem description if something is wrong, C{None} otherwise
628

629
    """
630
    result = self._RunXen(["info"])
631
    if result.failed:
632
      return "'xm info' failed: %s, %s" % (result.fail_reason, result.output)
633

    
634
    return None
635

    
636
  def MigrationInfo(self, instance):
637
    """Get instance information to perform a migration.
638

639
    @type instance: L{objects.Instance}
640
    @param instance: instance to be migrated
641
    @rtype: string
642
    @return: content of the xen config file
643

644
    """
645
    return self._ReadConfigFile(instance.name)
646

    
647
  def AcceptInstance(self, instance, info, target):
648
    """Prepare to accept an instance.
649

650
    @type instance: L{objects.Instance}
651
    @param instance: instance to be accepted
652
    @type info: string
653
    @param info: content of the xen config file on the source node
654
    @type target: string
655
    @param target: target host (usually ip), on this node
656

657
    """
658
    pass
659

    
660
  def FinalizeMigrationDst(self, instance, info, success):
661
    """Finalize an instance migration.
662

663
    After a successful migration we write the xen config file.
664
    We do nothing on a failure, as we did not change anything at accept time.
665

666
    @type instance: L{objects.Instance}
667
    @param instance: instance whose migration is being finalized
668
    @type info: string
669
    @param info: content of the xen config file on the source node
670
    @type success: boolean
671
    @param success: whether the migration was a success or a failure
672

673
    """
674
    if success:
675
      self._WriteConfigFile(instance.name, info)
676

    
677
  def MigrateInstance(self, instance, target, live):
678
    """Migrate an instance to a target node.
679

680
    The migration will not be attempted if the instance is not
681
    currently running.
682

683
    @type instance: L{objects.Instance}
684
    @param instance: the instance to be migrated
685
    @type target: string
686
    @param target: ip address of the target node
687
    @type live: boolean
688
    @param live: perform a live migration
689

690
    """
691
    port = instance.hvparams[constants.HV_MIGRATION_PORT]
692

    
693
    # TODO: Pass cluster name via RPC
694
    cluster_name = ssconf.SimpleStore().GetClusterName()
695

    
696
    return self._MigrateInstance(cluster_name, instance.name, target, port,
697
                                 live)
698

    
699
  def _MigrateInstance(self, cluster_name, instance_name, target, port, live,
700
                       _ping_fn=netutils.TcpPing):
701
    """Migrate an instance to a target node.
702

703
    @see: L{MigrateInstance} for details
704

705
    """
706
    if self.GetInstanceInfo(instance_name) is None:
707
      raise errors.HypervisorError("Instance not running, cannot migrate")
708

    
709
    cmd = self._GetCommand()
710

    
711
    if (cmd == constants.XEN_CMD_XM and
712
        not _ping_fn(target, port, live_port_needed=True)):
713
      raise errors.HypervisorError("Remote host %s not listening on port"
714
                                   " %s, cannot migrate" % (target, port))
715

    
716
    args = ["migrate"]
717

    
718
    if cmd == constants.XEN_CMD_XM:
719
      args.extend(["-p", "%d" % port])
720
      if live:
721
        args.append("-l")
722

    
723
    elif cmd == constants.XEN_CMD_XL:
724
      args.extend([
725
        "-s", constants.XL_SSH_CMD % cluster_name,
726
        "-C", self._ConfigFileName(instance_name),
727
        ])
728

    
729
    else:
730
      raise errors.HypervisorError("Unsupported Xen command: %s" % self._cmd)
731

    
732
    args.extend([instance_name, target])
733

    
734
    result = self._RunXen(args)
735
    if result.failed:
736
      raise errors.HypervisorError("Failed to migrate instance %s: %s" %
737
                                   (instance_name, result.output))
738

    
739
  def FinalizeMigrationSource(self, instance, success, live):
740
    """Finalize the instance migration on the source node.
741

742
    @type instance: L{objects.Instance}
743
    @param instance: the instance that was migrated
744
    @type success: bool
745
    @param success: whether the migration succeeded or not
746
    @type live: bool
747
    @param live: whether the user requested a live migration or not
748

749
    """
750
    # pylint: disable=W0613
751
    if success:
752
      # remove old xen file after migration succeeded
753
      try:
754
        self._RemoveConfigFile(instance.name)
755
      except EnvironmentError:
756
        logging.exception("Failure while removing instance config file")
757

    
758
  def GetMigrationStatus(self, instance):
759
    """Get the migration status
760

761
    As MigrateInstance for Xen is still blocking, if this method is called it
762
    means that MigrateInstance has completed successfully. So we can safely
763
    assume that the migration was successful and notify this fact to the client.
764

765
    @type instance: L{objects.Instance}
766
    @param instance: the instance that is being migrated
767
    @rtype: L{objects.MigrationStatus}
768
    @return: the status of the current migration (one of
769
             L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
770
             progress info that can be retrieved from the hypervisor
771

772
    """
773
    return objects.MigrationStatus(status=constants.HV_MIGRATION_COMPLETED)
774

    
775
  @classmethod
776
  def PowercycleNode(cls):
777
    """Xen-specific powercycle.
778

779
    This first does a Linux reboot (which triggers automatically a Xen
780
    reboot), and if that fails it tries to do a Xen reboot. The reason
781
    we don't try a Xen reboot first is that the xen reboot launches an
782
    external command which connects to the Xen hypervisor, and that
783
    won't work in case the root filesystem is broken and/or the xend
784
    daemon is not working.
785

786
    """
787
    try:
788
      cls.LinuxPowercycle()
789
    finally:
790
      utils.RunCmd([constants.XEN_CMD, "debug", "R"])
791

    
792

    
793
class XenPvmHypervisor(XenHypervisor):
794
  """Xen PVM hypervisor interface"""
795

    
796
  PARAMETERS = {
797
    constants.HV_USE_BOOTLOADER: hv_base.NO_CHECK,
798
    constants.HV_BOOTLOADER_PATH: hv_base.OPT_FILE_CHECK,
799
    constants.HV_BOOTLOADER_ARGS: hv_base.NO_CHECK,
800
    constants.HV_KERNEL_PATH: hv_base.REQ_FILE_CHECK,
801
    constants.HV_INITRD_PATH: hv_base.OPT_FILE_CHECK,
802
    constants.HV_ROOT_PATH: hv_base.NO_CHECK,
803
    constants.HV_KERNEL_ARGS: hv_base.NO_CHECK,
804
    constants.HV_MIGRATION_PORT: hv_base.REQ_NET_PORT_CHECK,
805
    constants.HV_MIGRATION_MODE: hv_base.MIGRATION_MODE_CHECK,
806
    # TODO: Add a check for the blockdev prefix (matching [a-z:] or similar).
807
    constants.HV_BLOCKDEV_PREFIX: hv_base.NO_CHECK,
808
    constants.HV_REBOOT_BEHAVIOR:
809
      hv_base.ParamInSet(True, constants.REBOOT_BEHAVIORS),
810
    constants.HV_CPU_MASK: hv_base.OPT_MULTI_CPU_MASK_CHECK,
811
    constants.HV_CPU_CAP: hv_base.OPT_NONNEGATIVE_INT_CHECK,
812
    constants.HV_CPU_WEIGHT:
813
      (False, lambda x: 0 < x < 65536, "invalid weight", None, None),
814
    constants.HV_XEN_CMD:
815
      hv_base.ParamInSet(True, constants.KNOWN_XEN_COMMANDS),
816
    }
817

    
818
  def _GetConfig(self, instance, startup_memory, block_devices):
819
    """Write the Xen config file for the instance.
820

821
    """
822
    hvp = instance.hvparams
823
    config = StringIO()
824
    config.write("# this is autogenerated by Ganeti, please do not edit\n#\n")
825

    
826
    # if bootloader is True, use bootloader instead of kernel and ramdisk
827
    # parameters.
828
    if hvp[constants.HV_USE_BOOTLOADER]:
829
      # bootloader handling
830
      bootloader_path = hvp[constants.HV_BOOTLOADER_PATH]
831
      if bootloader_path:
832
        config.write("bootloader = '%s'\n" % bootloader_path)
833
      else:
834
        raise errors.HypervisorError("Bootloader enabled, but missing"
835
                                     " bootloader path")
836

    
837
      bootloader_args = hvp[constants.HV_BOOTLOADER_ARGS]
838
      if bootloader_args:
839
        config.write("bootargs = '%s'\n" % bootloader_args)
840
    else:
841
      # kernel handling
842
      kpath = hvp[constants.HV_KERNEL_PATH]
843
      config.write("kernel = '%s'\n" % kpath)
844

    
845
      # initrd handling
846
      initrd_path = hvp[constants.HV_INITRD_PATH]
847
      if initrd_path:
848
        config.write("ramdisk = '%s'\n" % initrd_path)
849

    
850
    # rest of the settings
851
    config.write("memory = %d\n" % startup_memory)
852
    config.write("maxmem = %d\n" % instance.beparams[constants.BE_MAXMEM])
853
    config.write("vcpus = %d\n" % instance.beparams[constants.BE_VCPUS])
854
    cpu_pinning = _CreateConfigCpus(hvp[constants.HV_CPU_MASK])
855
    if cpu_pinning:
856
      config.write("%s\n" % cpu_pinning)
857
    cpu_cap = hvp[constants.HV_CPU_CAP]
858
    if cpu_cap:
859
      config.write("cpu_cap=%d\n" % cpu_cap)
860
    cpu_weight = hvp[constants.HV_CPU_WEIGHT]
861
    if cpu_weight:
862
      config.write("cpu_weight=%d\n" % cpu_weight)
863

    
864
    config.write("name = '%s'\n" % instance.name)
865

    
866
    vif_data = []
867
    for nic in instance.nics:
868
      nic_str = "mac=%s" % (nic.mac)
869
      ip = getattr(nic, "ip", None)
870
      if ip is not None:
871
        nic_str += ", ip=%s" % ip
872
      if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
873
        nic_str += ", bridge=%s" % nic.nicparams[constants.NIC_LINK]
874
      vif_data.append("'%s'" % nic_str)
875

    
876
    disk_data = \
877
      _GetConfigFileDiskData(block_devices, hvp[constants.HV_BLOCKDEV_PREFIX])
878

    
879
    config.write("vif = [%s]\n" % ",".join(vif_data))
880
    config.write("disk = [%s]\n" % ",".join(disk_data))
881

    
882
    if hvp[constants.HV_ROOT_PATH]:
883
      config.write("root = '%s'\n" % hvp[constants.HV_ROOT_PATH])
884
    config.write("on_poweroff = 'destroy'\n")
885
    if hvp[constants.HV_REBOOT_BEHAVIOR] == constants.INSTANCE_REBOOT_ALLOWED:
886
      config.write("on_reboot = 'restart'\n")
887
    else:
888
      config.write("on_reboot = 'destroy'\n")
889
    config.write("on_crash = 'restart'\n")
890
    config.write("extra = '%s'\n" % hvp[constants.HV_KERNEL_ARGS])
891

    
892
    return config.getvalue()
893

    
894

    
895
class XenHvmHypervisor(XenHypervisor):
896
  """Xen HVM hypervisor interface"""
897

    
898
  ANCILLARY_FILES = XenHypervisor.ANCILLARY_FILES + [
899
    pathutils.VNC_PASSWORD_FILE,
900
    ]
901
  ANCILLARY_FILES_OPT = XenHypervisor.ANCILLARY_FILES_OPT + [
902
    pathutils.VNC_PASSWORD_FILE,
903
    ]
904

    
905
  PARAMETERS = {
906
    constants.HV_ACPI: hv_base.NO_CHECK,
907
    constants.HV_BOOT_ORDER: (True, ) +
908
      (lambda x: x and len(x.strip("acdn")) == 0,
909
       "Invalid boot order specified, must be one or more of [acdn]",
910
       None, None),
911
    constants.HV_CDROM_IMAGE_PATH: hv_base.OPT_FILE_CHECK,
912
    constants.HV_DISK_TYPE:
913
      hv_base.ParamInSet(True, constants.HT_HVM_VALID_DISK_TYPES),
914
    constants.HV_NIC_TYPE:
915
      hv_base.ParamInSet(True, constants.HT_HVM_VALID_NIC_TYPES),
916
    constants.HV_PAE: hv_base.NO_CHECK,
917
    constants.HV_VNC_BIND_ADDRESS:
918
      (False, netutils.IP4Address.IsValid,
919
       "VNC bind address is not a valid IP address", None, None),
920
    constants.HV_KERNEL_PATH: hv_base.REQ_FILE_CHECK,
921
    constants.HV_DEVICE_MODEL: hv_base.REQ_FILE_CHECK,
922
    constants.HV_VNC_PASSWORD_FILE: hv_base.REQ_FILE_CHECK,
923
    constants.HV_MIGRATION_PORT: hv_base.REQ_NET_PORT_CHECK,
924
    constants.HV_MIGRATION_MODE: hv_base.MIGRATION_MODE_CHECK,
925
    constants.HV_USE_LOCALTIME: hv_base.NO_CHECK,
926
    # TODO: Add a check for the blockdev prefix (matching [a-z:] or similar).
927
    constants.HV_BLOCKDEV_PREFIX: hv_base.NO_CHECK,
928
    # Add PCI passthrough
929
    constants.HV_PASSTHROUGH: hv_base.NO_CHECK,
930
    constants.HV_REBOOT_BEHAVIOR:
931
      hv_base.ParamInSet(True, constants.REBOOT_BEHAVIORS),
932
    constants.HV_CPU_MASK: hv_base.OPT_MULTI_CPU_MASK_CHECK,
933
    constants.HV_CPU_CAP: hv_base.NO_CHECK,
934
    constants.HV_CPU_WEIGHT:
935
      (False, lambda x: 0 < x < 65535, "invalid weight", None, None),
936
    constants.HV_VIF_TYPE:
937
      hv_base.ParamInSet(False, constants.HT_HVM_VALID_VIF_TYPES),
938
    constants.HV_XEN_CMD:
939
      hv_base.ParamInSet(True, constants.KNOWN_XEN_COMMANDS),
940
    }
941

    
942
  def _GetConfig(self, instance, startup_memory, block_devices):
943
    """Create a Xen 3.1 HVM config file.
944

945
    """
946
    hvp = instance.hvparams
947

    
948
    config = StringIO()
949

    
950
    # kernel handling
951
    kpath = hvp[constants.HV_KERNEL_PATH]
952
    config.write("kernel = '%s'\n" % kpath)
953

    
954
    config.write("builder = 'hvm'\n")
955
    config.write("memory = %d\n" % startup_memory)
956
    config.write("maxmem = %d\n" % instance.beparams[constants.BE_MAXMEM])
957
    config.write("vcpus = %d\n" % instance.beparams[constants.BE_VCPUS])
958
    cpu_pinning = _CreateConfigCpus(hvp[constants.HV_CPU_MASK])
959
    if cpu_pinning:
960
      config.write("%s\n" % cpu_pinning)
961
    cpu_cap = hvp[constants.HV_CPU_CAP]
962
    if cpu_cap:
963
      config.write("cpu_cap=%d\n" % cpu_cap)
964
    cpu_weight = hvp[constants.HV_CPU_WEIGHT]
965
    if cpu_weight:
966
      config.write("cpu_weight=%d\n" % cpu_weight)
967

    
968
    config.write("name = '%s'\n" % instance.name)
969
    if hvp[constants.HV_PAE]:
970
      config.write("pae = 1\n")
971
    else:
972
      config.write("pae = 0\n")
973
    if hvp[constants.HV_ACPI]:
974
      config.write("acpi = 1\n")
975
    else:
976
      config.write("acpi = 0\n")
977
    config.write("apic = 1\n")
978
    config.write("device_model = '%s'\n" % hvp[constants.HV_DEVICE_MODEL])
979
    config.write("boot = '%s'\n" % hvp[constants.HV_BOOT_ORDER])
980
    config.write("sdl = 0\n")
981
    config.write("usb = 1\n")
982
    config.write("usbdevice = 'tablet'\n")
983
    config.write("vnc = 1\n")
984
    if hvp[constants.HV_VNC_BIND_ADDRESS] is None:
985
      config.write("vnclisten = '%s'\n" % constants.VNC_DEFAULT_BIND_ADDRESS)
986
    else:
987
      config.write("vnclisten = '%s'\n" % hvp[constants.HV_VNC_BIND_ADDRESS])
988

    
989
    if instance.network_port > constants.VNC_BASE_PORT:
990
      display = instance.network_port - constants.VNC_BASE_PORT
991
      config.write("vncdisplay = %s\n" % display)
992
      config.write("vncunused = 0\n")
993
    else:
994
      config.write("# vncdisplay = 1\n")
995
      config.write("vncunused = 1\n")
996

    
997
    vnc_pwd_file = hvp[constants.HV_VNC_PASSWORD_FILE]
998
    try:
999
      password = utils.ReadFile(vnc_pwd_file)
1000
    except EnvironmentError, err:
1001
      raise errors.HypervisorError("Failed to open VNC password file %s: %s" %
1002
                                   (vnc_pwd_file, err))
1003

    
1004
    config.write("vncpasswd = '%s'\n" % password.rstrip())
1005

    
1006
    config.write("serial = 'pty'\n")
1007
    if hvp[constants.HV_USE_LOCALTIME]:
1008
      config.write("localtime = 1\n")
1009

    
1010
    vif_data = []
1011
    # Note: what is called 'nic_type' here, is used as value for the xen nic
1012
    # vif config parameter 'model'. For the xen nic vif parameter 'type', we use
1013
    # the 'vif_type' to avoid a clash of notation.
1014
    nic_type = hvp[constants.HV_NIC_TYPE]
1015

    
1016
    if nic_type is None:
1017
      vif_type_str = ""
1018
      if hvp[constants.HV_VIF_TYPE]:
1019
        vif_type_str = ", type=%s" % hvp[constants.HV_VIF_TYPE]
1020
      # ensure old instances don't change
1021
      nic_type_str = vif_type_str
1022
    elif nic_type == constants.HT_NIC_PARAVIRTUAL:
1023
      nic_type_str = ", type=paravirtualized"
1024
    else:
1025
      # parameter 'model' is only valid with type 'ioemu'
1026
      nic_type_str = ", model=%s, type=%s" % \
1027
        (nic_type, constants.HT_HVM_VIF_IOEMU)
1028
    for nic in instance.nics:
1029
      nic_str = "mac=%s%s" % (nic.mac, nic_type_str)
1030
      ip = getattr(nic, "ip", None)
1031
      if ip is not None:
1032
        nic_str += ", ip=%s" % ip
1033
      if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1034
        nic_str += ", bridge=%s" % nic.nicparams[constants.NIC_LINK]
1035
      vif_data.append("'%s'" % nic_str)
1036

    
1037
    config.write("vif = [%s]\n" % ",".join(vif_data))
1038

    
1039
    disk_data = \
1040
      _GetConfigFileDiskData(block_devices, hvp[constants.HV_BLOCKDEV_PREFIX])
1041

    
1042
    iso_path = hvp[constants.HV_CDROM_IMAGE_PATH]
1043
    if iso_path:
1044
      iso = "'file:%s,hdc:cdrom,r'" % iso_path
1045
      disk_data.append(iso)
1046

    
1047
    config.write("disk = [%s]\n" % (",".join(disk_data)))
1048
    # Add PCI passthrough
1049
    pci_pass_arr = []
1050
    pci_pass = hvp[constants.HV_PASSTHROUGH]
1051
    if pci_pass:
1052
      pci_pass_arr = pci_pass.split(";")
1053
      config.write("pci = %s\n" % pci_pass_arr)
1054
    config.write("on_poweroff = 'destroy'\n")
1055
    if hvp[constants.HV_REBOOT_BEHAVIOR] == constants.INSTANCE_REBOOT_ALLOWED:
1056
      config.write("on_reboot = 'restart'\n")
1057
    else:
1058
      config.write("on_reboot = 'destroy'\n")
1059
    config.write("on_crash = 'restart'\n")
1060

    
1061
    return config.getvalue()