Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_chroot.py @ db169865

History | View | Annotate | Download (8.9 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-msg=W0611
33
from ganeti import utils
34
from ganeti.hypervisor import hv_base
35
from ganeti.errors import HypervisorError
36

    
37

    
38
class ChrootManager(hv_base.BaseHypervisor):
39
  """Chroot manager.
40

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

59
  """
60
  _ROOT_DIR = constants.RUN_GANETI_DIR + "/chroot-hypervisor"
61

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

    
68
  def __init__(self):
69
    hv_base.BaseHypervisor.__init__(self)
70
    if not os.path.exists(self._ROOT_DIR):
71
      os.mkdir(self._ROOT_DIR)
72
    if not os.path.isdir(self._ROOT_DIR):
73
      raise HypervisorError("Needed path %s is not a directory" %
74
                            self._ROOT_DIR)
75

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

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

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

90
    This function is Linux-specific.
91

92
    """
93
    #TODO(iustin): investigate and document non-linux options
94
    #(e.g. via mount output)
95
    data = []
96
    fh = open("/proc/mounts", "r")
97
    try:
98
      for line in fh:
99
        _, mountpoint, _ = line.split(" ", 2)
100
        if (mountpoint.startswith(path) and
101
            mountpoint != path):
102
          data.append(mountpoint)
103
    finally:
104
      fh.close()
105
    data.sort(key=lambda x: x.count("/"), reverse=True)
106
    return data
107

    
108
  def ListInstances(self):
109
    """Get the list of running instances.
110

111
    """
112
    return [name for name in os.listdir(self._ROOT_DIR)
113
            if self._IsDirLive(os.path.join(self._ROOT_DIR, name))]
114

    
115
  def GetInstanceInfo(self, instance_name):
116
    """Get instance properties.
117

118
    @type instance_name: string
119
    @param instance_name: the instance name
120

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

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

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

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

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

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

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

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

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

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

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

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

181
    """
182
    root_dir = "%s/%s" % (self._ROOT_DIR, instance.name)
183
    if not os.path.exists(root_dir) or not self._IsDirLive(root_dir):
184
      return
185

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

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

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

    
205
    for mpath in self._GetMountSubdirs(root_dir):
206
      utils.RunCmd(["umount", mpath])
207

    
208
    result = utils.RunCmd(["umount", root_dir])
209
    if result.failed and force:
210
      msg = ("Processes still alive in the chroot: %s" %
211
             utils.RunCmd("fuser -vm %s" % root_dir).output)
212
      logging.error(msg)
213
      raise HypervisorError("Can't umount the chroot dir: %s (%s)" %
214
                            (result.output, msg))
215

    
216
  def RebootInstance(self, instance):
217
    """Reboot an instance.
218

219
    This is not (yet) implemented for the chroot manager.
220

221
    """
222
    raise HypervisorError("The chroot manager doesn't implement the"
223
                          " reboot functionality")
224

    
225
  def GetNodeInfo(self):
226
    """Return information about the node.
227

228
    This is just a wrapper over the base GetLinuxNodeInfo method.
229

230
    @return: a dict with the following keys (values in MiB):
231
          - memory_total: the total memory size on the node
232
          - memory_free: the available memory on the node for instances
233
          - memory_dom0: the memory used by the node itself, if available
234

235
    """
236
    return self.GetLinuxNodeInfo()
237

    
238
  @classmethod
239
  def GetShellCommandForConsole(cls, instance, hvparams, beparams):
240
    """Return a command for connecting to the console of an instance.
241

242
    """
243
    root_dir = "%s/%s" % (cls._ROOT_DIR, instance.name)
244
    if not os.path.ismount(root_dir):
245
      raise HypervisorError("Instance %s is not running" % instance.name)
246

    
247
    return "chroot %s" % root_dir
248

    
249
  def Verify(self):
250
    """Verify the hypervisor.
251

252
    For the chroot manager, it just checks the existence of the base dir.
253

254
    """
255
    if not os.path.exists(self._ROOT_DIR):
256
      return "The required directory '%s' does not exist." % self._ROOT_DIR
257

    
258
  @classmethod
259
  def PowercycleNode(cls):
260
    """Chroot powercycle, just a wrapper over Linux powercycle.
261

262
    """
263
    cls.LinuxPowercycle()
264

    
265
  def MigrateInstance(self, instance, target, live):
266
    """Migrate an instance.
267

268
    @type instance: L{object.Instance}
269
    @param instance: the instance to be migrated
270
    @type target: string
271
    @param target: hostname (usually ip) of the target node
272
    @type live: boolean
273
    @param live: whether to do a live or non-live migration
274

275
    """
276
    raise HypervisorError("Migration not supported by the chroot hypervisor")