hv_fake.py 6.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#
#

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


"""Fake hypervisor

"""

import os
import os.path
28
import re
29
30
31
32

from ganeti import utils
from ganeti import constants
from ganeti import errors
33
from ganeti.hypervisor import hv_base
34
35


36
class FakeHypervisor(hv_base.BaseHypervisor):
37
38
39
40
41
42
43
44
45
  """Fake hypervisor interface.

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

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

  def __init__(self):
46
    hv_base.BaseHypervisor.__init__(self)
47
48
49
50
51
52
53
54
55
56
57
58
    if not os.path.exists(self._ROOT_DIR):
      os.mkdir(self._ROOT_DIR)

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

    """
    return os.listdir(self._ROOT_DIR)

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

Iustin Pop's avatar
Iustin Pop committed
59
60
61
    @param instance_name: the instance name

    @return: tuple of (name, id, memory, vcpus, stat, times)
62
63
64
65
66
67

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

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

Iustin Pop's avatar
Iustin Pop committed
85
86
    @return: list of tuples (name, id, memory, vcpus, stat, times)

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

110
  def StartInstance(self, instance, block_devices, extra_args):
111
112
113
114
115
116
117
118
119
120
121
122
123
124
    """Start an instance.

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

    """
    file_name = self._ROOT_DIR + "/%s" % instance.name
    if os.path.exists(file_name):
      raise errors.HypervisorError("Failed to start instance %s: %s" %
                                   (instance.name, "already running"))
    try:
      fh = file(file_name, "w")
      try:
125
126
127
        fh.write("0\n%d\n%d\n" %
                 (instance.beparams[constants.BE_MEMORY],
                  instance.beparams[constants.BE_VCPUS]))
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
      finally:
        fh.close()
    except IOError, err:
      raise errors.HypervisorError("Failed to start instance %s: %s" %
                                   (instance.name, err))

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

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

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

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

    For the fake hypervisor, this does nothing.

    """
    return

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

Iustin Pop's avatar
Iustin Pop committed
158
159
160
161
    @return: a dict with the following keys (values in MiB):
          - memory_total: the total memory size on the node
          - memory_free: the available memory on the node for instances
          - memory_dom0: the memory used by the node itself, if available
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

    """
    # global ram usage from the xm info command
    # memory                 : 3583
    # free_memory            : 747
    # note: in xen 3, memory has changed to total_memory
    try:
      fh = file("/proc/meminfo")
      try:
        data = fh.readlines()
      finally:
        fh.close()
    except IOError, err:
      raise errors.HypervisorError("Failed to list node info: %s" % err)

    result = {}
    sum_free = 0
    for line in data:
      splitfields = line.split(":", 1)

      if len(splitfields) > 1:
        key = splitfields[0].strip()
        val = splitfields[1].strip()
        if key == 'MemTotal':
          result['memory_total'] = int(val.split()[0])/1024
        elif key in ('MemFree', 'Buffers', 'Cached'):
          sum_free += int(val.split()[0])/1024
        elif key == 'Active':
          result['memory_dom0'] = int(val.split()[0])/1024
    result['memory_free'] = sum_free
192

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

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

213
214
    return result

215
  @classmethod
216
  def GetShellCommandForConsole(cls, instance, hvparams, beparams):
217
218
219
220
221
222
223
224
225
226
227
228
229
230
    """Return a command for connecting to the console of an instance.

    """
    return "echo Console not available for fake hypervisor"

  def Verify(self):
    """Verify the hypervisor.

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

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