Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_chroot.py @ 0bbec3af

History | View | Annotate | Download (10.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009 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
"""Chroot manager hypervisor
23

24
"""
25

    
26
import os
27
import os.path
28
import time
29
import logging
30

    
31
from ganeti import constants
32
from ganeti import errors # pylint: disable=W0611
33
from ganeti import utils
34
from ganeti import objects
35
from ganeti import pathutils
36
from ganeti.hypervisor import hv_base
37
from ganeti.errors import HypervisorError
38

    
39

    
40
class ChrootManager(hv_base.BaseHypervisor):
41
  """Chroot manager.
42

43
  This not-really hypervisor allows ganeti to manage chroots. It has
44
  special behaviour and requirements on the OS definition and the node
45
  environemnt:
46
    - the start and stop of the chroot environment are done via a
47
      script called ganeti-chroot located in the root directory of the
48
      first drive, which should be created by the OS definition
49
    - this script must accept the start and stop argument and, on
50
      shutdown, it should cleanly shutdown the daemons/processes
51
      using the chroot
52
    - the daemons run in chroot should only bind to the instance IP
53
      (to which the OS create script has access via the instance name)
54
    - since some daemons in the node could be listening on the wildcard
55
      address, some ports might be unavailable
56
    - the instance listing will show no memory usage
57
    - on shutdown, the chroot manager will try to find all mountpoints
58
      under the root dir of the instance and unmount them
59
    - instance alive check is based on whether any process is using the chroot
60

61
  """
62
  _ROOT_DIR = pathutils.RUN_DIR + "/chroot-hypervisor"
63

    
64
  PARAMETERS = {
65
    constants.HV_INIT_SCRIPT: (True, utils.IsNormAbsPath,
66
                               "must be an absolute normalized path",
67
                               None, None),
68
    }
69

    
70
  def __init__(self):
71
    hv_base.BaseHypervisor.__init__(self)
72
    utils.EnsureDirs([(self._ROOT_DIR, constants.RUN_DIRS_MODE)])
73

    
74
  @staticmethod
75
  def _IsDirLive(path):
76
    """Check if a directory looks like a live chroot.
77

78
    """
79
    if not os.path.ismount(path):
80
      return False
81
    result = utils.RunCmd(["fuser", "-m", path])
82
    return not result.failed
83

    
84
  @staticmethod
85
  def _GetMountSubdirs(path):
86
    """Return the list of mountpoints under a given path.
87

88
    """
89
    result = []
90
    for _, mountpoint, _, _ in utils.GetMounts():
91
      if (mountpoint.startswith(path) and
92
          mountpoint != path):
93
        result.append(mountpoint)
94

    
95
    result.sort(key=lambda x: x.count("/"), reverse=True)
96
    return result
97

    
98
  @classmethod
99
  def _InstanceDir(cls, instance_name):
100
    """Return the root directory for an instance.
101

102
    """
103
    return utils.PathJoin(cls._ROOT_DIR, instance_name)
104

    
105
  def ListInstances(self, hvparams=None):
106
    """Get the list of running instances.
107

108
    """
109
    return [name for name in os.listdir(self._ROOT_DIR)
110
            if self._IsDirLive(utils.PathJoin(self._ROOT_DIR, name))]
111

    
112
  def GetInstanceInfo(self, instance_name, hvparams=None):
113
    """Get instance properties.
114

115
    @type instance_name: string
116
    @param instance_name: the instance name
117
    @type hvparams: dict of strings
118
    @param hvparams: hvparams to be used with this instance
119

120
    @return: (name, id, memory, vcpus, stat, times)
121

122
    """
123
    dir_name = self._InstanceDir(instance_name)
124
    if not self._IsDirLive(dir_name):
125
      raise HypervisorError("Instance %s is not running" % instance_name)
126
    return (instance_name, 0, 0, 0, 0, 0)
127

    
128
  def GetAllInstancesInfo(self):
129
    """Get properties of all instances.
130

131
    @return: [(name, id, memory, vcpus, stat, times),...]
132

133
    """
134
    data = []
135
    for file_name in os.listdir(self._ROOT_DIR):
136
      path = utils.PathJoin(self._ROOT_DIR, file_name)
137
      if self._IsDirLive(path):
138
        data.append((file_name, 0, 0, 0, 0, 0))
139
    return data
140

    
141
  def StartInstance(self, instance, block_devices, startup_paused):
142
    """Start an instance.
143

144
    For the chroot manager, we try to mount the block device and
145
    execute '/ganeti-chroot start'.
146

147
    """
148
    root_dir = self._InstanceDir(instance.name)
149
    if not os.path.exists(root_dir):
150
      try:
151
        os.mkdir(root_dir)
152
      except IOError, err:
153
        raise HypervisorError("Failed to start instance %s: %s" %
154
                              (instance.name, err))
155
      if not os.path.isdir(root_dir):
156
        raise HypervisorError("Needed path %s is not a directory" % root_dir)
157

    
158
    if not os.path.ismount(root_dir):
159
      if not block_devices:
160
        raise HypervisorError("The chroot manager needs at least one disk")
161

    
162
      sda_dev_path = block_devices[0][1]
163
      result = utils.RunCmd(["mount", sda_dev_path, root_dir])
164
      if result.failed:
165
        raise HypervisorError("Can't mount the chroot dir: %s" % result.output)
166
    init_script = instance.hvparams[constants.HV_INIT_SCRIPT]
167
    result = utils.RunCmd(["chroot", root_dir, init_script, "start"])
168
    if result.failed:
169
      raise HypervisorError("Can't run the chroot start script: %s" %
170
                            result.output)
171

    
172
  def StopInstance(self, instance, force=False, retry=False, name=None):
173
    """Stop an instance.
174

175
    This method has complicated cleanup tests, as we must:
176
      - try to kill all leftover processes
177
      - try to unmount any additional sub-mountpoints
178
      - finally unmount the instance dir
179

180
    """
181
    if name is None:
182
      name = instance.name
183

    
184
    root_dir = self._InstanceDir(name)
185
    if not os.path.exists(root_dir) or not self._IsDirLive(root_dir):
186
      return
187

    
188
    # Run the chroot stop script only once
189
    if not retry and not force:
190
      result = utils.RunCmd(["chroot", root_dir, "/ganeti-chroot", "stop"])
191
      if result.failed:
192
        raise HypervisorError("Can't run the chroot stop script: %s" %
193
                              result.output)
194

    
195
    if not force:
196
      utils.RunCmd(["fuser", "-k", "-TERM", "-m", root_dir])
197
    else:
198
      utils.RunCmd(["fuser", "-k", "-KILL", "-m", root_dir])
199
      # 2 seconds at most should be enough for KILL to take action
200
      time.sleep(2)
201

    
202
    if self._IsDirLive(root_dir):
203
      if force:
204
        raise HypervisorError("Can't stop the processes using the chroot")
205
      return
206

    
207
  def CleanupInstance(self, instance_name):
208
    """Cleanup after a stopped instance
209

210
    """
211
    root_dir = self._InstanceDir(instance_name)
212

    
213
    if not os.path.exists(root_dir):
214
      return
215

    
216
    if self._IsDirLive(root_dir):
217
      raise HypervisorError("Processes are still using the chroot")
218

    
219
    for mpath in self._GetMountSubdirs(root_dir):
220
      utils.RunCmd(["umount", mpath])
221

    
222
    result = utils.RunCmd(["umount", root_dir])
223
    if result.failed:
224
      msg = ("Processes still alive in the chroot: %s" %
225
             utils.RunCmd("fuser -vm %s" % root_dir).output)
226
      logging.error(msg)
227
      raise HypervisorError("Can't umount the chroot dir: %s (%s)" %
228
                            (result.output, msg))
229

    
230
  def RebootInstance(self, instance):
231
    """Reboot an instance.
232

233
    This is not (yet) implemented for the chroot manager.
234

235
    """
236
    raise HypervisorError("The chroot manager doesn't implement the"
237
                          " reboot functionality")
238

    
239
  def BalloonInstanceMemory(self, instance, mem):
240
    """Balloon an instance memory to a certain value.
241

242
    @type instance: L{objects.Instance}
243
    @param instance: instance to be accepted
244
    @type mem: int
245
    @param mem: actual memory size to use for instance runtime
246

247
    """
248
    # Currently chroots don't have memory limits
249
    pass
250

    
251
  def GetNodeInfo(self, hvparams=None):
252
    """Return information about the node.
253

254
    This is just a wrapper over the base GetLinuxNodeInfo method.
255

256
    @type hvparams: dict of strings
257
    @param hvparams: hypervisor parameters, not used in this class
258

259
    @return: a dict with the following keys (values in MiB):
260
          - memory_total: the total memory size on the node
261
          - memory_free: the available memory on the node for instances
262
          - memory_dom0: the memory used by the node itself, if available
263

264
    """
265
    return self.GetLinuxNodeInfo()
266

    
267
  @classmethod
268
  def GetInstanceConsole(cls, instance, # pylint: disable=W0221
269
                         hvparams, beparams, root_dir=None):
270
    """Return information for connecting to the console of an instance.
271

272
    """
273
    if root_dir is None:
274
      root_dir = cls._InstanceDir(instance.name)
275
      if not os.path.ismount(root_dir):
276
        raise HypervisorError("Instance %s is not running" % instance.name)
277

    
278
    return objects.InstanceConsole(instance=instance.name,
279
                                   kind=constants.CONS_SSH,
280
                                   host=instance.primary_node,
281
                                   user=constants.SSH_CONSOLE_USER,
282
                                   command=["chroot", root_dir])
283

    
284
  def Verify(self, hvparams=None):
285
    """Verify the hypervisor.
286

287
    For the chroot manager, it just checks the existence of the base dir.
288

289
    @type hvparams: dict of strings
290
    @param hvparams: hypervisor parameters to be verified against, not used
291
      in for chroot
292

293
    @return: Problem description if something is wrong, C{None} otherwise
294

295
    """
296
    if os.path.exists(self._ROOT_DIR):
297
      return None
298
    else:
299
      return "The required directory '%s' does not exist" % self._ROOT_DIR
300

    
301
  @classmethod
302
  def PowercycleNode(cls):
303
    """Chroot powercycle, just a wrapper over Linux powercycle.
304

305
    """
306
    cls.LinuxPowercycle()
307

    
308
  def MigrateInstance(self, instance, target, live):
309
    """Migrate an instance.
310

311
    @type instance: L{objects.Instance}
312
    @param instance: the instance to be migrated
313
    @type target: string
314
    @param target: hostname (usually ip) of the target node
315
    @type live: boolean
316
    @param live: whether to do a live or non-live migration
317

318
    """
319
    raise HypervisorError("Migration not supported by the chroot hypervisor")
320

    
321
  def GetMigrationStatus(self, instance):
322
    """Get the migration status
323

324
    @type instance: L{objects.Instance}
325
    @param instance: the instance that is being migrated
326
    @rtype: L{objects.MigrationStatus}
327
    @return: the status of the current migration (one of
328
             L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
329
             progress info that can be retrieved from the hypervisor
330

331
    """
332
    raise HypervisorError("Migration not supported by the chroot hypervisor")