Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_fake.py @ 2a7e887b

History | View | Annotate | Download (6.9 kB)

1
#
2
#
3

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

24
"""
25

    
26
import os
27
import os.path
28
import re
29

    
30
from ganeti import utils
31
from ganeti import constants
32
from ganeti import errors
33
from ganeti.hypervisor import hv_base
34

    
35

    
36
class FakeHypervisor(hv_base.BaseHypervisor):
37
  """Fake hypervisor interface.
38

39
  This can be used for testing the ganeti code without having to have
40
  a real virtualisation software installed.
41

42
  """
43
  _ROOT_DIR = constants.RUN_DIR + "/ganeti-fake-hypervisor"
44

    
45
  def __init__(self):
46
    hv_base.BaseHypervisor.__init__(self)
47
    if not os.path.exists(self._ROOT_DIR):
48
      os.mkdir(self._ROOT_DIR)
49

    
50
  def ListInstances(self):
51
    """Get the list of running instances.
52

53
    """
54
    return os.listdir(self._ROOT_DIR)
55

    
56
  def GetInstanceInfo(self, instance_name):
57
    """Get instance properties.
58

59
    @param instance_name: the instance name
60

61
    @return: tuple of (name, id, memory, vcpus, stat, times)
62

63
    """
64
    file_name = "%s/%s" % (self._ROOT_DIR, instance_name)
65
    if not os.path.exists(file_name):
66
      return None
67
    try:
68
      fh = open(file_name, "r")
69
      try:
70
        inst_id = fh.readline().strip()
71
        memory = utils.TryConvert(int, fh.readline().strip())
72
        vcpus = utils.TryConvert(fh.readline().strip())
73
        stat = "---b-"
74
        times = "0"
75
        return (instance_name, inst_id, memory, vcpus, stat, times)
76
      finally:
77
        fh.close()
78
    except IOError, err:
79
      raise errors.HypervisorError("Failed to list instance %s: %s" %
80
                                   (instance_name, err))
81

    
82
  def GetAllInstancesInfo(self):
83
    """Get properties of all instances.
84

85
    @return: list of tuples (name, id, memory, vcpus, stat, times)
86

87
    """
88
    data = []
89
    for file_name in os.listdir(self._ROOT_DIR):
90
      try:
91
        fh = open(self._ROOT_DIR+"/"+file_name, "r")
92
        inst_id = "-1"
93
        memory = 0
94
        vcpus = 1
95
        stat = "-----"
96
        times = "-1"
97
        try:
98
          inst_id = fh.readline().strip()
99
          memory = utils.TryConvert(int, fh.readline().strip())
100
          vcpus = utils.TryConvert(int, fh.readline().strip())
101
          stat = "---b-"
102
          times = "0"
103
        finally:
104
          fh.close()
105
        data.append((file_name, inst_id, memory, vcpus, stat, times))
106
      except IOError, err:
107
        raise errors.HypervisorError("Failed to list instances: %s" % err)
108
    return data
109

    
110
  def StartInstance(self, instance, block_devices):
111
    """Start an instance.
112

113
    For the fake hypervisor, it just creates a file in the base dir,
114
    creating an exception if it already exists. We don't actually
115
    handle race conditions properly, since these are *FAKE* instances.
116

117
    """
118
    file_name = self._ROOT_DIR + "/%s" % instance.name
119
    if os.path.exists(file_name):
120
      raise errors.HypervisorError("Failed to start instance %s: %s" %
121
                                   (instance.name, "already running"))
122
    try:
123
      fh = file(file_name, "w")
124
      try:
125
        fh.write("0\n%d\n%d\n" %
126
                 (instance.beparams[constants.BE_MEMORY],
127
                  instance.beparams[constants.BE_VCPUS]))
128
      finally:
129
        fh.close()
130
    except IOError, err:
131
      raise errors.HypervisorError("Failed to start instance %s: %s" %
132
                                   (instance.name, err))
133

    
134
  def StopInstance(self, instance, force=False):
135
    """Stop an instance.
136

137
    For the fake hypervisor, this just removes the file in the base
138
    dir, if it exist, otherwise we raise an exception.
139

140
    """
141
    file_name = self._ROOT_DIR + "/%s" % instance.name
142
    if not os.path.exists(file_name):
143
      raise errors.HypervisorError("Failed to stop instance %s: %s" %
144
                                   (instance.name, "not running"))
145
    utils.RemoveFile(file_name)
146

    
147
  def RebootInstance(self, instance):
148
    """Reboot an instance.
149

150
    For the fake hypervisor, this does nothing.
151

152
    """
153
    return
154

    
155
  def GetNodeInfo(self):
156
    """Return information about the node.
157

158
    @return: a dict with the following keys (values in MiB):
159
          - memory_total: the total memory size on the node
160
          - memory_free: the available memory on the node for instances
161
          - memory_dom0: the memory used by the node itself, if available
162

163
    """
164
    # global ram usage from the xm info command
165
    # memory                 : 3583
166
    # free_memory            : 747
167
    # note: in xen 3, memory has changed to total_memory
168
    try:
169
      fh = file("/proc/meminfo")
170
      try:
171
        data = fh.readlines()
172
      finally:
173
        fh.close()
174
    except IOError, err:
175
      raise errors.HypervisorError("Failed to list node info: %s" % err)
176

    
177
    result = {}
178
    sum_free = 0
179
    for line in data:
180
      splitfields = line.split(":", 1)
181

    
182
      if len(splitfields) > 1:
183
        key = splitfields[0].strip()
184
        val = splitfields[1].strip()
185
        if key == 'MemTotal':
186
          result['memory_total'] = int(val.split()[0])/1024
187
        elif key in ('MemFree', 'Buffers', 'Cached'):
188
          sum_free += int(val.split()[0])/1024
189
        elif key == 'Active':
190
          result['memory_dom0'] = int(val.split()[0])/1024
191
    result['memory_free'] = sum_free
192

    
193
    # substract running instances
194
    all_instances = self.GetAllInstancesInfo()
195
    result['memory_free'] -= min(result['memory_free'],
196
                                 sum([row[2] for row in all_instances]))
197

    
198
    cpu_total = 0
199
    try:
200
      fh = open("/proc/cpuinfo")
201
      try:
202
        cpu_total = len(re.findall("(?m)^processor\s*:\s*[0-9]+\s*$",
203
                                   fh.read()))
204
      finally:
205
        fh.close()
206
    except EnvironmentError, err:
207
      raise errors.HypervisorError("Failed to list node info: %s" % err)
208
    result['cpu_total'] = cpu_total
209
    # FIXME: export correct data here
210
    result['cpu_nodes'] = 1
211
    result['cpu_sockets'] = 1
212

    
213
    return result
214

    
215
  @classmethod
216
  def GetShellCommandForConsole(cls, instance, hvparams, beparams):
217
    """Return a command for connecting to the console of an instance.
218

219
    """
220
    return "echo Console not available for fake hypervisor"
221

    
222
  def Verify(self):
223
    """Verify the hypervisor.
224

225
    For the fake hypervisor, it just checks the existence of the base
226
    dir.
227

228
    """
229
    if not os.path.exists(self._ROOT_DIR):
230
      return "The required directory '%s' does not exist." % self._ROOT_DIR