Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_base.py @ 1f4b9d39

History | View | Annotate | Download (17.1 kB)

1 65a6f9b7 Michael Hanselmann
#
2 65a6f9b7 Michael Hanselmann
#
3 65a6f9b7 Michael Hanselmann
4 53fde1ac Iustin Pop
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2012, 2013 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 323f9095 Stephen Shirley
  def StartInstance(self, instance, block_devices, startup_paused):
173 65a6f9b7 Michael Hanselmann
    """Start an instance."""
174 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
175 65a6f9b7 Michael Hanselmann
176 bbcf7ad0 Iustin Pop
  def StopInstance(self, instance, force=False, retry=False, name=None):
177 07b49e41 Guido Trotter
    """Stop an instance
178 07b49e41 Guido Trotter

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

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

196 f28ec899 Guido Trotter
    This is an optional method, used by hypervisors that need to cleanup after
197 f28ec899 Guido Trotter
    an instance has been stopped.
198 f28ec899 Guido Trotter

199 f28ec899 Guido Trotter
    @type instance_name: string
200 f28ec899 Guido Trotter
    @param instance_name: instance name to cleanup after
201 f28ec899 Guido Trotter

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

216 cd42d0ad Guido Trotter
    @type instance_name: string
217 c41eea6e Iustin Pop
    @param instance_name: the instance name
218 65a6f9b7 Michael Hanselmann

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

221 65a6f9b7 Michael Hanselmann
    """
222 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
223 65a6f9b7 Michael Hanselmann
224 65a6f9b7 Michael Hanselmann
  def GetAllInstancesInfo(self):
225 65a6f9b7 Michael Hanselmann
    """Get properties of all instances.
226 65a6f9b7 Michael Hanselmann

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

229 65a6f9b7 Michael Hanselmann
    """
230 65a6f9b7 Michael Hanselmann
    raise NotImplementedError
231 65a6f9b7 Michael Hanselmann
232 65a6f9b7 Michael Hanselmann
  def GetNodeInfo(self):
233 65a6f9b7 Michael Hanselmann
    """Return information about the node.
234 65a6f9b7 Michael Hanselmann

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

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

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

255 69ab2e12 Guido Trotter
    @rtype: (list of absolute paths, list of absolute paths)
256 69ab2e12 Guido Trotter
    @return: (all files, optional files)
257 e1b8653f Guido Trotter

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

269 cd04dfd2 Michael Hanselmann
    @return: Problem description if something is wrong, C{None} otherwise
270 cd04dfd2 Michael Hanselmann

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

511 f5118ade Iustin Pop
    """
512 f5118ade Iustin Pop
    try:
513 f5118ade Iustin Pop
      fd = os.open("/proc/sysrq-trigger", os.O_WRONLY)
514 f5118ade Iustin Pop
      try:
515 f5118ade Iustin Pop
        os.write(fd, "b")
516 f5118ade Iustin Pop
      finally:
517 f5118ade Iustin Pop
        fd.close()
518 f5118ade Iustin Pop
    except OSError:
519 f5118ade Iustin Pop
      logging.exception("Can't open the sysrq-trigger file")
520 f5118ade Iustin Pop
      result = utils.RunCmd(["reboot", "-n", "-f"])
521 f5118ade Iustin Pop
      if not result:
522 f5118ade Iustin Pop
        logging.error("Can't run shutdown: %s", result.output)
523 53fde1ac Iustin Pop
524 53fde1ac Iustin Pop
  @staticmethod
525 53fde1ac Iustin Pop
  def _FormatVerifyResults(msgs):
526 53fde1ac Iustin Pop
    """Formats the verification results, given a list of errors.
527 53fde1ac Iustin Pop

528 53fde1ac Iustin Pop
    @param msgs: list of errors, possibly empty
529 53fde1ac Iustin Pop
    @return: overall problem description if something is wrong,
530 53fde1ac Iustin Pop
        C{None} otherwise
531 53fde1ac Iustin Pop

532 53fde1ac Iustin Pop
    """
533 53fde1ac Iustin Pop
    if msgs:
534 53fde1ac Iustin Pop
      return "; ".join(msgs)
535 53fde1ac Iustin Pop
    else:
536 53fde1ac Iustin Pop
      return None