Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_base.py @ af89fa76

History | View | Annotate | Download (16.8 kB)

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

24 205ab586 Iustin Pop
The syntax for the _CHECK variables and the contents of the PARAMETERS
25 205ab586 Iustin Pop
dict is the same, see the docstring for L{BaseHypervisor.PARAMETERS}.
26 205ab586 Iustin Pop

27 205ab586 Iustin Pop
@var _FILE_CHECK: stub for file checks, without the required flag
28 205ab586 Iustin Pop
@var _DIR_CHECK: stub for directory checks, without the required flag
29 205ab586 Iustin Pop
@var REQ_FILE_CHECK: mandatory file parameter
30 205ab586 Iustin Pop
@var OPT_FILE_CHECK: optional file parameter
31 205ab586 Iustin Pop
@var REQ_DIR_CHECK: mandatory directory parametr
32 205ab586 Iustin Pop
@var OPT_DIR_CHECK: optional directory parameter
33 205ab586 Iustin Pop
@var NO_CHECK: parameter without any checks at all
34 205ab586 Iustin Pop
@var REQUIRED_CHECK: parameter required to exist (and non-false), but
35 205ab586 Iustin Pop
    without other checks; beware that this can't be used for boolean
36 205ab586 Iustin Pop
    parameters, where you should use NO_CHECK or a custom checker
37 205ab586 Iustin Pop

38 65a6f9b7 Michael Hanselmann
"""
39 65a6f9b7 Michael Hanselmann
40 205ab586 Iustin Pop
import os
41 572e52bf Iustin Pop
import re
42 29921401 Iustin Pop
import logging
43 572e52bf Iustin Pop
44 572e52bf Iustin Pop
45 f48148c3 Iustin Pop
from ganeti import errors
46 205ab586 Iustin Pop
from ganeti import utils
47 e71b9ef4 Iustin Pop
from ganeti import constants
48 205ab586 Iustin Pop
49 205ab586 Iustin Pop
50 e3ed5316 Balazs Lecz
def _IsCpuMaskWellFormed(cpu_mask):
51 b9511385 Tsachy Shacham
  """Verifies if the given single CPU mask is valid
52 b9511385 Tsachy Shacham

53 b9511385 Tsachy Shacham
  The single CPU mask should be in the form "a,b,c,d", where each
54 b9511385 Tsachy Shacham
  letter is a positive number or range.
55 b9511385 Tsachy Shacham

56 b9511385 Tsachy Shacham
  """
57 e3ed5316 Balazs Lecz
  try:
58 e3ed5316 Balazs Lecz
    cpu_list = utils.ParseCpuMask(cpu_mask)
59 e3ed5316 Balazs Lecz
  except errors.ParseError, _:
60 e3ed5316 Balazs Lecz
    return False
61 e3ed5316 Balazs Lecz
  return isinstance(cpu_list, list) and len(cpu_list) > 0
62 e3ed5316 Balazs Lecz
63 e3ed5316 Balazs Lecz
64 b9511385 Tsachy Shacham
def _IsMultiCpuMaskWellFormed(cpu_mask):
65 b9511385 Tsachy Shacham
  """Verifies if the given multiple CPU mask is valid
66 b9511385 Tsachy Shacham

67 b9511385 Tsachy Shacham
  A valid multiple CPU mask is in the form "a:b:c:d", where each
68 b9511385 Tsachy Shacham
  letter is a single CPU mask.
69 b9511385 Tsachy Shacham

70 b9511385 Tsachy Shacham
  """
71 b9511385 Tsachy Shacham
  try:
72 b9511385 Tsachy Shacham
    utils.ParseMultiCpuMask(cpu_mask)
73 b9511385 Tsachy Shacham
  except errors.ParseError, _:
74 b9511385 Tsachy Shacham
    return False
75 b9511385 Tsachy Shacham
76 b9511385 Tsachy Shacham
  return True
77 b9511385 Tsachy Shacham
78 b9511385 Tsachy Shacham
79 205ab586 Iustin Pop
# Read the BaseHypervisor.PARAMETERS docstring for the syntax of the
80 205ab586 Iustin Pop
# _CHECK values
81 205ab586 Iustin Pop
82 205ab586 Iustin Pop
# must be afile
83 17c61836 Guido Trotter
_FILE_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
84 5ae4945a Iustin Pop
               os.path.isfile, "not found or not a file")
85 205ab586 Iustin Pop
86 205ab586 Iustin Pop
# must be a directory
87 17c61836 Guido Trotter
_DIR_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
88 5ae4945a Iustin Pop
              os.path.isdir, "not found or not a directory")
89 205ab586 Iustin Pop
90 e3ed5316 Balazs Lecz
# CPU mask must be well-formed
91 e3ed5316 Balazs Lecz
# TODO: implement node level check for the CPU mask
92 e3ed5316 Balazs Lecz
_CPU_MASK_CHECK = (_IsCpuMaskWellFormed,
93 e3ed5316 Balazs Lecz
                   "CPU mask definition is not well-formed",
94 e3ed5316 Balazs Lecz
                   None, None)
95 e3ed5316 Balazs Lecz
96 b9511385 Tsachy Shacham
# Multiple CPU mask must be well-formed
97 b9511385 Tsachy Shacham
_MULTI_CPU_MASK_CHECK = (_IsMultiCpuMaskWellFormed,
98 b9511385 Tsachy Shacham
                         "Multiple CPU mask definition is not well-formed",
99 b9511385 Tsachy Shacham
                         None, None)
100 b9511385 Tsachy Shacham
101 e2d14329 Andrea Spadaccini
# Check for validity of port number
102 e2d14329 Andrea Spadaccini
_NET_PORT_CHECK = (lambda x: 0 < x < 65535, "invalid port number",
103 e2d14329 Andrea Spadaccini
                   None, None)
104 e2d14329 Andrea Spadaccini
105 2c368f28 Guido Trotter
# Check that an integer is non negative
106 2c368f28 Guido Trotter
_NONNEGATIVE_INT_CHECK = (lambda x: x >= 0, "cannot be negative", None, None)
107 2c368f28 Guido Trotter
108 205ab586 Iustin Pop
# nice wrappers for users
109 205ab586 Iustin Pop
REQ_FILE_CHECK = (True, ) + _FILE_CHECK
110 205ab586 Iustin Pop
OPT_FILE_CHECK = (False, ) + _FILE_CHECK
111 205ab586 Iustin Pop
REQ_DIR_CHECK = (True, ) + _DIR_CHECK
112 205ab586 Iustin Pop
OPT_DIR_CHECK = (False, ) + _DIR_CHECK
113 e2d14329 Andrea Spadaccini
REQ_NET_PORT_CHECK = (True, ) + _NET_PORT_CHECK
114 e2d14329 Andrea Spadaccini
OPT_NET_PORT_CHECK = (False, ) + _NET_PORT_CHECK
115 e3ed5316 Balazs Lecz
REQ_CPU_MASK_CHECK = (True, ) + _CPU_MASK_CHECK
116 e2d14329 Andrea Spadaccini
OPT_CPU_MASK_CHECK = (False, ) + _CPU_MASK_CHECK
117 b9511385 Tsachy Shacham
REQ_MULTI_CPU_MASK_CHECK = (True, ) + _MULTI_CPU_MASK_CHECK
118 b9511385 Tsachy Shacham
OPT_MULTI_CPU_MASK_CHECK = (False, ) + _MULTI_CPU_MASK_CHECK
119 2c368f28 Guido Trotter
REQ_NONNEGATIVE_INT_CHECK = (True, ) + _NONNEGATIVE_INT_CHECK
120 2c368f28 Guido Trotter
OPT_NONNEGATIVE_INT_CHECK = (False, ) + _NONNEGATIVE_INT_CHECK
121 205ab586 Iustin Pop
122 205ab586 Iustin Pop
# no checks at all
123 205ab586 Iustin Pop
NO_CHECK = (False, None, None, None, None)
124 205ab586 Iustin Pop
125 205ab586 Iustin Pop
# required, but no other checks
126 205ab586 Iustin Pop
REQUIRED_CHECK = (True, None, None, None, None)
127 205ab586 Iustin Pop
128 e71b9ef4 Iustin Pop
# migration type
129 783a6c0b Iustin Pop
MIGRATION_MODE_CHECK = (True, lambda x: x in constants.HT_MIGRATION_MODES,
130 783a6c0b Iustin Pop
                        "invalid migration mode", None, None)
131 e71b9ef4 Iustin Pop
132 d73ef63f Michael Hanselmann
133 205ab586 Iustin Pop
def ParamInSet(required, my_set):
134 205ab586 Iustin Pop
  """Builds parameter checker for set membership.
135 205ab586 Iustin Pop

136 205ab586 Iustin Pop
  @type required: boolean
137 205ab586 Iustin Pop
  @param required: whether this is a required parameter
138 205ab586 Iustin Pop
  @type my_set: tuple, list or set
139 205ab586 Iustin Pop
  @param my_set: allowed values set
140 205ab586 Iustin Pop

141 205ab586 Iustin Pop
  """
142 205ab586 Iustin Pop
  fn = lambda x: x in my_set
143 ab3e6da8 Iustin Pop
  err = ("The value must be one of: %s" % utils.CommaJoin(my_set))
144 205ab586 Iustin Pop
  return (required, fn, err, None, None)
145 f48148c3 Iustin Pop
146 f48148c3 Iustin Pop
147 65a6f9b7 Michael Hanselmann
class BaseHypervisor(object):
148 65a6f9b7 Michael Hanselmann
  """Abstract virtualisation technology interface
149 65a6f9b7 Michael Hanselmann

150 f48148c3 Iustin Pop
  The goal is that all aspects of the virtualisation technology are
151 f48148c3 Iustin Pop
  abstracted away from the rest of code.
152 65a6f9b7 Michael Hanselmann

153 205ab586 Iustin Pop
  @cvar PARAMETERS: a dict of parameter name: check type; the check type is
154 205ab586 Iustin Pop
      a five-tuple containing:
155 205ab586 Iustin Pop
          - the required flag (boolean)
156 205ab586 Iustin Pop
          - a function to check for syntax, that will be used in
157 205ab586 Iustin Pop
            L{CheckParameterSyntax}, in the master daemon process
158 205ab586 Iustin Pop
          - an error message for the above function
159 205ab586 Iustin Pop
          - a function to check for parameter validity on the remote node,
160 205ab586 Iustin Pop
            in the L{ValidateParameters} function
161 205ab586 Iustin Pop
          - an error message for the above function
162 d271c6fd Iustin Pop
  @type CAN_MIGRATE: boolean
163 d271c6fd Iustin Pop
  @cvar CAN_MIGRATE: whether this hypervisor can do migration (either
164 d271c6fd Iustin Pop
      live or non-live)
165 205ab586 Iustin Pop

166 65a6f9b7 Michael Hanselmann
  """
167 205ab586 Iustin Pop
  PARAMETERS = {}
168 e1b8653f Guido Trotter
  ANCILLARY_FILES = []
169 69ab2e12 Guido Trotter
  ANCILLARY_FILES_OPT = []
170 d271c6fd Iustin Pop
  CAN_MIGRATE = False
171 f48148c3 Iustin Pop
172 65a6f9b7 Michael Hanselmann
  def __init__(self):
173 65a6f9b7 Michael Hanselmann
    pass
174 65a6f9b7 Michael Hanselmann
175 323f9095 Stephen Shirley
  def StartInstance(self, instance, block_devices, startup_paused):
176 65a6f9b7 Michael Hanselmann
    """Start an instance."""
177 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
178 65a6f9b7 Michael Hanselmann
179 bbcf7ad0 Iustin Pop
  def StopInstance(self, instance, force=False, retry=False, name=None):
180 07b49e41 Guido Trotter
    """Stop an instance
181 07b49e41 Guido Trotter

182 07b49e41 Guido Trotter
    @type instance: L{objects.Instance}
183 07b49e41 Guido Trotter
    @param instance: instance to stop
184 07b49e41 Guido Trotter
    @type force: boolean
185 07b49e41 Guido Trotter
    @param force: whether to do a "hard" stop (destroy)
186 07b49e41 Guido Trotter
    @type retry: boolean
187 07b49e41 Guido Trotter
    @param retry: whether this is just a retry call
188 bbcf7ad0 Iustin Pop
    @type name: string or None
189 bbcf7ad0 Iustin Pop
    @param name: if this parameter is passed, the the instance object
190 bbcf7ad0 Iustin Pop
        should not be used (will be passed as None), and the shutdown
191 bbcf7ad0 Iustin Pop
        must be done by name only
192 07b49e41 Guido Trotter

193 07b49e41 Guido Trotter
    """
194 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
195 65a6f9b7 Michael Hanselmann
196 f28ec899 Guido Trotter
  def CleanupInstance(self, instance_name):
197 f28ec899 Guido Trotter
    """Cleanup after a stopped instance
198 f28ec899 Guido Trotter

199 f28ec899 Guido Trotter
    This is an optional method, used by hypervisors that need to cleanup after
200 f28ec899 Guido Trotter
    an instance has been stopped.
201 f28ec899 Guido Trotter

202 f28ec899 Guido Trotter
    @type instance_name: string
203 f28ec899 Guido Trotter
    @param instance_name: instance name to cleanup after
204 f28ec899 Guido Trotter

205 f28ec899 Guido Trotter
    """
206 f28ec899 Guido Trotter
    pass
207 f28ec899 Guido Trotter
208 65a6f9b7 Michael Hanselmann
  def RebootInstance(self, instance):
209 65a6f9b7 Michael Hanselmann
    """Reboot an instance."""
210 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
211 65a6f9b7 Michael Hanselmann
212 65a6f9b7 Michael Hanselmann
  def ListInstances(self):
213 65a6f9b7 Michael Hanselmann
    """Get the list of running instances."""
214 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
215 65a6f9b7 Michael Hanselmann
216 65a6f9b7 Michael Hanselmann
  def GetInstanceInfo(self, instance_name):
217 65a6f9b7 Michael Hanselmann
    """Get instance properties.
218 65a6f9b7 Michael Hanselmann

219 cd42d0ad Guido Trotter
    @type instance_name: string
220 c41eea6e Iustin Pop
    @param instance_name: the instance name
221 65a6f9b7 Michael Hanselmann

222 c41eea6e Iustin Pop
    @return: tuple (name, id, memory, vcpus, state, times)
223 65a6f9b7 Michael Hanselmann

224 65a6f9b7 Michael Hanselmann
    """
225 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
226 65a6f9b7 Michael Hanselmann
227 65a6f9b7 Michael Hanselmann
  def GetAllInstancesInfo(self):
228 65a6f9b7 Michael Hanselmann
    """Get properties of all instances.
229 65a6f9b7 Michael Hanselmann

230 c41eea6e Iustin Pop
    @return: list of tuples (name, id, memory, vcpus, stat, times)
231 c41eea6e Iustin Pop

232 65a6f9b7 Michael Hanselmann
    """
233 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
234 65a6f9b7 Michael Hanselmann
235 65a6f9b7 Michael Hanselmann
  def GetNodeInfo(self):
236 65a6f9b7 Michael Hanselmann
    """Return information about the node.
237 65a6f9b7 Michael Hanselmann

238 c41eea6e Iustin Pop
    @return: a dict with the following keys (values in MiB):
239 c41eea6e Iustin Pop
          - memory_total: the total memory size on the node
240 c41eea6e Iustin Pop
          - memory_free: the available memory on the node for instances
241 c41eea6e Iustin Pop
          - memory_dom0: the memory used by the node itself, if available
242 65a6f9b7 Michael Hanselmann

243 65a6f9b7 Michael Hanselmann
    """
244 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
245 65a6f9b7 Michael Hanselmann
246 637ce7f9 Guido Trotter
  @classmethod
247 55cc0a44 Michael Hanselmann
  def GetInstanceConsole(cls, instance, hvparams, beparams):
248 55cc0a44 Michael Hanselmann
    """Return information for connecting to the console of an instance.
249 65a6f9b7 Michael Hanselmann

250 65a6f9b7 Michael Hanselmann
    """
251 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
252 65a6f9b7 Michael Hanselmann
253 e1b8653f Guido Trotter
  @classmethod
254 e1b8653f Guido Trotter
  def GetAncillaryFiles(cls):
255 e1b8653f Guido Trotter
    """Return a list of ancillary files to be copied to all nodes as ancillary
256 e1b8653f Guido Trotter
    configuration files.
257 e1b8653f Guido Trotter

258 69ab2e12 Guido Trotter
    @rtype: (list of absolute paths, list of absolute paths)
259 69ab2e12 Guido Trotter
    @return: (all files, optional files)
260 e1b8653f Guido Trotter

261 e1b8653f Guido Trotter
    """
262 e1b8653f Guido Trotter
    # By default we return a member variable, so that if an hypervisor has just
263 e1b8653f Guido Trotter
    # a static list of files it doesn't have to override this function.
264 69ab2e12 Guido Trotter
    assert set(cls.ANCILLARY_FILES).issuperset(cls.ANCILLARY_FILES_OPT), \
265 69ab2e12 Guido Trotter
      "Optional ancillary files must be a subset of ancillary files"
266 69ab2e12 Guido Trotter
267 69ab2e12 Guido Trotter
    return (cls.ANCILLARY_FILES, cls.ANCILLARY_FILES_OPT)
268 e1b8653f Guido Trotter
269 65a6f9b7 Michael Hanselmann
  def Verify(self):
270 65a6f9b7 Michael Hanselmann
    """Verify the hypervisor.
271 65a6f9b7 Michael Hanselmann

272 65a6f9b7 Michael Hanselmann
    """
273 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
274 6e7275c0 Iustin Pop
275 b459a848 Andrea Spadaccini
  def MigrationInfo(self, instance): # pylint: disable=R0201,W0613
276 cd42d0ad Guido Trotter
    """Get instance information to perform a migration.
277 cd42d0ad Guido Trotter

278 cd42d0ad Guido Trotter
    By default assume no information is needed.
279 cd42d0ad Guido Trotter

280 cd42d0ad Guido Trotter
    @type instance: L{objects.Instance}
281 cd42d0ad Guido Trotter
    @param instance: instance to be migrated
282 cd42d0ad Guido Trotter
    @rtype: string/data (opaque)
283 cd42d0ad Guido Trotter
    @return: instance migration information - serialized form
284 cd42d0ad Guido Trotter

285 cd42d0ad Guido Trotter
    """
286 d0c8c01d Iustin Pop
    return ""
287 cd42d0ad Guido Trotter
288 cd42d0ad Guido Trotter
  def AcceptInstance(self, instance, info, target):
289 cd42d0ad Guido Trotter
    """Prepare to accept an instance.
290 cd42d0ad Guido Trotter

291 cd42d0ad Guido Trotter
    By default assume no preparation is needed.
292 cd42d0ad Guido Trotter

293 cd42d0ad Guido Trotter
    @type instance: L{objects.Instance}
294 cd42d0ad Guido Trotter
    @param instance: instance to be accepted
295 cd42d0ad Guido Trotter
    @type info: string/data (opaque)
296 cd42d0ad Guido Trotter
    @param info: migration information, from the source node
297 cd42d0ad Guido Trotter
    @type target: string
298 cd42d0ad Guido Trotter
    @param target: target host (usually ip), on this node
299 cd42d0ad Guido Trotter

300 cd42d0ad Guido Trotter
    """
301 cd42d0ad Guido Trotter
    pass
302 cd42d0ad Guido Trotter
303 b990eedd Guido Trotter
  def BalloonInstanceMemory(self, instance, mem):
304 b990eedd Guido Trotter
    """Balloon an instance memory to a certain value.
305 b990eedd Guido Trotter

306 b990eedd Guido Trotter
    @type instance: L{objects.Instance}
307 b990eedd Guido Trotter
    @param instance: instance to be accepted
308 b990eedd Guido Trotter
    @type mem: int
309 b990eedd Guido Trotter
    @param mem: actual memory size to use for instance runtime
310 b990eedd Guido Trotter

311 b990eedd Guido Trotter
    """
312 b990eedd Guido Trotter
    raise NotImplementedError
313 b990eedd Guido Trotter
314 6a1434d7 Andrea Spadaccini
  def FinalizeMigrationDst(self, instance, info, success):
315 6a1434d7 Andrea Spadaccini
    """Finalize the instance migration on the target node.
316 cd42d0ad Guido Trotter

317 cd42d0ad Guido Trotter
    Should finalize or revert any preparation done to accept the instance.
318 cd42d0ad Guido Trotter
    Since by default we do no preparation, we also don't have anything to do
319 cd42d0ad Guido Trotter

320 cd42d0ad Guido Trotter
    @type instance: L{objects.Instance}
321 fea922fa Guido Trotter
    @param instance: instance whose migration is being finalized
322 cd42d0ad Guido Trotter
    @type info: string/data (opaque)
323 cd42d0ad Guido Trotter
    @param info: migration information, from the source node
324 cd42d0ad Guido Trotter
    @type success: boolean
325 cd42d0ad Guido Trotter
    @param success: whether the migration was a success or a failure
326 cd42d0ad Guido Trotter

327 cd42d0ad Guido Trotter
    """
328 cd42d0ad Guido Trotter
    pass
329 cd42d0ad Guido Trotter
330 58d38b02 Iustin Pop
  def MigrateInstance(self, instance, target, live):
331 6e7275c0 Iustin Pop
    """Migrate an instance.
332 6e7275c0 Iustin Pop

333 3a488770 Iustin Pop
    @type instance: L{objects.Instance}
334 9044275a Michael Hanselmann
    @param instance: the instance to be migrated
335 cd42d0ad Guido Trotter
    @type target: string
336 cd42d0ad Guido Trotter
    @param target: hostname (usually ip) of the target node
337 cd42d0ad Guido Trotter
    @type live: boolean
338 cd42d0ad Guido Trotter
    @param live: whether to do a live or non-live migration
339 6e7275c0 Iustin Pop

340 6e7275c0 Iustin Pop
    """
341 6e7275c0 Iustin Pop
    raise NotImplementedError
342 f48148c3 Iustin Pop
343 6a1434d7 Andrea Spadaccini
  def FinalizeMigrationSource(self, instance, success, live):
344 6a1434d7 Andrea Spadaccini
    """Finalize the instance migration on the source node.
345 6a1434d7 Andrea Spadaccini

346 6a1434d7 Andrea Spadaccini
    @type instance: L{objects.Instance}
347 6a1434d7 Andrea Spadaccini
    @param instance: the instance that was migrated
348 6a1434d7 Andrea Spadaccini
    @type success: bool
349 6a1434d7 Andrea Spadaccini
    @param success: whether the migration succeeded or not
350 6a1434d7 Andrea Spadaccini
    @type live: bool
351 6a1434d7 Andrea Spadaccini
    @param live: whether the user requested a live migration or not
352 6a1434d7 Andrea Spadaccini

353 6a1434d7 Andrea Spadaccini
    """
354 6a1434d7 Andrea Spadaccini
    pass
355 6a1434d7 Andrea Spadaccini
356 6a1434d7 Andrea Spadaccini
  def GetMigrationStatus(self, instance):
357 6a1434d7 Andrea Spadaccini
    """Get the migration status
358 6a1434d7 Andrea Spadaccini

359 6a1434d7 Andrea Spadaccini
    @type instance: L{objects.Instance}
360 6a1434d7 Andrea Spadaccini
    @param instance: the instance that is being migrated
361 6a1434d7 Andrea Spadaccini
    @rtype: L{objects.MigrationStatus}
362 6a1434d7 Andrea Spadaccini
    @return: the status of the current migration (one of
363 6a1434d7 Andrea Spadaccini
             L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
364 6a1434d7 Andrea Spadaccini
             progress info that can be retrieved from the hypervisor
365 6a1434d7 Andrea Spadaccini

366 6a1434d7 Andrea Spadaccini
    """
367 6a1434d7 Andrea Spadaccini
    raise NotImplementedError
368 6a1434d7 Andrea Spadaccini
369 61eb1a46 Guido Trotter
  def _InstanceStartupMemory(self, instance):
370 61eb1a46 Guido Trotter
    """Get the correct startup memory for an instance
371 61eb1a46 Guido Trotter

372 61eb1a46 Guido Trotter
    This function calculates how much memory an instance should be started
373 61eb1a46 Guido Trotter
    with, making sure it's a value between the minimum and the maximum memory,
374 61eb1a46 Guido Trotter
    but also trying to use no more than the current free memory on the node.
375 61eb1a46 Guido Trotter

376 61eb1a46 Guido Trotter
    @type instance: L{objects.Instance}
377 61eb1a46 Guido Trotter
    @param instance: the instance that is being started
378 61eb1a46 Guido Trotter
    @rtype: integer
379 61eb1a46 Guido Trotter
    @return: memory the instance should be started with
380 61eb1a46 Guido Trotter

381 61eb1a46 Guido Trotter
    """
382 61eb1a46 Guido Trotter
    free_memory = self.GetNodeInfo()["memory_free"]
383 61eb1a46 Guido Trotter
    max_start_mem = min(instance.beparams[constants.BE_MAXMEM], free_memory)
384 61eb1a46 Guido Trotter
    start_mem = max(instance.beparams[constants.BE_MINMEM], max_start_mem)
385 61eb1a46 Guido Trotter
    return start_mem
386 61eb1a46 Guido Trotter
387 f48148c3 Iustin Pop
  @classmethod
388 f48148c3 Iustin Pop
  def CheckParameterSyntax(cls, hvparams):
389 f48148c3 Iustin Pop
    """Check the given parameters for validity.
390 f48148c3 Iustin Pop

391 f48148c3 Iustin Pop
    This should check the passed set of parameters for
392 f48148c3 Iustin Pop
    validity. Classes should extend, not replace, this function.
393 f48148c3 Iustin Pop

394 f48148c3 Iustin Pop
    @type hvparams:  dict
395 f48148c3 Iustin Pop
    @param hvparams: dictionary with parameter names/value
396 f48148c3 Iustin Pop
    @raise errors.HypervisorError: when a parameter is not valid
397 f48148c3 Iustin Pop

398 f48148c3 Iustin Pop
    """
399 f48148c3 Iustin Pop
    for key in hvparams:
400 f48148c3 Iustin Pop
      if key not in cls.PARAMETERS:
401 205ab586 Iustin Pop
        raise errors.HypervisorError("Parameter '%s' is not supported" % key)
402 205ab586 Iustin Pop
403 205ab586 Iustin Pop
    # cheap tests that run on the master, should not access the world
404 205ab586 Iustin Pop
    for name, (required, check_fn, errstr, _, _) in cls.PARAMETERS.items():
405 205ab586 Iustin Pop
      if name not in hvparams:
406 205ab586 Iustin Pop
        raise errors.HypervisorError("Parameter '%s' is missing" % name)
407 205ab586 Iustin Pop
      value = hvparams[name]
408 205ab586 Iustin Pop
      if not required and not value:
409 205ab586 Iustin Pop
        continue
410 205ab586 Iustin Pop
      if not value:
411 205ab586 Iustin Pop
        raise errors.HypervisorError("Parameter '%s' is required but"
412 205ab586 Iustin Pop
                                     " is currently not defined" % (name, ))
413 205ab586 Iustin Pop
      if check_fn is not None and not check_fn(value):
414 205ab586 Iustin Pop
        raise errors.HypervisorError("Parameter '%s' fails syntax"
415 205ab586 Iustin Pop
                                     " check: %s (current value: '%s')" %
416 205ab586 Iustin Pop
                                     (name, errstr, value))
417 205ab586 Iustin Pop
418 205ab586 Iustin Pop
  @classmethod
419 205ab586 Iustin Pop
  def ValidateParameters(cls, hvparams):
420 f48148c3 Iustin Pop
    """Check the given parameters for validity.
421 f48148c3 Iustin Pop

422 f48148c3 Iustin Pop
    This should check the passed set of parameters for
423 f48148c3 Iustin Pop
    validity. Classes should extend, not replace, this function.
424 f48148c3 Iustin Pop

425 f48148c3 Iustin Pop
    @type hvparams:  dict
426 f48148c3 Iustin Pop
    @param hvparams: dictionary with parameter names/value
427 f48148c3 Iustin Pop
    @raise errors.HypervisorError: when a parameter is not valid
428 f48148c3 Iustin Pop

429 f48148c3 Iustin Pop
    """
430 205ab586 Iustin Pop
    for name, (required, _, _, check_fn, errstr) in cls.PARAMETERS.items():
431 205ab586 Iustin Pop
      value = hvparams[name]
432 205ab586 Iustin Pop
      if not required and not value:
433 205ab586 Iustin Pop
        continue
434 205ab586 Iustin Pop
      if check_fn is not None and not check_fn(value):
435 205ab586 Iustin Pop
        raise errors.HypervisorError("Parameter '%s' fails"
436 205ab586 Iustin Pop
                                     " validation: %s (current value: '%s')" %
437 205ab586 Iustin Pop
                                     (name, errstr, value))
438 572e52bf Iustin Pop
439 f5118ade Iustin Pop
  @classmethod
440 f5118ade Iustin Pop
  def PowercycleNode(cls):
441 f5118ade Iustin Pop
    """Hard powercycle a node using hypervisor specific methods.
442 f5118ade Iustin Pop

443 f5118ade Iustin Pop
    This method should hard powercycle the node, using whatever
444 f5118ade Iustin Pop
    methods the hypervisor provides. Note that this means that all
445 f5118ade Iustin Pop
    instances running on the node must be stopped too.
446 f5118ade Iustin Pop

447 f5118ade Iustin Pop
    """
448 f5118ade Iustin Pop
    raise NotImplementedError
449 f5118ade Iustin Pop
450 94fed7da Iustin Pop
  @staticmethod
451 94fed7da Iustin Pop
  def GetLinuxNodeInfo():
452 572e52bf Iustin Pop
    """For linux systems, return actual OS information.
453 572e52bf Iustin Pop

454 572e52bf Iustin Pop
    This is an abstraction for all non-hypervisor-based classes, where
455 572e52bf Iustin Pop
    the node actually sees all the memory and CPUs via the /proc
456 572e52bf Iustin Pop
    interface and standard commands. The other case if for example
457 572e52bf Iustin Pop
    xen, where you only see the hardware resources via xen-specific
458 572e52bf Iustin Pop
    tools.
459 572e52bf Iustin Pop

460 572e52bf Iustin Pop
    @return: a dict with the following keys (values in MiB):
461 572e52bf Iustin Pop
          - memory_total: the total memory size on the node
462 572e52bf Iustin Pop
          - memory_free: the available memory on the node for instances
463 572e52bf Iustin Pop
          - memory_dom0: the memory used by the node itself, if available
464 572e52bf Iustin Pop

465 572e52bf Iustin Pop
    """
466 572e52bf Iustin Pop
    try:
467 3374afa9 Guido Trotter
      data = utils.ReadFile("/proc/meminfo").splitlines()
468 572e52bf Iustin Pop
    except EnvironmentError, err:
469 572e52bf Iustin Pop
      raise errors.HypervisorError("Failed to list node info: %s" % (err,))
470 572e52bf Iustin Pop
471 572e52bf Iustin Pop
    result = {}
472 572e52bf Iustin Pop
    sum_free = 0
473 572e52bf Iustin Pop
    try:
474 572e52bf Iustin Pop
      for line in data:
475 572e52bf Iustin Pop
        splitfields = line.split(":", 1)
476 572e52bf Iustin Pop
477 572e52bf Iustin Pop
        if len(splitfields) > 1:
478 572e52bf Iustin Pop
          key = splitfields[0].strip()
479 572e52bf Iustin Pop
          val = splitfields[1].strip()
480 d0c8c01d Iustin Pop
          if key == "MemTotal":
481 e687ec01 Michael Hanselmann
            result["memory_total"] = int(val.split()[0]) / 1024
482 d0c8c01d Iustin Pop
          elif key in ("MemFree", "Buffers", "Cached"):
483 e687ec01 Michael Hanselmann
            sum_free += int(val.split()[0]) / 1024
484 d0c8c01d Iustin Pop
          elif key == "Active":
485 e687ec01 Michael Hanselmann
            result["memory_dom0"] = int(val.split()[0]) / 1024
486 572e52bf Iustin Pop
    except (ValueError, TypeError), err:
487 572e52bf Iustin Pop
      raise errors.HypervisorError("Failed to compute memory usage: %s" %
488 572e52bf Iustin Pop
                                   (err,))
489 d0c8c01d Iustin Pop
    result["memory_free"] = sum_free
490 572e52bf Iustin Pop
491 572e52bf Iustin Pop
    cpu_total = 0
492 572e52bf Iustin Pop
    try:
493 572e52bf Iustin Pop
      fh = open("/proc/cpuinfo")
494 572e52bf Iustin Pop
      try:
495 572e52bf Iustin Pop
        cpu_total = len(re.findall("(?m)^processor\s*:\s*[0-9]+\s*$",
496 572e52bf Iustin Pop
                                   fh.read()))
497 572e52bf Iustin Pop
      finally:
498 572e52bf Iustin Pop
        fh.close()
499 572e52bf Iustin Pop
    except EnvironmentError, err:
500 572e52bf Iustin Pop
      raise errors.HypervisorError("Failed to list node info: %s" % (err,))
501 d0c8c01d Iustin Pop
    result["cpu_total"] = cpu_total
502 572e52bf Iustin Pop
    # FIXME: export correct data here
503 d0c8c01d Iustin Pop
    result["cpu_nodes"] = 1
504 d0c8c01d Iustin Pop
    result["cpu_sockets"] = 1
505 572e52bf Iustin Pop
506 572e52bf Iustin Pop
    return result
507 f5118ade Iustin Pop
508 f5118ade Iustin Pop
  @classmethod
509 f5118ade Iustin Pop
  def LinuxPowercycle(cls):
510 f5118ade Iustin Pop
    """Linux-specific powercycle method.
511 f5118ade Iustin Pop

512 f5118ade Iustin Pop
    """
513 f5118ade Iustin Pop
    try:
514 f5118ade Iustin Pop
      fd = os.open("/proc/sysrq-trigger", os.O_WRONLY)
515 f5118ade Iustin Pop
      try:
516 f5118ade Iustin Pop
        os.write(fd, "b")
517 f5118ade Iustin Pop
      finally:
518 f5118ade Iustin Pop
        fd.close()
519 f5118ade Iustin Pop
    except OSError:
520 f5118ade Iustin Pop
      logging.exception("Can't open the sysrq-trigger file")
521 f5118ade Iustin Pop
      result = utils.RunCmd(["reboot", "-n", "-f"])
522 f5118ade Iustin Pop
      if not result:
523 f5118ade Iustin Pop
        logging.error("Can't run shutdown: %s", result.output)